问:
MotionLayout no animation
I am trying to create a collapsing view animation via MotionLayout.  I want to make the view collapse when scrolling down and does not appear until the full scrolling up. My animation doesn't work now (video). Also my recycler view is not visible until the first click. What am I doing wrong? Thank

MainActivity layout:

```<code><androidx.constraintlayout.motion.widget.MotionLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray_more_white"

app:layoutDescription="@xml/collapsing_toolbar"
tools:showPaths="true">

<include
    android:id="@+id/include"
    layout="@layout/toolbar"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<com.github.florent37.shapeofview.shapes.ArcView
    android:id="@+id/header_view"
    android:layout_width="0dp"
    android:layout_height="100dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/include"
    app:shape_arc_cropDirection="outside"
    app:shape_arc_height="20dp"
    app:shape_arc_position="bottom">

    <View
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimaryDark" />

</com.github.florent37.shapeofview.shapes.ArcView>

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/swipe_view"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/include">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</androidx.constraintlayout.motion.widget.MotionLayout>
</code>```

MotionScene:

```<code><MotionScene
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:motion="http://schemas.android.com/apk/res-auto">

<Transition
    app:constraintSetEnd="@id/end"
    app:constraintSetStart="@id/start"
    app:duration="1000">

    <OnSwipe
        app:touchAnchorId="@id/swipe_view"
        app:dragDirection="dragDown"
        app:touchAnchorSide="top"
        app:moveWhenScrollAtTop="true"/>
</Transition>

<ConstraintSet android:id="@+id/start">
    <Constraint
        android:id="@id/header_view"
        android:layout_width="0dp"
        android:layout_height="100dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/include">
    </Constraint>
</ConstraintSet>

<ConstraintSet android:id="@+id/end">
    <Constraint
        android:id="@id/header_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/include">
    </Constraint>
</ConstraintSet>

</MotionScene>
</code>```

答:
So, after many attempts, I managed to fix this bug.

1) The trigger of the animation (in my case, RecyclerView) must necessarily be related to what the animation is directed to. And not necessarily directly (in my case RecyclerView and header are connected through Space)

2) The trigger of the animation or the element linking them should not overlap what the animation is directed to. (Those, in my case, Space should use constraintBottom_toBottomOf = "@ id / header" + marginBottom instead of constraintTop_toBottomOf = "@ id / header".

So, here is the final layout.

```<code><androidx.constraintlayout.motion.widget.MotionLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray_more_white"
app:layoutDescription="@xml/catalog_motion">

<com.github.florent37.shapeofview.shapes.ArcView
    android:id="@+id/header"
    android:layout_width="0dp"
    android:layout_height="100dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/include"
    app:shape_arc_cropDirection="outside"
    app:shape_arc_height="20dp"
    app:shape_arc_position="bottom">

    <View
        android:id="@+id/header_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimaryDark" />

</com.github.florent37.shapeofview.shapes.ArcView>

<Space
    android:id="@+id/space"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="100dp"
    app:layout_constraintBottom_toBottomOf="@id/header"
    app:layout_constraintStart_toStartOf="@id/header"
    app:layout_constraintEnd_toEndOf="@id/header"/>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/space" />

<include
    android:id="@+id/include"
    layout="@layout/toolbar"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>
</code>```

Title: MotionLayout no animation

Body:
I am trying to create a collapsing view animation via MotionLayout.  I want to make the view collapse when scrolling down and does not appear until the full scrolling up. My animation doesn't work now (video). Also my recycler view is not visible until the first click. What am I doing wrong? Thank

MainActivity layout:

<androidx.constraintlayout.motion.widget.MotionLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray_more_white"

app:layoutDescription="@xml/collapsing_toolbar"
tools:showPaths="true">

<include
    android:id="@+id/include"
    layout="@layout/toolbar"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<com.github.florent37.shapeofview.shapes.ArcView
    android:id="@+id/header_view"
    android:layout_width="0dp"
    android:layout_height="100dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/include"
    app:shape_arc_cropDirection="outside"
    app:shape_arc_height="20dp"
    app:shape_arc_position="bottom">

    <View
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimaryDark" />

</com.github.florent37.shapeofview.shapes.ArcView>

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/swipe_view"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/include">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</androidx.constraintlayout.motion.widget.MotionLayout>

MotionScene:

<MotionScene
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:motion="http://schemas.android.com/apk/res-auto">

<Transition
    app:constraintSetEnd="@id/end"
    app:constraintSetStart="@id/start"
    app:duration="1000">

    <OnSwipe
        app:touchAnchorId="@id/swipe_view"
        app:dragDirection="dragDown"
        app:touchAnchorSide="top"
        app:moveWhenScrollAtTop="true"/>
</Transition>

<ConstraintSet android:id="@+id/start">
    <Constraint
        android:id="@id/header_view"
        android:layout_width="0dp"
        android:layout_height="100dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/include">
    </Constraint>
</ConstraintSet>

<ConstraintSet android:id="@+id/end">
    <Constraint
        android:id="@id/header_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/include">
    </Constraint>
</ConstraintSet>

</MotionScene>

Body:
So, after many attempts, I managed to fix this bug.

1) The trigger of the animation (in my case, RecyclerView) must necessarily be related to what the animation is directed to. And not necessarily directly (in my case RecyclerView and header are connected through Space)

