问:
Rails 6 and neo4j.rb?
Is there development happening for Rails 6 in Neo4j.rb? In a new rails 6(rc1) project, if I create a couple scaffolds then run 'rake neo4j:migrate:all' I get an error that when I follow it quickly rabbitholes much deeper into the internals of ActiveModel than I can parse:</p>

```<code>NoMethodError: undefined method `force_change' for #<ActiveModel::NullMutationTracker:0x00007fa1aadd8788>
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/activemodel-6.0.0.rc1/lib/active_model/dirty.rb:268:in `attribute_will_change!'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/activemodel-6.0.0.rc1/lib/active_model/attribute_methods.rb:383:in `migration_id_will_change!'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/property.rb:213:in `block in attribute!'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/property.rb:51:in `block in send_props'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/property.rb:51:in `each'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/property.rb:51:in `send_props'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/property.rb:32:in `initialize'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/active_node/property.rb:7:in `initialize'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/callbacks.rb:19:in `block in initialize'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/activesupport-6.0.0.rc1/lib/active_support/callbacks.rb:101:in `run_callbacks'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/callbacks.rb:19:in `initialize'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/active_node.rb:53:in `initialize'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/active_node/persistence.rb:116:in `new'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/active_node/persistence.rb:116:in `create!'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/base.rb:31:in `migrate_up'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/base.rb:16:in `block in migrate'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/2.6.0/benchmark.rb:308:in `realtime'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/base.rb:15:in `migrate'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:127:in `block in migrate'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:133:in `migration_message'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:125:in `migrate'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:26:in `block in all'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:24:in `each'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:24:in `all'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/tasks/migration.rake:116:in `block (3 levels) in <main>'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:273:in `block in execute'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:273:in `each'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:273:in `execute'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:214:in `block in invoke_with_call_chain'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/2.6.0/monitor.rb:230:in `mon_synchronize'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:194:in `invoke_with_call_chain'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:183:in `invoke'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:160:in `invoke_task'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:116:in `block (2 levels) in top_level'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:116:in `each'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:116:in `block in top_level'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:125:in `run_with_threads'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:110:in `top_level'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:83:in `block in run'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:186:in `standard_exception_handling'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:80:in `run'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/exe/rake:27:in `<top (required)>'
/Users/metkat/.rvm/gems/ruby-2.6.0/bin/rake:23:in `load'
/Users/metkat/.rvm/gems/ruby-2.6.0/bin/rake:23:in `<main>'
/Users/metkat/.rvm/gems/ruby-2.6.0/bin/ruby_executable_hooks:24:in `eval'
/Users/metkat/.rvm/gems/ruby-2.6.0/bin/ruby_executable_hooks:24:in `<main>'
Tasks: TOP => neo4j:migrate:all
</code>```

答:
It looks like it's related to this PR which landed in RC1, I'm running into the same issue. I pinged that thread to see if it was intentional. In the meantime, try rolling back to the last beta or monkey patching ActiveModel::NullMutationTracker (which is what I did and confirmed it fixed the issue) by adding the following methods back into it:

```<code>  def forget_change(attr_name)
  end

  def original_value(attr_name)
  end

  def force_change(attr_name)
  end
</code>```

Title: Rails 6 and neo4j.rb?

Body:
Is there development happening for Rails 6 in Neo4j.rb? In a new rails 6(rc1) project, if I create a couple scaffolds then run 'rake neo4j:migrate:all' I get an error that when I follow it quickly rabbitholes much deeper into the internals of ActiveModel than I can parse:

NoMethodError: undefined method `force_change' for #<ActiveModel::NullMutationTracker:0x00007fa1aadd8788>
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/activemodel-6.0.0.rc1/lib/active_model/dirty.rb:268:in `attribute_will_change!'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/activemodel-6.0.0.rc1/lib/active_model/attribute_methods.rb:383:in `migration_id_will_change!'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/property.rb:213:in `block in attribute!'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/property.rb:51:in `block in send_props'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/property.rb:51:in `each'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/property.rb:51:in `send_props'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/property.rb:32:in `initialize'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/active_node/property.rb:7:in `initialize'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/callbacks.rb:19:in `block in initialize'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/activesupport-6.0.0.rc1/lib/active_support/callbacks.rb:101:in `run_callbacks'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/shared/callbacks.rb:19:in `initialize'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/active_node.rb:53:in `initialize'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/active_node/persistence.rb:116:in `new'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/active_node/persistence.rb:116:in `create!'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/base.rb:31:in `migrate_up'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/base.rb:16:in `block in migrate'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/2.6.0/benchmark.rb:308:in `realtime'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/base.rb:15:in `migrate'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:127:in `block in migrate'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:133:in `migration_message'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:125:in `migrate'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:26:in `block in all'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:24:in `each'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/migrations/runner.rb:24:in `all'
/Users/metkat/.rvm/gems/ruby-2.6.0/gems/neo4j-9.2.4/lib/neo4j/tasks/migration.rake:116:in `block (3 levels) in '
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:273:in `block in execute'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:273:in `each'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:273:in `execute'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:214:in `block in invoke_with_call_chain'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/2.6.0/monitor.rb:230:in `mon_synchronize'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:194:in `invoke_with_call_chain'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/task.rb:183:in `invoke'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:160:in `invoke_task'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:116:in `block (2 levels) in top_level'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:116:in `each'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:116:in `block in top_level'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:125:in `run_with_threads'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:110:in `top_level'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:83:in `block in run'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:186:in `standard_exception_handling'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/lib/rake/application.rb:80:in `run'
/Users/metkat/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/rake-12.3.2/exe/rake:27:in `<top (required)>'
/Users/metkat/.rvm/gems/ruby-2.6.0/bin/rake:23:in `load'
/Users/metkat/.rvm/gems/ruby-2.6.0/bin/rake:23:in `'
/Users/metkat/.rvm/gems/ruby-2.6.0/bin/ruby_executable_hooks:24:in `eval'
/Users/metkat/.rvm/gems/ruby-2.6.0/bin/ruby_executable_hooks:24:in `'
Tasks: TOP => neo4j:migrate:all

Body:
It looks like it's related to this PR which landed in RC1, I'm running into the same issue. I pinged that thread to see if it was intentional. In the meantime, try rolling back to the last beta or monkey patching ActiveModel::NullMutationTracker (which is what I did and confirmed it fixed the issue) by adding the following methods back into it:

  def forget_change(attr_name)
  end

  def original_value(attr_name)
  end

  def force_change(attr_name)
  end


来源: stackexchange

问:
Losing event publishing in Persistent Actor on crash
In this example from Akka persistance documentation

    val receiveRecover: Receive = {
    case evt: Evt                                 => updateState(evt)
    case SnapshotOffer(_, snapshot: ExampleState) => state = snapshot
    }

    val snapShotInterval = 1000
    val receiveCommand: Receive = {
    case Cmd(data) =>
      persist(Evt(s"${data}-${numEvents}")) { event =>
        updateState(event)
        context.system.eventStream.publish(event)
        if (lastSequenceNr % snapShotInterval == 0 && lastSequenceNr != 0)
          saveSnapshot(state)
      }
    case "print" => println(state)
    }
```

<p>I understand that this lambda:</p>

<pre class="lang-scala prettyprint-override"><code>    event =>
    updateState(event)
    context.system.eventStream.publish(event)
    if (lastSequenceNr % snapShotInterval == 0 && lastSequenceNr != 0)
      saveSnapshot(state)
