问:
JMeter GUI - execute using NewDriver failed to view Function Helper Dialog
I try to test a new function in JMeter.

I download JMeter 3.3 code and add plugins including JMeterPluginsCMD

I also download jmeter-plugins-extras-1.4.0.jar with HttpSimpleTableControlGui class

I execute NewDriver which opens JMeter GUI, I try to open Options -> Function Helper Dialog but I have no functions

log:

```<code>2017-11-13 16:16:56,661 WARN o.a.j.g.u.MenuFactory: Could not instantiate class: org.jmeterplugins.protocol.http.control.gui.HttpSimpleTableControlGui
java.lang.ClassNotFoundException: org.jmeterplugins.protocol.http.control.gui.HttpSimpleTableControlGui
    at java.net.URLClassLoader$1.run(Unknown Source) ~[?:1.8.0_25]
    at java.net.URLClassLoader$1.run(Unknown Source) ~[?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_25]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_25]
    at org.apache.jmeter.gui.util.MenuFactory.initializeMenus(MenuFactory.java:499) [core/:?]
    at org.apache.jmeter.gui.util.MenuFactory.<clinit>(MenuFactory.java:169) [core/:?]
    at org.apache.jmeter.control.gui.WorkBenchGui.createPopupMenu(WorkBenchGui.java:119) [core/:?]
    at org.apache.jmeter.gui.tree.JMeterTreeNode.createPopupMenu(JMeterTreeNode.java:159) [core/:?]
    at org.apache.jmeter.gui.action.EditCommand.doAction(EditCommand.java:46) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:88) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$0(ActionRouter.java:70) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter$$Lambda$43/1433208870.run(Unknown Source) [core/:?]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.access$400(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_25]
2017-11-13 16:16:59,670 ERROR o.a.j.g.a.ActionRouter: Error processing org.apache.jmeter.gui.action.CreateFunctionDialog@45e37a7e
java.lang.NullPointerException: null
    at org.apache.jmeter.functions.gui.FunctionHelper.initParameterPanel(FunctionHelper.java:165) ~[core/:?]
    at org.apache.jmeter.functions.gui.FunctionHelper.setVisible(FunctionHelper.java:228) ~[core/:?]
    at org.apache.jmeter.gui.action.CreateFunctionDialog.doAction(CreateFunctionDialog.java:50) ~[core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:88) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$0(ActionRouter.java:70) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter$$Lambda$43/1433208870.run(Unknown Source) [core/:?]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.access$400(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_25]
</code>```

答:
It seems that the right (or possible) way to call JMeter GUI is

```<code> ant run_gui
</code>```

Function Helper worked with my changes

Body:
I try to test a new function in JMeter.

I download JMeter 3.3 code and add plugins including JMeterPluginsCMD

I also download jmeter-plugins-extras-1.4.0.jar with HttpSimpleTableControlGui class

I execute NewDriver which opens JMeter GUI, I try to open Options -> Function Helper Dialog but I have no functions

log:

2017-11-13 16:16:56,661 WARN o.a.j.g.u.MenuFactory: Could not instantiate class: org.jmeterplugins.protocol.http.control.gui.HttpSimpleTableControlGui
java.lang.ClassNotFoundException: org.jmeterplugins.protocol.http.control.gui.HttpSimpleTableControlGui
    at java.net.URLClassLoader$1.run(Unknown Source) ~[?:1.8.0_25]
    at java.net.URLClassLoader$1.run(Unknown Source) ~[?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_25]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_25]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_25]
    at org.apache.jmeter.gui.util.MenuFactory.initializeMenus(MenuFactory.java:499) [core/:?]
    at org.apache.jmeter.gui.util.MenuFactory.<clinit>(MenuFactory.java:169) [core/:?]
    at org.apache.jmeter.control.gui.WorkBenchGui.createPopupMenu(WorkBenchGui.java:119) [core/:?]
    at org.apache.jmeter.gui.tree.JMeterTreeNode.createPopupMenu(JMeterTreeNode.java:159) [core/:?]
    at org.apache.jmeter.gui.action.EditCommand.doAction(EditCommand.java:46) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:88) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$0(ActionRouter.java:70) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter$$Lambda$43/1433208870.run(Unknown Source) [core/:?]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.access$400(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_25]
2017-11-13 16:16:59,670 ERROR o.a.j.g.a.ActionRouter: Error processing org.apache.jmeter.gui.action.CreateFunctionDialog@45e37a7e
java.lang.NullPointerException: null
    at org.apache.jmeter.functions.gui.FunctionHelper.initParameterPanel(FunctionHelper.java:165) ~[core/:?]
    at org.apache.jmeter.functions.gui.FunctionHelper.setVisible(FunctionHelper.java:228) ~[core/:?]
    at org.apache.jmeter.gui.action.CreateFunctionDialog.doAction(CreateFunctionDialog.java:50) ~[core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:88) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$0(ActionRouter.java:70) [core/:?]
    at org.apache.jmeter.gui.action.ActionRouter$$Lambda$43/1433208870.run(Unknown Source) [core/:?]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.access$400(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_25]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_25]
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) [?:1.8.0_25]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_25]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_25]

Body:
It seems that the right (or possible) way to call JMeter GUI is

 ant run_gui

Function Helper worked with my changes


来源: stackexchange

问:
findRooms by name or email address
Using the Microsoft Graph API, I would like to find rooms by either name or email address, such as:

```<code>https://graph.microsoft.com/beta/me/findRooms?$filter=startswith(mail,'cal_')
</code>```

or

```<code>https://graph.microsoft.com/beta/me/findRooms?$filter=startswith(name,'Building 1')
</code>```

Our rooms are not in RoomLists, and there are well over 100 rooms.

How can I query for a specific, or subset of rooms?

答: The API is very limited in beta, and doesn't support OData query parameters like $filter. Let the team know how you feel about it :) https://officespdev.uservoice.com/.

ContentLicense: CC BY-SA 3.0

Title: findRooms by name or email address

Body:
Using the Microsoft Graph API, I would like to find rooms by either name or email address, such as:

https://graph.microsoft.com/beta/me/findRooms?$filter=startswith(mail,'cal_')

or

https://graph.microsoft.com/beta/me/findRooms?$filter=startswith(name,'Building 1')

Our rooms are not in RoomLists, and there are well over 100 rooms.

How can I query for a specific, or subset of rooms?


问:
Is it OK to pass on OAuth Access Token between services?
Considering the following scenario in a context of the SSO/OAuth/microservices:

User successfully logs-in to the web application using OAuth's Implicit Flow.

Web app requests some data from Service A and Service B passing on user's Access Token to authorize both requests.

Service A also calls Service B (passing on the same Access Token!) in order to build response to the initial Web App request.

Now, is this OK to pass on the user's Access Token from Service A to Service B?

Or should Service A use "Client Credentials" grant to obtain its own Access Token to authorize call to the Service B?

UPDATE:

Please assume both services are owned by the same organization and both trust the same Authorization Server. Also both services are behind the same API Gateway which validates Access Tokens.

答:
I have found below 3 options:

If each microservice is verifying the token then we can pass the same token. But the problem is - in between same token can be expired.

If we use client_credentials grant then there we are having two issues: one is, we need to send the username/id in next microservice. Another one is, we need to request two times - first for getting the access token, next for actual call.

If we do the token verification in API gateway only (not in microservices) then from the API gateway we need to send the username in every microservices. And microservices implementation needs to be changed to accept that param/header.


问:
Trying to understand class and instance
I'm half way through 'real world haskell' and thought I'd have a go at writing my first code. Didn't get very far...