2) The trigger of the animation or the element linking them should not overlap what the animation is directed to. (Those, in my case, Space should use constraintBottom_toBottomOf = "@ id / header" + marginBottom instead of constraintTop_toBottomOf = "@ id / header".

So, here is the final layout.

<androidx.constraintlayout.motion.widget.MotionLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray_more_white"
app:layoutDescription="@xml/catalog_motion">

<com.github.florent37.shapeofview.shapes.ArcView
    android:id="@+id/header"
    android:layout_width="0dp"
    android:layout_height="100dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/include"
    app:shape_arc_cropDirection="outside"
    app:shape_arc_height="20dp"
    app:shape_arc_position="bottom">

    <View
        android:id="@+id/header_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimaryDark" />

</com.github.florent37.shapeofview.shapes.ArcView>

<Space
    android:id="@+id/space"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="100dp"
    app:layout_constraintBottom_toBottomOf="@id/header"
    app:layout_constraintStart_toStartOf="@id/header"
    app:layout_constraintEnd_toEndOf="@id/header"/>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/space" />

<include
    android:id="@+id/include"
    layout="@layout/toolbar"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>


来源: stackexchange

问:
How check, if button pressed twice?
I am able to press the Enter button in Python, using Pygame.
Now, it prints "once" into the console everytime I press the button.
How can i detect if the button is pressed more than once and print "more than once"?</p>

```<code>  press = False
  if event.key == pygame.K_RETURN:
      press = True

      print("once")
  if press == True:
      print("more than once")
</code>```

答:
You're nearly there. Just use an if/else block and set press to True after printing:

```<code>import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
run = True
press = False

while run:
  for e in pygame.event.get():
    if e.type == pygame.QUIT:
        run = False
    if e.type == pygame.KEYDOWN:
        if e.key == pygame.K_RETURN:
            if not press:
                print('once')
            else:
                print('more than once')
            press = True

  screen.fill((30, 30, 30))
  pygame.display.flip()
</code>```

ContentLicense: CC BY-SA 4.0

Title: How check, if button pressed twice?

Body:
I am able to press the Enter button in Python, using Pygame.
Now, it prints "once" into the console everytime I press the button.
How can i detect if the button is pressed more than once and print "more than once"?

  press = False
  if event.key == pygame.K_RETURN:
      press = True

      print("once")
  if press == True:
      print("more than once")

Body:
You're nearly there. Just use an if/else block and set press to True after printing:

import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
run = True
press = False

while run:
  for e in pygame.event.get():
    if e.type == pygame.QUIT:
        run = False
    if e.type == pygame.KEYDOWN:
        if e.key == pygame.K_RETURN:
            if not press:
                print('once')
            else:
                print('more than once')
            press = True

  screen.fill((30, 30, 30))
  pygame.display.flip()


问:
how do I link a button to the webview of another controller having a link that changes based on the cell pressed?
I have a button that needs to open a web view on another controller in modally. currently the button executes the code you see below. I would like the button to open the webview directly. the link changes because it is an rss reader and therefore, based on the cell pressed, changes the link of the button that must open the webview.

this is the code that manages the controller that appears after the cell has been pressed

```<code>class FeedItemWebViewController: UIViewController, UIWebViewDelegate {

@IBOutlet weak var textView: UITextView!
var link: String? = nil
var descriptionTesto:String? = nil

override func viewDidLoad() {
    super.viewDidLoad()
  self.textView.text = descriptionTesto
}
@IBAction func apri(_ sender: UIBarButtonItem) {
     guard let url = URL(string: self.link ?? "") else { return }
   UIApplication.shared.open(url, options: [:], completionHandler: nil)

}

}
</code>```

here is where it manages the controller where I entered the webview

```<code>class OpenSafariController: UIViewController, UIWebViewDelegate {

@IBOutlet weak var myWebView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func ritornaLista(_ sender: UIBarButtonItem) {
    self.presentingViewController?.presentingViewController?.dismiss(animated: false, completion: nil)
}
}
</code>```

答:
delete the webview controller that is not needed. import SafariServices. here is the code to put on the button</p>

```<code>@IBAction func apri(_ sender: UIBarButtonItem) {

  let svc = SFSafariViewController(url: URL(string: self.link ?? "")!)
    self.present(svc, animated: true, completion: nil)
}
</code>```

Body:
I have a button that needs to open a web view on another controller in modally. currently the button executes the code you see below. I would like the button to open the webview directly. the link changes because it is an rss reader and therefore, based on the cell pressed, changes the link of the button that must open the webview.

this is the code that manages the controller that appears after the cell has been pressed

class FeedItemWebViewController: UIViewController, UIWebViewDelegate {

@IBOutlet weak var textView: UITextView!
var link: String? = nil
var descriptionTesto:String? = nil

override func viewDidLoad() {
    super.viewDidLoad()
  self.textView.text = descriptionTesto
}
@IBAction func apri(_ sender: UIBarButtonItem) {
     guard let url = URL(string: self.link ?? "") else { return }
   UIApplication.shared.open(url, options: [:], completionHandler: nil)

}

}

here is where it manages the controller where I entered the webview

class OpenSafariController: UIViewController, UIWebViewDelegate {

@IBOutlet weak var myWebView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func ritornaLista(_ sender: UIBarButtonItem) {
    self.presentingViewController?.presentingViewController?.dismiss(animated: false, completion: nil)
}
}

Body:
delete the webview controller that is not needed. import SafariServices. here is the code to put on the button

@IBAction func apri(_ sender: UIBarButtonItem) {

  let svc = SFSafariViewController(url: URL(string: self.link ?? "")!)
    self.present(svc, animated: true, completion: nil)
}


问:
How to make a horizontal StackView to have the first element's width and fill the rest of it
I'm new with swift and trying to create an input field at the moment. My problem is, that I would like to have a Label as shown in the picture:

So far, I'm working with StackViews: One vertical one for the input fields, and three horizontal ones to have the Title and the user input. My code so far is as follows:

```<code>// Initialize outter stackview
    let feedbackOutterSV = UIStackView()
    view.addSubview(feedbackOutterSV)
    feedbackOutterSV.translatesAutoresizingMaskIntoConstraints = false
    feedbackOutterSV.axis = NSLayoutConstraint.Axis.vertical
    NSLayoutConstraint.activate([
        feedbackOutterSV.topAnchor.constraint(equalTo: tutorialText.bottomAnchor, constant: 10),
        feedbackOutterSV.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
        feedbackOutterSV.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
        feedbackOutterSV.heightAnchor.constraint(equalToConstant: 300)
    ])

    // Initalize inner stackview for title
    let feedbackInnerSVTitle = UIStackView()
    feedbackOutterSV.addArrangedSubview(feedbackInnerSVTitle)
    feedbackInnerSVTitle.translatesAutoresizingMaskIntoConstraints = false
    feedbackInnerSVTitle.axis = .horizontal
    feedbackInnerSVTitle.alignment = .fill
    feedbackInnerSVTitle.distribution = .fillProportionally

    let titleLabel = UILabel()
    feedbackInnerSVTitle.addArrangedSubview(titleLabel)
    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.text = "feedback.input.title".localize()
    titleLabel.font = UIFont.preferredFont(forTextStyle: .body)
    titleLabel.textColor = .gray

    let titleTextView = UITextView()
    feedbackInnerSVTitle.addArrangedSubview(titleTextView)
    titleTextView.translatesAutoresizingMaskIntoConstraints = false
    titleTextView.font = UIFont.preferredFont(forTextStyle: .body)
    titleTextView.isScrollEnabled = false

    NSLayoutConstraint.activate([
        titleLabel.widthAnchor.constraint(equalToConstant: 39)
    ])
</code>```

This code gives the expected output for English, however I have to implement it in different languages, so I can't use a constant width.

Can anyone tell me how to change my code, so I don't need the constant constraint but the width of the Label is adjusted to the length of the word?

Thanks in advance

答:
In your code, width constraint on titleLabel must be set to titleLabel.intrinsicContentSize.width

```<code>NSLayoutConstraint.activate([
   titleLabel.widthAnchor.constraint(equalToConstant: titleLabel.intrinsicContentSize.width)
])
</code>```

Also, set the distribution of feedbackInnerSVTitle as .fill

```<code>feedbackInnerSVTitle.distribution = .fill
</code>```

Body:
I'm new with swift and trying to create an input field at the moment. My problem is, that I would like to have a Label as shown in the picture:

So far, I'm working with StackViews: One vertical one for the input fields, and three horizontal ones to have the Title and the user input. My code so far is as follows:

// Initialize outter stackview
    let feedbackOutterSV = UIStackView()
    view.addSubview(feedbackOutterSV)
    feedbackOutterSV.translatesAutoresizingMaskIntoConstraints = false
    feedbackOutterSV.axis = NSLayoutConstraint.Axis.vertical
    NSLayoutConstraint.activate([
        feedbackOutterSV.topAnchor.constraint(equalTo: tutorialText.bottomAnchor, constant: 10),
        feedbackOutterSV.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
        feedbackOutterSV.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
        feedbackOutterSV.heightAnchor.constraint(equalToConstant: 300)
    ])

    // Initalize inner stackview for title
    let feedbackInnerSVTitle = UIStackView()
    feedbackOutterSV.addArrangedSubview(feedbackInnerSVTitle)
    feedbackInnerSVTitle.translatesAutoresizingMaskIntoConstraints = false
    feedbackInnerSVTitle.axis = .horizontal
    feedbackInnerSVTitle.alignment = .fill
    feedbackInnerSVTitle.distribution = .fillProportionally

    let titleLabel = UILabel()
    feedbackInnerSVTitle.addArrangedSubview(titleLabel)
    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.text = "feedback.input.title".localize()
    titleLabel.font = UIFont.preferredFont(forTextStyle: .body)
    titleLabel.textColor = .gray

    let titleTextView = UITextView()
    feedbackInnerSVTitle.addArrangedSubview(titleTextView)
    titleTextView.translatesAutoresizingMaskIntoConstraints = false
    titleTextView.font = UIFont.preferredFont(forTextStyle: .body)
    titleTextView.isScrollEnabled = false

    NSLayoutConstraint.activate([
        titleLabel.widthAnchor.constraint(equalToConstant: 39)
    ])

This code gives the expected output for English, however I have to implement it in different languages, so I can't use a constant width.

Can anyone tell me how to change my code, so I don't need the constant constraint but the width of the Label is adjusted to the length of the word?

Thanks in advance

Body:
In your code, width constraint on titleLabel must be set to titleLabel.intrinsicContentSize.width

NSLayoutConstraint.activate([
   titleLabel.widthAnchor.constraint(equalToConstant: titleLabel.intrinsicContentSize.width)
])

Also, set the distribution of feedbackInnerSVTitle as .fill

feedbackInnerSVTitle.distribution = .fill


问:
Is it possible to connect a git submodule to a specific commit on a branch on the main project?
I have this situation with git version 2.8.0.windows.1.

I have one "release" branch of the main project and I push there everytime I've a new release.

This project has a submodule that is developed in parallel, so I expect many commits there.

Project Master branch and Submodule Master branches goes ahead (almost) in parallel.

Master Commit 1 => Master Commit 2 => Master Commit 3 => Master Commit 4

Submodule Commit 1 => Submodule Commit 2 => Submodule Commit 3 => Submodule Commit 4

In this case Master Commit 4 is aligned with Submodule Commit 4.

The issue arises when someone tries to get the release branch too late.

So if I push the release branch at Master Commit 1 and someone pull release branch when we are at Master Commit 4 we have a misalignment (because release is related to Master Commit 1, while now we are on Submodule Commit 4).

The solution I see is to coerce somehow Submodule Commit 1 to release branch, but I don't know how yet.

I know that a great solution would be just to add a branch or tag on the submodule as explained here.

But I've no authority over the submodule repository, so it won't be easy for me to set branches or tags there.

Are there any workarounds to coerce a specific submodule commit on my release branch and not just a submodule branch/tag?

答:
This is how submodules work anyway so I don't understand your problem. Let's me try to enhance or fix your workflow. You need every commit in the release branch points to the corresponding commit in the submodule, right? This is easy: before making commits in the release branch update the submodule, checkout the correct commit in the submodule and commit the change in superproject:

```<code># In the superproject
git checkout release

cd subdir # into the submodule
git checkout master # reconcile detached HEAD
git pull origin master # update the submodule
git checkout some-sha1 # if you don't want the latest commit in master

cd .. # back into superproject
git add subdir
git commit -m "Update submodule"
</code>```

Now everyone who git clone --recursive the superproject gets the submodule pointed to the correct commit for every commit in the branch release.

Body:
This is how submodules work anyway so I don't understand your problem. Let's me try to enhance or fix your workflow. You need every commit in the release branch points to the corresponding commit in the submodule, right? This is easy: before making commits in the release branch update the submodule, checkout the correct commit in the submodule and commit the change in superproject:

# In the superproject
git checkout release

cd subdir # into the submodule
git checkout master # reconcile detached HEAD
git pull origin master # update the submodule
git checkout some-sha1 # if you don't want the latest commit in master

cd .. # back into superproject
git add subdir
git commit -m "Update submodule"

Now everyone who git clone --recursive the superproject gets the submodule pointed to the correct commit for every commit in the branch release.


问:
Compare two list to sort the second list
I would like to compare two lists, if the value of the first list corresponds to the code of the second list, it would be necessary that the second list is sorted according to the values compared

First list :

```<code>      var List1 = [{id : "idValue2"}, {id : "idValue5"}]
</code>```

Second List (before sorting)

```<code>     var List2 = [
                  {code : "idValue1", label: "value1"},
                  {code : "idValue2", label: "value2"},
                  {code : "idValue3", label: "value3"},
                  {code : "idValue4", label: "value4"};
                  {code : "idValue5", label: "value5"}]
</code>```

After comparing list1 ids and list2 codes would get list2 sorted

Second List (after sorting)

```<code>     var List2 = [
                  {code : "idValue2", label: "value2"},
                  {code : "idValue5", label: "value5"}
                  {code : "idValue1", label: "value1"},
                  {code : "idValue3", label: "value3"},
                  {code : "idValue4", label: "value4"}]
</code>```

Here idValue2 and idValue5 take  the first places.

Do you have a solution ?

答:
This a simple, yet maybe not really performant solution. You basically have two nested for loops, which loop through the List1 and List2. If the id and the code are similar the element of List2 is pushed to the result array, and from a copy of the List2, this element is removed. Why a copy? So we don't modify the List2 while iterating over it.
In the end the result (the sorted items) and copyList2 (the remaining, not sorted items) are joined together via concat.

var List1 = [{id : "idValue2"}, {id : "idValue5"}]

var List2 = [
   {code : "idValue1", label: "value1"},
   {code : "idValue2", label: "value2"},
   {code : "idValue3", label: "value3"},
   {code : "idValue4", label: "value4"},
   {code : "idValue5", label: "value5"}
]

var result = [];
var copyList2 = List2;

for(var i = 0; i < List1.length; i++){
  for(var j = 0; j < List2.length; j++){
   if(List1[i].id === List2[j].code){
     result.push(List2[j]);
     copyList2.splice(j, 1);
   }
  }
}

result = result.concat(copyList2);
console.log(result);```

Body:
I would like to compare two lists, if the value of the first list corresponds to the code of the second list, it would be necessary that the second list is sorted according to the values compared

First list :

      var List1 = [{id : "idValue2"}, {id : "idValue5"}]

Second List (before sorting)

     var List2 = [
                  {code : "idValue1", label: "value1"},
                  {code : "idValue2", label: "value2"},
                  {code : "idValue3", label: "value3"},
                  {code : "idValue4", label: "value4"};
                  {code : "idValue5", label: "value5"}]

After comparing list1 ids and list2 codes would get list2 sorted

Second List (after sorting)

     var List2 = [
                  {code : "idValue2", label: "value2"},
                  {code : "idValue5", label: "value5"}
                  {code : "idValue1", label: "value1"},
                  {code : "idValue3", label: "value3"},
                  {code : "idValue4", label: "value4"}]

Here idValue2 and idValue5 take  the first places.

Do you have a solution ?


问:
How to compare input and Document in mongoDB
When I Register [ input Email / password to DB ] success. Then, I want to login. If input[email/pass] == document in collection >> go to next page, else console.log['wrong email/pass']

I try to wirte IF/else code but I don't know check condition.

This code is Register form

```<code>app.post('/register',function(req,res){
    MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");
  let myobj = { Email: req.body.email, Password: req.body.psw } ;

  dbo.collection("Register").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log(" document inserted");
    db.close();
  });
});

});
</code>```

This code is Login form

```<code>app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");

  let cursor = dbo.collection('Register').find();
   cursor.each(function(err,doc) {
    if (doc == req.body.email && req.body.psw){
      console.log("goto next page");

    }
    else{
      console.log('wrong');
    }

   });
    db.close();
  });
});
</code>```

Correct input and wrong input Output is = Wrong

Pls insert loop check all of array pls.

```<code>app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("project");

  dbo.collection("Register").findOne({}, function(err, result) {

    if (result.Email == req.body.email && result.Password == req.body.psw) {
      console.log("OK");
    }
    else{
      console.log(result.Email && result.Password);
    }
    db.close();
  });
});
});
</code>```

答:
Firstly you should check for valid request body and the you should do a fineone query instead of running a for-loop and checking. see the corrected one below :

app.post("/index", function(req, res) {
  let {
    email,
    psw
  } = req.body;
  if (email && psw) {
    console.log("wrong credentials");
    return;
  } else {
    MongoClient.connect(url, function(err, db) {
      if (err) throw err;
      let dbo = db.db("project");
      let data = dbo.collection("Register").findOne({
        Email: email,
        Password: psw
      });
      if (data) {
        console.log("goto next page");
      } else {
        console.log("wrong");
      }
      db.close();
    });
  }
});```