</code>```

Is executed when the event has been successfully persisted.
What if the actor crashes while this lambda is being executed BEFORE successful publishing of the event, ie before context.system.eventStream.publish(event)?

Do I understand correctly that in such case the event is never published which may lead to an inconsistent state of the system? If so, is there any way to detect that such thing happened?

[EDIT]

Also, if you use the event publishing in your system, then correct me if I am wrong:

If your application is deployed in one JVM and you use the default Akka's event publishing facilities, then JVM crash will mean that all events published but not yet processed will be lost since that facility does not have any recovery mechanisms.

If your application is deployed in a cluster then you'll run in the same situation as above only if the whole cluster goes down.

For any production setup you should configure something like Kafka for event publishing/consuming.

答:
I understand that this lambda:

...

Is executed when the event has been successfully persisted. What if
  the actor crashes while this lambda is being executed BEFORE
  successful publishing of the event, ie before
  context.system.eventStream.publish(event)?

The lambda is run after the state is persisted. And the actor essentially suspends itself (putting all pending work in the stash) until that persistence is complete so that it remains consistent.

Do I understand correctly that in such case the event is never
  published which may lead to an inconsistent state of the system?

No, it will remain consistent for the above reason.

If your application is deployed in one JVM and you use the default Akka's event publishing facilities, then JVM crash will mean that all events published but not yet processed will be lost since that facility does not have any recovery mechanisms.

I guess it depends on what you mean by default event publishing. Regular actors, yes. If you lose the JVM you lose "regular" actors. Regular actors are in memory, essentially like normal Java/Scala objects. Persistent Actors, are, of course a different story.

You also say "published but not yet processed". Those, of course, are lost as well. Anything that isn't "processed" is essentially like a JDBC statement that hasn't been received by the database yet, or a message not transmitted to Kafka, etc. The design is essentially to save the event to the database immediately (almost like a transaction log) and then do the work after it is known to be safely persisted.

If your application is deployed in a cluster then you'll run in the same situation as above only if the whole cluster goes down.

A cluster essentially just gives a place for the persistent actor to recover. The cluster still relies on the persistent store for recovery.

(I'm keeping this answer focused on Akka Persistent Actors, the answers get more varied with things like Distributed Data.)

For any production setup you should configure something like Kafka for event publishing/consuming.

Not necessarily. The persistent module is definitely a consistent option. Kafka and Akka are really just different animals with different goals. Kafka is effectively pub/sub, Akka essentially takes a much more event sourced approach. I've worked systems that use both, but they use them for very different purposes.

ContentLicense: CC BY-SA 4.0

Body:
In this example from Akka persistance documentation

    val receiveRecover: Receive = {
    case evt: Evt                                 => updateState(evt)
    case SnapshotOffer(_, snapshot: ExampleState) => state = snapshot
    }

    val snapShotInterval = 1000
    val receiveCommand: Receive = {
    case Cmd(data) =>
      persist(Evt(s"${data}-${numEvents}")) { event =>
        updateState(event)
        context.system.eventStream.publish(event)
        if (lastSequenceNr % snapShotInterval == 0 && lastSequenceNr != 0)
          saveSnapshot(state)
      }
    case "print" => println(state)
    }

I understand that this lambda:

    event =>
    updateState(event)
    context.system.eventStream.publish(event)
    if (lastSequenceNr % snapShotInterval == 0 && lastSequenceNr != 0)
      saveSnapshot(state)

Is executed when the event has been successfully persisted.
What if the actor crashes while this lambda is being executed BEFORE successful publishing of the event, ie before context.system.eventStream.publish(event)?

Do I understand correctly that in such case the event is never published which may lead to an inconsistent state of the system? If so, is there any way to detect that such thing happened?

[EDIT]

Also, if you use the event publishing in your system, then correct me if I am wrong:

If your application is deployed in one JVM and you use the default Akka's event publishing facilities, then JVM crash will mean that all events published but not yet processed will be lost since that facility does not have any recovery mechanisms.

If your application is deployed in a cluster then you'll run in the same situation as above only if the whole cluster goes down.

For any production setup you should configure something like Kafka for event publishing/consuming.


问:
How to block access to a file to other functions within same process?
I don’t mean locking the file!

What I want to achieve is that all other threads should access the file without any problem, but in some circumstances I want to fail calls which are accessing that file through fd like dup2(2), ftruncate(2), etc. One option is to make a wrapper for all such functions like dup2(2), that will first check if to allow fd or no and then call the real dup2(2). But its a long task to do it with every sys call using fd.

Maybe if there is a solution to password protect a file so that it can only be accessed when specified password is given.

My library is being injected to anonymous process so I don’t have control over the caller and I observe that anonymous process doesn’t check fd before using it. It ends up using the fd my library is using.

Kindly don’t complain about the design issues. Please just focus on problem.

答: It sounds like you're injecting a library into a process that has a different constrained memory model and your library is incompatible. You could try using dup2() to move your own handles to really high values and hope it works.


问:
UIView Constraints TextView contentSize Bug
I have a function that returns a UIView. I want to dynamically change the size of my UIView(fullView) based on how much text is shown in the UITextView(thirdTextView).

I have tried setting the height dependant on the sizeThatFits of thirdTextView but it outputs "30" every time? What am I doing wrong?

```<code>let fullView = UIView()

    fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

    let firstButton = UIButton()
    firstButton.translatesAutoresizingMaskIntoConstraints = false
    let secondButton = UIButton()
    secondButton.translatesAutoresizingMaskIntoConstraints = false

    let thirdTextView = UITextView()
    thirdTextView.translatesAutoresizingMaskIntoConstraints = true
    thirdTextView.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
    thirdTextView.backgroundColor = .clear
    thirdTextView.isScrollEnabled = false

    firstButton.setTitle("Button1", for: .normal)
    firstButton.setTitleColor(.black, for: .normal)
    firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    firstButton.contentHorizontalAlignment = .left

    secondButton.setTitle("Button2", for: .normal)
    secondButton.setTitleColor(.black, for: .normal)
    secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    secondButton.contentHorizontalAlignment = .right

    let descriptionBarStackView =  UIStackView(arrangedSubviews: [firstButton, UIView() ,secondButton])
    descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
    descriptionBarStackView.axis = .horizontal
    descriptionBarStackView.alignment = .fill

    let viewWithStackViews = UIStackView(arrangedSubviews: [descriptionBarStackView, thirdTextView])
    viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false
    viewWithStackViews.axis = .vertical
    viewWithStackViews.layoutMargins = UIEdgeInsets(top: 15, left: 10, bottom: 5, right:10)
    viewWithStackViews.isLayoutMarginsRelativeArrangement = true

    fullView.addSubview(viewWithStackViews)

    NSLayoutConstraint(item: descriptionBarStackView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 30).isActive = true

    NSLayoutConstraint.activate([
        viewWithStackViews.topAnchor.constraint(equalTo: fullView.topAnchor, constant: 0),
        viewWithStackViews.leadingAnchor.constraint(equalTo: fullView.leadingAnchor, constant: 0),
        viewWithStackViews.trailingAnchor.constraint(equalTo: fullView.trailingAnchor, constant: 0),
        viewWithStackViews.bottomAnchor.constraint(equalTo: fullView.bottomAnchor, constant: 0),
        ])

    let test = thirdTextView.sizeThatFits(thirdTextView.frame.size).height
    print(test)

    fullView.frame = CGRect(x: 0, y: 0, width: textView.frame.width - 10, height: test)

    fullView.layer.cornerRadius = 5

    return fullView
}
</code>```

答:
The problem is here you add constraints between fullView and view while it's not a subview

```<code> fullView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -10).isActive = true
 fullView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
 fullView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
</code>```

May be you miss

```<code>self.view.addSubview(fullView)
</code>```

For rendering purposes there are many ways

1- Giving it a frame

2- Giving the view width/height

3- Adding it as a subview but hidden

Best option is the first

Body:
I have a function that returns a UIView. I want to dynamically change the size of my UIView(fullView) based on how much text is shown in the UITextView(thirdTextView).

I have tried setting the height dependant on the sizeThatFits of thirdTextView but it outputs "30" every time? What am I doing wrong?

let fullView = UIView()

    fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

    let firstButton = UIButton()
    firstButton.translatesAutoresizingMaskIntoConstraints = false
    let secondButton = UIButton()
    secondButton.translatesAutoresizingMaskIntoConstraints = false

    let thirdTextView = UITextView()
    thirdTextView.translatesAutoresizingMaskIntoConstraints = true
    thirdTextView.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
    thirdTextView.backgroundColor = .clear
    thirdTextView.isScrollEnabled = false

    firstButton.setTitle("Button1", for: .normal)
    firstButton.setTitleColor(.black, for: .normal)
    firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    firstButton.contentHorizontalAlignment = .left

    secondButton.setTitle("Button2", for: .normal)
    secondButton.setTitleColor(.black, for: .normal)
    secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    secondButton.contentHorizontalAlignment = .right

    let descriptionBarStackView =  UIStackView(arrangedSubviews: [firstButton, UIView() ,secondButton])
    descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
    descriptionBarStackView.axis = .horizontal
    descriptionBarStackView.alignment = .fill

    let viewWithStackViews = UIStackView(arrangedSubviews: [descriptionBarStackView, thirdTextView])
    viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false
    viewWithStackViews.axis = .vertical
    viewWithStackViews.layoutMargins = UIEdgeInsets(top: 15, left: 10, bottom: 5, right:10)
    viewWithStackViews.isLayoutMarginsRelativeArrangement = true

    fullView.addSubview(viewWithStackViews)

    NSLayoutConstraint(item: descriptionBarStackView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 30).isActive = true

    NSLayoutConstraint.activate([
        viewWithStackViews.topAnchor.constraint(equalTo: fullView.topAnchor, constant: 0),
        viewWithStackViews.leadingAnchor.constraint(equalTo: fullView.leadingAnchor, constant: 0),
        viewWithStackViews.trailingAnchor.constraint(equalTo: fullView.trailingAnchor, constant: 0),
        viewWithStackViews.bottomAnchor.constraint(equalTo: fullView.bottomAnchor, constant: 0),
        ])

    let test = thirdTextView.sizeThatFits(thirdTextView.frame.size).height
    print(test)

    fullView.frame = CGRect(x: 0, y: 0, width: textView.frame.width - 10, height: test)

    fullView.layer.cornerRadius = 5

    return fullView
}

Body:
The problem is here you add constraints between fullView and view while it's not a subview

 fullView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -10).isActive = true
 fullView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
 fullView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

May be you miss

self.view.addSubview(fullView)

For rendering purposes there are many ways

1- Giving it a frame

2- Giving the view width/height

3- Adding it as a subview but hidden

Best option is the first


问:
Build folder not generating in android studio project
Migrated to gradle kotlin dsl and ever since running the project from android studio fails to generate a build folder and an apk. Build succeeds but installation fails with the message:

```<code>The APK file /Users/user/AndroidStudioProjects/project/app/build/outputs/apk/Stage/debug/stage-debug.apk does not exist on disk.
Error while Installing APK
</code>```

This build folder is not being generated at all. Before migrating to gradle kotlin dsl, apk would be picked from build/intermediates/.....splitapk.apk

I am using android studio 3.4 RC3

答: You have to use Build -> (Build Apk's / Bundle) -> Build Apk on Studio. Then you will see it under app->build->outputs->apk</p>

Body:
Migrated to gradle kotlin dsl and ever since running the project from android studio fails to generate a build folder and an apk. Build succeeds but installation fails with the message:

The APK file /Users/user/AndroidStudioProjects/project/app/build/outputs/apk/Stage/debug/stage-debug.apk does not exist on disk.
Error while Installing APK

This build folder is not being generated at all. Before migrating to gradle kotlin dsl, apk would be picked from build/intermediates/.....splitapk.apk

I am using android studio 3.4 RC3


问:
Unary operator precedence in yacc
I'm getting a strange error in my YACC parser. It's a simple boolean algebra expression evaluator.

Everything works except the following type of situation:

```<code>> True and False
False
> (True and False)
False
> not (True and False)     <--- interpreted as (not True and False)
False
</code>```

example.y:

```<code>%{
#include <stdio.h>
int yylex();
void yyerror(const char *err);

%}