Basically, I thought I'd try and implement an array syntax for doubles and double lists so I can do numerical calculations on lists. Am I right in thinking that 'class' is like a generic function in CLOS? I made a 'class' with a function arplus to add arrays and scalars, and made it work for scalars. Now I don't know how to do the same for lists. (Doing the calculation is easy, I just don't know what to put in place of 'Double' for the list version).

```<code>class Narray a where
    arplus :: a -> a -> a

instance Narray Double where
    arplus a b =  a + b
</code>```

Then, how do I do mixed versions? Array-scalar and scalar array?

Will I need something like:

```<code>class Narray a where
   arplus :: a -> b -> a
</code>```

instead?

As an example of the code I'm trying to write, see the sbcl code below:
(Note - I've done this with arrays in lisp, but I was doing it in lists in haskell as they're typed. Doesn't really matter in terms of the question 'though.)

```<code>;; Generic add for arrays and scalar
(defgeneric .+ (a b))

;; Scalar-scalar
(defmethod .+ ((a double-float) (b double-float)) (+ a b))

;; Array-array
(defmethod .+ ((a SB-KERNEL::SIMPLE-ARRAY-DOUBLE-FLOAT)
       (b SB-KERNEL::SIMPLE-ARRAY-DOUBLE-FLOAT))
     (dotimes (i (array-total-size a))
        (setf (row-major-aref a i)
        (+ (row-major-aref a i)
           (row-major-aref b i)))) a)

;; Array-scaler
(defmethod .+ ((a SB-KERNEL::SIMPLE-ARRAY-DOUBLE-FLOAT) (b double-float))
  (dotimes (i (array-total-size a))
      (setf (row-major-aref a i)
        (+ (row-major-aref a i)
           b))) a)

;; Scalar-array
(defmethod .+ ((a double-float) (b SB-KERNEL::SIMPLE-ARRAY-DOUBLE-FLOAT))
  (dotimes (i (array-total-size b))
      (setf (row-major-aref b i)
        (+ a
           (row-major-aref b i)))) b)

;; Just to demo the code
(defun indgen (n)
  (let ((r (make-array n :element-type 'double-float)))
    (dotimes (i n)
      (setf (row-major-aref r i) (coerce i 'double-float))) r))

* (load "arrays.lisp")

T
* (.+ (indgen 6) 10d0)

#(10.0d0 11.0d0 12.0d0 13.0d0 14.0d0 15.0d0)
* (.+ (indgen 6) (indgen 6))

#(0.0d0 2.0d0 4.0d0 6.0d0 8.0d0 10.0d0)
*
</code>```

答:
Basically, I thought I'd try and implement an array syntax for doubles and double lists so I can do numerical calculations on lists. Am I right in thinking that 'class' is like a generic function in CLOS?

Haskell's type classes are a means of implementing what's sometimes called "ad-hoc polymorphism", meaning that a function can operate on multiple types but do different things for each one. They're not completely comparable to anything in most other languages, but from what little I know of it CLOS's "generic functions" sound pretty similar.

Then, how do I do mixed versions? Array-scalar and scalar array?

I assume your arrays and scalars are of different types--which obviously poses a problem because type classes have a single type parameter. If you're using GHC, there's a language extension MultiParamTypeClasses that does... exactly what it says, basically.

Unfortunately it can be kind of a pain in practice for various reasons, but in this case the problem is that you want the mixed version to work for either argument order, but the result needs to be an array for both. The most direct way to do that is to make the result a third type parameter--but then Haskell can't know that arplus applied to an array and a scalar is an array, since type parameters are independent of each other. To deal with this, other extensions exist, but things can get complicated quickly for some tasks.

Now, I'm a bit too rusty with lisps to be sure I'm reading your example correctly, but here's a stab at what I think you want:

```<code>{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}

class Narray a b c | a b -> c where
    arplus :: a -> b -> c

instance Narray Double Double Double where
    arplus = (+)

instance Narray Double [Double] [Double] where
    arplus x = map (x +)

instance Narray [Double] Double [Double] where
    arplus x y = map (+ y) x

instance Narray [Double] [Double] [Double] where
    arplus = zipWith (+)
</code>```

You can look up the extensions I've used in GHC's documentation for further details.

That said, please take the above as an example of how to do simple multiple-dispatch style overloading, not as necessarily a good idea in practice--as @luqui's comment says, this type class conflates operations that are conceptually different, and does so to little benefit.

I'm not sure if a discussion of better overall design would be useful to you, but suffice it to say that in this case I wouldn't bother with type classes at all.

Title: Trying to understand class and instance

Body:
I'm half way through 'real world haskell' and thought I'd have a go at writing my first code. Didn't get very far...

Basically, I thought I'd try and implement an array syntax for doubles and double lists so I can do numerical calculations on lists. Am I right in thinking that 'class' is like a generic function in CLOS? I made a 'class' with a function arplus to add arrays and scalars, and made it work for scalars. Now I don't know how to do the same for lists. (Doing the calculation is easy, I just don't know what to put in place of 'Double' for the list version).

class Narray a where
    arplus :: a -> a -> a

instance Narray Double where
    arplus a b =  a + b

Then, how do I do mixed versions? Array-scalar and scalar array?

Will I need something like:

class Narray a where
   arplus :: a -> b -> a

instead?

As an example of the code I'm trying to write, see the sbcl code below:
(Note - I've done this with arrays in lisp, but I was doing it in lists in haskell as they're typed. Doesn't really matter in terms of the question 'though.)

;; Generic add for arrays and scalar
(defgeneric .+ (a b))

;; Scalar-scalar
(defmethod .+ ((a double-float) (b double-float)) (+ a b))

;; Array-array
(defmethod .+ ((a SB-KERNEL::SIMPLE-ARRAY-DOUBLE-FLOAT)
       (b SB-KERNEL::SIMPLE-ARRAY-DOUBLE-FLOAT))
     (dotimes (i (array-total-size a))
        (setf (row-major-aref a i)
        (+ (row-major-aref a i)
           (row-major-aref b i)))) a)

;; Array-scaler
(defmethod .+ ((a SB-KERNEL::SIMPLE-ARRAY-DOUBLE-FLOAT) (b double-float))
  (dotimes (i (array-total-size a))
      (setf (row-major-aref a i)
        (+ (row-major-aref a i)
           b))) a)

;; Scalar-array
(defmethod .+ ((a double-float) (b SB-KERNEL::SIMPLE-ARRAY-DOUBLE-FLOAT))
  (dotimes (i (array-total-size b))
      (setf (row-major-aref b i)
        (+ a
           (row-major-aref b i)))) b)

;; Just to demo the code
(defun indgen (n)
  (let ((r (make-array n :element-type 'double-float)))
    (dotimes (i n)
      (setf (row-major-aref r i) (coerce i 'double-float))) r))

* (load "arrays.lisp")

T
* (.+ (indgen 6) 10d0)

#(10.0d0 11.0d0 12.0d0 13.0d0 14.0d0 15.0d0)
* (.+ (indgen 6) (indgen 6))

#(0.0d0 2.0d0 4.0d0 6.0d0 8.0d0 10.0d0)
*

Body:
Basically, I thought I'd try and implement an array syntax for doubles and double lists so I can do numerical calculations on lists. Am I right in thinking that 'class' is like a generic function in CLOS?

Haskell's type classes are a means of implementing what's sometimes called "ad-hoc polymorphism", meaning that a function can operate on multiple types but do different things for each one. They're not completely comparable to anything in most other languages, but from what little I know of it CLOS's "generic functions" sound pretty similar.

Then, how do I do mixed versions? Array-scalar and scalar array?

I assume your arrays and scalars are of different types--which obviously poses a problem because type classes have a single type parameter. If you're using GHC, there's a language extension MultiParamTypeClasses that does... exactly what it says, basically.

Unfortunately it can be kind of a pain in practice for various reasons, but in this case the problem is that you want the mixed version to work for either argument order, but the result needs to be an array for both. The most direct way to do that is to make the result a third type parameter--but then Haskell can't know that arplus applied to an array and a scalar is an array, since type parameters are independent of each other. To deal with this, other extensions exist, but things can get complicated quickly for some tasks.

Now, I'm a bit too rusty with lisps to be sure I'm reading your example correctly, but here's a stab at what I think you want:

{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}

class Narray a b c | a b -> c where
    arplus :: a -> b -> c

instance Narray Double Double Double where
    arplus = (+)

instance Narray Double [Double] [Double] where
    arplus x = map (x +)

instance Narray [Double] Double [Double] where
    arplus x y = map (+ y) x

instance Narray [Double] [Double] [Double] where
    arplus = zipWith (+)

You can look up the extensions I've used in GHC's documentation for further details.

That said, please take the above as an example of how to do simple multiple-dispatch style overloading, not as necessarily a good idea in practice--as @luqui's comment says, this type class conflates operations that are conceptually different, and does so to little benefit.

I'm not sure if a discussion of better overall design would be useful to you, but suffice it to say that in this case I wouldn't bother with type classes at all.

ContentLicense: CC BY-SA 2.5


问:
UITableView: Update label in custom cell?
I have two Table Views in one View Controller. One of the Table Views is using a custom cell. I have made a custom class for the two Table Views.

In the custom cell, I have some labels and two buttons. The buttons is a pluss button, and a minus button. I want these buttons to add 1, or subtract 1 from the label called counterLabel.

Custom Class:

```<code>import UIKit
class MainTableViewCell : UITableViewCell
{
    @IBOutlet weak var refMainCell: UILabel!

}

class SubTableViewCell : UITableViewCell
{
    var counter: Int = 0
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var subtitleLabel: UILabel!
    @IBAction func minusButton(_ sender: UIButton)
    {
        counter -= 1
    }
    @IBAction func plussButton(_ sender: UIButton)
    {
        counter += 1

    }
    @IBOutlet weak var counterLabel: UILabel!
}
</code>```

Setup from Main View Controller:

```<code>import UIKit
class MenyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    struct Objects {
        var sectionName: String!
        var SectionObjects: [String]!
        var subtitleArray: [String]!
    }

    var hovedMenyArray = ["Main1", "Main2", "Main3", "Main4"]
    var underMenyArray = [Objects]()
    var subtitleArray = ["", "","",""] /
    let detailArray = ["Detail1", "Detail2", "Detail3", "Detail4", "Detail5", "Detail6", "Detail7", "Detail8"]

    @IBOutlet weak var hovedMenyTableView: UITableView!
    @IBOutlet weak var underMenyTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        underMenyArray = [Objects.init(sectionName: "Section 1", SectionObjects: ["Item 1", "Item 2", "Item 3"], subtitleArray: ["Subtitle 1", "Subtitle 2", ""]),
                          Objects.init(sectionName: "Section 2", SectionObjects: ["Item 3", "Item 4", "Item 5"], subtitleArray: ["Subtitle 4", "Subtitle 5", "Subtitle 6"]),
                          Objects.init(sectionName: "Section 3", SectionObjects: ["Item 6", "Item 7", "Item 8"], subtitleArray: ["Subtitle 7", "Subtitle 8", "Subtitle 9"]),
                          Objects.init(sectionName: "Section 4", SectionObjects: ["Item 6", "Item 7", "Item 8"], subtitleArray: ["Subtitle 10", "Subtitle 11", "Subtitle 12"])]
       }
</code>```

And:

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
        {
           if (tableView == MainTableView)
            {
                let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath) as! MainTableViewCell
                cell.refMainCell.text = mainArray[indexPath.row]
                cell.detailTextLabel?.text = subtitleArray[indexPath.row]
                cell.accessoryType = .disclosureIndicator
                return cell
            }else
            {
                let cell: UITableViewCell
                cell = tableView.dequeueReusableCell(withIdentifier: "SubCell", for: indexPath)
                if let customCell = cell as? SubTableViewCell
                {
                    customCell.label.text = subArray[indexPath.section].SectionObjects[indexPath.row]
                    customCell.SubtitleLabel.text = subArray[indexPath.section].subtitleArray[indexPath.row]
                    customCell.counterLabel.text = String (customCell.counter)  //Here I'm trying to use the pluss and minus buttons.

                return cell
            }
       }
</code>```

In this setup, the counterLabel sort of works, but it updates labels in every section. I suppose that's right, since its not told to update a specific cell.

How should I go about to get the right label to update?

I also have to scroll down and up for the label to update, but I suppose there is a update function to use as well?

答:
Add an observer to your counter variable. The correct label will update every time the value of counter changes.</p>

```<code>var counter: Int = 0 {
    didSet {
        counterLabel.text = String(counter)
    }
}
</code>```

Body:
I have two Table Views in one View Controller. One of the Table Views is using a custom cell. I have made a custom class for the two Table Views.

In the custom cell, I have some labels and two buttons. The buttons is a pluss button, and a minus button. I want these buttons to add 1, or subtract 1 from the label called counterLabel.

Custom Class:

import UIKit
class MainTableViewCell : UITableViewCell
{
    @IBOutlet weak var refMainCell: UILabel!

}

class SubTableViewCell : UITableViewCell
{
    var counter: Int = 0
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var subtitleLabel: UILabel!
    @IBAction func minusButton(_ sender: UIButton)
    {
        counter -= 1
    }
    @IBAction func plussButton(_ sender: UIButton)
    {
        counter += 1

    }
    @IBOutlet weak var counterLabel: UILabel!
}

Setup from Main View Controller:

import UIKit
class MenyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    struct Objects {
        var sectionName: String!
        var SectionObjects: [String]!
        var subtitleArray: [String]!
    }

    var hovedMenyArray = ["Main1", "Main2", "Main3", "Main4"]
    var underMenyArray = [Objects]()
    var subtitleArray = ["", "","",""] /
    let detailArray = ["Detail1", "Detail2", "Detail3", "Detail4", "Detail5", "Detail6", "Detail7", "Detail8"]

    @IBOutlet weak var hovedMenyTableView: UITableView!
    @IBOutlet weak var underMenyTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        underMenyArray = [Objects.init(sectionName: "Section 1", SectionObjects: ["Item 1", "Item 2", "Item 3"], subtitleArray: ["Subtitle 1", "Subtitle 2", ""]),
                          Objects.init(sectionName: "Section 2", SectionObjects: ["Item 3", "Item 4", "Item 5"], subtitleArray: ["Subtitle 4", "Subtitle 5", "Subtitle 6"]),
                          Objects.init(sectionName: "Section 3", SectionObjects: ["Item 6", "Item 7", "Item 8"], subtitleArray: ["Subtitle 7", "Subtitle 8", "Subtitle 9"]),
                          Objects.init(sectionName: "Section 4", SectionObjects: ["Item 6", "Item 7", "Item 8"], subtitleArray: ["Subtitle 10", "Subtitle 11", "Subtitle 12"])]
       }

And:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
        {
           if (tableView == MainTableView)
            {
                let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath) as! MainTableViewCell
                cell.refMainCell.text = mainArray[indexPath.row]
                cell.detailTextLabel?.text = subtitleArray[indexPath.row]
                cell.accessoryType = .disclosureIndicator
                return cell
            }else
            {
                let cell: UITableViewCell
                cell = tableView.dequeueReusableCell(withIdentifier: "SubCell", for: indexPath)
                if let customCell = cell as? SubTableViewCell
                {
                    customCell.label.text = subArray[indexPath.section].SectionObjects[indexPath.row]
                    customCell.SubtitleLabel.text = subArray[indexPath.section].subtitleArray[indexPath.row]
                    customCell.counterLabel.text = String (customCell.counter)  //Here I'm trying to use the pluss and minus buttons.

                return cell
            }
       }

In this setup, the counterLabel sort of works, but it updates labels in every section. I suppose that's right, since its not told to update a specific cell.

How should I go about to get the right label to update?

I also have to scroll down and up for the label to update, but I suppose there is a update function to use as well?

Body:
Add an observer to your counter variable. The correct label will update every time the value of counter changes.

var counter: Int = 0 {
    didSet {
        counterLabel.text = String(counter)
    }
}


问:
Service Reference error upon creation
I'm currently having an issue with adding an OData service in a C# project. The service looks like this.

My step by step process looks like this:

STEP 1: Entering the OData URL

STEP 2: After hitting OK, the following error pops up.

STEP 3: Trying to update the service

----> Which results in following error.

I can't seem to figure out what causes these issues. If anyone has any suggestions, please let me know. It would be greatly appreciated!

答:
Instead of using the service reference with UWP. I used Ajax calls to get the data. Some of them weren't allowed in a Unity build. This is why I used tags to exclude scripts like this:

```<code>#if (UNITY_EDITOR)
... your class/code ...
#endif
</code>```

More information about this can be found by following this url.

https://support.unity3d.com/hc/en-us/articles/208456906-Excluding-Scripts-and-Assets-from-builds

ContentLicense: CC BY-SA 4.0

Title: Service Reference error upon creation

Body:
Instead of using the service reference with UWP. I used Ajax calls to get the data. Some of them weren't allowed in a Unity build. This is why I used tags to exclude scripts like this:

#if (UNITY_EDITOR)
... your class/code ...
#endif

More information about this can be found by following this url.

https://support.unity3d.com/hc/en-us/articles/208456906-Excluding-Scripts-and-Assets-from-builds


问:
How can i make this media query work to see the menu vertically?
I created this small icon menu with the help of a tutorial and I am trying to make it responsive, but it is not working.

When the width is 400px I want the menu to be vertical.

body {
  margin: 0px;
}

.cuadro {
  width: 100%;
  background-color: pink;
  overflow: auto;
}

.cuadro a {
  float: left;
  text-align: center;
  width: 20%;
  padding: 12px 0;
  transition: all 0.3s ease;
  color: white;
  font-size: 36px;
}

.cuadro a:hover {
  background-color: green;
}

.active {
  background-color: purple !important;
}

@media only screen and (max-width: 414px) {
  body {
    margin: 0px;
  }
  .cuadro {
    position: fixed;
    width: 414px;
    text-align: center;
    color: white;
    font-size: 36px
  }
  .cuadro a {
    background-color: pink;
    display: block;
    padding: 16px;
    color: white;
  }
  .cuadro a:hover {
    transition: all 0.3s ease;
    background-color: green;
  }
  .active {
    background-color: purple !important;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>Title</title>
  <meta charset="utf-8">
  <meta content="viewport" content="width=device-width initial-scale=1">
  <script src="https://use.fontawesome.com/ea180863a6.js"></script>
</head>

<body>
  <div class="cuadro">
    <i class="fa fa-skype" aria-hidden="true"></i>
    <i class="fa fa-spotify" aria-hidden="true"></i>
    <i class="fa fa-snapchat-ghost" aria-hidden="true"></i>
    <i class="fa fa-whatsapp" aria-hidden="true"></i>
    <i class="fa fa-vk" aria-hidden="true"></i>
  </div>
</body>

</html></code>```

What am I doing wrong?

答:
There is a lot of repetition in your CSS. There's no need to declare rules twice.

An alternative to float is to use flexbox. Note that you only need to change the direction of the container for smaller screens.

Good introduction to flexbox

example

I've removed / changed a few styles.. let me know if you have questions.

body {
  margin: 0;
}

.cuadro {
  background-color: pink;
  display: flex;
}

.cuadro a {
  text-align: center;
  flex: 1 0 20%;
  transition: all 0.3s ease;
  color: white;
  font-size: 36px;
  padding: 12px 0;
}

.cuadro a:not(.active):hover {
  background-color: green;
}

.active {
  background-color: purple;
}

@media only screen and (max-width: 414px) {
  .cuadro {
    flex-direction: column;
    justify-content: center;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://use.fontawesome.com/ea180863a6.js"></script>
<div class="cuadro">
  <i class="fa fa-skype" aria-hidden="true"></i>
  <i class="fa fa-spotify" aria-hidden="true"></i>
  <i class="fa fa-snapchat-ghost" aria-hidden="true"></i>
  <i class="fa fa-whatsapp" aria-hidden="true"></i>
  <i class="fa fa-vk" aria-hidden="true"></i>
</div></code>```

Body:
I created this small icon menu with the help of a tutorial and I am trying to make it responsive, but it is not working.

When the width is 400px I want the menu to be vertical.

body {
  margin: 0px;
}

.cuadro {
  width: 100%;
  background-color: pink;
  overflow: auto;
}

.cuadro a {
  float: left;
  text-align: center;
  width: 20%;
  padding: 12px 0;
  transition: all 0.3s ease;
  color: white;
  font-size: 36px;
}

.cuadro a:hover {
  background-color: green;
}

.active {
  background-color: purple !important;
}

@media only screen and (max-width: 414px) {
  body {
    margin: 0px;
  }
  .cuadro {
    position: fixed;
    width: 414px;
    text-align: center;
    color: white;
    font-size: 36px
  }
  .cuadro a {
    background-color: pink;
    display: block;
    padding: 16px;
    color: white;
  }
  .cuadro a:hover {
    transition: all 0.3s ease;
    background-color: green;
  }
  .active {
    background-color: purple !important;
  }
}

<!DOCTYPE html>

  <title>Title</title>
  <meta charset="utf-8">
  <meta content="viewport" content="width=device-width initial-scale=1">

What am I doing wrong?

Body:
There is a lot of repetition in your CSS. There's no need to declare rules twice.

An alternative to float is to use flexbox. Note that you only need to change the direction of the container for smaller screens.

Good introduction to flexbox

example

I've removed / changed a few styles.. let me know if you have questions.

body {
  margin: 0;
}

.cuadro {
  background-color: pink;
  display: flex;
}

.cuadro a {
  text-align: center;
  flex: 1 0 20%;
  transition: all 0.3s ease;
  color: white;
  font-size: 36px;
  padding: 12px 0;
}

.cuadro a:not(.active):hover {
  background-color: green;
}

.active {
  background-color: purple;
}

@media only screen and (max-width: 414px) {
  .cuadro {
    flex-direction: column;
    justify-content: center;
  }
}

<script src="https://use.fontawesome.com/ea180863a6.js"></script>
<div class="cuadro">
  <a class="active" href="#"><i class="fa fa-skype" aria-hidden="true"></i></a>
  <a href="#"><i class="fa fa-spotify" aria-hidden="true"></i></a>
  <a href="#"><i class="fa fa-snapchat-ghost" aria-hidden="true"></i></a>
  <a href="#"><i class="fa fa-whatsapp" aria-hidden="true"></i></a>
  <a href="#"><i class="fa fa-vk" aria-hidden="true"></i></a>
</div>


问:
ServiceEventSource and Service Fabric
Following a very simple code to play with the exception handling and logging in Service Fabric:

```<code>public async Task<IActionResult> Get()
{
    ServiceEventSource.Current.ServiceMessage(serviceContext, $"Entered 'GetAll' method");

    IActionResult result = null;
    List<Customer> list = new List<Customer>();

    try
    {
        using (CustomersContext context = new CustomersContext(connectionString))
        {
            list = context.Customers.Where(a => a.IsDeleted == false).ToList<Customer>();
        }
        result = Json(list);

        throw new ArgumentException("Argument exception", new NullReferenceException("Null reference exception"));
    }
    catch (Exception ex)
    {
        result = StatusCode(StatusCodes.Status500InternalServerError);
        ServiceEventSource.Current.ServiceMessage(serviceContext, $"Exception: " + JsonConvert.SerializeObject(ex));
    }
    finally
    {
        ServiceEventSource.Current.ServiceMessage(serviceContext, $"Exiting 'GetAll' method");
    }
    return result;
}
</code>```

My question is: why this line of code at the beginning

ServiceEventSource.Current.ServiceMessage(serviceContext, $"Entered 'GetAll' method");

and this line of code in finally block

ServiceEventSource.Current.ServiceMessage(serviceContext, $"Exiting 'GetAll' method");

work fine and log entry in Diagnostic Events, while this one in catch block

ServiceEventSource.Current.ServiceMessage(serviceContext, $"Exception: " + JsonConvert.SerializeObject(ex));

has the following error: "ServiceEventSource error CS0103: The name 'ServiceEventSource' does not exist in the current context"?

Thank you!

答:
SOLVED

Analyzing the signature and code of the called method, we note one thing:

```<code>public void ServiceMessage(ServiceContext serviceContext, string message, params objects[] args)
</code>```

This means that message parameter is used in a string.Format method.

My problem was that passing a Json string, with "{" and "}" characters, it throws an exception because it doesn't recognize the format.

Title: ServiceEventSource and Service Fabric

Body:
Following a very simple code to play with the exception handling and logging in Service Fabric:

public async Task<IActionResult> Get()
{
    ServiceEventSource.Current.ServiceMessage(serviceContext, $"Entered 'GetAll' method");

    IActionResult result = null;
    List<Customer> list = new List<Customer>();

    try
    {
        using (CustomersContext context = new CustomersContext(connectionString))
        {
            list = context.Customers.Where(a => a.IsDeleted == false).ToList<Customer>();
        }
        result = Json(list);

        throw new ArgumentException("Argument exception", new NullReferenceException("Null reference exception"));
    }
    catch (Exception ex)
    {
        result = StatusCode(StatusCodes.Status500InternalServerError);
        ServiceEventSource.Current.ServiceMessage(serviceContext, $"Exception: " + JsonConvert.SerializeObject(ex));
    }
    finally
    {
        ServiceEventSource.Current.ServiceMessage(serviceContext, $"Exiting 'GetAll' method");
    }
    return result;
}

My question is: why this line of code at the beginning

ServiceEventSource.Current.ServiceMessage(serviceContext, $"Entered 'GetAll' method");

and this line of code in finally block

ServiceEventSource.Current.ServiceMessage(serviceContext, $"Exiting 'GetAll' method");

work fine and log entry in Diagnostic Events, while this one in catch block

ServiceEventSource.Current.ServiceMessage(serviceContext, $"Exception: " + JsonConvert.SerializeObject(ex));

has the following error: "ServiceEventSource error CS0103: The name 'ServiceEventSource' does not exist in the current context"?

Thank you!

Body:
SOLVED

Analyzing the signature and code of the called method, we note one thing:

public void ServiceMessage(ServiceContext serviceContext, string message, params objects[] args)

This means that message parameter is used in a string.Format method.

My problem was that passing a Json string, with "{" and "}" characters, it throws an exception because it doesn't recognize the format.


问:
missing line number issue in fabric crashlytics log
We are using the fabric crashlytics to track crash report. While application crash, we can see the crash log in fabric console. In that crash log we can see the "missing" text for framework class files.

Is there any way to resolve this "missing" text in the crash log for framework class file?

Sample crashlytics log image

答:
Crashlytics needs the framework dSYM to symbolicate the stack traces and show line numbers.

If this is a publicly distributed framework and you don't have the dSYM to upload, Crashlytics can't show line numbers.

If this is an internal framework and you have the dSYM, you can configure the upload-symbols script to upload all of your dSYMs at build time: https://docs.fabric.io/apple/crashlytics/missing-dsyms.html#upload-symbols-script


问:
How to write to a big excel file fast using C# ? Now very slow
I have a program to write the cells of a big excel file.(About 40 Mega Bytes).

I found it's very slow even just a move that writing a cell only.
This is what I do for my project.

```<code>Excel.Workbook apoWorkBook = _Excel.Workbooks.Open(apo);
Excel.Worksheet apoWorkSheet = apoWorkBook.Worksheets[1];
Excel.Range apoRange = apoWorkSheet.UsedRange;
</code>```

Then when I am going to write a cell like this:

```<code>apoRange.Cells[target_row, 23].Value2 = "Value"; // ( Repeats in different rows and columns )
</code>```

It spends about 20 or more seconds to finish this line of source codes.

But I have many many same codes to write like this. This would spend so much time to finish it.

I made an experiment to write to a small empty excel file, it only used about < 0.1 seconds to do that.

I think it's very slow to write to a big excel file because it's like the program saves the file after writing to a cell every time.

What's the fastest way to write in an BIG excel file ? Can it be just like puting all values on the cells then just save at once.

Please help, thanks !

答:
you can try turning off auto recalcuation

```<code>set Application.Calculation = xlCalculationManual
</code>```

may help, but interop is slow so doubt difference will be much.

Have you considered writing a csv file then opening that at the end?

Could even write the csv, then use interop to do the formatting after if that matters.

Body:
I have a program to write the cells of a big excel file.(About 40 Mega Bytes).

I found it's very slow even just a move that writing a cell only.
This is what I do for my project.

Excel.Workbook apoWorkBook = _Excel.Workbooks.Open(apo);
Excel.Worksheet apoWorkSheet = apoWorkBook.Worksheets[1];
Excel.Range apoRange = apoWorkSheet.UsedRange;

Then when I am going to write a cell like this:

apoRange.Cells[target_row, 23].Value2 = "Value"; // ( Repeats in different rows and columns )

It spends about 20 or more seconds to finish this line of source codes.

But I have many many same codes to write like this. This would spend so much time to finish it.

I made an experiment to write to a small empty excel file, it only used about < 0.1 seconds to do that.

I think it's very slow to write to a big excel file because it's like the program saves the file after writing to a cell every time.

What's the fastest way to write in an BIG excel file ? Can it be just like puting all values on the cells then just save at once.

Please help, thanks !

Body:
you can try turning off auto recalcuation

set Application.Calculation = xlCalculationManual

may help, but interop is slow so doubt difference will be much.

Have you considered writing a csv file then opening that at the end?

Could even write the csv, then use interop to do the formatting after if that matters.


问:
how to return boolean value in controller with $http.get
So i would like to return boolean value in my controller. Only I would like to do is try to use it with ng-show / ng-hide when boolean is true / false to hide content not desired for normal user but for admin only. This is my code:

parts of my adminController.js:

```<code>.constant("userUrl", "http://localhost:5500/users/type")
.controller("typeCtrl", function($scope, $http, userUrl) {
    $http.get(userUrl, {withCredentials : true})
        .success(function (data) {
            $scope.users = data;
        })
        .error(function (error) {
            $scope.error = error;
        });
    $scope.thisUser;
})
</code>```

part of my admin.html i would like to use the value for example :

```<code><div ng-show="thisUser == true" class="col-xs-3 panel-body">
</code>```

I hope you understand what I mean.

I am beginning with angular and can't return the value of "type" in my resource "users" to put it in the view from the controller.

答:
You have to do something like:</p>

```<code>$http.get(userUrl, {withCredentials : true})
    .success(function (data) {
        $scope.user = data;
    })

<div ng-show="user.type == 'admin'" class="col-xs-3 panel-body">
</code>```

Body:
So i would like to return boolean value in my controller. Only I would like to do is try to use it with ng-show / ng-hide when boolean is true / false to hide content not desired for normal user but for admin only. This is my code:

parts of my adminController.js:

.constant("userUrl", "http://localhost:5500/users/type")
.controller("typeCtrl", function($scope, $http, userUrl) {
    $http.get(userUrl, {withCredentials : true})
        .success(function (data) {
            $scope.users = data;
        })
        .error(function (error) {
            $scope.error = error;
        });
    $scope.thisUser;
})

part of my admin.html i would like to use the value for example :

I hope you understand what I mean.

I am beginning with angular and can't return the value of "type" in my resource "users" to put it in the view from the controller.

Body:
You have to do something like:

$http.get(userUrl, {withCredentials : true})
    .success(function (data) {
        $scope.user = data;
    })

<div ng-show="user.type == 'admin'" class="col-xs-3 panel-body">


问:
How to cache a query response with Postgres?
I have a database that syncs completely every 2 hours. All data is dropped and populated from the main data source.

I have some queries coming from client app, that have the same response for the current 2-hours dataset. So, if 100 clients run their apps, I will have to run this query 100 times for each of them, even though they don't differ.

How do I avoid running this real query against my database every time, but just keep its response somewhere and return it instead?

I think I can run this query after each sync and save to its own table then return from it.

What are other options, probably provided by Postgres itself?

答:
You should use something like redis to store the result or your query in memory. It comes with many clients. You can invalidate the result of this query when it's time to.

There are other memory caching like memcache, easy to install & to use.

Note these are specific to postgres.


问:
How to add commission to products at bluesnap using forms
I'm integrating BlueSnap with my website,
Is it possible to add the commission parameters "commissionPercent" to my form request like this:

https://www.bluesnap.com/jsp/checkout.jsp?currency=EUR&developerId=XXXXXXX&commissionPercent=30&vendorId=XXXXXX

答: No you cannot add commission parameters "commissionPercent" to your form request </p>


问:
NSTask Does Not Terminate
I'm trying to use NSTask to run the UNIX 'apropos' command. Here's my code:

```<code>NSTask *apropos = [[NSTask alloc] init];
NSPipe *pipe = [[NSPipe alloc] init];
[apropos setLaunchPath:@"/usr/bin/apropos"];
[apropos setArguments:[NSArray arrayWithObjects:@"filename", @"match", nil]];
[apropos setStandardOutput:pipe];
[apropos launch];
[apropos waitUntilExit];
</code>```

The problem is that this never returns. I also tried using Apple's example code (TaskWrapper) and it returns the output (in three segments) but it never calls the processFinished handler.

Furthermore, the appendOutput: handler receives duplicates. So, for example, if apropos returns this:

1
2
3
4
5

I might receive something like this:

1
2
3

1
2
3
4

5

(grouped into 3 append messages).

I note that Apropos displays the output in a format where it's possible to scroll up and down in the command line instead of just directly outputting the data straight to standard output; how do I read this reliably through NSTask and NSPipe?

答: With your original code, I would imagine it's because you're not reading the output of the command. The pipes only have a limited buffer size, and if you don't read the output of the task, it can end up hung waiting for the buffer to empty out. I don't know anything about the sample code you tried so I can't help there. As for the last question, apropos only uses the pager when it's connected to a terminal. You're not emulating a terminal, so you don't have to worry. You can prove this by running apropos whatever | cat in the terminal and verifying that the pager is not invoked.

Title: NSTask Does Not Terminate

Body:
I'm trying to use NSTask to run the UNIX 'apropos' command. Here's my code:

NSTask *apropos = [[NSTask alloc] init];
NSPipe *pipe = [[NSPipe alloc] init];
[apropos setLaunchPath:@"/usr/bin/apropos"];
[apropos setArguments:[NSArray arrayWithObjects:@"filename", @"match", nil]];
[apropos setStandardOutput:pipe];
[apropos launch];
[apropos waitUntilExit];

The problem is that this never returns. I also tried using Apple's example code (TaskWrapper) and it returns the output (in three segments) but it never calls the processFinished handler.

Furthermore, the appendOutput: handler receives duplicates. So, for example, if apropos returns this:

1
2
3
4
5

I might receive something like this:

1
2
3

1
2
3
4

5

(grouped into 3 append messages).

I note that Apropos displays the output in a format where it's possible to scroll up and down in the command line instead of just directly outputting the data straight to standard output; how do I read this reliably through NSTask and NSPipe?


问:
Google Cloud CDN doesn't cache from storage bucket?
I've been trying for the past couple of weeks to get this Load Balancer + Cloud Storage + CDN combo to work. It just doesn't, at least for me.

Got some static files (2 jpg's, svg's and css's just in case) into a multi-regional US (tried on regional too) bucket to test it out, but it just seems like it doesn't wanna cache at all.

Everytime I try checking it's headers, all I get is this same old boring bucket metadata:

Cache control are set just fine, you can see the v=2 at the top because I just keep trying to make it cache in different ways and cache strings was the last attempt. Unsucessful as well. LB works because this IP resolves from it.

What the hell am I doing wrong?

You can check the links in here:

http://35.227.213.66/style.css

http://35.227.213.66/logo.svg

http://35.227.213.66/1.jpg

http://35.227.213.66/2.jpg

答:
I can see that you are using the correct metadata

```<code> Cache-Control: public, max-age=604800
</code>```

It would be interesting to check how many requests have been answered from the CDN and how many from the bucket. You can use a query with 'gcloud beta logging' to check this:

From CDN

```<code>$ gcloud beta logging read 'resource.type="http_load_balancer" AND "logo.svg" AND httpRequest.cacheHit=true  AND timestamp>="2017-12-04T07:23:00.054257251Z"' | wc -l
</code>```

From your bucket

```<code>$ gcloud beta logging read 'resource.type="http_load_balancer" AND "logo.svg" AND httpRequest.cacheHit=false  AND timestamp>="2017-12-04T07:23:00.054257251Z"' | wc -l
</code>```

Body:
I can see that you are using the correct metadata

 Cache-Control: public, max-age=604800

It would be interesting to check how many requests have been answered from the CDN and how many from the bucket. You can use a query with 'gcloud beta logging' to check this:

From CDN

$ gcloud beta logging read 'resource.type="http_load_balancer" AND "logo.svg" AND httpRequest.cacheHit=true  AND timestamp>="2017-12-04T07:23:00.054257251Z"' | wc -l

From your bucket

$ gcloud beta logging read 'resource.type="http_load_balancer" AND "logo.svg" AND httpRequest.cacheHit=false  AND timestamp>="2017-12-04T07:23:00.054257251Z"' | wc -l


问:
JavaFX, countdown timer in Label setText
I'm building app for making tests. I have a scene made in SceneBuilder. There is a ImageView under image Label with Question and 3 buttons "A", "B", "C", Texts to buttons and question's Label are taken from DataBase, if you click answer new Image, question and asnwers are loading, everything works, but i want to add a Timer in the corner. When image and question show on the screen there will be "Time to read the question" and countdown from 10 to 0, and then "Time to answer" and again countdown from 10 to 0. If timer ends and there is no answer question and image will change automaticly. But the problem is that, i can do the timer, its counting down, and after this time it change the question but I dont know how to put it into Label. If inside Timer I do something like seconds-- label.setText(seconds) there is no error but when I start app there is a lot of exceptions. Can you help me how I can put this variable which is decrementing in timer after each second to Label ?

```<code>public void setTimer() {
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if(interval > 0)
            {
                timeElapsed.setText("Time to read the question: "+interval);
                System.out.println(interval);
                interval--;
            }
            else
                timer.cancel();
        }
    }, 1000,1000);
}
</code>```

Now i have something like this, in console everything is working there is a countdown from 10 to 0 but no effect in scene.

And errors:

```<code>Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0
at javafx.graphics/com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:291)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:423)
at javafx.graphics/javafx.scene.Parent$3.onProposedChange(Parent.java:493)
at javafx.base/com.sun.javafx.collections.VetoableListDecorator.setAll(VetoableListDecorator.java:113)
at javafx.base/com.sun.javafx.collections.VetoableListDecorator.setAll(VetoableListDecorator.java:108)
at javafx.controls/javafx.scene.control.skin.LabeledSkinBase.updateChildren(LabeledSkinBase.java:271)
at javafx.controls/javafx.scene.control.skin.LabeledSkinBase.lambda$new$11(LabeledSkinBase.java:219)
at javafx.controls/com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler.lambda$new$1(LambdaMultiplePropertyChangeListenerHandler.java:49)
at javafx.base/javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:89)
at javafx.base/com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:181)
at javafx.base/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:80)
at javafx.base/javafx.beans.property.StringPropertyBase.fireValueChangedEvent(StringPropertyBase.java:104)
at javafx.base/javafx.beans.property.StringPropertyBase.markInvalid(StringPropertyBase.java:111)
at javafx.base/javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:145)
at javafx.base/javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:50)
at javafx.base/javafx.beans.property.StringProperty.setValue(StringProperty.java:65)
at javafx.controls/javafx.scene.control.Labeled.setText(Labeled.java:147)
at gui.controller.StudentTestYesNoController$1.run(StudentTestYesNoController.java:40)
at java.base/java.util.TimerThread.mainLoop(Timer.java:556)
at java.base/java.util.TimerThread.run(Timer.java:506)
</code>```

答:
The problem is that you are trying to change the UI from a thread other than the application.

This should solve the problems with your current implementation

```<code>public void setTimer() {
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if(interval > 0)
            {
                Platform.runLater(() -> timeElapsed.setText("Time to read the question: "+interval));
                System.out.println(interval);
                interval--;
            }
            else
                timer.cancel();
        }
    }, 1000,1000);
}
</code>```

Also, you can take a look at something specific about the javafx - Timeline

JavaFX periodic background task

Body:
I'm building app for making tests. I have a scene made in SceneBuilder. There is a ImageView under image Label with Question and 3 buttons "A", "B", "C", Texts to buttons and question's Label are taken from DataBase, if you click answer new Image, question and asnwers are loading, everything works, but i want to add a Timer in the corner. When image and question show on the screen there will be "Time to read the question" and countdown from 10 to 0, and then "Time to answer" and again countdown from 10 to 0. If timer ends and there is no answer question and image will change automaticly. But the problem is that, i can do the timer, its counting down, and after this time it change the question but I dont know how to put it into Label. If inside Timer I do something like seconds-- label.setText(seconds) there is no error but when I start app there is a lot of exceptions. Can you help me how I can put this variable which is decrementing in timer after each second to Label ?

public void setTimer() {
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if(interval > 0)
            {
                timeElapsed.setText("Time to read the question: "+interval);
                System.out.println(interval);
                interval--;
            }
            else
                timer.cancel();
        }
    }, 1000,1000);
}

Now i have something like this, in console everything is working there is a countdown from 10 to 0 but no effect in scene.

And errors:

Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0
at javafx.graphics/com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:291)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:423)
at javafx.graphics/javafx.scene.Parent$3.onProposedChange(Parent.java:493)
at javafx.base/com.sun.javafx.collections.VetoableListDecorator.setAll(VetoableListDecorator.java:113)
at javafx.base/com.sun.javafx.collections.VetoableListDecorator.setAll(VetoableListDecorator.java:108)
at javafx.controls/javafx.scene.control.skin.LabeledSkinBase.updateChildren(LabeledSkinBase.java:271)
at javafx.controls/javafx.scene.control.skin.LabeledSkinBase.lambda$new$11(LabeledSkinBase.java:219)
at javafx.controls/com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler.lambda$new$1(LambdaMultiplePropertyChangeListenerHandler.java:49)
at javafx.base/javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:89)
at javafx.base/com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:181)
at javafx.base/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:80)
at javafx.base/javafx.beans.property.StringPropertyBase.fireValueChangedEvent(StringPropertyBase.java:104)
at javafx.base/javafx.beans.property.StringPropertyBase.markInvalid(StringPropertyBase.java:111)
at javafx.base/javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:145)
at javafx.base/javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:50)
at javafx.base/javafx.beans.property.StringProperty.setValue(StringProperty.java:65)
at javafx.controls/javafx.scene.control.Labeled.setText(Labeled.java:147)
at gui.controller.StudentTestYesNoController$1.run(StudentTestYesNoController.java:40)
at java.base/java.util.TimerThread.mainLoop(Timer.java:556)
at java.base/java.util.TimerThread.run(Timer.java:506)

Body:
The problem is that you are trying to change the UI from a thread other than the application.

This should solve the problems with your current implementation

public void setTimer() {
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if(interval > 0)
            {
                Platform.runLater(() -> timeElapsed.setText("Time to read the question: "+interval));
                System.out.println(interval);
                interval--;
            }
            else
                timer.cancel();
        }
    }, 1000,1000);
}

Also, you can take a look at something specific about the javafx - Timeline

JavaFX periodic background task


问:
Angular outputting JSON
I want to output only the short_title from "id": 28 but I
am unusure how to just call the title from all the JSON and then output
it in Angular within a HTML page.

```<code>  {
    "content": [
    {
        "id": 29,
        "short_title": "Flow",
        "long_title": "Flow",
        "fields": {
            "images": [
                {
                    "src": "content/29/images/QMTQUZxTMCoJMGrjOeowwqChJmnIe4fmFFT7pSph.jpeg",
                    "title": "Flow_2560.jpg"
                }
            ]
        },
        "type_id": 4,
        "folder_id": 3,
        "created_at": "2017-11-28 16:40:12",
        "updated_at": "2017-11-28 16:40:12",
        "type": {
            "id": 4,
            "code": "image-only",
            "title": "Full screen image",
            "visible_fields": [
                "images"
            ],
            "created_at": "2017-08-31 14:22:59",
            "updated_at": "2017-08-31 14:22:59"
        }
    },
    {
        "id": 28,
        "short_title": "Navigation buttons",
</code>```

I want to just output this short title

```<code>        "long_title": "Nav buttons 21st November",
        "fields": {
            "links": [
                {
                    "icon": "1",
                    "link": "http://sportspecific.digitaltesting.net/",
                    "size": "full",
                    "title": "Button 1",
                    "bg_colour": "#a64343",
                    "link_type": "url"
                },
                {
                    "icon": "2",
                    "link": "http://sportspecific.digitaltesting.net/",
                    "size": "full",
                    "title": "Button 2",
                    "bg_colour": "#742d2d",
                    "link_type": "url"
                }
            ]
        },
</code>```

答:
If you don't know what index id: 28 is at, you can use the find method.

```<code>let content = data.content.find(item => item.id === 28);
this.shortTitle = content.short_title;
</code>```

Then display it in your html

```<code>{{shortTitle}}
</code>```

Note: find is an es6 function, so you'll need to add a polyfill

Title: Angular outputting JSON

Body:
I want to output only the short_title from "id": 28 but I
am unusure how to just call the title from all the JSON and then output
it in Angular within a HTML page.

  {
    "content": [
    {
        "id": 29,
        "short_title": "Flow",
        "long_title": "Flow",
        "fields": {
            "images": [
                {
                    "src": "content/29/images/QMTQUZxTMCoJMGrjOeowwqChJmnIe4fmFFT7pSph.jpeg",
                    "title": "Flow_2560.jpg"
                }
            ]
        },
        "type_id": 4,
        "folder_id": 3,
        "created_at": "2017-11-28 16:40:12",
        "updated_at": "2017-11-28 16:40:12",
        "type": {
            "id": 4,
            "code": "image-only",
            "title": "Full screen image",
            "visible_fields": [
                "images"
            ],
            "created_at": "2017-08-31 14:22:59",
            "updated_at": "2017-08-31 14:22:59"
        }
    },
    {
        "id": 28,
        "short_title": "Navigation buttons",

I want to just output this short title

        "long_title": "Nav buttons 21st November",
        "fields": {
            "links": [
                {
                    "icon": "1",
                    "link": "http://sportspecific.digitaltesting.net/",
                    "size": "full",
                    "title": "Button 1",
                    "bg_colour": "#a64343",
                    "link_type": "url"
                },
                {
                    "icon": "2",
                    "link": "http://sportspecific.digitaltesting.net/",
                    "size": "full",
                    "title": "Button 2",
                    "bg_colour": "#742d2d",
                    "link_type": "url"
                }
            ]
        },

Body:
If you don't know what index id: 28 is at, you can use the find method.

let content = data.content.find(item => item.id === 28);
this.shortTitle = content.short_title;

Then display it in your html

{{shortTitle}}

Note: find is an es6 function, so you'll need to add a polyfill


问:
what is the best way to argue about the big O or about theta?
We're asked to provide a  $ n+4![\sqrt{n}] =O(n) $ with having a good argumentation and a logical build up for it but it's not said how a good argumentation would look like, so I know that $2n+4\sqrt{n}$ always bigger for n=1 but i wouldn't know how to argue about it and how to logically build it since i just thought about it and it happened to be true. Can someone help out with this example so i would know how to do it?</p>

答:
You should look at the following site https://en.wikipedia.org/wiki/Big_O_notation

For the O big notation we would say that if a function is the following: X^3+X^2+100X = O(x^3). This is with idea that if X-> some very big number, the X^3 term will become the dominant factor in the equation.

You can use the same logic to your equation. Which term will become dominant in your equation.
If this is not clear you should try to plot both terms and see how they scale. This could be more clarifying.


问:
how to make this mysql sub query work
```<code>SELECT c.noreg AS noreg, count( * ) AS jumlah
FROM kamar a, reservasi b, register c, identitas_psn d, sub_unit_kamar e
WHERE a.idkamar = b.kamar
AND b.noreg = c.id_reg_lengkap
AND c.norm = d.norm
AND c.idunit = e.id_subunit
AND c.noreg NOT
IN (

SELECT noreg
FROM register_keluar
)
AND (
c.idunit LIKE '20%'
)
AND jumlah > 1
GROUP BY noreg
ORDER BY jumlah DESC
</code>```

<p>// error is : AND jumlah > 1</p>

答:
Move jumlah > 1 into a HAVING clause, e.g.:

```<code>...
GROUP BY ...
HAVING jumlah > 1
ORDER BY ...
</code>```

http://en.wikipedia.org/wiki/Having_(SQL):

A HAVING clause in SQL specifies that
  an SQL SELECT statement should only
  return rows where aggregate values
  meet the specified conditions.

Title: how to make this mysql sub query work

Body:
SELECT c.noreg AS noreg, count( * ) AS jumlah
FROM kamar a, reservasi b, register c, identitas_psn d, sub_unit_kamar e
WHERE a.idkamar = b.kamar
AND b.noreg = c.id_reg_lengkap
AND c.norm = d.norm
AND c.idunit = e.id_subunit
AND c.noreg NOT
IN (

SELECT noreg
FROM register_keluar
)
AND (
c.idunit LIKE '20%'
)
AND jumlah > 1
GROUP BY noreg
ORDER BY jumlah DESC

// error is : AND jumlah > 1

Body:
Move jumlah > 1 into a HAVING clause, e.g.:

...
GROUP BY ...
HAVING jumlah > 1
ORDER BY ...

http://en.wikipedia.org/wiki/Having_(SQL):

A HAVING clause in SQL specifies that
  an SQL SELECT statement should only
  return rows where aggregate values
  meet the specified conditions.


问:
How do you change the music instrument for a MusicTrack?
Using audiotoolbox, I created a MusicSeqence by NewMusicSequence. Then I created a MusicTrack by MusicSequenceNewTrack. I inserted a few notes into the MusicTrack by MusicTrackNewMIDINoteEvent. And I created an AVMIDIPlayer to play the MusicSequence. However, I can play it with only one music instrument: piano. My question is that if it is possible to change the music instrument for a MusicTrack? For example, play a MusicTrack with violin. If it is possible, how do you do that?</p>

答:
Ok, I figured it out.

```<code>var inMessage = MIDIChannelMessage(status: 0xE0, data1: 120, data2: 0, reserved: 0)
MusicTrackNewMIDIChannelEvent(musicTrack!, 0, &inMessage)
// set msb to 120 and lsb to 0

inMessage = MIDIChannelMessage(status: 0xC0, data1: 48, data2: 0, reserved: 0)
MusicTrackNewMIDIChannelEvent(musicTrack!, 0, &inMessage)
// change program to 48
// you changed the instrument to Orchestra Drums
</code>```

And you can get all instruments information from CopyInstrumentInfoFromSoundBank.

The status and its corresponding data1 and data2 for MusicTrackNewMIDIChannelEvent can be found in here

Body:
Ok, I figured it out.

var inMessage = MIDIChannelMessage(status: 0xE0, data1: 120, data2: 0, reserved: 0)
MusicTrackNewMIDIChannelEvent(musicTrack!, 0, &inMessage)
// set msb to 120 and lsb to 0

inMessage = MIDIChannelMessage(status: 0xC0, data1: 48, data2: 0, reserved: 0)
MusicTrackNewMIDIChannelEvent(musicTrack!, 0, &inMessage)
// change program to 48
// you changed the instrument to Orchestra Drums

And you can get all instruments information from CopyInstrumentInfoFromSoundBank.

The status and its corresponding data1 and data2 for MusicTrackNewMIDIChannelEvent can be found in here


问:
Android log cat error
The logcat message shows this:

```<code>12-05 19:24:09.406 28495-28495/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.user.fragment, PID: 28495
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.fragment/com.example.user.fragment.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                       at com.example.user.fragment.MainActivity.onCreate(MainActivity.java:25)
                                                       at android.app.Activity.performCreate(Activity.java:6672)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
</code>```

The app has suddenly stopped working. What could be the possible error?

答: You have button defined in Activity file, and you are accessing layout button but which is actually not there. Please check at your end.</p>

Title: Android log cat error

Body:
The logcat message shows this:

12-05 19:24:09.406 28495-28495/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.user.fragment, PID: 28495
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.fragment/com.example.user.fragment.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                       at com.example.user.fragment.MainActivity.onCreate(MainActivity.java:25)
                                                       at android.app.Activity.performCreate(Activity.java:6672)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

The app has suddenly stopped working. What could be the possible error?


问:
Improper Neutralization of CRLF Sequences ('CRLF Injection') in Mailadress in JAVA
This code:

```<code>    InternetAddress[] myAdrs = getAdrs(message.getToAddresses());
    for (int i = 0; i < myAdrs.length; i++) {
        String s = myAdrs[i].getAddress();
        s = s.replace("\r","").replace("\n","").replace("%0A","").replace("%0a","").replace("%0D","").replace("%0d","");
        InternetAddress adr = new InternetAddress( s, false );
        // --> Improper Neutralization of CRLF Sequences ('CRLF Injection') (CWE ID 93)
        lMessage.addRecipient(Message.RecipientType.TO, adr);
    }
</code>```

still gives me the CWE ID 93 although I removed any unwanted strings in s with s=s.replace(\r....
In the examples i found one the web the s=s.replace should be the solution but still i have this flaw? Whats do I miss?
Any hints would be very appreciated!

答:
I faced such situations when Veracode doesn't accept handmade solutions like usage of StringEscapeUtils and simple replace methods.
Try ESAPI library. Veracode usually accepts ESAPI as trusted tool to defeat vulnerabilities. For example:

```<code>//need to handle ValidationException
String s = ESAPI.validator().getValidInput("User Email", myAdrs[i].getAddress(), "Email", 255, true);
InternetAddress adr = new InternetAddress( s, false );
</code>```

And put regex to test your email to validation.properties (or other file you specify in ESAPI.properties file as Validator.ConfigurationFile=validation.properties) file as Validation.Email property. For example:

```<code>Validator.Email=^[A-Za-z0-9._%'-]+@[A-Za-z0-9.-]+\\.[a-zA-Z]{2,6}$
</code>```

Body:
This code:

    InternetAddress[] myAdrs = getAdrs(message.getToAddresses());
    for (int i = 0; i < myAdrs.length; i++) {
        String s = myAdrs[i].getAddress();
        s = s.replace("\r","").replace("\n","").replace("%0A","").replace("%0a","").replace("%0D","").replace("%0d","");
        InternetAddress adr = new InternetAddress( s, false );
        // --> Improper Neutralization of CRLF Sequences ('CRLF Injection') (CWE ID 93)
        lMessage.addRecipient(Message.RecipientType.TO, adr);
    }

still gives me the CWE ID 93 although I removed any unwanted strings in s with s=s.replace(\r....
In the examples i found one the web the s=s.replace should be the solution but still i have this flaw? Whats do I miss?
Any hints would be very appreciated!

Body:
I faced such situations when Veracode doesn't accept handmade solutions like usage of StringEscapeUtils and simple replace methods.
Try ESAPI library. Veracode usually accepts ESAPI as trusted tool to defeat vulnerabilities. For example:

//need to handle ValidationException
String s = ESAPI.validator().getValidInput("User Email", myAdrs[i].getAddress(), "Email", 255, true);
InternetAddress adr = new InternetAddress( s, false );

And put regex to test your email to validation.properties (or other file you specify in ESAPI.properties file as Validator.ConfigurationFile=validation.properties) file as Validation.Email property. For example:

Validator.Email=^[A-Za-z0-9._%'-]+@[A-Za-z0-9.-]+\\.[a-zA-Z]{2,6}$


问:
Using Sphinx with Markdown instead of reST
I hate reST but love Sphinx. Is there a way that Sphinx reads Markdown instead of reStructuredText?</p>

答:
Note that building documentation using maven and embedded Sphinx + MarkDown support is fully supported by following maven plugin :

https://trustin.github.io/sphinx-maven-plugin/index.html

```<code><plugin>
  <groupId>kr.motd.maven</groupId>
  <artifactId>sphinx-maven-plugin</artifactId>
  <version>1.6.1</version>
  <configuration>
    <outputDirectory>${project.build.directory}/docs</outputDirectory>
  </configuration>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>
</plugin>
</code>```

Body:
Note that building documentation using maven and embedded Sphinx + MarkDown support is fully supported by following maven plugin :

https://trustin.github.io/sphinx-maven-plugin/index.html

<plugin>
  <groupId>kr.motd.maven</groupId>
  <artifactId>sphinx-maven-plugin</artifactId>
  <version>1.6.1</version>
  <configuration>
    <outputDirectory>${project.build.directory}/docs</outputDirectory>
  </configuration>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>
</plugin>


问:
How to put a property in a different table
I have a class:

```<code>@Entity
public class myClass {
  @Id
  @Column(name="id")
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;

  private String name;
...

  private String orderIndex;
}
</code>```

I would like to put orderIndex in a different table, since only few entities will have this property. I would like the tables to looks like this:

```<code>table myClass:
id  |  name | ...

table myClass_orderIndex:
myClass_id  |  orderIndex
</code>```

I could not find the annotations to do this in hibernate

答:
Perhaps a one-to-one relation will fit your requirements. The one-to-one is guaranteed by a @JoinColumn(unique=true)

```<code>@Entity
@Table(name="myClass_orderIndex")
public class OtherClass {
   private String orderIndex;
   @ManyToOne
   @JoinColumn(unique=true)
   private MyClass myClass;
   ...
}

@Entity
public class MyClass {
  @Id
  @Column(name="id")
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;

  private String name;

  @OneToMany(mappedBy="myClass", cascade = javax.persistence.CascadeType.ALL, orphanRemoval = true)
  @Cascade(CascadeType.ALL)
  private List<OtherClass> list;

  @Transient
  public String getOrderIndex() {
    if (list != null && list.size() == 1) return list.get(0).getOrderIndex();
    return null;
  }
}
</code>```

This will create two tables as per your requirement.

Body:
I have a class:

@Entity
public class myClass {
  @Id
  @Column(name="id")
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;

  private String name;
...

  private String orderIndex;
}

I would like to put orderIndex in a different table, since only few entities will have this property. I would like the tables to looks like this:

table myClass:
id  |  name | ...

table myClass_orderIndex:
myClass_id  |  orderIndex

I could not find the annotations to do this in hibernate

Body:
Perhaps a one-to-one relation will fit your requirements. The one-to-one is guaranteed by a @JoinColumn(unique=true)

@Entity
@Table(name="myClass_orderIndex")
public class OtherClass {
   private String orderIndex;
   @ManyToOne
   @JoinColumn(unique=true)
   private MyClass myClass;
   ...
}

@Entity
public class MyClass {
  @Id
  @Column(name="id")
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;

  private String name;

  @OneToMany(mappedBy="myClass", cascade = javax.persistence.CascadeType.ALL, orphanRemoval = true)
  @Cascade(CascadeType.ALL)
  private List<OtherClass> list;

  @Transient
  public String getOrderIndex() {
    if (list != null && list.size() == 1) return list.get(0).getOrderIndex();
    return null;
  }
}

This will create two tables as per your requirement.


问:
String.data to java (Swift)
Sorry if it's an amateur question. I cant seem to find the right answer to it. What is the android (java) equivalent of swift's:

```<code>"somestring".data(using:.utf8)
</code>```

method?

Thanks a lot

EDIT:

I am creating a java version of the following method:

```<code>guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }

let credential = data.base64EncodedString(options: [])

return (key: "Authorization", value: "Basic \(credential)")
</code>```

答:
Okay so I was playing a bit. Then I remembered on Obj-c that string is madeup of NSData and nsdata's java equivalent would be byte[] so what I did was convert string to byte array before converting it back to string:

```<code>byte[] data = (user+":"+password).getBytes("utf-8");
String credential = Base64.encodeToString(data,Base64.DEFAULT);
return new KeyValue("Authorization", "Basic "+credential);
</code>```

Thanks a lot. Hope this helps anyone.

Title: String.data to java (Swift)

Body:
Sorry if it's an amateur question. I cant seem to find the right answer to it. What is the android (java) equivalent of swift's:

"somestring".data(using:.utf8)

method?

Thanks a lot

EDIT:

I am creating a java version of the following method:

guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }

let credential = data.base64EncodedString(options: [])

return (key: "Authorization", value: "Basic \(credential)")

Body:
Okay so I was playing a bit. Then I remembered on Obj-c that string is madeup of NSData and nsdata's java equivalent would be byte[] so what I did was convert string to byte array before converting it back to string:

byte[] data = (user+":"+password).getBytes("utf-8");
String credential = Base64.encodeToString(data,Base64.DEFAULT);
return new KeyValue("Authorization", "Basic "+credential);

Thanks a lot. Hope this helps anyone.


问:
how to upload image to wordpress using JSon api
I am very new to wordpress, trying to create post with featured image from a separate .Net application using JSon api. Please help with the info about how can I upload image from external source (using url) and mark as featured image using the api.

Thanks..

答: use XML rpc .. it can not be done with json api ..</p>


问:
Crashlytics REST API for Closing Issues
Are there any REST APIs from Crashlytics that could be used to close issues, comment issues etc...? Specifically they're servicing/managing functions of the platform rather than the ones for creating Issues for crashes.

I'm planning on adding a webhook on our internal git server (Gogs) that would parse commit messages looking for certain tag (like "Closes FCI123", FCI meaning Fabric Crashlytics Issue and after it is the issue number) and close and comment issues automatically in order to keep things in sync across the tools we're using. Sort of automating certain tasks and increasing productivity.

答: Crashlytics doesn't currently have a public API.</p>

Title: Crashlytics REST API for Closing Issues


问:
Selenium - compound class names not permitted
I am trying to get all elements with a certain class name:

```<code>theButtons = browser.find_elements_by_class_name("Icon Icon--medium Icon--reply");
</code>```

However I get the error:

```<code>Compound class names not permitted
</code>```

I understand that spaces are not allowed in the class name to get it, but then what should I do?

Thanks

答:
Try with xpath:

```<code>theButtons = browser.find_elements_by_xpath("//*[contains(@class,'Icon Icon--medium Icon--reply')]");
</code>```

or

```<code>theButtons = browser.find_elements_by_xpath("//*[@class='Icon Icon--medium Icon--reply']");
</code>```

Replace the quotes if I am wrong as I have less knowledge of Python

Body:
I am trying to get all elements with a certain class name:

theButtons = browser.find_elements_by_class_name("Icon Icon--medium Icon--reply");

However I get the error:

Compound class names not permitted

I understand that spaces are not allowed in the class name to get it, but then what should I do?

Thanks

Body:
Try with xpath:

theButtons = browser.find_elements_by_xpath("//*[contains(@class,'Icon Icon--medium Icon--reply')]");

or

theButtons = browser.find_elements_by_xpath("//*[@class='Icon Icon--medium Icon--reply']");

Replace the quotes if I am wrong as I have less knowledge of Python


问:
JPA - One to many - duplicate key value error
I need implement join table for users which will have 2 columns USER_CONTACTS(user_id, contact_id)

I need store for contacts lists for users. I need to make possible that user with id 1 can have in contacts user with id 5, but user 5 can also have in contacts user with id 1 (but he musn't).

I need to be possible do following inserts:

```<code>INSERT INTO USERS_CONTACTS(user_id, contact_id) VALUES(1, 5);
INSERT INTO USERS_CONTACTS(user_id, contact_id) VALUES(5, 1);
</code>```

Now I got this error:

Unsuccessful: INSERT INTO USERS_CONTACTS(user_id, contact_id)
  VALUES(2, 3) 2017-12-05 15:00:15.146 ERROR 14268 --- [           main]
  org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: duplicate key value
  violates unique constraint "uk_j9ggomsdbjte1eqfo5e61vh8a"

Here is my relationship implementation of User in JPA:

```<code>@Entity
public class User{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", columnDefinition = "serial")
    private long id;

    @OneToMany
    @JoinTable(name = "USERS_CONTACTS",
            joinColumns = @JoinColumn(name = "USER_ID"),
            inverseJoinColumns = @JoinColumn(name = "CONTACT_ID"))
    private List<User> contacts;

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

Can you tell me how to fix it? I am using Postgre 9.5. Thanks.

EDIT

For hibernate I have these properties:

```<code>spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
</code>```

答:
Try to solve this task yourself.

Enable Hibernate SQL log

Create a database schema with Hibernate on a test database (a tablespace) or using H2 database. You can download this project and play with mappings using unit tests: https://github.com/v-ladynev/hibernate-experimental.

Check generated SQL.

Perhaps, you will notice that contact_id is made unique by uk_j9ggomsdbjte1eqfo5e61vh8a constraint. The reason is that for @OneToMany relation child must has only one parent.

I think you need @ManyToMany relation.

Body:
I need implement join table for users which will have 2 columns USER_CONTACTS(user_id, contact_id)

I need store for contacts lists for users. I need to make possible that user with id 1 can have in contacts user with id 5, but user 5 can also have in contacts user with id 1 (but he musn't).

I need to be possible do following inserts:

INSERT INTO USERS_CONTACTS(user_id, contact_id) VALUES(1, 5);
INSERT INTO USERS_CONTACTS(user_id, contact_id) VALUES(5, 1);

Now I got this error:

Unsuccessful: INSERT INTO USERS_CONTACTS(user_id, contact_id)
  VALUES(2, 3) 2017-12-05 15:00:15.146 ERROR 14268 --- [           main]
  org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: duplicate key value
  violates unique constraint "uk_j9ggomsdbjte1eqfo5e61vh8a"

Here is my relationship implementation of User in JPA:

@Entity
public class User{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", columnDefinition = "serial")
    private long id;

    @OneToMany
    @JoinTable(name = "USERS_CONTACTS",
            joinColumns = @JoinColumn(name = "USER_ID"),
            inverseJoinColumns = @JoinColumn(name = "CONTACT_ID"))
    private List<User> contacts;

   // ...
}

Can you tell me how to fix it? I am using Postgre 9.5. Thanks.

EDIT

For hibernate I have these properties:

spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl


问:
Regex capture all words in a line before the last 2
I have a bunch of line data I need to capture like so:

```<code>Level production data TD Index
Total Agriculture\Production data TS Index
</code>```

I need to capture everything before the last two words, for example in this case my regex output should be Level production data for the first match.  How can I do this while also assuming varying number of words before the TD Index. Thanks!

答:
Try this regex:

^.*(?=(?:\s+\S+){2}$)

Click for Demo

Explanation:

^ - asserts the start of the string

.* - matches 0+ occurrences of any character except a newline character

(?=(?:\s+\S+){2}$) - positive lookahead to validate that current position is followed by 2 words (1+ white space followed by 1+ occurrences of non-whitespace)X2 just before the end of the string

Body:
I have a bunch of line data I need to capture like so:

Level production data TD Index
Total Agriculture\Production data TS Index

I need to capture everything before the last two words, for example in this case my regex output should be Level production data for the first match.  How can I do this while also assuming varying number of words before the TD Index. Thanks!


问:
python spyder - debug only current cell or selection?
Similarly to these (very useful!) two functions:

"Run current cell"
"Run selection or current line"

Is it possible to do this with debugging? I dont want to start from the top of my large script files every time I debug.

I'm using Spyder version 3.2.4

答:
If you are using IPython as your interpreter, you can use the magic %pdb in IPython to automatically start pdb when an error is encountered.

Then you can "Run current cell" and break out into the debugger when you need to.

For example I have a simple script:

```<code>my_var = 4
raise ValueError
</code>```

Now, in the IPython terminal I first run %pdb, and then I run my script.

```<code>In [4]: my_var = 4
   ...: raise ValueError
Traceback (most recent call last):

  File "<ipython-input-4-31dc119cb1f3>", line 2, in <module>
    raise ValueError

ValueError

> <ipython-input-4-31dc119cb1f3>(2)<module>()
      1 my_var = 4
----> 2 raise ValueError

ipdb>
</code>```

and I have the debugger available.

Body:
If you are using IPython as your interpreter, you can use the magic %pdb in IPython to automatically start pdb when an error is encountered.

Then you can "Run current cell" and break out into the debugger when you need to.

For example I have a simple script:

my_var = 4
raise ValueError

Now, in the IPython terminal I first run %pdb, and then I run my script.

In [4]: my_var = 4
   ...: raise ValueError
Traceback (most recent call last):

  File "<ipython-input-4-31dc119cb1f3>", line 2, in <module>
    raise ValueError

ValueError

> <ipython-input-4-31dc119cb1f3>(2)<module>()
      1 my_var = 4
----> 2 raise ValueError

ipdb>

and I have the debugger available.


问:
Git_can't push locate update to remote branch successfully
```<code> $git log
 commit e9b08e2b428f9dd58aa0b792ebeb29da4270dfab (HEAD -> master)

 $git remote -v
 origin  https://github.com/Shell_learning (fetch)
 origin  https://github.com/Shell_learning (push)

 $git branch -a
 * master

 $git push -u origin master
 remote: Not Found
 fatal: repository 'https://github.com/Shell_learning/' not found

 $git remote add origin https://github.com/ekoopgj/Shell_learning
 fatal: remote origin already exists.
 #It is really strange that the repository already exists ,but I can't push my local update to remote branch.
</code>```

I have created a repository in my github like below:

So , please tell me what's the issue.

答:
you need to append .git to the repository address:

```<code> git remote set-url origin https://github.com/ekoopgj/Shell_learning.git
</code>```

Body:
 $git log
 commit e9b08e2b428f9dd58aa0b792ebeb29da4270dfab (HEAD -> master)

 $git remote -v
 origin  https://github.com/Shell_learning (fetch)
 origin  https://github.com/Shell_learning (push)

 $git branch -a
 * master

 $git push -u origin master
 remote: Not Found
 fatal: repository 'https://github.com/Shell_learning/' not found

 $git remote add origin https://github.com/ekoopgj/Shell_learning
 fatal: remote origin already exists.
 #It is really strange that the repository already exists ,but I can't push my local update to remote branch.

I have created a repository in my github like below:

So , please tell me what's the issue.

Body:
you need to append .git to the repository address:

 git remote set-url origin https://github.com/ekoopgj/Shell_learning.git