Body:
When I Register [ input Email / password to DB ] success. Then, I want to login. If input[email/pass] == document in collection >> go to next page, else console.log['wrong email/pass']

I try to wirte IF/else code but I don't know check condition.

This code is Register form

app.post('/register',function(req,res){
    MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");
  let myobj = { Email: req.body.email, Password: req.body.psw } ;

  dbo.collection("Register").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log(" document inserted");
    db.close();
  });
});

});

This code is Login form

app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");

  let cursor = dbo.collection('Register').find();
   cursor.each(function(err,doc) {
    if (doc == req.body.email && req.body.psw){
      console.log("goto next page");

    }
    else{
      console.log('wrong');
    }

   });
    db.close();
  });
});

Correct input and wrong input Output is = Wrong

Pls insert loop check all of array pls.

app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("project");

  dbo.collection("Register").findOne({}, function(err, result) {

    if (result.Email == req.body.email && result.Password == req.body.psw) {
      console.log("OK");
    }
    else{
      console.log(result.Email && result.Password);
    }
    db.close();
  });
});
});


问:
Branch from the past in mercurial
I'm a single developer using Mercurial to create a program.  I have so far committed at every step of developing, and I have messed things up and want to work on something else.

How shall I go to a previous state (ie. rollback) and then create a branch, maintaining the newer states?

Does rollback ever delete anything?  Should that be all I do? Just rollback untill I'm at the place where I want, edit, then commit?  Will I be able to merge the changesets later, or at least look at them?  Of course I can just save this repository, rollback, and then create new changesets, then merge the two repositories?

I'm new to SCM and of course DSCM, so be gentle :)

答:
The other answer will work but it is excessive. All you need to do is:

```<code>hg up <revnum>
</code>```

and your local working folder will be updated to the state of files at the specified revision. You can just work from there.

As soon as you commit it will create an anonymous branch automatically. Your original commits remain preserved but out of your way.

This is the simplest possible approach (IMHO) which I would recommend starting with.

ContentLicense: CC BY-SA 2.5

Title: Branch from the past in mercurial

LastEditorDisplayName: Chad Birch

Body:
The other answer will work but it is excessive. All you need to do is:

hg up <revnum>

and your local working folder will be updated to the state of files at the specified revision. You can just work from there.

As soon as you commit it will create an anonymous branch automatically. Your original commits remain preserved but out of your way.

This is the simplest possible approach (IMHO) which I would recommend starting with.


问:
eigenvalues of the matrix - polynomial
I calculate the eigenvalues of the matrix. I want to write a program that will help me (step by step). I know the eigen function, but I'd like to see a polynomial (like here) a link
and then calculate the polynomial elements.

I can enter a matrix, but I do not know how to enter a new matrix after subtracting "a" from the main diagonal, let alone determine the function that the polynomial (matrix determinant) will give me.

I am asking for directions
Can you do the same as "charpoly (B, x)" and solve (polyB) in R

答:
Use charpoly and roots from the pracma package:

```<code>library(pracma)

m <- matrix(c(1,2,0,2,4,6,0,6,5), 3, byrow = TRUE)
cp <- charpoly(m)

cp
## [1]   1 -10 -11  36

roots(cp)
## [1] 10.71311 -2.22404  1.51093

# same (except for order)
eigen(m)$values
## [1] 10.71311  1.51093 -2.22404
</code>```

Title: eigenvalues of the matrix - polynomial

Body:
Use charpoly and roots from the pracma package:

library(pracma)

m <- matrix(c(1,2,0,2,4,6,0,6,5), 3, byrow = TRUE)
cp <- charpoly(m)

cp
## [1]   1 -10 -11  36

roots(cp)
## [1] 10.71311 -2.22404  1.51093

# same (except for order)
eigen(m)$values
## [1] 10.71311  1.51093 -2.22404


问:
Binary value calculation based on string length
Example:
for 4 i need binary value as 0100
for 4a i need binary value as 01001010

I tried but the leading zeros are not coming.

```<code>field_reset = bin(int(field_reset, 16))[2:]

field_reset = bin(int(field_reset, 16))[2:]
</code>```

leading zeros are not coming.please share me if you have any thoughts.
Thanks!

答:
I'm assuming field_reset value is 4a.

When you do field_reset = bin(int(field_reset, 16))[2:], you are trimming out the beginning part which contains 0b. Try below one.

```<code>aa=bin(int('4a',16))[2:]
aa.zfill(len(aa)+1)
</code>```

Body:
Example:
for 4 i need binary value as 0100
for 4a i need binary value as 01001010

I tried but the leading zeros are not coming.

field_reset = bin(int(field_reset, 16))[2:]

field_reset = bin(int(field_reset, 16))[2:]

leading zeros are not coming.please share me if you have any thoughts.
Thanks!

Body:
I'm assuming field_reset value is 4a.

When you do field_reset = bin(int(field_reset, 16))[2:], you are trimming out the beginning part which contains 0b. Try below one.

aa=bin(int('4a',16))[2:]
aa.zfill(len(aa)+1)


问:
Angular RxJS: event emitted twice
I've coded two observables:

One for cathing form submit events:

```<code><form role="form" (ngSubmit)="search()">
   ...
</form>
</code>```

And search() is reached and emits:

```<code>private search(): void {
    this.searchClickSubject.next();
}
</code>```

In component constructor:

```<code>private searchClickSubject:Subject<void>;
private searchClick$:Observable<any>;

constructor() {
    this.searchClickSubject = new Subject<void>();
    this.searchClick$ = this.searchClickSubject.asObservable();
}
</code>```

As you can see I create an Observable from subject searchClickSubject using searchClickSubject.asObservable method on searchClick$.

From now on, I'm using this searchClick$ Observable in order to catch submit form.

After that, I'm creating another Observable:

```<code>    this.searchQuery$ = this.searchClick$.pipe(
        map(() => <Query>{
            offset: 0,
            limit: 10
        })
    );
</code>```

So, each time a Query is emitted I make requestm using custom pipeable functions:

```<code>    this.metrics$ = this.searchQuery$
        .pipe(
          pageLoading(),
          makeRequest(),
          loadedPage()
        );
</code>```

This is my ngOnInit():

```<code>public ngOnInit() {
    // Grab search button click event
    this.searchQuery$ = this.searchClick$.pipe(
        map(() => <Query>{
            offset: 0,
            limit: 10
        })
    );

    this.metrics$ = this.searchQuery$
        .pipe(
          //...
        );
}
</code>```

However, request is launched twice.

I create subscriptions using async pipeline:

```<code><div class="row" *ngIf="!(metrics$ | async)" style="margin: 1.54em;">

<div *ngIf="metrics$ | async; let metric;"...
</code>```

Any ideas?

答:
You subscribe to the observable metrics$ two times. Here is what happens:

You subscribe by using *ngIf="!(metrics$ | async)".

When you click search, it immediately fires the observable, and everything you chained on it, including your request.

You subscribe using *ngIf="metrics$ | async; let metric;".

Step 2 happens again, separately.

Use the share() operator in metrics$ to prevent remaking the request on a new subscription. If you want to have a deeper understanding of this topic, check out this great article.

Title: Angular RxJS: event emitted twice

Body:
I've coded two observables:

One for cathing form submit events:

<form role="form" (ngSubmit)="search()">
   ...
</form>

And search() is reached and emits:

private search(): void {
    this.searchClickSubject.next();
}

In component constructor:

private searchClickSubject:Subject<void>;
private searchClick$:Observable<any>;

constructor() {
    this.searchClickSubject = new Subject<void>();
    this.searchClick$ = this.searchClickSubject.asObservable();
}