%token NEWLINE EQUIV IMPL OR AND NOT CONST

%union {
    bool value;
}

%type <value> CONST value not and or impl equiv expr

%%

program:
    |
    program expr NEWLINE
    ;

expr:
    equiv               { printf("%s\n", $1?"True":"False"); }
    ;

equiv:
    impl                { $$ = $1; }
    |
    equiv EQUIV impl    { $$ = $1 == $3; }
    ;

impl:
    or              { $$ = $1; }
    |
    impl IMPL or    { $$ = !$1 || $3; }
    ;

or:
    and             { $$ = $1; }
    |
    or OR and       { $$ = $1 || $3; }
    ;

and:
    not             { $$ = $1; }
    |
    and AND not     { $$ = $1 && $3; }
    ;

not:
    value           { $$ = $1; }
    |
    NOT not         { $$ = !$2; }
    ;

value:
    CONST           { $$ = $1; }
    |
    '(' expr ')'    { $$ = $2; }
    ;

%%

void yyerror(const char *err) {
    fprintf(stderr, "%s\n", err);
}

int main() {
    yyparse();
}
</code>```

example.l:

```<code>%{
#include "y.tab.h"
extern "C" int yywrap();
%}

%%

True                yylval.value = true; return CONST;
False               yylval.value = false; return CONST;

"<=>"               return EQUIV;
=>                  return IMPL;
or                  return OR;
and                 return AND;
not                 return NOT;

[ \t]               ;
\n                  return NEWLINE;
.                   ;

%%

int yywrap() {
    return 1;
}
</code>```

Compiled with

```<code>bison -dy example.y
flex -l example.l
g++ y.tab.c lex.yy.c
</code>```

答: The only rule in your lexer that matches parentheses is the . rule, which does not return anything (or give any indication that a character has been ignored, which is a bad idea exactly because it makes problems like this so much easier to miss). Thus the parentheses in your input are completely ignored, the '(' and ')' in your grammar can never be matched and the input the parser sees is simply not True and False.

Title: Unary operator precedence in yacc

Body:
I'm getting a strange error in my YACC parser. It's a simple boolean algebra expression evaluator.

Everything works except the following type of situation:

> True and False
False
> (True and False)
False
> not (True and False)     <--- interpreted as (not True and False)
False

example.y:

%{
#include <stdio.h>
int yylex();
void yyerror(const char *err);

%}

%token NEWLINE EQUIV IMPL OR AND NOT CONST

%union {
    bool value;
}

%type <value> CONST value not and or impl equiv expr

%%

program:
    |
    program expr NEWLINE
    ;

expr:
    equiv               { printf("%s\n", $1?"True":"False"); }
    ;

equiv:
    impl                { $$ = $1; }
    |
    equiv EQUIV impl    { $$ = $1 == $3; }
    ;

impl:
    or              { $$ = $1; }
    |
    impl IMPL or    { $$ = !$1 || $3; }
    ;

or:
    and             { $$ = $1; }
    |
    or OR and       { $$ = $1 || $3; }
    ;

and:
    not             { $$ = $1; }
    |
    and AND not     { $$ = $1 && $3; }
    ;

not:
    value           { $$ = $1; }
    |
    NOT not         { $$ = !$2; }
    ;

value:
    CONST           { $$ = $1; }
    |
    '(' expr ')'    { $$ = $2; }
    ;

%%

void yyerror(const char *err) {
    fprintf(stderr, "%s\n", err);
}

int main() {
    yyparse();
}

example.l:

%{
#include "y.tab.h"
extern "C" int yywrap();
%}

%%

True                yylval.value = true; return CONST;
False               yylval.value = false; return CONST;

"<=>"               return EQUIV;
=>                  return IMPL;
or                  return OR;
and                 return AND;
not                 return NOT;

[ \t]               ;
\n                  return NEWLINE;
.                   ;

%%

int yywrap() {
    return 1;
}

Compiled with

bison -dy example.y
flex -l example.l
g++ y.tab.c lex.yy.c


问:
FirebaseNetworkException cannot be cast to com.google.firebase.auth.FirebaseAuthException
There is a cast problem which is FirebaseAuthException. In some cases, task exception cannot cast to FirebaseAuthException. How can i handle this situation? I want to try this casting process. If it will be success, i will show error with details to user. Otherwise If it will not success, i want to show just error.</p>

```<code>   if(task.getException() != null){

    try {
        String errorCode = ((FirebaseAuthException) task.getException()).getErrorCode();

        switch(errorCode) {
            case "ERROR_EMAIL_ALREADY_IN_USE":
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.ERROR_EMAIL_ALREADY_IN_USE),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            case "ERROR_INVALID_EMAIL":
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.ERROR_INVALID_EMAIL),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            case "ERROR_WEAK_PASSWORD":
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.ERROR_WEAK_PASSWORD),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            case "ERROR_CREDENTIAL_ALREADY_IN_USE":
                Toast.makeText(LoginActivity.this, "CREDENTIAL ALREADY IN USE",
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            default:
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.Error),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();

        }
    }
    catch (WindowManager.BadTokenException e) {
        Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.Error),
                Toast.LENGTH_SHORT).show();
        stopIndicator();
    }

}else{
    Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.Error),
            Toast.LENGTH_SHORT).show();
    stopIndicator();
}
</code>```

答:
```<code>String errorCode;
    if(task.getException()).getErrorCode() instanceof  FirebaseAuthException){
        errorCode = ((FirebaseAuthException) task.getException()).getErrorCode();

        switch(errorCode) {
            case "ERROR_EMAIL_ALREADY_IN_USE":
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.ERROR_EMAIL_ALREADY_IN_USE),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            case "ERROR_INVALID_EMAIL":
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.ERROR_INVALID_EMAIL),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            case "ERROR_WEAK_PASSWORD":
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.ERROR_WEAK_PASSWORD),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            case "ERROR_CREDENTIAL_ALREADY_IN_USE":
                Toast.makeText(LoginActivity.this, "CREDENTIAL ALREADY IN USE",
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            default:
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.Error),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();

        }

    }else{
         errorCode="";
    }
</code>```

Body:
There is a cast problem which is FirebaseAuthException. In some cases, task exception cannot cast to FirebaseAuthException. How can i handle this situation? I want to try this casting process. If it will be success, i will show error with details to user. Otherwise If it will not success, i want to show just error.

   if(task.getException() != null){

    try {
        String errorCode = ((FirebaseAuthException) task.getException()).getErrorCode();

        switch(errorCode) {
            case "ERROR_EMAIL_ALREADY_IN_USE":
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.ERROR_EMAIL_ALREADY_IN_USE),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            case "ERROR_INVALID_EMAIL":
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.ERROR_INVALID_EMAIL),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            case "ERROR_WEAK_PASSWORD":
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.ERROR_WEAK_PASSWORD),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            case "ERROR_CREDENTIAL_ALREADY_IN_USE":
                Toast.makeText(LoginActivity.this, "CREDENTIAL ALREADY IN USE",
                        Toast.LENGTH_SHORT).show();
                stopIndicator();
                break;
            default:
                Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.Error),
                        Toast.LENGTH_SHORT).show();
                stopIndicator();

        }
    }
    catch (WindowManager.BadTokenException e) {
        Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.Error),
                Toast.LENGTH_SHORT).show();
        stopIndicator();
    }

}else{
    Toast.makeText(LoginActivity.this, LoginActivity.this.getResources().getString(R.string.Error),
            Toast.LENGTH_SHORT).show();
    stopIndicator();
}


问:
List of all imports in python 3
How to find out list of all available imports in python 3 via program? I tried this at first, but couldn't understand what it returned

```<code>import sys
    sys.modules
</code>```

I think this isn't the way, although this struck my mind first. I searched the web and found this http://effbot.org/librarybook/core-modules-index.htm

Can someone tell me whether this is correct or not?

答:
From http://docs.python.org/library/sys.html (a good place to look for documentation on python stdlib)

sys.builtin_module_names

is a tuple (a bit like a immutable anonymous structs) of strings giving
  the names of all modules that are compiled into this Python
  interpreter.

sys.modules

This is a dictionary that maps module names to modules (module objects)
  which have already been loaded. This can be manipulated to force
  reloading of modules and other tricks. Note that removing a module
  from this dictionary is not the same as calling reload() on the
  corresponding module object.

So modules is a dictionary (a mapping of module names to the actual module objects). To get just the names type sys.modules.keys() although it probably isn't that usefull.

ContentLicense: CC BY-SA 3.0

Title: List of all imports in python 3

Body:
How to find out list of all available imports in python 3 via program? I tried this at first, but couldn't understand what it returned

import sys
    sys.modules

I think this isn't the way, although this struck my mind first. I searched the web and found this http://effbot.org/librarybook/core-modules-index.htm

Can someone tell me whether this is correct or not?


问:
Using different fonts for vertex labels in bipartite network graph (Rstudio)
I want to use different fonts for the vertex labels in a bipartite network graph in R. The first colum is the name of a person and the second column is the organisation to which the person is affiliated (double affiliation is possible).

This is an example of the data

```<code># R version 3.5.1 (2018-07-02) -- "Feather Spray"
# igraph 1.2.4

set.seed(7)

# bipartite network data
nodes <- read.csv("example.csv", header = TRUE, sep =";")
> nodes
   Person Organisation
1    John          SPD
2   Maria          SPD
3    John          CDU
4    Karl          CDU
5    Maik       Greens
6    Lisa         Left
7  Holger          SPD
8    Nico          CDU
9   Peter       Greens
10 Astrid          SPD
11   Theo         Left
12   Rita       Greens
13   Eric          FDP
14 Walter          CDU
15  Hilda          FDP
16  Boris          CDU
17   Olga          FDP
18   Nina         Left
19  Doris          CDU
20    Udo          SPD
summary(nodes)

library(igraph)

# different fonts and node shapes
shape <- c("circle", "square")
let <- c("Times", "Helvetica")

# creating graph (g)
g <- graph.data.frame(nodes, directed = FALSE)

# creating bipartite network
V(g)$type <- FALSE
V(g)$type[V(g)$name %in% nodes[, 1]] <- TRUE

plot(g, layout= layout_with_kk,
     vertex.shape= shape[as.numeric(V(g)$type) + 1],
     vertex.label.family= let[as.numeric(V(g)$type)+1]
)
</code>```

I assign two font styles (no special ones) to the data that these are recognised in the plot. However, the following error occurs and I don't know how to solve this:

```<code>In doTryCatch(return(expr), name, parentenv, handler) :
  Zeichensatzfamilie in der Windows Zeichensatzdatenbank nicht gefunden (Translation: Font family is not found in the Windows font database)
</code>```

I could not find any related question here.
 Thank you for your help and suggestions in advance!

答:
If I just run your code, I get a similar error message, but you can fix this by including these statements before your plot statement.

```<code>windowsFonts("Times" = windowsFont("Times"))
windowsFonts("Helvetica" = windowsFont("Helvetica"))
</code>```

When I included these statements, I got no error message and the different node types were displayed with different fonts.

Body:
I want to use different fonts for the vertex labels in a bipartite network graph in R. The first colum is the name of a person and the second column is the organisation to which the person is affiliated (double affiliation is possible).

This is an example of the data

# R version 3.5.1 (2018-07-02) -- "Feather Spray"
# igraph 1.2.4

set.seed(7)

# bipartite network data
nodes <- read.csv("example.csv", header = TRUE, sep =";")
> nodes
   Person Organisation
1    John          SPD
2   Maria          SPD
3    John          CDU
4    Karl          CDU
5    Maik       Greens
6    Lisa         Left
7  Holger          SPD
8    Nico          CDU
9   Peter       Greens
10 Astrid          SPD
11   Theo         Left
12   Rita       Greens
13   Eric          FDP
14 Walter          CDU
15  Hilda          FDP
16  Boris          CDU
17   Olga          FDP
18   Nina         Left
19  Doris          CDU
20    Udo          SPD
summary(nodes)

library(igraph)

# different fonts and node shapes
shape <- c("circle", "square")
let <- c("Times", "Helvetica")

# creating graph (g)
g <- graph.data.frame(nodes, directed = FALSE)

# creating bipartite network
V(g)$type <- FALSE
V(g)$type[V(g)$name %in% nodes[, 1]] <- TRUE

plot(g, layout= layout_with_kk,
     vertex.shape= shape[as.numeric(V(g)$type) + 1],
     vertex.label.family= let[as.numeric(V(g)$type)+1]
)

I assign two font styles (no special ones) to the data that these are recognised in the plot. However, the following error occurs and I don't know how to solve this:

In doTryCatch(return(expr), name, parentenv, handler) :
  Zeichensatzfamilie in der Windows Zeichensatzdatenbank nicht gefunden (Translation: Font family is not found in the Windows font database)

I could not find any related question here.
 Thank you for your help and suggestions in advance!

Body:
If I just run your code, I get a similar error message, but you can fix this by including these statements before your plot statement.

windowsFonts("Times" = windowsFont("Times"))
windowsFonts("Helvetica" = windowsFont("Helvetica"))

When I included these statements, I got no error message and the different node types were displayed with different fonts.


问:
Where to put ssl certificates when trying to connect to a remote database using psycopg2?
I have created a Google PostgreSQL instance and I'm trying to operate it from a remote webserver, I have whitelisted the IP and turned on SSL-only mode. I created client certificates, but I'm clueless as to where to put them or how to reference them. I can't find anything about it online.

Any help would be appreciated

My psycopg2 connect statement looks like this and gives me an error saying it needs client certificates:

```<code>conn = psycopg2.connect(
            user="postgres",
            password="password",
            host="{IP_ADDRESS}",
            port="5432",
            database="testdb",
            sslmode="require",
}
</code>```

答:
Since you have created the client certificates to connect to your instance using SSL, there must be three things to look for :

A server certificate saved as server-ca.pem.

A client public key certificate saved as client-cert.pem.

A client private key saved as client-key.pem.

Depending on which tool you use to connect, these three items are specified in different ways. For example, when connecting using psql command-line client, these three files are the values for the sslrootcert, sslcert, and sslkey parameters in the psql connection string. Further To connection using SQL client and SSL/TLS, see Connecting with psql Client

Here's some steps if you need more detail  Connecting psql client using public IP

Body:
I have created a Google PostgreSQL instance and I'm trying to operate it from a remote webserver, I have whitelisted the IP and turned on SSL-only mode. I created client certificates, but I'm clueless as to where to put them or how to reference them. I can't find anything about it online.

Any help would be appreciated

My psycopg2 connect statement looks like this and gives me an error saying it needs client certificates:

conn = psycopg2.connect(
            user="postgres",
            password="password",
            host="{IP_ADDRESS}",
            port="5432",
            database="testdb",
            sslmode="require",
}


问:
How can I create a text box on iOS/Android and handle the input in MonoGame?
I want that people can create a new account in my MonoGame iOS and Android application. I need a text box for username, password and recovery e-mail address (if someone forgot his password).

How can I create the text box? Should I make a white rectangle sprite (Texture2D) and a spriteFont to write the text (for example the username)?
Or are there better ways to create the text box?

How can I find out if someone tapped with his finger on the blank text box? Can I use Rectangle.Intersects(TappRectangle) or is it better to do this differently?

How can I show the keyboard on iOS/Android after someone tapped on the text box so that they can write their username in the textbox?

How can I get the characters they tapped on the keyboard?

Is it possible to save/remember the text(login data) so that people don't need to write it always when they start my application? I want that the text boxes are already filled out with their login credentials when they start the application, then they would just need to tap on a login button to log in.

答:
You can use the KeyboardInput.Show(string WindowTitle, string Prompt, string Default, bool HidePassword = false) method.

```<code>// Load saved data into the following variables:
var defaultUsername = "";
var defaultPassword = "";
var defaultEmail = "";