As you can see I create an Observable from subject searchClickSubject using searchClickSubject.asObservable method on searchClick$.

From now on, I'm using this searchClick$ Observable in order to catch submit form.

After that, I'm creating another Observable:

    this.searchQuery$ = this.searchClick$.pipe(
        map(() => <Query>{
            offset: 0,
            limit: 10
        })
    );

So, each time a Query is emitted I make requestm using custom pipeable functions:

    this.metrics$ = this.searchQuery$
        .pipe(
          pageLoading(),
          makeRequest(),
          loadedPage()
        );

This is my ngOnInit():

public ngOnInit() {
    // Grab search button click event
    this.searchQuery$ = this.searchClick$.pipe(
        map(() => <Query>{
            offset: 0,
            limit: 10
        })
    );

    this.metrics$ = this.searchQuery$
        .pipe(
          //...
        );
}

However, request is launched twice.

I create subscriptions using async pipeline:

<div *ngIf="metrics$ | async; let metric;"...

Any ideas?


答:
You could store the ids in an temp-array as values. Then use a custom sort-function on the list2-array to compare the the positions of the code in the temp-array:

let list1 = [{id : "idValue2"}, {id : "idValue5"}];
let list2 = [
  {code : "idValue1", label: "value1"},
  {code : "idValue2", label: "value2"},
  {code : "idValue3", label: "value3"},
  {code : "idValue4", label: "value4"},
  {code : "idValue5", label: "value5"}
];

let tempArray = [];
for (let obj of list1) {
  tempArray.push(obj.id);
}

list2.sort(function(a, b) {
  let iA = tempArray.indexOf(a.code);
  let iB = tempArray.indexOf(b.code);
  if (iA == iB) {
      return 0;
  }
  if (iA == -1) {
    return 1;
  }
  if (iB == -1) {
    return -1;
  }
  if (iA < iB) {
    return -1;
  }
  if (iA > iB) {
    return 1;
  }
});

console.log(list2);```

Title: Compare two list to sort the second list


问:
how to send a GET request using two send functions?
This code is sending a GET request with the help of one send function
but I want to send the same GET request, but break it down and send it using two send function. The code is given below.

```<code>#include<iostream>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>//the new file.
#include<unistd.h>//for using the sleep function.
using namespace std;
int main(int argc,char* argv[]){
    //first we will do thigns with only one thread.
    char* address;
    address=argv[1];
    int network_socket;
    network_socket=socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in server_address;
    server_address.sin_family=AF_INET;
    server_address.sin_port=htons(80);
    //now we will set the ip address of the required field.
    inet_aton(address,(struct in_addr*)&server_address.sin_addr.s_addr);
    int connection_status=connect(network_socket,(struct sockaddr*)&server_address,sizeof(server_address));
    if(connection_status){
            cout<<"error in the setting up the connection"<<endl;
    }
    /*
    now since we want to mimic the http we will first send
    a request and then we will accept the reply.

    main question?
    -> how to construct a request ??:)
    */
    char request1[]="GET /index.html HTTP/1.1\r\n\r\n";
    char response[4096];
    send(network_socket,request1,sizeof(request1),0);
    recv(network_socket,&response,sizeof(response),0);
    cout<<response<<endl;
    close(network_socket);
    return 0;
    }
    /*
      but i want something like this
      char request1[]="GET /index.ht";
      char request2[]="ml HTTP/1.1\r\n\r\n";
      send(network_socket,request2,sizeof(request2),0);
      send(network_socket,request2,sizeof(request2),0);

      */
       //but doing this will make server give 400 error
</code>```

答:
You can replace the following part of your code:

```<code>char request1[]="GET /index.html HTTP/1.1\r\n\r\n";
send(network_socket,request1,sizeof(request1),0);
</code>```

..for example with this way:

```<code>char request1a[]="GET /index.html";
char request1b[]=" HTTP/1.1\r\n\r\n";
send(network_socket,request1a,sizeof(request1a)-1,0);
send(network_socket,request1b,sizeof(request1b),0);
</code>```

Note the -1. It is needed, because you don't want to send extra '\0' to the server. Using strlen() could be alternative way.

TCP is stream oriented, so several sends won't add any message boundaries to the transmitted data. It may generate more IP-packets, but it won't break the functionality.

Remember to add error checking for those function calls.

Body:
This code is sending a GET request with the help of one send function
but I want to send the same GET request, but break it down and send it using two send function. The code is given below.

#include<iostream>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>//the new file.
#include<unistd.h>//for using the sleep function.
using namespace std;
int main(int argc,char* argv[]){
    //first we will do thigns with only one thread.
    char* address;
    address=argv[1];
    int network_socket;
    network_socket=socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in server_address;
    server_address.sin_family=AF_INET;
    server_address.sin_port=htons(80);
    //now we will set the ip address of the required field.
    inet_aton(address,(struct in_addr*)&server_address.sin_addr.s_addr);
    int connection_status=connect(network_socket,(struct sockaddr*)&server_address,sizeof(server_address));
    if(connection_status){
            cout<<"error in the setting up the connection"<<endl;
    }
    /*
    now since we want to mimic the http we will first send
    a request and then we will accept the reply.

    main question?
    -> how to construct a request ??:)
    */
    char request1[]="GET /index.html HTTP/1.1\r\n\r\n";
    char response[4096];
    send(network_socket,request1,sizeof(request1),0);
    recv(network_socket,&response,sizeof(response),0);
    cout<<response<<endl;
    close(network_socket);
    return 0;
    }
    /*
      but i want something like this
      char request1[]="GET /index.ht";
      char request2[]="ml HTTP/1.1\r\n\r\n";
      send(network_socket,request2,sizeof(request2),0);
      send(network_socket,request2,sizeof(request2),0);

      */
       //but doing this will make server give 400 error

Body:
You can replace the following part of your code:

char request1[]="GET /index.html HTTP/1.1\r\n\r\n";
send(network_socket,request1,sizeof(request1),0);

..for example with this way:

char request1a[]="GET /index.html";
char request1b[]=" HTTP/1.1\r\n\r\n";
send(network_socket,request1a,sizeof(request1a)-1,0);
send(network_socket,request1b,sizeof(request1b),0);

Note the -1. It is needed, because you don't want to send extra '\0' to the server. Using strlen() could be alternative way.

TCP is stream oriented, so several sends won't add any message boundaries to the transmitted data. It may generate more IP-packets, but it won't break the functionality.

Remember to add error checking for those function calls.


问:
Looping through XML nodes
I'm trying to loop through nodes and check the InnerText to determine if they contain a keyword. I had this working in WPF, but I'm new to using UWP and this is giving me a headache. Any suggestions would be appreciated.

I'm currently only getting HERE: 0 so I know it starts the foreach loop. There is about 100 nodes that should show up.

In WPF, I used this which worked fine:

```<code>foreach (XmlNode node in nodeList)
</code>```

Attempting this in UWP which isn't working:

```<code>foreach (IXmlNode node in nodeList)
</code>```

Here's the part of my code I'm having troubles with:

var doc = new XmlDocument();

StorageFile tempFile = await ApplicationData.Current.LocalFolder.GetFileAsync("weatheralerts.xml");
                    String datas = await FileIO.ReadTextAsync(tempFile);

doc.LoadXml(datas);

var nodeList = doc.SelectNodesNS("/ns:feed/ns:entry", "xmlns:ns='http://www.w3.org/2005/Atom'");

var x = 0;

foreach (IXmlNode node in nodeList)
{
   Data1.Text = "HERE: " + x;
   x++;
}
```

答:
If you use a System.Xml.XmlDocument instead of a Windows.Data.Xml.Dom.XmlDocument, you should be able to use the SelectNodes method with an XmlNamespaceManager:

```<code>var doc = new XmlDocument();

StorageFile tempFile = await ApplicationData.Current.LocalFolder.GetFileAsync("weatheralerts.xml");
String datas = await FileIO.ReadTextAsync(tempFile);

doc.LoadXml(datas);

var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ns", "http://www.w3.org/2005/Atom");
var nodeList = doc.SelectNodes("/ns:feed/ns:entry", nsmgr);

var x = 0;
foreach (XmlNode node in nodeList)
{
    Data1.Text = "HERE: " + x;
    x++;
}
</code>```

Title: Looping through XML nodes

Body:
I'm trying to loop through nodes and check the InnerText to determine if they contain a keyword. I had this working in WPF, but I'm new to using UWP and this is giving me a headache. Any suggestions would be appreciated.

I'm currently only getting HERE: 0 so I know it starts the foreach loop. There is about 100 nodes that should show up.

In WPF, I used this which worked fine:

foreach (XmlNode node in nodeList)

Attempting this in UWP which isn't working:

foreach (IXmlNode node in nodeList)

Here's the part of my code I'm having troubles with:

var doc = new XmlDocument();

StorageFile tempFile = await ApplicationData.Current.LocalFolder.GetFileAsync("weatheralerts.xml");
                    String datas = await FileIO.ReadTextAsync(tempFile);

doc.LoadXml(datas);

var nodeList = doc.SelectNodesNS("/ns:feed/ns:entry", "xmlns:ns='http://www.w3.org/2005/Atom'");

var x = 0;

foreach (IXmlNode node in nodeList)
{
   Data1.Text = "HERE: " + x;
   x++;
}

Body:
If you use a System.Xml.XmlDocument instead of a Windows.Data.Xml.Dom.XmlDocument, you should be able to use the SelectNodes method with an XmlNamespaceManager:

var doc = new XmlDocument();

StorageFile tempFile = await ApplicationData.Current.LocalFolder.GetFileAsync("weatheralerts.xml");
String datas = await FileIO.ReadTextAsync(tempFile);

doc.LoadXml(datas);

var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ns", "http://www.w3.org/2005/Atom");
var nodeList = doc.SelectNodes("/ns:feed/ns:entry", nsmgr);

var x = 0;
foreach (XmlNode node in nodeList)
{
    Data1.Text = "HERE: " + x;
    x++;
}


问:
Query array using whereHas
I want to filter products by category (manyToMany relationship). Basically the user select which categories to show. The categories I want to filter are in $request->keywords. This is what I tried:

```<code>  $products = Product::all();
  foreach($request->keywords as $keyword) {
    $products = Product::whereHas('categories', function($q) use ($keyword){
      $q->where('title', '=', $keyword);
    })->get();
  }

  return response()->json($products);
</code>```