var username = await KeyboardInput.Show("Name", "What's your username?", defaultUsername);
var password = await KeyboardInput.Show("Password", "What's your Password?", defaultPassword, true);
var email = await KeyboardInput.Show("E-Mail", "What's your Email?", defaultEmail);

// validate and save if the values do not match the defaults above

</code>```

This will show three separate input boxes, but it handles prompts and pop-up keyboard display and input.

As far as saving the data: Look at the TitleContainer class. You can use standard file I/O to read and write the data.

Body:
You can use the KeyboardInput.Show(string WindowTitle, string Prompt, string Default, bool HidePassword = false) method.

// Load saved data into the following variables:
var defaultUsername = "";
var defaultPassword = "";
var defaultEmail = "";

var username = await KeyboardInput.Show("Name", "What's your username?", defaultUsername);
var password = await KeyboardInput.Show("Password", "What's your Password?", defaultPassword, true);
var email = await KeyboardInput.Show("E-Mail", "What's your Email?", defaultEmail);

// validate and save if the values do not match the defaults above

This will show three separate input boxes, but it handles prompts and pop-up keyboard display and input.

As far as saving the data: Look at the TitleContainer class. You can use standard file I/O to read and write the data.


问:
Haskell getsizeof big integer
I'm trying to get the size in bytes of a big integer, given that there's arbitrary precision math under the hood, and I'd like to know how much space the result is actually using.

Here's a sample:

```<code>Prelude> import Data.Bits
Prelude> let fac1000 = product [1..1000] # big!
Prelude Data.Bits> finiteBitSize fac1000

<interactive>:37:1: error:
    • Ambiguous type variable ‘b0’ arising from a use of ‘finiteBitSize’
      prevents the constraint ‘(FiniteBits b0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘b0’ should be.
      These potential instances exist:
        instance FiniteBits Bool -- Defined in ‘Data.Bits’
        instance FiniteBits Int -- Defined in ‘Data.Bits’
        instance FiniteBits Word -- Defined in ‘Data.Bits’
    • In the expression: finiteBitSize fac1000
      In an equation for ‘it’: it = finiteBitSize fac1000

<interactive>:37:15: error:
    • Ambiguous type variable ‘b0’ arising from a use of ‘fac1000’
      prevents the constraint ‘(Num b0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘b0’ should be.
      These potential instances exist:
        instance Num Integer -- Defined in ‘GHC.Num’
        instance Num Double -- Defined in ‘GHC.Float’
        instance Num Float -- Defined in ‘GHC.Float’
        ...plus two others
        (use -fprint-potential-instances to see them all)
    • In the first argument of ‘finiteBitSize’, namely ‘fac1000’
      In the expression: finiteBitSize fac1000
      In an equation for ‘it’: it = finiteBitSize fac1000
</code>```

The type annotations they are suggesting do not seem reasonable, when I coerce to an integer for example:

```<code>Prelude Data.Bits> finiteBitSize (fac1000 :: Int)
64
</code>```

Well, that's a big number and I don't believe it.  In python, I get:

```<code>>>> import sys, math
>>> sys.getsizeof(math.factorial(1000))
1164
</code>```

which looks a lot more credible to me for the astronomically large 4.02e2568.

答:
You may approximate the number of bytes by asking for its log base 256 using the integer-logarithms package:

```<code>Math.NumberTheory.Logarithms> integerLogBase 256 (product [1..1000])
1066
</code>```

This is only an approximation because it accounts only for the bytes being used to store the number; typically arbitrary-precision integers also have some overhead for storing information about the length of the number and probably a bit of over-allocation, and neither of these will be accounted for by taking the logarithm.

If you don't mind getting the approximate size reported in bits instead of bytes, integerLog2 will be faster.

```<code>Math.NumberTheory.Logarithms> integerLog2 (product [1..1000])
8529
</code>```

If you want the true answer, you'll have to touch some really low-level APIs and depend on the exact definition of Integer:

```<code>{-# LANGUAGE MagicHash #-}
import Data.Bits
import GHC.Exts
import GHC.Integer.GMP.Internals
import GHC.Prim

sizeOfInteger :: Integer -> Int
sizeOfInteger n = constructorSize + case n of
    S# i -> finiteBitSize (I# i) `div` 8
    Jp# bn -> sizeOfBigNat bn
    Jn# bn -> sizeOfBigNat bn
    where
    constructorSize = finiteBitSize (0 :: Word) `div` 8
    sizeOfBigNat (BN# arr) = constructorSize + I# (sizeofByteArray# arr)
</code>```

Try it out in ghci:

```<code>> sizeOfInteger (product [1..1000])
1088
</code>```

Beware! I don't know all the promises of these internal APIs. It's possible that computing equal Integers in different ways may produce values that are represented differently. When touching these internal APIs you sometimes lose the guarantees of the abstract external API; in this case, you may not have that x == y implies sizeOfInteger x == sizeOfInteger y. Read the docs carefully if you plan to take this route!

Title: Haskell getsizeof big integer

Body:
I'm trying to get the size in bytes of a big integer, given that there's arbitrary precision math under the hood, and I'd like to know how much space the result is actually using.

Here's a sample:

Prelude> import Data.Bits
Prelude> let fac1000 = product [1..1000] # big!
Prelude Data.Bits> finiteBitSize fac1000

<interactive>:37:1: error:
    • Ambiguous type variable ‘b0’ arising from a use of ‘finiteBitSize’
      prevents the constraint ‘(FiniteBits b0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘b0’ should be.
      These potential instances exist:
        instance FiniteBits Bool -- Defined in ‘Data.Bits’
        instance FiniteBits Int -- Defined in ‘Data.Bits’
        instance FiniteBits Word -- Defined in ‘Data.Bits’
    • In the expression: finiteBitSize fac1000
      In an equation for ‘it’: it = finiteBitSize fac1000

<interactive>:37:15: error:
    • Ambiguous type variable ‘b0’ arising from a use of ‘fac1000’
      prevents the constraint ‘(Num b0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘b0’ should be.
      These potential instances exist:
        instance Num Integer -- Defined in ‘GHC.Num’
        instance Num Double -- Defined in ‘GHC.Float’
        instance Num Float -- Defined in ‘GHC.Float’
        ...plus two others
        (use -fprint-potential-instances to see them all)
    • In the first argument of ‘finiteBitSize’, namely ‘fac1000’
      In the expression: finiteBitSize fac1000
      In an equation for ‘it’: it = finiteBitSize fac1000

The type annotations they are suggesting do not seem reasonable, when I coerce to an integer for example:

Prelude Data.Bits> finiteBitSize (fac1000 :: Int)
64

Well, that's a big number and I don't believe it.  In python, I get:

>>> import sys, math
>>> sys.getsizeof(math.factorial(1000))
1164

which looks a lot more credible to me for the astronomically large 4.02e2568.

Body:
You may approximate the number of bytes by asking for its log base 256 using the integer-logarithms package:

Math.NumberTheory.Logarithms> integerLogBase 256 (product [1..1000])
1066

This is only an approximation because it accounts only for the bytes being used to store the number; typically arbitrary-precision integers also have some overhead for storing information about the length of the number and probably a bit of over-allocation, and neither of these will be accounted for by taking the logarithm.

If you don't mind getting the approximate size reported in bits instead of bytes, integerLog2 will be faster.

Math.NumberTheory.Logarithms> integerLog2 (product [1..1000])
8529

If you want the true answer, you'll have to touch some really low-level APIs and depend on the exact definition of Integer:

{-# LANGUAGE MagicHash #-}
import Data.Bits
import GHC.Exts
import GHC.Integer.GMP.Internals
import GHC.Prim

sizeOfInteger :: Integer -> Int
sizeOfInteger n = constructorSize + case n of
    S# i -> finiteBitSize (I# i) `div` 8
    Jp# bn -> sizeOfBigNat bn
    Jn# bn -> sizeOfBigNat bn
    where
    constructorSize = finiteBitSize (0 :: Word) `div` 8
    sizeOfBigNat (BN# arr) = constructorSize + I# (sizeofByteArray# arr)

Try it out in ghci:

> sizeOfInteger (product [1..1000])
1088

Beware! I don't know all the promises of these internal APIs. It's possible that computing equal Integers in different ways may produce values that are represented differently. When touching these internal APIs you sometimes lose the guarantees of the abstract external API; in this case, you may not have that x == y implies sizeOfInteger x == sizeOfInteger y. Read the docs carefully if you plan to take this route!


问:
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)

答:
It's not clear whether you want to run this stored proc once before any SQL is executed, or before every SQL statement is executed. Here's a suggestion for both cases:

Once Only

Call the method that invokes the stored proc in Bootrap.init()

Before Every

Call the method from the before* GORM event handlers


问:
Django sending users to the wrong template location?
I'm working on Python Crash Course Chapter 19, where we are setting up a 'learning log' application. I'm stuck (on page 440) with a template reference error.

I have reworked this section of the book, in addition to taking all of the updates listed here: https://ehmatthes.github.io/pcc/chapter_19/README.html

but seem to keep getting what looks to be a template reference error. I noticed the template is referencing the 'learning_logs' directory when looking for the login.html, which is incorrect -- it should be looking in the 'learning_log' directory.

learning_log\users\urls.py

from django.contrib.auth import views as auth_views

from . import views

app_name = 'users'
urlpatterns = [
    # Login page.
    path('login/',
        auth_views.LoginView.as_view(template_name='users/login.html'),
        name='login'),
]
```

<p>learning_logs\urls.py</p>

<pre class="lang-py prettyprint-override"><code>"""learning_logs URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

"""Defines URL patterns for learning_logs."""

from django.urls import path

from . import views

app_name = 'learning_logs'
urlpatterns = [
    # Home page.
    path('', views.index, name='index'),

    #Show all topics.
    path('topics/', views.topics, name='topics'),

    #Detail page for a single topic.
    path('topics/<int:topic_id>/', views.topic, name='topic'),

    #Page for adding a new topic.
    path('new_topic/', views.new_topic, name='new_topic'),

    #Page for adding a new entry.
    path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),

    #Page for editing an entry.
    path('edit_entry/<int:entry_id>/', views.edit_entry, name='edit_entry'),
]
</code>```

learning_log\urls.py

"""learning_log URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('users.urls')),
    path('', include('learning_logs.urls')),
]
```

<p>Here is the browser error:</p>

<pre class="lang-py prettyprint-override"><code>TemplateDoesNotExist at /users/login/
users/login.html
Request Method:
GET
Request URL:
http://localhost:8000/users/login/
Django Version:
2.2.1
Exception Type:
TemplateDoesNotExist
Exception Value:
users/login.html
Exception Location:
C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py in select_template, line 47
Python Executable:
C:\Users\kevin\Documents\webapps\11_env\Scripts\python.exe
Python Version:
3.7.3
Python Path:
['C:\\Users\\kevin\\Documents\\webapps',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env\\lib\\site-packages']
Server time:
Sun, 26 May 2019 22:14:26 +0000
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\admin\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\auth\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\learning_logs\templates\users\login.html (Source does not exist)
</code>```

Here is the server error:

    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:27] "GET /users/login/ HTTP/1.1" 500 79384
    Not Found: /users/
    [26/May/2019 15:12:39] "GET /users/ HTTP/1.1" 404 3224
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:43] "GET /users/login/ HTTP/1.1" 500 79384
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html

```

答: It appears that the book suggests you save the login.html file to the learning_log/users/templates folder, but it should be in the learning_logs folder. Once I moved the templates, that fixed my issue. Thank you both Nurhun and Lumiobyte!</p>

Body:
I'm working on Python Crash Course Chapter 19, where we are setting up a 'learning log' application. I'm stuck (on page 440) with a template reference error.

I have reworked this section of the book, in addition to taking all of the updates listed here: https://ehmatthes.github.io/pcc/chapter_19/README.html

but seem to keep getting what looks to be a template reference error. I noticed the template is referencing the 'learning_logs' directory when looking for the login.html, which is incorrect -- it should be looking in the 'learning_log' directory.

learning_log\users\urls.py

from django.contrib.auth import views as auth_views

from . import views

app_name = 'users'
urlpatterns = [
    # Login page.
    path('login/',
        auth_views.LoginView.as_view(template_name='users/login.html'),
        name='login'),
]

learning_logs\urls.py

"""learning_logs URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

"""Defines URL patterns for learning_logs."""

from django.urls import path

from . import views

app_name = 'learning_logs'
urlpatterns = [
    # Home page.
    path('', views.index, name='index'),

    #Show all topics.
    path('topics/', views.topics, name='topics'),

    #Detail page for a single topic.
    path('topics/<int:topic_id>/', views.topic, name='topic'),

    #Page for adding a new topic.
    path('new_topic/', views.new_topic, name='new_topic'),

    #Page for adding a new entry.
    path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'),

    #Page for editing an entry.
    path('edit_entry/<int:entry_id>/', views.edit_entry, name='edit_entry'),
]

learning_log\urls.py

"""learning_log URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('users.urls')),
    path('', include('learning_logs.urls')),
]

Here is the browser error:

TemplateDoesNotExist at /users/login/
users/login.html
Request Method:
GET
Request URL:
http://localhost:8000/users/login/
Django Version:
2.2.1
Exception Type:
TemplateDoesNotExist
Exception Value:
users/login.html
Exception Location:
C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py in select_template, line 47
Python Executable:
C:\Users\kevin\Documents\webapps\11_env\Scripts\python.exe
Python Version:
3.7.3
Python Path:
['C:\\Users\\kevin\\Documents\\webapps',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\kevin\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env',
 'C:\\Users\\kevin\\Documents\\webapps\\11_env\\lib\\site-packages']
Server time:
Sun, 26 May 2019 22:14:26 +0000
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\admin\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\contrib\auth\templates\users\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\kevin\Documents\webapps\learning_logs\templates\users\login.html (Source does not exist)

Here is the server error:

    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:27] "GET /users/login/ HTTP/1.1" 500 79384
    Not Found: /users/
    [26/May/2019 15:12:39] "GET /users/ HTTP/1.1" 404 3224
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html
    [26/May/2019 15:12:43] "GET /users/login/ HTTP/1.1" 500 79384
    Internal Server Error: /users/login/
    Traceback (most recent call last):
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response
        response = response.render()
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 106, in render
        self.content = self.rendered_content
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 81, in rendered_content
        template = self.resolve_template(self.template_name)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\response.py", line 63, in resolve_template
        return select_template(template, using=self.using)
      File "C:\Users\kevin\Documents\webapps\11_env\lib\site-packages\django\template\loader.py", line 47, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: users/login.html


问:
Why does adding a margin to my div push its content (columns) off the page?
Adding a margin to the  div pushes the right column off the edge of the screen to the right.

I have tried adding margins to both  and , altering  widths and even removing a width property from the  CSS altogether.

With no margin at all, the 3 columns fit the width of the screen perfectly with a default tiny margin showing the background colour of my page. Adding ANY margin to  messes the whole thing up.

```<code><HTML>
<main>
    <section>
    Some text 1
    </section>

    <section>
    Some text 2
    </section>

    <section>
    Some text 3
    </section>
</main>

CSS

<<<<<<<SOME MEDIA QUERIES TO MAKE IT ADAPTABLE FOR MOBILE>>>>>>>

@media (min-width: 620px) {
main {
    column-count: 2;
}
section {
    break-inside: avoid;
}
}

@media (min-width: 960px) {
    main {
        column-count: 3;
    }
}

<<<<<<<<<<<<NORMAL CSS>>>>>>>>>>>>>>

main {
    width: 100%;
    margin-right: 5%;  <<<<<PROBLEM AREA
    margin-left: 5%;
}

section {
    height: 25%;
    margin-bottom: 5%;
    padding: 20px;
    display: inline-block;
}
</code>```

I would like a 5% margin on the left and right of the  div with no margin between the  divs.

答:
CSS margins are added to the outside of the element. If you have a
 with a width of 100% and you add 5% margin on both sides, that element is now 110% wide.

If you want to add margins you have to account for them in the element's width. If both the width and margins are percentages, you can just subtract the margin:

main {
  width: 90%;
  margin-left: 5%;
  margin-right: 5%;
}
```

<p>If width and margin are using different units (e.g. width: 100%, margin: 24px), you can use css calc:</p>

```main {
  width: calc(100% - 48px);
  margin-left: 24px;
  margin-right: 24px;
}
```