The problem is that this does not get all the categories, only the products with the last category in the array. I guess at this point: $q->where('title', '=', $keyword);, $q does not keep the results of the last loop iteration but always deletes the last loop results.
I also tried the same thing with $q->orWhere('title', '=', $keyword);, but that actually doesn't give me any results.

Thanks for your help!

答:
You can simply use whereIn on the title field by passing in your keywords.

```<code>$products = Product::all();
$titles = [];
foreach($request->keywords as $keyword) {
    $titles[] = $keyword;
}
$products = Product::whereHas('categories', function($q) use ($keyword){
    $q->whereIn('title', $titles);
})->get();
</code>```

Title: Query array using whereHas

Body:
I want to filter products by category (manyToMany relationship). Basically the user select which categories to show. The categories I want to filter are in $request->keywords. This is what I tried:

  $products = Product::all();
  foreach($request->keywords as $keyword) {
    $products = Product::whereHas('categories', function($q) use ($keyword){
      $q->where('title', '=', $keyword);
    })->get();
  }

  return response()->json($products);

The problem is that this does not get all the categories, only the products with the last category in the array. I guess at this point: $q->where('title', '=', $keyword);, $q does not keep the results of the last loop iteration but always deletes the last loop results.
I also tried the same thing with $q->orWhere('title', '=', $keyword);, but that actually doesn't give me any results.

Thanks for your help!

Body:
You can simply use whereIn on the title field by passing in your keywords.

$products = Product::all();
$titles = [];
foreach($request->keywords as $keyword) {
    $titles[] = $keyword;
}
$products = Product::whereHas('categories', function($q) use ($keyword){
    $q->whereIn('title', $titles);
})->get();


问:
How to accumulate a column based on a condition
I am trying to go through a list and mark parents so I can join an flat list onto it self

```<code>ID  Type     Idx
200 EPIC      0
201 Feature   1
202 Feature   2
203 Feature   3
204 EPIC      4
205 Feature   5
206 Feature   6

Prefeered result
ID  Type     Idx   Parent
200 EPIC      0    200
201 Feature   1    200
202 Feature   2    200
203 Feature   3    200
204 EPIC      4    204
205 Feature   5    204
206 Feature   6    204
</code>```

I have tried making self-referencing conditional columns but thats not possible,

#"Added Custom" = Table.AddColumn(#"Added Index", "Parent", each if [Work Item Type] = "Epic" then [ID] else #"Added Custom"{[Index]-1}[ID]),

答:
Add custom column. Fill down.  Assuming data is in Table1 with 2 columns named ID and Type, then</p>

```<code>let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Added Custom" = Table.AddColumn(Source, "Parent", each if [Type]="EPIC" then [#"ID"] else null),
#"Filled Down" = Table.FillDown(#"Added Custom",{"Parent"})
in #"Filled Down"
</code>```

Body:
I am trying to go through a list and mark parents so I can join an flat list onto it self

ID  Type     Idx
200 EPIC      0
201 Feature   1
202 Feature   2
203 Feature   3
204 EPIC      4
205 Feature   5
206 Feature   6

Prefeered result
ID  Type     Idx   Parent
200 EPIC      0    200
201 Feature   1    200
202 Feature   2    200
203 Feature   3    200
204 EPIC      4    204
205 Feature   5    204
206 Feature   6    204

I have tried making self-referencing conditional columns but thats not possible,

#"Added Custom" = Table.AddColumn(#"Added Index", "Parent", each if [Work Item Type] = "Epic" then [ID] else #"Added Custom"{[Index]-1}[ID]),

Body:
Add custom column. Fill down.  Assuming data is in Table1 with 2 columns named ID and Type, then

let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Added Custom" = Table.AddColumn(Source, "Parent", each if [Type]="EPIC" then [#"ID"] else null),
#"Filled Down" = Table.FillDown(#"Added Custom",{"Parent"})
in #"Filled Down"


问:
Does image file type matter in terms of accuracy or speed when training/evaluating in machine learning?
I would like to know if the image file type matters at all in image classification using Keras, Tensorflow, or any other machine learning library. For example:

If I were to train using only JPG files, will the accuracy be significantly affected if I were to evaluate the model using only PNG files?

If so, will it be better to train using both JPG and PNG files so I can evaluate using both types?

Or does the image file type not matter at all?

答:
The file type does not matter.

During training (and inference for that matter) images are converted into a tensors (you can think of this just as a multi dimensional array) where each pixel is represented by a small group of numbers (or a single number for black and white images).

Machine learning is performed on these tensors rather than the image itself so the original file format really doesn't matter.


问:
How to make a OptionMenu maintain the same width?
I have a snippet which creates an OptionMenu widget.

```<code>...
options = ('White', 'Grey', 'Black', 'Red', 'Orange',
           'Yellow', 'Green', 'Blue', 'Cyan', 'Purple')
var = StringVar()
optionmenu = OptionMenu(par, var, *options)
optionmenu.grid(column=column, row=row)
...
</code>```

One problem I've encountered is every time a new option is selected, the width of the widget changes. I believe this is due to the text within the widget changing widths. How do I make the widget hold a consistent width?

答: When you use the grid command to place the widget in its parent, have the widget fill its cell (try sticky="ew")

ContentLicense: CC BY-SA 3.0

Body:
I have a snippet which creates an OptionMenu widget.

...
options = ('White', 'Grey', 'Black', 'Red', 'Orange',
           'Yellow', 'Green', 'Blue', 'Cyan', 'Purple')
var = StringVar()
optionmenu = OptionMenu(par, var, *options)
optionmenu.grid(column=column, row=row)
...

One problem I've encountered is every time a new option is selected, the width of the widget changes. I believe this is due to the text within the widget changing widths. How do I make the widget hold a consistent width?


问:
How can use Checkbox content type in block content type and how can i get values of checkboxes from block content type in Sulu-minimal?
How can use Checkbox content type in block content type and how can i get values of checkboxes from block content type in Sulu-minimal?

```<code><block name="block_basic_guarantees" default-type="text" minOccurs="0">
<meta>enter code here
<title lang="en">Garanties de base</title>
</meta>
<types>
<type name="Boolean">
<meta>
<title lang="en">Button</title>
<title lang="de">Button</title>
</meta>
<properties>
<property name="formule-lessentiel" type="checkbox">
<meta>
<title lang="en">Formule L’ESSENTIEL 1</title>
</meta>
<params>
<param name="type" value="checkbox"/>
</params>
</property>
<property name="formule-confort" type="checkbox">
<meta>
<title lang="en">Formule CONFORT</title>
</meta>
<params>
<param name="type" value="checkbox"/>
</params>
</property>
<property name="formule-letendue" type="checkbox">
<meta>
<title lang="en">Formule L’ETENDUE</title>
</meta>
<params>
<param name="type" value="checkbox"/>
</params>
</property>
<property name="formule-surmesure" type="checkbox">
<meta>
<title lang="en">Formule LE SUR-MESURE</title>
</meta>
<params>
<param name="type" value="checkbox"/>
</params>
</property>
</properties>
</type>
</types>
</block>
</code>```

I have tried this,

```<code>{% set basic_guarantees = content.block_basic_guarantees %}
{% for guarante in basic_guarantees %}
      {{ guarante.formule-lessentiel }}
      {{ guarante.formule-confort}}
      {{ guarante.formule-letendue }}
      {{ guarante.formule-surmesure }}
{% endfor %}
</code>```

I want result if checkbox is checked then, true or 1 otherwise if not checked then, false or 0.

答:
As danrot mention the problem here is the dash in your property name.
So if you write:

```<code>{{ guarante.formule-lessentiel }}
</code>```

Its the same as you would write:

```<code>{{ guarante.formule - lessentiel }}
</code>```

To access a variable with dash in it you can do:

```<code>{{ guarante['formule-lessentiel'] }}
</code>```

or

```<code>{{ attribute(guarante, 'formule-lessentiel') }}
</code>```

Which is very ugly so as danrot recommended use underlines instead.

Body:
How can use Checkbox content type in block content type and how can i get values of checkboxes from block content type in Sulu-minimal?

<block name="block_basic_guarantees" default-type="text" minOccurs="0">
<meta>enter code here
<title lang="en">Garanties de base</title>
</meta>
<types>
<type name="Boolean">
<meta>
<title lang="en">Button</title>
<title lang="de">Button</title>
</meta>
<properties>
<property name="formule-lessentiel" type="checkbox">
<meta>
<title lang="en">Formule L’ESSENTIEL 1</title>
</meta>
<params>
<param name="type" value="checkbox"/>
</params>
</property>
<property name="formule-confort" type="checkbox">
<meta>
<title lang="en">Formule CONFORT</title>
</meta>
<params>
<param name="type" value="checkbox"/>
</params>
</property>
<property name="formule-letendue" type="checkbox">
<meta>
<title lang="en">Formule L’ETENDUE</title>
</meta>
<params>
<param name="type" value="checkbox"/>
</params>
</property>
<property name="formule-surmesure" type="checkbox">
<meta>
<title lang="en">Formule LE SUR-MESURE</title>
</meta>
<params>
<param name="type" value="checkbox"/>
</params>
</property>
</properties>
</type>
</types>
</block>

I have tried this,

{% set basic_guarantees = content.block_basic_guarantees %}
{% for guarante in basic_guarantees %}
      {{ guarante.formule-lessentiel }}
      {{ guarante.formule-confort}}
      {{ guarante.formule-letendue }}
      {{ guarante.formule-surmesure }}
{% endfor %}

I want result if checkbox is checked then, true or 1 otherwise if not checked then, false or 0.

Body:
As danrot mention the problem here is the dash in your property name.
So if you write:

{{ guarante.formule-lessentiel }}

Its the same as you would write:

{{ guarante.formule - lessentiel }}

To access a variable with dash in it you can do:

{{ guarante['formule-lessentiel'] }}

or

{{ attribute(guarante, 'formule-lessentiel') }}

Which is very ugly so as danrot recommended use underlines instead.


问:
using python: How can I convert given UT time to LST time Such that the function automatically increments day after 24 Hr check
I want to convert given Universal Time (UT)  to  Local Time (LT) . Such that the function automatically increments day after 24 Hr check. I tried various codes. I successfully converted time but unable to increment it by certain duration in a loop.</p>