<p>In the snippet below, the only difference between the first row and the second is the margin. Notice that the boxes themselves are the same size. The margin is added outside the box.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.grid {
  background-color: white;
  background-image: linear-gradient(transparent 24px, #999 25px), linear-gradient(90deg, transparent 24px, #999 25px);
  background-size: 25px 25px, 25px 25px;
  background-position: 1px 1px;
  height: 100vh;
}

.container > div {
  display: inline-block;
  width: 100px;
  background: bisque;
  margin: 0 21px 22px 0;
  min-height: 50px;
}

.container.second > div {
  background: tomato;
  margin: 0 46px 15px 0;
}</code>```

```

Body:
Adding a margin to the  div pushes the right column off the edge of the screen to the right.

I have tried adding margins to both  and , altering  widths and even removing a width property from the  CSS altogether.

With no margin at all, the 3 columns fit the width of the screen perfectly with a default tiny margin showing the background colour of my page. Adding ANY margin to  messes the whole thing up.

    Some text 1

    Some text 2

    Some text 3

CSS

<<<<<<<SOME MEDIA QUERIES TO MAKE IT ADAPTABLE FOR MOBILE>>>>>>>

@media (min-width: 620px) {
main {
    column-count: 2;
}
section {
    break-inside: avoid;
}
}

@media (min-width: 960px) {
    main {
        column-count: 3;
    }
}

<<<<<<<<<<<<NORMAL CSS>>>>>>>>>>>>>>

main {
    width: 100%;
    margin-right: 5%;  <<<<<PROBLEM AREA
    margin-left: 5%;
}

section {
    height: 25%;
    margin-bottom: 5%;
    padding: 20px;
    display: inline-block;
}

I would like a 5% margin on the left and right of the  div with no margin between the  divs.

Body:
CSS margins are added to the outside of the element. If you have a <div> with a width of 100% and you add 5% margin on both sides, that element is now 110% wide.

If you want to add margins you have to account for them in the element's width. If both the width and margins are percentages, you can just subtract the margin:

main {
  width: 90%;
  margin-left: 5%;
  margin-right: 5%;
}

If width and margin are using different units (e.g. width: 100%, margin: 24px), you can use css calc:

main {
  width: calc(100% - 48px);
  margin-left: 24px;
  margin-right: 24px;
}

In the snippet below, the only difference between the first row and the second is the margin. Notice that the boxes themselves are the same size. The margin is added outside the box.

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.grid {
  background-color: white;
  background-image: linear-gradient(transparent 24px, #999 25px), linear-gradient(90deg, transparent 24px, #999 25px);
  background-size: 25px 25px, 25px 25px;
  background-position: 1px 1px;
  height: 100vh;
}

.container > div {
  display: inline-block;
  width: 100px;
  background: bisque;
  margin: 0 21px 22px 0;
  min-height: 50px;
}

.container.second > div {
  background: tomato;
  margin: 0 46px 15px 0;
}

<div class="grid">
  <div class="container first">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>

  <div class="container second">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
</div>


问:
How to pass a variable from one component to another that is at the same level?
How to pass a variable from one component to another that is at the same level? I have the user variable in the Auth component service

```<code>@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private user: string = null;

  getUser() {
    return this.user;
  }

  setUser(username) {
    sessionStorage.setItem('username', username);
    this.user = sessionStorage.getItem('username');
    console.log('VAMOS!!!', this.user);
  }
}
</code>```

in the first component I inject it and if I get the value of the user variable then when the user authenticates I redirect it with this.router.navigate (['/ meet']) that is, I visualize the next component.

In this next component called list-user in which I get null in getUser ().

```<code>async ngOnInit() {
  console.log('HOY', this.authService.getUser());
}
</code>```

答:
When you redirect to ['/meet'], Authservice component is removed from DOM.

That's why it is providing null.

Why don't you use sessionStorage.getItem in your current component?

```<code>async ngOnInit() {

    console.log('HOY',sessionStorage.getItem('username'));
}
</code>```

Body:
How to pass a variable from one component to another that is at the same level? I have the user variable in the Auth component service

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private user: string = null;

  getUser() {
    return this.user;
  }

  setUser(username) {
    sessionStorage.setItem('username', username);
    this.user = sessionStorage.getItem('username');
    console.log('VAMOS!!!', this.user);
  }
}

in the first component I inject it and if I get the value of the user variable then when the user authenticates I redirect it with this.router.navigate (['/ meet']) that is, I visualize the next component.

In this next component called list-user in which I get null in getUser ().

async ngOnInit() {
  console.log('HOY', this.authService.getUser());
}

Body:
When you redirect to ['/meet'], Authservice component is removed from DOM.

That's why it is providing null.

Why don't you use sessionStorage.getItem in your current component?

async ngOnInit() {

    console.log('HOY',sessionStorage.getItem('username'));
}


问:
Solve the linear equations system AX = B in Python, np.linalg.solve not working
I'm trying to solve the linear equation AX=B where A,X,B are Matrices.

I've tried using the np.linalg.solve function of numpy but the result seems to be wrong.

Example:

```<code>Matrix A
[9 1 8]
[3 2 5]
[1 6 5]

Matrix B
[7 0 5]
[7 8 4]
[5 6 7]
</code>```

So to solve X, i've used:

X = np.linalg.solve(A,B)
```

<p>The result is:</p>

```X
[ 1.17521368 -0.17948718  0.40598291]
[ 0.20512821 -0.30769231  0.74358974]
[-0.56410256 -0.15384615  1.20512821]
```

<p>But if i try to verify the result by multiplying A by X, the result is anything but B:</p>

```B
[ 5.40598291 -2.02564103  8.86752137]
[ 7.61111111 -4.33333333 13.61111111]
[ 3.15811966 -3.82051282 14.92735043]
```

<p>If i use this:</p>

```np.matmul(B, np.linalg.inv(A))
```

<p>Instead of the solve function, i get the same results.</p>

<p>Is there something i am missing here?</p>

<p><strong>EDIT 1:</strong>
I've printed </p>

```np.allclose(np.dot(A, X), B)
```

<p>And is returning <strong>False</strong></p>

<p><strong>EDIT 2</strong><br>
Here is the code i'm using:</p>

<pre class="lang-py prettyprint-override"><code>B = np.array([7,0,5,7,8,4,5,6,7]).reshape(3,3)
A = np.array([9,1,8,3,2,5,1,6,5]).reshape(3,3)
X = np.linalg.solve(A,B)
print(x)
#[[-1.70967742 -4.48387097  0.08064516]
# [-1.35483871 -2.74193548  0.79032258]
# [ 2.96774194  5.38709677  0.43548387]]
</code>```

My apologies if this is a very basic question, i appreciate any help.
Thanks.

Body:
I'm trying to solve the linear equation AX=B where A,X,B are Matrices.

I've tried using the np.linalg.solve function of numpy but the result seems to be wrong.

Example:

Matrix A
[9 1 8]
[3 2 5]
[1 6 5]

Matrix B
[7 0 5]
[7 8 4]
[5 6 7]

So to solve X, i've used:

X = np.linalg.solve(A,B)

The result is:

X
[ 1.17521368 -0.17948718  0.40598291]
[ 0.20512821 -0.30769231  0.74358974]
[-0.56410256 -0.15384615  1.20512821]

But if i try to verify the result by multiplying A by X, the result is anything but B:

B
[ 5.40598291 -2.02564103  8.86752137]
[ 7.61111111 -4.33333333 13.61111111]
[ 3.15811966 -3.82051282 14.92735043]

If i use this:

np.matmul(B, np.linalg.inv(A))

Instead of the solve function, i get the same results.

Is there something i am missing here?

EDIT 1:
I've printed

np.allclose(np.dot(A, X), B)

And is returning False

EDIT 2

Here is the code i'm using:

B = np.array([7,0,5,7,8,4,5,6,7]).reshape(3,3)
A = np.array([9,1,8,3,2,5,1,6,5]).reshape(3,3)
X = np.linalg.solve(A,B)
print(x)
#[[-1.70967742 -4.48387097  0.08064516]
# [-1.35483871 -2.74193548  0.79032258]
# [ 2.96774194  5.38709677  0.43548387]]

My apologies if this is a very basic question, i appreciate any help.
Thanks.

Body:
My results with your arrays look right:

In [582]: A=np.array([9,1,8,3,2,5,1,6,5]).reshape(3,3)
In [583]: B=np.array([7,0,5,7,8,4,5,6,7]).reshape(3,3)
In [584]: x=np.linalg.solve(A,B)
In [585]: x
Out[585]:
array([[-1.70967742, -4.48387097,  0.08064516],
       [-1.35483871, -2.74193548,  0.79032258],
       [ 2.96774194,  5.38709677,  0.43548387]])
In [586]: A@x
Out[586]:
array([[7., 0., 5.],
       [7., 8., 4.],
       [5., 6., 7.]])

The other approach: AX=B => X=1/A B:

In [591]: np.linalg.inv(A)@B
Out[591]:
array([[-1.70967742, -4.48387097,  0.08064516],
       [-1.35483871, -2.74193548,  0.79032258],
       [ 2.96774194,  5.38709677,  0.43548387]])

And formally testing for equality:

In [602]: np.allclose(A@np.linalg.solve(A, B), B)
Out[602]: True


问:
Memset In C Using Sizeof Operator :
Here is a struct :

```<code>typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;
</code>```

For memset, which one should be used from below ?

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));
</code>```

or

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));
</code>```

What are the differences ?

答:
I like to use objects as arguments to sizeof

```<code>struct whatever *ptr;
/* ... */
ptr = malloc(nelems * sizeof *ptr);
memset(ptr, 0, nelems * sizeof *ptr);
</code>```

The advantage over using a parenthesized type is that the code only needs to be changed at one place should the type of the data change

```<code>struct before_change *ptr;
/* ... */
ptr = malloc(nelems * sizeof (struct before_change));
memset(ptr, 0, nelems * sizeof (struct before_change));
</code>```

Title: Memset In C Using Sizeof Operator :

Body:
Here is a struct :

typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;

For memset, which one should be used from below ?

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));

or

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));

What are the differences ?

Body:
I like to use objects as arguments to sizeof