答:
I am new to python coding.I have tried below code to convert given Universal         Time  (UT) to Local Time (LT) that is working properly. But I want to increment date and  time by a specified duration float (ex.1.036 seconds) in a loop from start LT time to end LT  time. Such that day gets incremented after 24 Hrs.

```<code>>>>startutc= '2019-03-25 14:26:18' # Start UTC in String format
>>>endutc= '2019-03-26 14:26:18'   # End UTC in String format
>>>utc_fmt = '%Y-%m-%d %H:%M:%S'
>>>local_fmt = '%Y-%m-%d %H:%M:%S'
>>>local_string1 = utc_str_to_local_str(startutc, utc_fmt, local_fmt)
>>>local_string2 = utc_str_to_local_str(endutc, utc_fmt, local_fmt)
>>>ls1=datetime.strptime(local_string1, '%Y-%m-%d %H:%M:%S')
>>>ls2=datetime.strptime(local_string2, '%Y-%m-%d %H:%M:%S')
>>>t2= np.array([ls1+timedelta(seconds=i) for i in range(0,scans)])
>>>t = date2num(t2)

Using function I found somewhere on stack overflow:
>>>def utc_str_to_local_str(utc_str: str, utc_format: str, local_format: str):
"""
>>>:param utc_str: UTC time string
>>>:param utc_format: format of UTC time string
>>>:param local_format: format of local time string
>>>:return: local time string
>>>"""
>>>temp1 = datetime.strptime(utc_str, utc_format)
>>>temp2 = temp1.replace(tzinfo=timezone.utc)
>>>local_time = temp2.astimezone()
>>>return local_time.strftime(local_format)
</code>```

Body:
I am new to python coding.I have tried below code to convert given Universal         Time  (UT) to Local Time (LT) that is working properly. But I want to increment date and  time by a specified duration float (ex.1.036 seconds) in a loop from start LT time to end LT  time. Such that day gets incremented after 24 Hrs.

>>>startutc= '2019-03-25 14:26:18' # Start UTC in String format
>>>endutc= '2019-03-26 14:26:18'   # End UTC in String format
>>>utc_fmt = '%Y-%m-%d %H:%M:%S'
>>>local_fmt = '%Y-%m-%d %H:%M:%S'
>>>local_string1 = utc_str_to_local_str(startutc, utc_fmt, local_fmt)
>>>local_string2 = utc_str_to_local_str(endutc, utc_fmt, local_fmt)
>>>ls1=datetime.strptime(local_string1, '%Y-%m-%d %H:%M:%S')
>>>ls2=datetime.strptime(local_string2, '%Y-%m-%d %H:%M:%S')
>>>t2= np.array([ls1+timedelta(seconds=i) for i in range(0,scans)])
>>>t = date2num(t2)

Using function I found somewhere on stack overflow:
>>>def utc_str_to_local_str(utc_str: str, utc_format: str, local_format: str):
"""
>>>:param utc_str: UTC time string
>>>:param utc_format: format of UTC time string
>>>:param local_format: format of local time string
>>>:return: local time string
>>>"""
>>>temp1 = datetime.strptime(utc_str, utc_format)
>>>temp2 = temp1.replace(tzinfo=timezone.utc)
>>>local_time = temp2.astimezone()
>>>return local_time.strftime(local_format)


问:
how to return the date as dd-FullMonth-yyyy
I have a date field in SharePoint list as mm/dd/yyyy

I want to list it as dd MonthName yyyy

When I use the below function, it return the date with one month added,
for example, if the field date is 1/1/2019 it will be displayed as 1 February 2019 (instead of January, it displays February)

I tried to subtract 1 from monthindex but it didn't work.

```<code>function formatDate(thedate) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];
  var diffrentformat = thedate.split(" ")[0];
  var divideddate = diffrentformat.split("-");
  var d = new Date(divideddate[0], divideddate[1], divideddate[2]);
  //var d = new Date(thedate.split[]);
  var day = d.getDate();
  var monthIndex = d.getMonth();
  var year = d.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}
</code>```

I expect the output to be dd MonthName yyyy, but I'm getting dd nextMonthName yyyy

答:
You say that your date format is mm/dd/yyyy but your code looks like it's yyyy-mm-dd.

When you create a Date, you're not subtracting 1 from the calendar month:

```<code>var d = new Date(divideddate[0], divideddate[1], divideddate[2]);
</code>```

should be:

```<code>var d = new Date(divideddate[0], divideddate[1] - 1, divideddate[2]);
</code>```

However, you don't need to create a Date, it's simpler and less code to just use the values in the string:

// Reformat mm/dd/yyyy to d mmmm yyyy
function formatDate(thedate) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];
  var b = thedate.split(/\D/);
  return +b[1] + ' ' + monthNames[b[0]-1] + ' ' + b[2];
}

console.log(formatDate('5/28/2019'))```

Note that the month array sets January as index 0, February as index 2, etc. so you can either subtract 1 from the month number in the string, or elide the first element in the array. I've done the former.

Body:
I have a date field in SharePoint list as mm/dd/yyyy

I want to list it as dd MonthName yyyy

When I use the below function, it return the date with one month added,
for example, if the field date is 1/1/2019 it will be displayed as 1 February 2019 (instead of January, it displays February)

I tried to subtract 1 from monthindex but it didn't work.

function formatDate(thedate) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];
  var diffrentformat = thedate.split(" ")[0];
  var divideddate = diffrentformat.split("-");
  var d = new Date(divideddate[0], divideddate[1], divideddate[2]);
  //var d = new Date(thedate.split[]);
  var day = d.getDate();
  var monthIndex = d.getMonth();
  var year = d.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

I expect the output to be dd MonthName yyyy, but I'm getting dd nextMonthName yyyy

Body:
You say that your date format is mm/dd/yyyy but your code looks like it's yyyy-mm-dd.

When you create a Date, you're not subtracting 1 from the calendar month:

var d = new Date(divideddate[0], divideddate[1], divideddate[2]);

should be:

var d = new Date(divideddate[0], divideddate[1] - 1, divideddate[2]);

However, you don't need to create a Date, it's simpler and less code to just use the values in the string:

// Reformat mm/dd/yyyy to d mmmm yyyy
function formatDate(thedate) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];
  var b = thedate.split(/\D/);
  return +b[1] + ' ' + monthNames[b[0]-1] + ' ' + b[2];
}

console.log(formatDate('5/28/2019'))

Note that the month array sets January as index 0, February as index 2, etc. so you can either subtract 1 from the month number in the string, or elide the first element in the array. I've done the former.


问:
I want to understand the following code lines defined in the function
I am a beginner in python and machine learning. while doing a project from the book "hands-on ML with sci-kit learn and TF" I came across this way of creating test-set using hashlib.
Can you please help me understand what this logic of the return statement, step by step-</p>

```<code>def test_set_check(identifier, test_ratio, hash):
    return hash(np.int64(identifier)).digest()[-1]<256 * test_ratio
</code>```

答:
assuming hash is something from hashlib:

cast identifier to a (numpy) 64bit integer

hash the cast identifier

get the value of the last byte from the hash

compare that value to (256 * test_ratio)

return the result of The comparison

Body:
I am a beginner in python and machine learning. while doing a project from the book "hands-on ML with sci-kit learn and TF" I came across this way of creating test-set using hashlib.
Can you please help me understand what this logic of the return statement, step by step-

def test_set_check(identifier, test_ratio, hash):
    return hash(np.int64(identifier)).digest()[-1]<256 * test_ratio


问:
How to parse XML tag by Javax.xml library
I'm trying to parse a simple XML file, like this:

```<code><customer id="100">
    <age value=" 29"/>
    <name value="Bob"/>
</customer>
</code>```

I used the library of JAX in this way:

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    @XmlAttribute(name = "id")
    String id;
    @XmlAttribute(name = "value")
    String value;
    String name;
    String age;

    public String getName() {
        return name;
    }

    @XmlElement(name = "value")
    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    @XmlElement(name = "value")
    public void setAge(String age) {
        this.age = age;
    }

    public String getId() {
        return id;
    }

    @XmlElement(name = "id")
    public void setId(String id) {
        this.id = id;
    }
}
</code>```

There is an IllegalAnnotationExceptions.
I was expired by this link: here but without success.

答:
Since "name" and "age" values are in fact attributes of child nodes, you should extract it into separate class, kinda:</p>

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public static class Customer {

    @XmlAttribute
    String id;

    @XmlElement
    NameAgeValue name;

    @XmlElement
    NameAgeValue age;

    public String getId() {
        return id;
    }

    public String getAge() {
        return (age == null) ? null : age.value;
    }

    public String getName() {
        return (name == null) ? null : name.value;
    }
}

@XmlType
public static class NameAgeValue {

    @XmlAttribute
    String value;
}
</code>```

Body:
I'm trying to parse a simple XML file, like this:

<customer id="100">
    <age value=" 29"/>
    <name value="Bob"/>
</customer>

I used the library of JAX in this way:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    @XmlAttribute(name = "id")
    String id;
    @XmlAttribute(name = "value")
    String value;
    String name;
    String age;

    public String getName() {
        return name;
    }

    @XmlElement(name = "value")
    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    @XmlElement(name = "value")
    public void setAge(String age) {
        this.age = age;
    }

    public String getId() {
        return id;
    }

    @XmlElement(name = "id")
    public void setId(String id) {
        this.id = id;
    }
}

There is an IllegalAnnotationExceptions.
I was expired by this link: here but without success.

Body:
Since "name" and "age" values are in fact attributes of child nodes, you should extract it into separate class, kinda:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public static class Customer {

    @XmlAttribute
    String id;

    @XmlElement
    NameAgeValue name;

    @XmlElement
    NameAgeValue age;

    public String getId() {
        return id;
    }

    public String getAge() {
        return (age == null) ? null : age.value;
    }

    public String getName() {
        return (name == null) ? null : name.value;
    }
}

@XmlType
public static class NameAgeValue {

    @XmlAttribute
    String value;
}


问:
GORM (Hibernate) Interceptor to run certain SQL before Hibernate runs it in the db in a Grails application?
I have a grails application in which I am using GORM. This works great. However I have a requirement where, before any SQL is called in the database, it has to run a certain stored procedure. So, is there a way I can do something that will trigger my method that kicks off a stored procedure before Hibernate runs the SQL for select, insert, update, delete etc.
Your response will be greatly appreciated.

(P.S.- The reason I have to run certain stored procedure is to change Oracle Workspace)

答:
There might be several options.

You could use a dataSource wrapper that extends org.springframework.jdbc.datasource.DelegatingDataSource and runs the statement whenever getConnection is called.
I guess it's ok to call the statement (stored proc) only once per transaction, so DelegatingDataSource is probably the most approriate solution.

You could also use http://www.grails.org/plugin/jdbc-pool plugin (wraps Tomcat JDBC Pool) and try to hook to the datasource pool implementation.  Tomcat JDBC Pool supports interceptors.

It's also possible to modify the SQL sent by GORM/Hibernate using a Hibernate interceptor, if that helps: Is it possible to map a table name for a domain object dynamically in grails? .


问:
How to re enable submit button after data-disable-with in rails
Using data-disable-with attribute in remote:true form

```<code><%= f.submit "Verify",'data-disable-with' => 'Verifying...' %>
</code>```

After submitting button disabled and text changes to "Verifying..." but issue is that let say in case of error, errors show in form and submit button renable but the text not change . It stills remain "Verifying"

How can I show previous text in case of error?

答:
Try this

```<code><%= f.submit "Verify",'data-disable-with' => 'Verifying...', id: 'submit-button' %>
</code>```

and in js

```<code>$(document).on('ajax:error', 'form-name', function (xhr, jqxhr) {
    $("#submit-button").removeAttr('data-disable-with');
 });
</code>```

replace the form-name with your form id or class

Body:
Using data-disable-with attribute in remote:true form

<%= f.submit "Verify",'data-disable-with' => 'Verifying...' %>

After submitting button disabled and text changes to "Verifying..." but issue is that let say in case of error, errors show in form and submit button renable but the text not change . It stills remain "Verifying"

How can I show previous text in case of error?

Body:
Try this

<%= f.submit "Verify",'data-disable-with' => 'Verifying...', id: 'submit-button' %>

and in js

$(document).on('ajax:error', 'form-name', function (xhr, jqxhr) {
    $("#submit-button").removeAttr('data-disable-with');
 });

replace the form-name with your form id or class


问:
How to query through nested Laravel relationships the eloquent ORM way
I have a relationship that is almost 5 levels deep.

In my blades I use this all time without a problem. For example:

```<code>{{ $user->team->department->region->company->name ?? ''}}
</code>```

How would I go about querying all users that belong to a company?

```<code>$users = User::where($user->team->department->region->company->id, '=', 1)->get(); ?????
</code>```

Company Relationships:

```<code>class Company extends Model
{
    public function region() {

        return $this->hasMany('App\Region', 'company_id', 'id');

    }
}
</code>```

Region Relationships:

```<code>class Region extends Model
{
    public function company() {

        return $this->hasOne('App\Company', 'id', 'company_id');

    }
    public function department() {

        return $this->hasMany('App\Department', 'region_id', 'id');

    }
}
</code>```

Department Relationships:

```<code>class Department extends Model
{
    public function region() {

        return $this->hasOne('App\Region', 'id', 'region_id');

    }

    public function team() {

        return $this->hasMany('App\Team', 'department_id', 'id');

    }

}
</code>```

Team Relationships:

```<code>class Team extends Model
{

    public function department() {

        return $this->hasOne('App\Department', 'id', 'department_id');

    }

    public function user() {

        return $this->hasMany('App\User', 'team_id', 'id');

    }

}
</code>```

User Relationships:

```<code>class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function team() {

        return $this->hasOne('App\Team', 'id', 'team_id');

    }
}
</code>```

I know there must be some easy way to query through nested relationships that Laravel provides a way for or a some facility for, but I have yet to find any decent examples from Googling around.

答:
You can use this package for your need.

https://github.com/staudenmeir/eloquent-has-many-deep

read the instructions, depth of the relationship is not limited.

Body:
I have a relationship that is almost 5 levels deep.

In my blades I use this all time without a problem. For example:

{{ $user->team->department->region->company->name ?? ''}}

How would I go about querying all users that belong to a company?

$users = User::where($user->team->department->region->company->id, '=', 1)->get(); ?????

Company Relationships:

class Company extends Model
{
    public function region() {

        return $this->hasMany('App\Region', 'company_id', 'id');

    }
}

Region Relationships:

class Region extends Model
{
    public function company() {

        return $this->hasOne('App\Company', 'id', 'company_id');

    }
    public function department() {

        return $this->hasMany('App\Department', 'region_id', 'id');

    }
}

Department Relationships:

class Department extends Model
{
    public function region() {

        return $this->hasOne('App\Region', 'id', 'region_id');

    }

    public function team() {

        return $this->hasMany('App\Team', 'department_id', 'id');

    }

}

Team Relationships:

class Team extends Model
{

    public function department() {

        return $this->hasOne('App\Department', 'id', 'department_id');

    }

    public function user() {

        return $this->hasMany('App\User', 'team_id', 'id');

    }

}

User Relationships:

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function team() {

        return $this->hasOne('App\Team', 'id', 'team_id');

    }
}

I know there must be some easy way to query through nested relationships that Laravel provides a way for or a some facility for, but I have yet to find any decent examples from Googling around.


问:
Automatic SNI resolution between CDN and origins is not currently supported for Azure CDN from Verizon
When activating SNI, we get 502 from azure CDN when using Azure Standard Verizon</p>

答: SNI is not enabled by default but can be applied to the Verizon CDN endpoint manually by raising a support ticket through the Azure portal. HTH</p>


问:
How to debug on Opera Mini?
How do I debug a website that looks weird on Opera Mini? The site is working fine on any other browser.</p>

答:
It is possible to view the original html source of the page that is represented in Opera Mini to give you some clues:

View page source

  It is possible to get a dump of the current page source by entering server:source into Opera Mini's address bar. This shows the current DOM tree from the Opera Mini server. Since reading the source from a cell phone display or even an enlarged microemulator isn't very pleasant, there is an even better way of obtaining a page's source code — posting it to a webserver by entering server:source?post=http://your.server.com/script into Opera Mini's address bar, where the script file that is passed the post data will handle the request, e.g. by storing the source in a database, or saving it to a text file. The posted data includes the fields url, host and html.

Taken from this great article on dev.opera.com about Opera Mini development, specs and debugging.

Title: How to debug on Opera Mini?


问:
Overflowing a child element outside the parent element
I have a simple card which contains an image .menu-card__header-image. On hover, I wish to lift that image up by some pixels. However, when I do lift the image, the image is not visible outside the parent container .menu-card.

.menu-card {
  font-family: sans-serif;
  color: red;
  margin-left: auto;
  margin-right: auto;
  width: 80%;
  overflow: hidden;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  padding-bottom: 20px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  overflow: visible;
}
.menu-card__header {
  background-color: orange;
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 6vw), 0 100%);
  max-height: 300px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  overflow: hidden;
  text-align: center;
}
.menu-card__header-image {
  margin-left: auto;
  margin-right: auto;
  z-index: 33;
  position: relative;
  bottom: 0px;
  transition: bottom 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  bottom: 80px;
}
.menu-card:first-child {
  margin-bottom: 50px;
}
.menu-card:last-child {
  margin-top: 50px;
}
.menu-card__title {
  padding: 0 12px;
}
.menu-card__description {
  padding: 0 12px;
}

.menu-card__title {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-card">
  <div class="menu-card__header">
    <img src="http://lorempixel.com/250/635" alt="" class="menu-card__header-image" height="400px" />
  </div>
  <h2 class="menu-card__title">
    Lorem Ipsum
  </h2>
  <p class="menu-card__description">
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex
  </p>
</div></code>```

Here is the relevant pen:  https://codepen.io/saifalfalah/pen/gJKNBE?editors=1100

How do I make the image be visible outside the parent container on hover without changing the markup (preferably)?

答:
I would do this differently an instead of clip-path I will consider a background on the title section to create the angled shape and yout image will simply be hidden behind. Then you do a simply transform animation and you won't have any issue with overflow.

I replaced the 6vw with 40px in the below example:

.menu-card {
  font-family: sans-serif;
  color: red;
  margin:40px auto;
  width: 80%;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-radius:0 0 5px 5px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}