struct whatever *ptr;
/* ... */
ptr = malloc(nelems * sizeof *ptr);
memset(ptr, 0, nelems * sizeof *ptr);

The advantage over using a parenthesized type is that the code only needs to be changed at one place should the type of the data change

struct before_change *ptr;
/* ... */
ptr = malloc(nelems * sizeof (struct before_change));
memset(ptr, 0, nelems * sizeof (struct before_change));


问:
Django order_by() filter with distinct()
How can I make an order_by like this ....

```<code>p = Product.objects.filter(vendornumber='403516006')\
                   .order_by('-created').distinct('vendor__name')
</code>```

The problem is that I have multiple vendors with the same name, and I only want the latest product by the vendor ..

Hope it makes sense?

I got this DB error:

SELECT DISTINCT ON expressions must match initial ORDER BY expressions
  LINE 1: SELECT DISTINCT ON ("search_vendor"."name")
  "search_product"...

答:
In case you are hoping to use a separate field for distinct and order by another field you can use the below code</p>

```<code>from django.db.models import Subquery

Model.objects.filter(
    pk__in=Subquery(
       Model.objects.all().distinct('foo').values('pk')
    )
).order_by('bar')
</code>```

Body:
How can I make an order_by like this ....

p = Product.objects.filter(vendornumber='403516006')\
                   .order_by('-created').distinct('vendor__name')

The problem is that I have multiple vendors with the same name, and I only want the latest product by the vendor ..

Hope it makes sense?

I got this DB error:

SELECT DISTINCT ON expressions must match initial ORDER BY expressions
  LINE 1: SELECT DISTINCT ON ("search_vendor"."name")
  "search_product"...

Body:
In case you are hoping to use a separate field for distinct and order by another field you can use the below code

from django.db.models import Subquery

Model.objects.filter(
    pk__in=Subquery(
       Model.objects.all().distinct('foo').values('pk')
    )
).order_by('bar')


问:
Why is var_dump displaying NULL when accessing a key that has an array as a value?
I'm trying to loop through the Wordpress themes I have installed to pull out a piece of data. I need to get access to $value->headers["TextDomain"] but when I try to access $value->headers I get a NULL response.

Here is the Wordpress Theme Object array that I am trying to pull data from:

```<code>object(WP_Theme)#795 (12) {
  ["update"]=>
  bool(false)
  ["theme_root":"WP_Theme":private]=>
  string(56) "/Users/tygoss/Projects/QuickPress/prod/wp-content/themes"
  ["headers":"WP_Theme":private]=>
  array(11) {
    ["Name"]=>
    string(10) "Black Jane"
    ["ThemeURI"]=>
    string(0) ""
    ["Description"]=>
    string(187) "Black Jane is a clean SuevaFree child theme with an optional slideshow on homepage, a new header layout in addition to the five header layouts available on SuevaFree and new Google Fonts."
    ["Author"]=>
    string(16) "ThemeinProgress."
    ["AuthorURI"]=>
    string(31) "https://www.themeinprogress.com"
    ["Version"]=>
    string(5) "1.0.4"
    ["Template"]=>
    string(9) "suevafree"
    ["Status"]=>
    string(0) ""
    ["Tags"]=>
    string(302) "blog, e-commerce, photography, custom-background, custom-colors, custom-header, custom-logo, custom-menu, featured-images, flexible-header, footer-widgets, post-formats, right-sidebar, sticky-post, theme-options, threaded-comments, translation-ready, one-column, two-columns, three-columns, grid-layout"
    ["TextDomain"]=>
    string(10) "black-jane"
    ["DomainPath"]=>
    string(10) "/languages"
  }
  ["name_translated":"WP_Theme":private]=>
  NULL
  ["errors":"WP_Theme":private]=>
  NULL
  ["stylesheet":"WP_Theme":private]=>
  string(10) "black-jane"
  ["template":"WP_Theme":private]=>
  string(9) "suevafree"
}
</code>```

If I var_dump( $value->stylesheet ) I get string(10) "black-jane"

But if I var_dump ( $value->headers ) I get NULL

Here is my loop:

```<code>    $all_themes = wp_get_themes();
    foreach ($all_themes as $key => $value) {
      echo '```';
      var_dump($value->headers);
      echo '```';
    }
</code>```

Shouldn't $value->headers dump out an array of 11 items? Why is it returning NULL and why does $value->stylesheet work but not $value-headers?

答: $value->get("the thing from the header array") works flawlessly!

Body:
I'm trying to loop through the Wordpress themes I have installed to pull out a piece of data. I need to get access to $value->headers["TextDomain"] but when I try to access $value->headers I get a NULL response.

Here is the Wordpress Theme Object array that I am trying to pull data from:

object(WP_Theme)#795 (12) {
  ["update"]=>
  bool(false)
  ["theme_root":"WP_Theme":private]=>
  string(56) "/Users/tygoss/Projects/QuickPress/prod/wp-content/themes"
  ["headers":"WP_Theme":private]=>
  array(11) {
    ["Name"]=>
    string(10) "Black Jane"
    ["ThemeURI"]=>
    string(0) ""
    ["Description"]=>
    string(187) "Black Jane is a clean SuevaFree child theme with an optional slideshow on homepage, a new header layout in addition to the five header layouts available on SuevaFree and new Google Fonts."
    ["Author"]=>
    string(16) "ThemeinProgress."
    ["AuthorURI"]=>
    string(31) "https://www.themeinprogress.com"
    ["Version"]=>
    string(5) "1.0.4"
    ["Template"]=>
    string(9) "suevafree"
    ["Status"]=>
    string(0) ""
    ["Tags"]=>
    string(302) "blog, e-commerce, photography, custom-background, custom-colors, custom-header, custom-logo, custom-menu, featured-images, flexible-header, footer-widgets, post-formats, right-sidebar, sticky-post, theme-options, threaded-comments, translation-ready, one-column, two-columns, three-columns, grid-layout"
    ["TextDomain"]=>
    string(10) "black-jane"
    ["DomainPath"]=>
    string(10) "/languages"
  }
  ["name_translated":"WP_Theme":private]=>
  NULL
  ["errors":"WP_Theme":private]=>
  NULL
  ["stylesheet":"WP_Theme":private]=>
  string(10) "black-jane"
  ["template":"WP_Theme":private]=>
  string(9) "suevafree"
}

If I var_dump( $value->stylesheet ) I get string(10) "black-jane"

But if I var_dump ( $value->headers ) I get NULL

Here is my loop:

    $all_themes = wp_get_themes();
    foreach ($all_themes as $key => $value) {
      echo '
';
      var_dump($value->headers);
      echo '
';
    }

Shouldn't $value->headers dump out an array of 11 items? Why is it returning NULL and why does $value->stylesheet work but not $value-headers?


问:
Sorting Youtube API result from playlist
I have been struggling with Youtube's API v3 now and I can't get it work in the way I want. My goal is to load the latest videos from a selected playlist into my website. The problem is that I only the the oldest videos in my response.

To load the playlist I request following API URI:
https://www.googleapis.com/youtube/v3/playlistItems

Here is an example of a request (just click execute):
http://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlistItems.list?part=id%252Csnippet%252CcontentDetails%252Cstatus&playlistId=PLOU2XLYxmsIKGo-dgliIJQNZ6L3G8UV4b&_h=1&

How can a sort the result and get the latest videos first? I can't find anything in the docs and I have been googling without any luck. There is no point with this API if you can't sort the result. The only way is to load all videos by keep loading the next page by token but that is just insane.

Any idea? Sounds like a basic problem but I can't find a solution...

答:
I had the same issue .. instead of using the API to get the newest first (there doesn't appear to be a way to do this), why don't you just sort the videos inside your playlist first, then use the API which will return them in the order they appear in the playlist.

Something like this:
https://community.tubepress.com/topic/5624-how-to-customize-sort-order-of-youtube-playlists/


答:
The result of X is correct. To verify if your solution is correct, as per the official docs you can use allclose() which should return True if two arrays (AX and B)are equal element-wise, within a tolerance.

```<code>import numpy as np

A = np.array([[9, 1, 8], [3, 2, 5], [1, 6, 5]])
B = np.array([[7, 0, 5], [7, 8, 4], [5, 6, 7]])

X = np.linalg.solve(A,B)

np.allclose(np.dot(A, X), B)
# True
</code>```

In your case, it indeed returns True.

Title: Solve the linear equations system AX = B in Python, np.linalg.solve not working

Body:
The result of X is correct. To verify if your solution is correct, as per the official docs you can use allclose() which should return True if two arrays (AX and B)are equal element-wise, within a tolerance.

import numpy as np

A = np.array([[9, 1, 8], [3, 2, 5], [1, 6, 5]])
B = np.array([[7, 0, 5], [7, 8, 4], [5, 6, 7]])

X = np.linalg.solve(A,B)

np.allclose(np.dot(A, X), B)
# True

In your case, it indeed returns True.