.menu-card__header {
  background-color: orange;
  max-height: 300px;
  border-radius: 5px 5px 0 0;
  text-align: center;
}
.menu-card__header-image {
  transition: transform 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  transform:translateY(-80px);
}
.menu-card__title {
  margin:0;
  padding:15px;
  padding-top:40px; /* space for the triangle shape */
  margin-top:-40px; /* to create the overlap with the top section (same as padding)*/
  background:
    /* top background will take 40px and draw a triangular shape*/
    linear-gradient(to bottom right,transparent 49%,#fff 50%)top/100% 40px,
    /* bottom background will take the remaining space as a rectangular shape*/
    linear-gradient(#fff,#fff) bottom/100% calc(100% - 40px);
  background-repeat:no-repeat;
  position:relative;
  text-align: center;
}
.menu-card__description {
  margin:0;
  padding: 0 12px 20px;
  background:#fff;
  position:relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-card">
  <div class="menu-card__header">
    <img src="https://picsum.photos/id/0/250/635" alt="" class="menu-card__header-image" height="400px" />
  </div>
  <h2 class="menu-card__title">
    Lorem Ipsum
  </h2>
  <p class="menu-card__description">
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex
  </p>
</div></code>```

Body:
I have a simple card which contains an image .menu-card__header-image. On hover, I wish to lift that image up by some pixels. However, when I do lift the image, the image is not visible outside the parent container .menu-card.

.menu-card {
  font-family: sans-serif;
  color: red;
  margin-left: auto;
  margin-right: auto;
  width: 80%;
  overflow: hidden;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  padding-bottom: 20px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  overflow: visible;
}
.menu-card__header {
  background-color: orange;
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 6vw), 0 100%);
  max-height: 300px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  overflow: hidden;
  text-align: center;
}
.menu-card__header-image {
  margin-left: auto;
  margin-right: auto;
  z-index: 33;
  position: relative;
  bottom: 0px;
  transition: bottom 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  bottom: 80px;
}
.menu-card:first-child {
  margin-bottom: 50px;
}
.menu-card:last-child {
  margin-top: 50px;
}
.menu-card__title {
  padding: 0 12px;
}
.menu-card__description {
  padding: 0 12px;
}

.menu-card__title {
  text-align: center;
}

    Lorem Ipsum

    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex

Here is the relevant pen:  https://codepen.io/saifalfalah/pen/gJKNBE?editors=1100

How do I make the image be visible outside the parent container on hover without changing the markup (preferably)?

Body:
I would do this differently an instead of clip-path I will consider a background on the title section to create the angled shape and yout image will simply be hidden behind. Then you do a simply transform animation and you won't have any issue with overflow.

I replaced the 6vw with 40px in the below example:

.menu-card {
  font-family: sans-serif;
  color: red;
  margin:40px auto;
  width: 80%;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-radius:0 0 5px 5px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}
.menu-card__header {
  background-color: orange;
  max-height: 300px;
  border-radius: 5px 5px 0 0;
  text-align: center;
}
.menu-card__header-image {
  transition: transform 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  transform:translateY(-80px);
}
.menu-card__title {
  margin:0;
  padding:15px;
  padding-top:40px; /* space for the triangle shape */
  margin-top:-40px; /* to create the overlap with the top section (same as padding)*/
  background:
    /* top background will take 40px and draw a triangular shape*/
    linear-gradient(to bottom right,transparent 49%,#fff 50%)top/100% 40px,
    /* bottom background will take the remaining space as a rectangular shape*/
    linear-gradient(#fff,#fff) bottom/100% calc(100% - 40px);
  background-repeat:no-repeat;
  position:relative;
  text-align: center;
}
.menu-card__description {
  margin:0;
  padding: 0 12px 20px;
  background:#fff;
  position:relative;
}

<div class="menu-card">
  <div class="menu-card__header">
    <img src="https://picsum.photos/id/0/250/635" alt="" class="menu-card__header-image" height="400px" />
  </div>
  <h2 class="menu-card__title">
    Lorem Ipsum
  </h2>
  <p class="menu-card__description">
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex
  </p>
</div>


问:
How to create custom background for UITableView section?
I'm trying to create a custom background for my tableview section. The look I'm going for is this:

How do I customize the tableview section background/layer please, rather than just the individual cells?

Edit: Just to clarify - I'm talking about the white background under 'Latest Transactions'. So the top of the section is rounded (as is bottom) but all the rows are rectangular.

答:
Have a look at func headerView(forSection section: Int) -> UITableViewHeaderFooterView?
headerView(forSection:) - UITableView | Apple Developer


问:
Promise.all getting Unhandled rejection
I'm using Promise.all and catch error but still getting Unhandled rejection

```<code>const Promise = require('bluebird');

function sleep(milis) {
return new Promise(function(resolve, reject) {
    if (milis == 1000) {
        console.log('Rejecting millis', milis)
        setTimeout(() => {
            reject('Got error')
        }, milis);

    } else {
        console.log('Processing millis', milis)
        setTimeout(() => {
            resolve(milis);
        }, milis);

    }
});
}

function test() {

try {
    let lists = [2000, 1000, 3000]
    Promise.all(
            lists.map(record => {
                try {
                    sleep(record)
                } catch (err) {
                    console.log('Error inside catch block1', err)
                    throw err
                }
            })
        ).then(data => {
            console.log('Resolved', data)
        })
        .catch(err => {
            console.log('Error inside catch block2', err)
            throw err

        });

} catch (err) {
    console.log('Error inside catch block3', err)
}
}

test();
</code>```

After using catch block why still getting Unhandled rejection. Any help appreciated. But if I use async await not getting Unhandled rejection.

答:
There are multiple issues with your code, let's step through them one by one:

Firstly

When you're mapping your lists array you never return the promise you get from your sleep() function. This means that what you provide to Promise.all() is an array filled with undefined. Promise.all() treats values that are not promises as a resolved promise, so your Promise.all() will always resolve regardless of whether the promises created by sleep() resolve or reject. This also means that nothing catches a rejected promise from sleep() and this is why your script is currently getting unhandled promise rejections.

You fix this by returning the promise properly with return sleep(record). But this won't be enough to get rid of all unhandled promise rejections so let's move on...

Secondly

You have wrapped your calls to sleep() in a try-catch block. Unless you're using async-await, a try-catch block will not catch rejected promises. In this case it will only catch errors thrown when the promise is created. That's all fine if that was your intent but if your intent was to catch the rejected promises it's not going to work.

Thirdly

You have attached a catch() handler to your Promise.all(). Unlike the aforementioned try-catch, that actually takes care of any rejected promises. However, you re-throw the error in this handler which means the promise chain will still be rejected. You have wrapped your Promise.all() in another try-catch block but as mentioned, this doesn't catch rejected promises so the still rejected promise will end up being unhandled.

In this case, you should simply not re-throw the error in your last catch() handler as I can't see any point in doing so here. If you for whatever reason need to re-throw it you need to add another catch() handler later in the chain.

Title: Promise.all getting Unhandled rejection

Body:
I'm using Promise.all and catch error but still getting Unhandled rejection

const Promise = require('bluebird');

function sleep(milis) {
return new Promise(function(resolve, reject) {
    if (milis == 1000) {
        console.log('Rejecting millis', milis)
        setTimeout(() => {
            reject('Got error')
        }, milis);

    } else {
        console.log('Processing millis', milis)
        setTimeout(() => {
            resolve(milis);
        }, milis);

    }
});
}

function test() {

try {
    let lists = [2000, 1000, 3000]
    Promise.all(
            lists.map(record => {
                try {
                    sleep(record)
                } catch (err) {
                    console.log('Error inside catch block1', err)
                    throw err
                }
            })
        ).then(data => {
            console.log('Resolved', data)
        })
        .catch(err => {
            console.log('Error inside catch block2', err)
            throw err

        });

} catch (err) {
    console.log('Error inside catch block3', err)
}
}

test();

After using catch block why still getting Unhandled rejection. Any help appreciated. But if I use async await not getting Unhandled rejection.


问:
conflicting focus on two fields inside the ajax success function used for validation
I have used ajax for validation on field blur (focus if invalid), but it conflicts with the ajax validation on next field

1.Tried setting a global variable and checking it in the next field validation.
2. Stored $(this) in variable and also called event on bind method.
3. Tried disabling other fields when focus is on current field but does not work on certain conditions.

```<code>$('input[name="ledgercode"]')
.bind(
'blur',
   '#ledgercode',
function(e) {
if ($('#dialog1').dialog('isOpen')) {
    e.preventDefault();
} else {
    $this = $(this);
var ledgercd = $(this).val();
if (ledgercd == "") {
   document.getElementById("msgbox1").innerHTML = "Code must be entered";

  $(this).focus();
  } else {
  $.ajax({
type : 'POST',
url : 'GL_Servlet?method=ledger_validation',
    dataType : 'json',
    data : {
    "json" : [ ledgercd,company ]
},
   success : function(data) {
    var ldgstat = (data.ldgstat);
    if (ldgstat == false) {
$this.focus(); //consistent focus if value invalid
    document.getElementById("msgbox1").innerHTML = "Invalid Code";
} else if (data.ldgstat == true) {
$('#txt_ldg_name').val(data.ldg_desc);
$this.closest("tr")
.find('input[name="ldg_desc"]').val(data.ldg_desc);
    document.getElementById("msgbox1").innerHTML = "";
}
    }
   });
}
}
   });
</code>```

If value on field is invalid the field should remain focused and not leave field till right value is entered.

答: By Setting (async : false,) in ajax issue is resolved.</p>

Body:
I have used ajax for validation on field blur (focus if invalid), but it conflicts with the ajax validation on next field

1.Tried setting a global variable and checking it in the next field validation.
2. Stored $(this) in variable and also called event on bind method.
3. Tried disabling other fields when focus is on current field but does not work on certain conditions.

$('input[name="ledgercode"]')
.bind(
'blur',
   '#ledgercode',
function(e) {
if ($('#dialog1').dialog('isOpen')) {
    e.preventDefault();
} else {
    $this = $(this);
var ledgercd = $(this).val();
if (ledgercd == "") {
   document.getElementById("msgbox1").innerHTML = "Code must be entered";

  $(this).focus();
  } else {
  $.ajax({
type : 'POST',
url : 'GL_Servlet?method=ledger_validation',
    dataType : 'json',
    data : {
    "json" : [ ledgercd,company ]
},
   success : function(data) {
    var ldgstat = (data.ldgstat);
    if (ldgstat == false) {
$this.focus(); //consistent focus if value invalid
    document.getElementById("msgbox1").innerHTML = "Invalid Code";
} else if (data.ldgstat == true) {
$('#txt_ldg_name').val(data.ldg_desc);
$this.closest("tr")
.find('input[name="ldg_desc"]').val(data.ldg_desc);
    document.getElementById("msgbox1").innerHTML = "";
}
    }
   });
}
}
   });

If value on field is invalid the field should remain focused and not leave field till right value is entered.


问:
What's the fastest way to test the validity of a large number of well-formed URLs
My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs

I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).

Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.

Can it be done?

答:
Using httplib and urlparse:</p>

```<code>def checkURL(url):
    import httplib
    import urlparse

    protocol, host, path, query, fragment = urlparse.urlsplit(url)

    if protocol == "http":
        conntype = httplib.HTTPConnection
    elif protocol == "https":
        conntype = httplib.HTTPSConnection
    else:
        raise ValueError("unsupported protocol: " + protocol)

    conn = conntype(host)
    conn.request("HEAD", path)
    resp = conn.getresponse()
    conn.close()

    if resp.status < 400:
        return true

    return false
</code>```

OwnerDisplayName: Salim Fadhley

Body:
Using httplib and urlparse:

def checkURL(url):
    import httplib
    import urlparse

    protocol, host, path, query, fragment = urlparse.urlsplit(url)

    if protocol == "http":
        conntype = httplib.HTTPConnection
    elif protocol == "https":
        conntype = httplib.HTTPSConnection
    else:
        raise ValueError("unsupported protocol: " + protocol)

    conn = conntype(host)
    conn.request("HEAD", path)
    resp = conn.getresponse()
    conn.close()

    if resp.status < 400:
        return true

    return false

OwnerDisplayName: Ben Blank