问:
Android Scroll Weighted Sum > 100%
In pure XML, I am creating a list of things which requires scrolling. I have a LinearLayout with a weighted sum of 3 and it contains four items inside of it. Altogether the items inside of the LinearLayout add up to 133% of their parents' height.

Trimmed down example:

```<code><LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:weightSum="3">

    <RelativeLayout android:layout_weight="1" />
    <RelativeLayout android:layout_weight="1" />
    <RelativeLayout android:layout_weight="1" />
    <RelativeLayout android:layout_weight="1" />

</LinearLayout>
</code>```

How can I use a ScrollView to bring the last item into view? Simply wrapping the LinearLayout in a scroller causes the layout to lose all concept of its height, causing its children's height to wrap_content, not stretch.

答:
Unless you can simply provide a constant height to each of the four inner views (instead of using weight), I don't believe there's any way to do what you want without resorting to Java code that adjusts the height of the inner views. This belief is based on two concepts:

First, in order to scroll, the contents of a ScrollView must be taller than the ScrollView itself. This means that you cannot use android:layout_height="match_parent" on the LinearLayout and also get scrolling.

Second, layout_weight only distributes excess space among child views. In other words, this attribute only takes effect when the child views' inherent dimensions are smaller than the parent's. This means that you cannot use android:layout_height="wrap_content" on the LinearLayout and also get weighted distribution of height.

That leaves setting a constant height as the only option.

If you're ok with using Java code to dynamically update the height of the child views, here's a template for doing so:

layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <View
            android:id="@+id/one"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="#caf"/>

        <View
            android:id="@+id/two"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="#fff"/>

        <View
            android:id="@+id/three"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="#fca"/>

        <View
            android:id="@+id/four"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="#afc"/>

    </LinearLayout>

</ScrollView>
</code>```

Java:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final View scrollingParent = findViewById(R.id.scroll);
    scrollingParent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int childHeight = scrollingParent.getHeight() / 3;
            setHeight(R.id.one, childHeight);
            setHeight(R.id.two, childHeight);
            setHeight(R.id.three, childHeight);
            setHeight(R.id.four, childHeight);
        }
    });
}

private void setHeight(int viewId, int height) {
    View v = findViewById(viewId);
    ViewGroup.LayoutParams params = v.getLayoutParams();
    params.height = height;
    v.setLayoutParams(params);
}
</code>```

The ViewTreeObserver.OnGlobalLayoutListener class and the associated addOnGlobalLayoutListener() call will wait until the scrolling parent is actually measured and laid out by the system, so that you have a real value for its height when you call scrollingParent.getHeight(). Then you just update the LayoutParams of each child view to have the height you want.

Title: Android Scroll Weighted Sum > 100%

Body:
In pure XML, I am creating a list of things which requires scrolling. I have a LinearLayout with a weighted sum of 3 and it contains four items inside of it. Altogether the items inside of the LinearLayout add up to 133% of their parents' height.

Trimmed down example:

<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:weightSum="3">

    <RelativeLayout android:layout_weight="1" />
    <RelativeLayout android:layout_weight="1" />
    <RelativeLayout android:layout_weight="1" />
    <RelativeLayout android:layout_weight="1" />

</LinearLayout>

How can I use a ScrollView to bring the last item into view? Simply wrapping the LinearLayout in a scroller causes the layout to lose all concept of its height, causing its children's height to wrap_content, not stretch.

Body:
Unless you can simply provide a constant height to each of the four inner views (instead of using weight), I don't believe there's any way to do what you want without resorting to Java code that adjusts the height of the inner views. This belief is based on two concepts:

First, in order to scroll, the contents of a ScrollView must be taller than the ScrollView itself. This means that you cannot use android:layout_height="match_parent" on the LinearLayout and also get scrolling.

Second, layout_weight only distributes excess space among child views. In other words, this attribute only takes effect when the child views' inherent dimensions are smaller than the parent's. This means that you cannot use android:layout_height="wrap_content" on the LinearLayout and also get weighted distribution of height.

That leaves setting a constant height as the only option.

If you're ok with using Java code to dynamically update the height of the child views, here's a template for doing so:

layout:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <View
            android:id="@+id/one"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="#caf"/>

        <View
            android:id="@+id/two"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="#fff"/>

        <View
            android:id="@+id/three"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="#fca"/>

        <View
            android:id="@+id/four"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="#afc"/>

    </LinearLayout>

</ScrollView>

Java:

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

    final View scrollingParent = findViewById(R.id.scroll);
    scrollingParent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int childHeight = scrollingParent.getHeight() / 3;
            setHeight(R.id.one, childHeight);
            setHeight(R.id.two, childHeight);
            setHeight(R.id.three, childHeight);
            setHeight(R.id.four, childHeight);
        }
    });
}

private void setHeight(int viewId, int height) {
    View v = findViewById(viewId);
    ViewGroup.LayoutParams params = v.getLayoutParams();
    params.height = height;
    v.setLayoutParams(params);
}

The ViewTreeObserver.OnGlobalLayoutListener class and the associated addOnGlobalLayoutListener() call will wait until the scrolling parent is actually measured and laid out by the system, so that you have a real value for its height when you call scrollingParent.getHeight(). Then you just update the LayoutParams of each child view to have the height you want.


来源: stackexchange

问:
Signer information does not match
I'm receiving the following error on log file.

(java.lang.SecurityException: class
"com.adventnet.snmp.snmp2.SecurityModelTable"'s  signer information
does not match signer information of other classes in the same
package thrown

The thing is when I run the below command, it says the jar is verified.

```<code>/usr/jdk/instances/jdk1.5.0/bin/jarsigner -verify -verbose Jarfile.jar
</code>```

If the jar file is verified then how can this problem occur?

答:
In my case I had:

```<code>Caused by: java.lang.SecurityException: class "org.bouncycastle.util.Strings"'s signer information does not match signer information of other classes in the same package
</code>```

It was a project with a lot of dependencies and the mvn dependency:tree information did not really helped me.

Here is how I solved my issue:

I did a search "Find in files" using notepad++ on all the M2_REPO

I found a project which redefined "Strings" class in a package exactly identical to "org.bouncycastle.util.Strings" which should originate from the "org.bouncycastle:bcprov-jdk15on" dependency.

Once found, I moved all of these problematic classes in a new package and updated this project version.

Finally I updated the pom of the project which caused me trouble in the first place to use my dependency that uses the new package name.

Problem solved.

ContentLicense: CC BY-SA 4.0

Title: Signer information does not match

Body:
I'm receiving the following error on log file.

(java.lang.SecurityException: class
"com.adventnet.snmp.snmp2.SecurityModelTable"'s  signer information
does not match signer information of other classes in the same
package thrown

The thing is when I run the below command, it says the jar is verified.

/usr/jdk/instances/jdk1.5.0/bin/jarsigner -verify -verbose Jarfile.jar

If the jar file is verified then how can this problem occur?

Body:
In my case I had:

Caused by: java.lang.SecurityException: class "org.bouncycastle.util.Strings"'s signer information does not match signer information of other classes in the same package

It was a project with a lot of dependencies and the mvn dependency:tree information did not really helped me.

Here is how I solved my issue:

I did a search "Find in files" using notepad++ on all the M2_REPO

I found a project which redefined "Strings" class in a package exactly identical to "org.bouncycastle.util.Strings" which should originate from the "org.bouncycastle:bcprov-jdk15on" dependency.

Once found, I moved all of these problematic classes in a new package and updated this project version.

Finally I updated the pom of the project which caused me trouble in the first place to use my dependency that uses the new package name.

Problem solved.

ContentLicense: CC BY-SA 3.0


问:
select distinct id when using left join and order by on two tables
I have two tables and I am going to get distinct id from first one based on a  complex order by clauses on both tables. I'm confused how to use distinct or groub by because both of them prevent using order by on other columns.

My code using distinct:

```<code>select distinct(shops.id) from shops
left join expiration on shops.id=expiration.shopid
order by
  shops.grade desc,
  expiration.startdate asc,
  expiration.enddate desc,
  shops.id
</code>```

ORDER BY items must appear in the select list if SELECT DISTINCT is
  specified

My code using group by:

```<code>select max(shops.id) as shopid from shops
left join expiration on shops.id=expiration.shopid
group by shopid
order by
  shops.grade desc,
  expiration.startdate asc,
  expiration.enddate desc,
  shops.id
</code>```

Column "shops.grade" is invalid in the ORDER BY clause because it is
  not contained in either an aggregate function or the GROUP BY clause.

答:
If I understand correctly, you have a prioritization query.  If so, you can handle it with row_number() not select distinct or group by:

```<code>select se.shopid
from (select s.id as shopid,
             row_number() over (partition by s.id
                                order by s.grade desc, e.startdate asc, e.enddate desc, s.id
                               ) as seqnum
      from shops s left join
           expiration e
           on s.id = e.shopid
     ) se
where seqnum = 1;
</code>```

Body:
I have two tables and I am going to get distinct id from first one based on a  complex order by clauses on both tables. I'm confused how to use distinct or groub by because both of them prevent using order by on other columns.

My code using distinct:

select distinct(shops.id) from shops
left join expiration on shops.id=expiration.shopid
order by
  shops.grade desc,
  expiration.startdate asc,
  expiration.enddate desc,
  shops.id

ORDER BY items must appear in the select list if SELECT DISTINCT is
  specified

My code using group by:

select max(shops.id) as shopid from shops
left join expiration on shops.id=expiration.shopid
group by shopid
order by
  shops.grade desc,
  expiration.startdate asc,
  expiration.enddate desc,
  shops.id

Column "shops.grade" is invalid in the ORDER BY clause because it is
  not contained in either an aggregate function or the GROUP BY clause.

Body:
If I understand correctly, you have a prioritization query.  If so, you can handle it with row_number() not select distinct or group by:

select se.shopid
from (select s.id as shopid,
             row_number() over (partition by s.id
                                order by s.grade desc, e.startdate asc, e.enddate desc, s.id
                               ) as seqnum
      from shops s left join
           expiration e
           on s.id = e.shopid
     ) se
where seqnum = 1;


问:
can't get returned values in a structure in swift 3
I'm having this code:

```<code>//
//  Measurement.swift
//  BicycleSpeed

    import Foundation
    import CoreBluetooth

    // CSC Measurement
    // https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.csc_measurement.xml
    //
    //  Flags : 1 byte.  Bit 0: Wheel. Bit 1: Crank
    //  Cumulative Wheel revolutions: 4 bytes uint32
    //  Last wheel event time: 2 bytes. uint16 (1/1024s)
    //  Cumulative Crank revolutions: 2 bytes uint16
    //  Last cranck event time: 2 bytes. uint16 (1/1024s)

    struct Measurement : CustomDebugStringConvertible {

      let hasWheel:Bool
      let hasCrank:Bool
      let cumulativeWheel:UInt32
      let lastWheelEventTime:TimeInterval
      let cumulativeCrank:UInt16
      let lastCrankEventTime:TimeInterval
      let wheelSize:UInt32

      init(data:Data, wheelSize:UInt32) {

        self.wheelSize = wheelSize
        // Flags
        var flags:UInt8=0
        (data as NSData).getBytes(&flags, range: NSRange(location: 0, length: 1))

        hasWheel = ((flags & BTConstants.WheelFlagMask) > 0)
        hasCrank = ((flags & BTConstants.CrankFlagMask) > 0)

        var wheel:UInt32=0
        var wheelTime:UInt16=0
        var crank:UInt16=0
        var crankTime:UInt16=0

        var currentOffset = 1
        var length = 0

        if ( hasWheel ) {

          length = MemoryLayout<UInt32>.size
          (data as NSData).getBytes(&wheel, range: NSRange(location: currentOffset, length: length))
          currentOffset += length

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&wheelTime, range: NSRange(location: currentOffset, length: length))
          currentOffset += length
        }

        if ( hasCrank ) {

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&crank, range: NSRange(location: currentOffset, length: length))
          currentOffset += length

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&crankTime, range: NSRange(location: currentOffset, length: length))
          currentOffset += length
        }

        cumulativeWheel     = CFSwapInt32LittleToHost(wheel)
        lastWheelEventTime  = TimeInterval( Double(CFSwapInt16LittleToHost(wheelTime))/BTConstants.TimeScale)
        cumulativeCrank     = CFSwapInt16LittleToHost(crank)
        lastCrankEventTime  = TimeInterval( Double(CFSwapInt16LittleToHost(crankTime))/BTConstants.TimeScale)

      }

      func timeIntervalForCurrentSample( _ current:TimeInterval, previous:TimeInterval ) -> TimeInterval {
        var timeDiff:TimeInterval = 0
        if( current >= previous ) {
            timeDiff = current - previous
        }
        else {
          // passed the maximum value
          timeDiff =  ( TimeInterval((Double( UINT16_MAX) / BTConstants.TimeScale)) - previous) + current
        }
        return timeDiff

      }

      func valueDiffForCurrentSample<T:UnsignedInteger>( _ current:T, previous:T , max:T) -> T {

        var diff:T = 0
        if  ( current >= previous ) {
          diff = current - previous
        }
        else {
           diff = ( max - previous ) + current
        }
        return diff
      }

      func valuesForPreviousMeasurement( _ previousSample:Measurement? ) -> ( cadenceinRPM:Double?, distanceinMeters:Double?, speedInMetersPerSecond:Double?)? {

        var distance:Double?, cadence:Double?, speed:Double?
        guard let previousSample = previousSample else {
          return nil
        }
        if ( hasWheel && previousSample.hasWheel ) {
          let wheelTimeDiff = timeIntervalForCurrentSample(lastWheelEventTime, previous: previousSample.lastWheelEventTime)
          let valueDiff = valueDiffForCurrentSample(cumulativeWheel, previous: previousSample.cumulativeWheel, max: UInt32.max)

          distance = Double( valueDiff * wheelSize) / 1000.0 // distance in meters
          if  distance != nil  &&  wheelTimeDiff > 0 {
            speed = (wheelTimeDiff == 0 ) ? 0 : distance! / wheelTimeDiff // m/s
          }
        }

        if( hasCrank && previousSample.hasCrank ) {
          let crankDiffTime = timeIntervalForCurrentSample(lastCrankEventTime, previous: previousSample.lastCrankEventTime)
          let valueDiff = Double(valueDiffForCurrentSample(cumulativeCrank, previous: previousSample.cumulativeCrank, max: UInt16.max))

          cadence = (crankDiffTime == 0) ? 0 : Double(60.0 * valueDiff / crankDiffTime) // RPM

        }
        print( "Cadence: \(String(describing: cadence)) RPM. Distance: \(String(describing: distance)) meters. Speed: \(String(describing: speed)) Km/h" )
        return ( cadenceinRPM:cadence, distanceinMeters:distance, speedInMetersPerSecond:speed)

      }

      var debugDescription:String {
        get {
            return "Wheel Revs: \(cumulativeWheel). Last wheel event time: \(lastWheelEventTime). Crank Revs: \(cumulativeCrank). Last Crank event time: \(lastCrankEventTime)"
        }
      }

        var myMeasurement = ((Measurement?) -> (cadenceinRPM: Double?, DistanceinMeters: Double?, speedinMetersPerSecond: Double?)).self

        struct dataVariables {

            static var mySpeed = myMeasurement.speedInMetersPerSecond

            static var myCadence : Double?
            static var miDistance : Double?

            static var myLastWheelEventTime : Double? = Measurement.valuesForPreviousMeasurement(lastWheelEventTime)

            static var myLastCrankEventTime : Double? = Measurement.valuesForPreviousMeasurement(lastCrankEventTime)

        }
    }

    }
</code>```

and I'm trying to assign to static variables inside the struct dataVariables the returned values cadenceinRPM,distanceinMeters,speedinMetersPerSecond

as well as lastWheelEventTime and lastCrankEventTime, so I can access them in another class, but I'm having the following errors:
on var mySpeed : Instance member'myMeasurement' cannot be used on type 'Measurement'
on var myLastWheelEventTime and var myLastCrankEventTime : Instance member 'valuesForPreviousMeasurement' cannot be used on type 'Measurement' ; did you mean to use a value of this type instead?
how can a reference to those returned values than?
Can somebody explain the error? I searched for other similar questions but I'm not getting to a solution yet
I have tried to change var myVariable to

```<code>var myMeasurement = Measurement.self
</code>```

but the errors stayed the same.

and this other code

```<code>    //
//  CadenceSensor.swift

import Foundation
import CoreBluetooth

/*
 // Bluetooth  "Cycling Speed and Cadence"
 https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.cycling_speed_and_cadence.xml

 Service Cycling Speed and Cadence. Characteristic [2A5B]  // Measurement
 Service Cycling Speed and Cadence. Characteristic [2A5C]  // Supported Features
 Service Cycling Speed and Cadence. Characteristic [2A5D]  // Sensor location
 Service Cycling Speed and Cadence. Characteristic [2A55]  // Control Point

 */

public struct BTConstants {
    static let CadenceService         = "1816"
    static let CSCMeasurementUUID     = "2a5b"
    static let CSCFeatureUUID         = "2a5c"
    static let SensorLocationUUID     = "2a5d"
    static let ControlPointUUID       = "2a55"
    static let WheelFlagMask:UInt8    = 0b01
    static let CrankFlagMask:UInt8    = 0b10
    static let DefaultWheelSize:UInt32   = UInt32(myVariables.circonferenzaRuota!)  // In millimiters. 700x30 (by default my bike's wheels) :)
    static let TimeScale              = 1024.0
}

protocol CadenceSensorDelegate {

    func errorDiscoveringSensorInformation(_ error:NSError)
    func sensorReady()
    func sensorUpdatedValues( speedInMetersPerSecond speed:Double?, cadenceInRpm cadence:Double?, distanceInMeters distance:Double? )
}

class CadenceSensor: NSObject {

    let peripheral:CBPeripheral
    var sensorDelegate:CadenceSensorDelegate?
    var measurementCharasteristic:CBCharacteristic?
    var lastMeasurement:Measurement?
    let wheelCircunference:UInt32

    init(peripheral:CBPeripheral , wheel:UInt32=BTConstants.DefaultWheelSize) {
        self.peripheral = peripheral
        wheelCircunference = wheel
    }

    func start() {
        self.peripheral.discoverServices(nil)
        self.peripheral.delegate = self
    }

    func stop() {
        if let measurementCharasteristic = measurementCharasteristic {
            peripheral.setNotifyValue(false, for: measurementCharasteristic)
        }

    }

    func handleValueData( _ data:Data ) {

        let measurement = Measurement(data: data, wheelSize: wheelCircunference)
        print("\(measurement)")

        let values = measurement.valuesForPreviousMeasurement(lastMeasurement)
        lastMeasurement = measurement

        sensorDelegate?.sensorUpdatedValues(speedInMetersPerSecond: values?.speedInMetersPerSecond, cadenceInRpm: values?.cadenceinRPM, distanceInMeters: values?.distanceinMeters)
    }
}

extension CadenceSensor : CBPeripheralDelegate {

    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil else {
            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("Error receiving measurements updates", comment:"")]))

            return
        }
        print("notification status changed for [\(characteristic.uuid)]...")
    }

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

        print("Updated [\(characteristic.uuid)]...")

        guard error == nil  , let data = characteristic.value  else {

            return
        }

        handleValueData(data)

    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard error == nil  else {
            sensorDelegate?.errorDiscoveringSensorInformation(error! as NSError)
            return
        }
        // Find the cadence service
        guard let cadenceService =  peripheral.services?.filter({ (service) -> Bool in
            return service.uuid == CBUUID(string: BTConstants.CadenceService)
        }).first else {

            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: NSNotFound, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("Cadence service not found for this peripheral", comment:"")]))
            return
        }
        // Discover the cadence service characteristics
        peripheral.discoverCharacteristics(nil, for:cadenceService )
        print("Cadence service discovered")

    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

        guard let characteristics = service.characteristics else {
            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: NSNotFound, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("No characteristics found for the cadence service", comment:"")]))
            return

        }

        print("Received characteristics");

        // Enable notifications for the measurement characteristic
        for characteristic in characteristics {

            print("Service \(service.uuid). Characteristic [\(characteristic.uuid)]")

            if characteristic.uuid == CBUUID(string: BTConstants.CSCMeasurementUUID) {

                print("Found measurement characteristic. Subscribing...")
                peripheral.setNotifyValue(true, for: characteristic)
                measurementCharasteristic  = characteristic

            }
        }
        sensorDelegate?.sensorReady()

    }

}
</code>```

and this other code

```<code>    //
//  MainViewController.swift
//  BicycleSpeed

import UIKit
import CoreBluetooth

class MainViewController: UIViewController {

  struct Constants {

    static let ScanSegue = "ScanSegue"
    static let SensorUserDefaultsKey = "lastsensorused"
  }

  var bluetoothManager:BluetoothManager!
  var sensor:CadenceSensor?
  weak var scanViewController:ScanViewController?
  var infoViewController:InfoTableViewController?
  var accumulatedDistance:Double?

  lazy var distanceFormatter:LengthFormatter = {

    let formatter = LengthFormatter()
    formatter.numberFormatter.maximumFractionDigits = 1

    return formatter
  }()

  //@IBOutlet var labelBTStatus:UILabel!
  @IBOutlet var scanItem:UIBarButtonItem!
  @IBOutlet weak var idLabel: UILabel!

  override func viewDidLoad() {

      bluetoothManager = BluetoothManager()
      bluetoothManager.bluetoothDelegate = self
      scanItem.isEnabled = false

  }

  deinit {
    disconnectSensor()
  }

  @IBAction func unwindSegue( _ segue:UIStoryboardSegue ) {
      bluetoothManager.stopScan()
    guard let sensor = (segue as? ScanUnwindSegue)?.sensor else {
      return
    }
    print("Need to connect to sensor \(sensor.peripheral.identifier)")
    connectToSensor(sensor)

  }

  func disconnectSensor( ) {
    if sensor != nil  {
      bluetoothManager.disconnectSensor(sensor!)
      sensor = nil
    }
    accumulatedDistance = nil
  }

  func connectToSensor(_ sensor:CadenceSensor) {

    self.sensor  = sensor
    bluetoothManager.connectToSensor(sensor)
    // Save the sensor ID
    UserDefaults.standard.set(sensor.peripheral.identifier.uuidString, forKey: Constants.SensorUserDefaultsKey)
    UserDefaults.standard.synchronize()

  }
  // TODO: REconnect. Try this every X seconds
  func checkPreviousSensor() {

    guard let sensorID = UserDefaults.standard.object(forKey: Constants.SensorUserDefaultsKey)  as? String else {
      return
    }
    guard let sensor = bluetoothManager.retrieveSensorWithIdentifier(sensorID) else {
      return
    }
    self.sensor = sensor
    connectToSensor(sensor)

  }

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let infoVC = segue.destination as? InfoTableViewController {
        infoViewController = infoVC
    }
    if segue.identifier == Constants.ScanSegue {

        // Scan segue
      bluetoothManager.startScan()
      scanViewController  = (segue.destination as? UINavigationController)?.viewControllers.first as? ScanViewController
    }

  }

}

extension MainViewController : CadenceSensorDelegate {

  func errorDiscoveringSensorInformation(_ error: NSError) {
      print("An error ocurred disconvering the sensor services/characteristics: \(error)")
  }

  func sensorReady() {
    print("Sensor ready to go...")
    accumulatedDistance = 0.0
  }

  func updateSensorInfo() {
    let name = sensor?.peripheral.name ?? ""
    let uuid = sensor?.peripheral.identifier.uuidString ?? ""

    OperationQueue.main.addOperation { () -> Void in
      self.infoViewController?.showDeviceName(name , uuid:uuid )
    }
  }

  func sensorUpdatedValues( speedInMetersPerSecond speed:Double?, cadenceInRpm cadence:Double?, distanceInMeters distance:Double? ) {

    accumulatedDistance? += distance ?? 0
    let distanceText = (accumulatedDistance != nil && accumulatedDistance! >= 1.0) ? distanceFormatter.string(fromMeters: accumulatedDistance!) : "N/A"
    let speedText = (speed != nil) ? distanceFormatter.string(fromValue: speed!*3.6, unit: .kilometer) + NSLocalizedString("/h", comment:"(km) Per hour") : "N/A"
    let cadenceText = (cadence != nil) ? String(format: "%.2f %@",  cadence!, NSLocalizedString("RPM", comment:"Revs per minute") ) : "N/A"

    OperationQueue.main.addOperation { () -> Void in

      self.infoViewController?.showMeasurementWithSpeed(speedText , cadence: cadenceText, distance: distanceText )
    }
  }

}

extension MainViewController : BluetoothManagerDelegate {

  func stateChanged(_ state: CBCentralManagerState) {
    print("State Changed: \(state)")
    var enabled = false
    var title = ""
    switch state {
    case .poweredOn:
        title = "Bluetooth ON"
        enabled = true
        // When the bluetooth changes to ON, try to reconnect to the previous sensor
        checkPreviousSensor()

    case .resetting:
        title = "Reseeting"
    case .poweredOff:
      title = "Bluetooth Off"
    case .unauthorized:
      title = "Bluetooth not authorized"
    case .unknown:
      title = "Unknown"
    case .unsupported:
      title = "Bluetooth not supported"
    }
    infoViewController?.showBluetoothStatusText( title )
    scanItem.isEnabled = enabled
  }

  func sensorConnection( _ sensor:CadenceSensor, error:NSError?) {
      print("")
    guard error == nil else {
      self.sensor = nil
      print("Error connecting to sensor: \(sensor.peripheral.identifier)")
      updateSensorInfo()
      accumulatedDistance = nil
      return
    }
    self.sensor = sensor
    self.sensor?.sensorDelegate = self
    print("Sensor connected. \(String(describing: sensor.peripheral.name)). [\(sensor.peripheral.identifier)]")
    updateSensorInfo()

    sensor.start()
  }

  func sensorDisconnected( _ sensor:CadenceSensor, error:NSError?) {
    print("Sensor disconnected")
    self.sensor = nil
  }

  func sensorDiscovered( _ sensor:CadenceSensor ) {
      scanViewController?.addSensor(sensor)
  }

}
</code>```

in MainViewController.swift, there is this func sensorUpdatedValues that converts the three values that I want, to strings and initialize the the func showMeasurementWithSpeed ins the InfoTableViewController.swift .

Could I just return the three values inside function sensorUpdateValues  instead to be able to store them into  new variables?

答:
I believe it's because you have that func declared as an instance level function rather than a class/struct level function.  You should be able to simply add the "static" keyword to make it accessible for the way you are using it in your sample code.  i.e. "static func valuesForPreviousMeasurement ..."

** UPDATE - Added a simple example to show the difference between class and instance functions.

```<code>// This is an instance function being used.  It's called such because
// you need an actual object instance in order to call the func.
var myCar: Car = Car()
myCar.startEngine()

// This is a class level function being used.  It's called such because
// you don't actually need an object instance: It's simply part of the class.
Car.PriceForModel("HondaCivic")
</code>```

Body:
I'm having this code:

//
//  Measurement.swift
//  BicycleSpeed

    import Foundation
    import CoreBluetooth

    // CSC Measurement
    // https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.csc_measurement.xml
    //
    //  Flags : 1 byte.  Bit 0: Wheel. Bit 1: Crank
    //  Cumulative Wheel revolutions: 4 bytes uint32
    //  Last wheel event time: 2 bytes. uint16 (1/1024s)
    //  Cumulative Crank revolutions: 2 bytes uint16
    //  Last cranck event time: 2 bytes. uint16 (1/1024s)

    struct Measurement : CustomDebugStringConvertible {

      let hasWheel:Bool
      let hasCrank:Bool
      let cumulativeWheel:UInt32
      let lastWheelEventTime:TimeInterval
      let cumulativeCrank:UInt16
      let lastCrankEventTime:TimeInterval
      let wheelSize:UInt32

      init(data:Data, wheelSize:UInt32) {

        self.wheelSize = wheelSize
        // Flags
        var flags:UInt8=0
        (data as NSData).getBytes(&flags, range: NSRange(location: 0, length: 1))

        hasWheel = ((flags & BTConstants.WheelFlagMask) > 0)
        hasCrank = ((flags & BTConstants.CrankFlagMask) > 0)

        var wheel:UInt32=0
        var wheelTime:UInt16=0
        var crank:UInt16=0
        var crankTime:UInt16=0

        var currentOffset = 1
        var length = 0

        if ( hasWheel ) {

          length = MemoryLayout<UInt32>.size
          (data as NSData).getBytes(&wheel, range: NSRange(location: currentOffset, length: length))
          currentOffset += length

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&wheelTime, range: NSRange(location: currentOffset, length: length))
          currentOffset += length
        }

        if ( hasCrank ) {

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&crank, range: NSRange(location: currentOffset, length: length))
          currentOffset += length

          length = MemoryLayout<UInt16>.size
          (data as NSData).getBytes(&crankTime, range: NSRange(location: currentOffset, length: length))
          currentOffset += length
        }

        cumulativeWheel     = CFSwapInt32LittleToHost(wheel)
        lastWheelEventTime  = TimeInterval( Double(CFSwapInt16LittleToHost(wheelTime))/BTConstants.TimeScale)
        cumulativeCrank     = CFSwapInt16LittleToHost(crank)
        lastCrankEventTime  = TimeInterval( Double(CFSwapInt16LittleToHost(crankTime))/BTConstants.TimeScale)

      }

      func timeIntervalForCurrentSample( _ current:TimeInterval, previous:TimeInterval ) -> TimeInterval {
        var timeDiff:TimeInterval = 0
        if( current >= previous ) {
            timeDiff = current - previous
        }
        else {
          // passed the maximum value
          timeDiff =  ( TimeInterval((Double( UINT16_MAX) / BTConstants.TimeScale)) - previous) + current
        }
        return timeDiff

      }

      func valueDiffForCurrentSample<T:UnsignedInteger>( _ current:T, previous:T , max:T) -> T {

        var diff:T = 0
        if  ( current >= previous ) {
          diff = current - previous
        }
        else {
           diff = ( max - previous ) + current
        }
        return diff
      }

      func valuesForPreviousMeasurement( _ previousSample:Measurement? ) -> ( cadenceinRPM:Double?, distanceinMeters:Double?, speedInMetersPerSecond:Double?)? {

        var distance:Double?, cadence:Double?, speed:Double?
        guard let previousSample = previousSample else {
          return nil
        }
        if ( hasWheel && previousSample.hasWheel ) {
          let wheelTimeDiff = timeIntervalForCurrentSample(lastWheelEventTime, previous: previousSample.lastWheelEventTime)
          let valueDiff = valueDiffForCurrentSample(cumulativeWheel, previous: previousSample.cumulativeWheel, max: UInt32.max)

          distance = Double( valueDiff * wheelSize) / 1000.0 // distance in meters
          if  distance != nil  &&  wheelTimeDiff > 0 {
            speed = (wheelTimeDiff == 0 ) ? 0 : distance! / wheelTimeDiff // m/s
          }
        }

        if( hasCrank && previousSample.hasCrank ) {
          let crankDiffTime = timeIntervalForCurrentSample(lastCrankEventTime, previous: previousSample.lastCrankEventTime)
          let valueDiff = Double(valueDiffForCurrentSample(cumulativeCrank, previous: previousSample.cumulativeCrank, max: UInt16.max))

          cadence = (crankDiffTime == 0) ? 0 : Double(60.0 * valueDiff / crankDiffTime) // RPM

        }
        print( "Cadence: \(String(describing: cadence)) RPM. Distance: \(String(describing: distance)) meters. Speed: \(String(describing: speed)) Km/h" )
        return ( cadenceinRPM:cadence, distanceinMeters:distance, speedInMetersPerSecond:speed)

      }

      var debugDescription:String {
        get {
            return "Wheel Revs: \(cumulativeWheel). Last wheel event time: \(lastWheelEventTime). Crank Revs: \(cumulativeCrank). Last Crank event time: \(lastCrankEventTime)"
        }
      }

        var myMeasurement = ((Measurement?) -> (cadenceinRPM: Double?, DistanceinMeters: Double?, speedinMetersPerSecond: Double?)).self

        struct dataVariables {

            static var mySpeed = myMeasurement.speedInMetersPerSecond

            static var myCadence : Double?
            static var miDistance : Double?

            static var myLastWheelEventTime : Double? = Measurement.valuesForPreviousMeasurement(lastWheelEventTime)

            static var myLastCrankEventTime : Double? = Measurement.valuesForPreviousMeasurement(lastCrankEventTime)

        }
    }

    }

and I'm trying to assign to static variables inside the struct dataVariables the returned values cadenceinRPM,distanceinMeters,speedinMetersPerSecond

as well as lastWheelEventTime and lastCrankEventTime, so I can access them in another class, but I'm having the following errors:
on var mySpeed : Instance member'myMeasurement' cannot be used on type 'Measurement'
on var myLastWheelEventTime and var myLastCrankEventTime : Instance member 'valuesForPreviousMeasurement' cannot be used on type 'Measurement' ; did you mean to use a value of this type instead?
how can a reference to those returned values than?
Can somebody explain the error? I searched for other similar questions but I'm not getting to a solution yet
I have tried to change var myVariable to

var myMeasurement = Measurement.self

but the errors stayed the same.

and this other code

    //
//  CadenceSensor.swift

import Foundation
import CoreBluetooth

/*
 // Bluetooth  "Cycling Speed and Cadence"
 https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.cycling_speed_and_cadence.xml

 Service Cycling Speed and Cadence. Characteristic [2A5B]  // Measurement
 Service Cycling Speed and Cadence. Characteristic [2A5C]  // Supported Features
 Service Cycling Speed and Cadence. Characteristic [2A5D]  // Sensor location
 Service Cycling Speed and Cadence. Characteristic [2A55]  // Control Point

 */

public struct BTConstants {
    static let CadenceService         = "1816"
    static let CSCMeasurementUUID     = "2a5b"
    static let CSCFeatureUUID         = "2a5c"
    static let SensorLocationUUID     = "2a5d"
    static let ControlPointUUID       = "2a55"
    static let WheelFlagMask:UInt8    = 0b01
    static let CrankFlagMask:UInt8    = 0b10
    static let DefaultWheelSize:UInt32   = UInt32(myVariables.circonferenzaRuota!)  // In millimiters. 700x30 (by default my bike's wheels) :)
    static let TimeScale              = 1024.0
}

protocol CadenceSensorDelegate {

    func errorDiscoveringSensorInformation(_ error:NSError)
    func sensorReady()
    func sensorUpdatedValues( speedInMetersPerSecond speed:Double?, cadenceInRpm cadence:Double?, distanceInMeters distance:Double? )
}

class CadenceSensor: NSObject {

    let peripheral:CBPeripheral
    var sensorDelegate:CadenceSensorDelegate?
    var measurementCharasteristic:CBCharacteristic?
    var lastMeasurement:Measurement?
    let wheelCircunference:UInt32

    init(peripheral:CBPeripheral , wheel:UInt32=BTConstants.DefaultWheelSize) {
        self.peripheral = peripheral
        wheelCircunference = wheel
    }

    func start() {
        self.peripheral.discoverServices(nil)
        self.peripheral.delegate = self
    }

    func stop() {
        if let measurementCharasteristic = measurementCharasteristic {
            peripheral.setNotifyValue(false, for: measurementCharasteristic)
        }

    }

    func handleValueData( _ data:Data ) {

        let measurement = Measurement(data: data, wheelSize: wheelCircunference)
        print("\(measurement)")

        let values = measurement.valuesForPreviousMeasurement(lastMeasurement)
        lastMeasurement = measurement

        sensorDelegate?.sensorUpdatedValues(speedInMetersPerSecond: values?.speedInMetersPerSecond, cadenceInRpm: values?.cadenceinRPM, distanceInMeters: values?.distanceinMeters)
    }
}

extension CadenceSensor : CBPeripheralDelegate {

    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil else {
            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("Error receiving measurements updates", comment:"")]))

            return
        }
        print("notification status changed for [\(characteristic.uuid)]...")
    }

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

        print("Updated [\(characteristic.uuid)]...")

        guard error == nil  , let data = characteristic.value  else {

            return
        }

        handleValueData(data)

    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard error == nil  else {
            sensorDelegate?.errorDiscoveringSensorInformation(error! as NSError)
            return
        }
        // Find the cadence service
        guard let cadenceService =  peripheral.services?.filter({ (service) -> Bool in
            return service.uuid == CBUUID(string: BTConstants.CadenceService)
        }).first else {

            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: NSNotFound, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("Cadence service not found for this peripheral", comment:"")]))
            return
        }
        // Discover the cadence service characteristics
        peripheral.discoverCharacteristics(nil, for:cadenceService )
        print("Cadence service discovered")

    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

        guard let characteristics = service.characteristics else {
            sensorDelegate?.errorDiscoveringSensorInformation(NSError(domain: CBErrorDomain, code: NSNotFound, userInfo: [NSLocalizedDescriptionKey:NSLocalizedString("No characteristics found for the cadence service", comment:"")]))
            return

        }

        print("Received characteristics");

        // Enable notifications for the measurement characteristic
        for characteristic in characteristics {

            print("Service \(service.uuid). Characteristic [\(characteristic.uuid)]")

            if characteristic.uuid == CBUUID(string: BTConstants.CSCMeasurementUUID) {

                print("Found measurement characteristic. Subscribing...")
                peripheral.setNotifyValue(true, for: characteristic)
                measurementCharasteristic  = characteristic

            }
        }
        sensorDelegate?.sensorReady()

    }

}

and this other code

    //
//  MainViewController.swift
//  BicycleSpeed

import UIKit
import CoreBluetooth

class MainViewController: UIViewController {

  struct Constants {

    static let ScanSegue = "ScanSegue"
    static let SensorUserDefaultsKey = "lastsensorused"
  }

  var bluetoothManager:BluetoothManager!
  var sensor:CadenceSensor?
  weak var scanViewController:ScanViewController?
  var infoViewController:InfoTableViewController?
  var accumulatedDistance:Double?

  lazy var distanceFormatter:LengthFormatter = {

    let formatter = LengthFormatter()
    formatter.numberFormatter.maximumFractionDigits = 1

    return formatter
  }()

  //@IBOutlet var labelBTStatus:UILabel!
  @IBOutlet var scanItem:UIBarButtonItem!
  @IBOutlet weak var idLabel: UILabel!

  override func viewDidLoad() {

      bluetoothManager = BluetoothManager()
      bluetoothManager.bluetoothDelegate = self
      scanItem.isEnabled = false

  }

  deinit {
    disconnectSensor()
  }

  @IBAction func unwindSegue( _ segue:UIStoryboardSegue ) {
      bluetoothManager.stopScan()
    guard let sensor = (segue as? ScanUnwindSegue)?.sensor else {
      return
    }
    print("Need to connect to sensor \(sensor.peripheral.identifier)")
    connectToSensor(sensor)

  }

  func disconnectSensor( ) {
    if sensor != nil  {
      bluetoothManager.disconnectSensor(sensor!)
      sensor = nil
    }
    accumulatedDistance = nil
  }

  func connectToSensor(_ sensor:CadenceSensor) {

    self.sensor  = sensor
    bluetoothManager.connectToSensor(sensor)
    // Save the sensor ID
    UserDefaults.standard.set(sensor.peripheral.identifier.uuidString, forKey: Constants.SensorUserDefaultsKey)
    UserDefaults.standard.synchronize()

  }
  // TODO: REconnect. Try this every X seconds
  func checkPreviousSensor() {

    guard let sensorID = UserDefaults.standard.object(forKey: Constants.SensorUserDefaultsKey)  as? String else {
      return
    }
    guard let sensor = bluetoothManager.retrieveSensorWithIdentifier(sensorID) else {
      return
    }
    self.sensor = sensor
    connectToSensor(sensor)

  }

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let infoVC = segue.destination as? InfoTableViewController {
        infoViewController = infoVC
    }
    if segue.identifier == Constants.ScanSegue {

        // Scan segue
      bluetoothManager.startScan()
      scanViewController  = (segue.destination as? UINavigationController)?.viewControllers.first as? ScanViewController
    }

  }

}

extension MainViewController : CadenceSensorDelegate {

  func errorDiscoveringSensorInformation(_ error: NSError) {
      print("An error ocurred disconvering the sensor services/characteristics: \(error)")
  }

  func sensorReady() {
    print("Sensor ready to go...")
    accumulatedDistance = 0.0
  }

  func updateSensorInfo() {
    let name = sensor?.peripheral.name ?? ""
    let uuid = sensor?.peripheral.identifier.uuidString ?? ""

    OperationQueue.main.addOperation { () -> Void in
      self.infoViewController?.showDeviceName(name , uuid:uuid )
    }
  }

  func sensorUpdatedValues( speedInMetersPerSecond speed:Double?, cadenceInRpm cadence:Double?, distanceInMeters distance:Double? ) {

    accumulatedDistance? += distance ?? 0
    let distanceText = (accumulatedDistance != nil && accumulatedDistance! >= 1.0) ? distanceFormatter.string(fromMeters: accumulatedDistance!) : "N/A"
    let speedText = (speed != nil) ? distanceFormatter.string(fromValue: speed!*3.6, unit: .kilometer) + NSLocalizedString("/h", comment:"(km) Per hour") : "N/A"
    let cadenceText = (cadence != nil) ? String(format: "%.2f %@",  cadence!, NSLocalizedString("RPM", comment:"Revs per minute") ) : "N/A"

    OperationQueue.main.addOperation { () -> Void in

      self.infoViewController?.showMeasurementWithSpeed(speedText , cadence: cadenceText, distance: distanceText )
    }
  }

}

extension MainViewController : BluetoothManagerDelegate {

  func stateChanged(_ state: CBCentralManagerState) {
    print("State Changed: \(state)")
    var enabled = false
    var title = ""
    switch state {
    case .poweredOn:
        title = "Bluetooth ON"
        enabled = true
        // When the bluetooth changes to ON, try to reconnect to the previous sensor
        checkPreviousSensor()

    case .resetting:
        title = "Reseeting"
    case .poweredOff:
      title = "Bluetooth Off"
    case .unauthorized:
      title = "Bluetooth not authorized"
    case .unknown:
      title = "Unknown"
    case .unsupported:
      title = "Bluetooth not supported"
    }
    infoViewController?.showBluetoothStatusText( title )
    scanItem.isEnabled = enabled
  }

  func sensorConnection( _ sensor:CadenceSensor, error:NSError?) {
      print("")
    guard error == nil else {
      self.sensor = nil
      print("Error connecting to sensor: \(sensor.peripheral.identifier)")
      updateSensorInfo()
      accumulatedDistance = nil
      return
    }
    self.sensor = sensor
    self.sensor?.sensorDelegate = self
    print("Sensor connected. \(String(describing: sensor.peripheral.name)). [\(sensor.peripheral.identifier)]")
    updateSensorInfo()

    sensor.start()
  }

  func sensorDisconnected( _ sensor:CadenceSensor, error:NSError?) {
    print("Sensor disconnected")
    self.sensor = nil
  }

  func sensorDiscovered( _ sensor:CadenceSensor ) {
      scanViewController?.addSensor(sensor)
  }

}

in MainViewController.swift, there is this func sensorUpdatedValues that converts the three values that I want, to strings and initialize the the func showMeasurementWithSpeed ins the InfoTableViewController.swift .

Could I just return the three values inside function sensorUpdateValues  instead to be able to store them into  new variables?

Body:
I believe it's because you have that func declared as an instance level function rather than a class/struct level function.  You should be able to simply add the "static" keyword to make it accessible for the way you are using it in your sample code.  i.e. "static func valuesForPreviousMeasurement ..."

** UPDATE - Added a simple example to show the difference between class and instance functions.

// This is an instance function being used.  It's called such because
// you need an actual object instance in order to call the func.
var myCar: Car = Car()
myCar.startEngine()

// This is a class level function being used.  It's called such because
// you don't actually need an object instance: It's simply part of the class.
Car.PriceForModel("HondaCivic")


问:
Set IntPtr value of COM DLL in VB.net project
my task is to write a VB.NET library to interact with a piece of VB6 application. This VB6 application provides some unmanaged COM DLLs.

I created interop types (by using tlbimp) and added them as a reference in my VB.NET project.

Well, there is also an old VB6 project (library) existing, which is also referencing the (native) COM DLLs, let's call them
COM1.dll, COM2.dll and COM3.dll.
This old project is having a "Class Module" called claMod where it is doing the following:

```<code>    Option Explicit
    Public Property Set GlobalProp(oObj As claClass1)
            Set COM1.MyPointer = oObj
            Set COM2.MyPointer = oObj
    End Property
</code>```

where claClass1 is a class in COM3 and COM1.MyPointer and COM2.MyPointer are of type System.IntPtr.

My question is: How is possible to set these two pointers without declaring the corresponding objects (instances of COM1 and COM2) ?? And secondly, how can I do the same in my new VB.NET library?

答:
To allow referencing of COM1 and COM2 without specifically instantiating them, set each class's Instancing property to GlobalMultiUse. Then the code that you have in your post will work without having to create a reference to it.

There are many such objects already running in the VB6 environment; the Screen object is a familiar example.

This is basically the same as declaring a Shared class in VB.Net or a static class in C#.

Body:
my task is to write a VB.NET library to interact with a piece of VB6 application. This VB6 application provides some unmanaged COM DLLs.

I created interop types (by using tlbimp) and added them as a reference in my VB.NET project.

Well, there is also an old VB6 project (library) existing, which is also referencing the (native) COM DLLs, let's call them
COM1.dll, COM2.dll and COM3.dll.
This old project is having a "Class Module" called claMod where it is doing the following:

    Option Explicit
    Public Property Set GlobalProp(oObj As claClass1)
            Set COM1.MyPointer = oObj
            Set COM2.MyPointer = oObj
    End Property

where claClass1 is a class in COM3 and COM1.MyPointer and COM2.MyPointer are of type System.IntPtr.

My question is: How is possible to set these two pointers without declaring the corresponding objects (instances of COM1 and COM2) ?? And secondly, how can I do the same in my new VB.NET library?


问:
browser = webdriver.Chrome() not working
I am getting started with Selenium for python and have this:

```<code>from selenium import webdriver
browser = webdriver.Chrome()
</code>```

However it gives this error:

```<code>Traceback (most recent call last):
File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
packages\selenium\webdriver\common\service.py", line 74, in start
stdout=self.log_file, stderr=self.log_file)
 File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 709, in
__init__
restore_signals, start_new_session)
File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 997, in
_execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
  File "C:\Users\Bradley Jo\Desktop\Project\app.py", line 3, in
 <module>
 browser = webdriver.Chrome()
  File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
  packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__
 self.service.start()
 File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
 packages\selenium\webdriver\common\service.py", line 81, in start
 os.path.basename(self.path), self.start_error_message)
 selenium.common.exceptions.WebDriverException: Message: 'chromedriver'
 executable needs to be in PATH. Please see
 https://sites.google.com/a/chromium.org/chromedriver/home

[Finished in 1.0s]
</code>```

Anyone have any idea how to fix this? Thanks

答:
For windows:

Check you have installed latest version of chrome browser

If not, install latest version of chrome

download the latest(or appropriate) version of chromedriver from here

Paste the chromedriver.exe file in "<Install Dir>/Python27/Scripts" Folder.

The below code should work now:

```<code>    from selenium import webdriver
    driver = webdriver.Chrome()
</code>```

Body:
I am getting started with Selenium for python and have this:

from selenium import webdriver
browser = webdriver.Chrome()

However it gives this error:

Traceback (most recent call last):
File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
packages\selenium\webdriver\common\service.py", line 74, in start
stdout=self.log_file, stderr=self.log_file)
 File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 709, in
__init__
restore_signals, start_new_session)
File "C:\Users\Bradley
Jo\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 997, in
_execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
  File "C:\Users\Bradley Jo\Desktop\Project\app.py", line 3, in
 <module>
 browser = webdriver.Chrome()
  File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
  packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__
 self.service.start()
 File "C:\Users\Bradley Jo\AppData\Local\Programs\Python\Python36\lib\site-
 packages\selenium\webdriver\common\service.py", line 81, in start
 os.path.basename(self.path), self.start_error_message)
 selenium.common.exceptions.WebDriverException: Message: 'chromedriver'
 executable needs to be in PATH. Please see
 https://sites.google.com/a/chromium.org/chromedriver/home

[Finished in 1.0s]

Anyone have any idea how to fix this? Thanks

Body:
For windows:

Check you have installed latest version of chrome browser

If not, install latest version of chrome

download the latest(or appropriate) version of chromedriver from here

Paste the chromedriver.exe file in "<Install Dir>/Python27/Scripts" Folder.

The below code should work now:

    from selenium import webdriver
    driver = webdriver.Chrome()


问:
SafeValue must use [property]=binding, but IT IS

Hello all, this is driving me nuts. I tried all the fixes I was able to find online and nothing seems to work.

I am loading the base64 image info from a DB, which returns the base64 encoded image, like this:

```<code>/9j/4AAQSkZJRgABAQEBLAEsAAD/4UHuRXhpZgAATU0AKgAAAAgABgEaAAUAAAABAAAAVgEbAAUAAAABAAAAXgEoAAMAAAABAAIAAAITAAMAAAABAAEAAIdpAAQAAAABAAAIcuocAAcAAAgMAAAAZgAAEOQAAAEsAAAAAQAAASwAAAABHOoAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA...
</code>```

Then in my TS file I have the following function:

```<code>photo_url(data:string){

     this.user_photo = this.domSanitizer.bypassSecurityTrustResourceUrl('data:image/jpeg;base64,' + data).toString();

}
</code>```

My HTML file looks as follows:

```<code><img [src]="user_photo ? user_photo : 'assets/img/default.png'">
</code>```

However I am getting the following error and the image is not displaying:

```<code>WARNING: sanitizing unsafe URL value SafeValue must use [property]=binding: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/4UHuRXhpZgAATU0AKgAAAAgABgEaAAUAAAABAAAAVgEbAAUAAAABAAAAXgEoAAMAAAABAAIAAAITAAMAAAABAAEAAIdpAAQAAAABAAAIcuocAAcAAAgMAAAAZgAAEOQAAAEsAAAAAQAAASwAAAABHOoAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA...
</code>```

Error says sanitizer should uses property binding, and it is, but it is still showing that error and the image does not display.

Am I missing something here?

Thanks!

答:
When you use .toString you are setting user_photo to a string instead of a SafeResourceUrl as required.

Actually simply removing the .toString() will make this work properly. Otherwise you are essentially just undoing the work of the DomSanitizer.

```<code>user_photo: SafeResourceUrl;
photo_url(data: string){
     this.user_photo = this.domSanitizer.bypassSecurityTrustResourceUrl(
       'data:image/jpeg;base64,' + data);
}
</code>```

Body:
Hello all, this is driving me nuts. I tried all the fixes I was able to find online and nothing seems to work.

I am loading the base64 image info from a DB, which returns the base64 encoded image, like this:

/9j/4AAQSkZJRgABAQEBLAEsAAD/4UHuRXhpZgAATU0AKgAAAAgABgEaAAUAAAABAAAAVgEbAAUAAAABAAAAXgEoAAMAAAABAAIAAAITAAMAAAABAAEAAIdpAAQAAAABAAAIcuocAAcAAAgMAAAAZgAAEOQAAAEsAAAAAQAAASwAAAABHOoAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA...

Then in my TS file I have the following function:

photo_url(data:string){

     this.user_photo = this.domSanitizer.bypassSecurityTrustResourceUrl('data:image/jpeg;base64,' + data).toString();

}

My HTML file looks as follows:

However I am getting the following error and the image is not displaying:

WARNING: sanitizing unsafe URL value SafeValue must use [property]=binding: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/4UHuRXhpZgAATU0AKgAAAAgABgEaAAUAAAABAAAAVgEbAAUAAAABAAAAXgEoAAMAAAABAAIAAAITAAMAAAABAAEAAIdpAAQAAAABAAAIcuocAAcAAAgMAAAAZgAAEOQAAAEsAAAAAQAAASwAAAABHOoAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA...

Error says sanitizer should uses property binding, and it is, but it is still showing that error and the image does not display.

Am I missing something here?

Thanks!

Body:
When you use .toString you are setting user_photo to a string instead of a SafeResourceUrl as required.

Actually simply removing the .toString() will make this work properly. Otherwise you are essentially just undoing the work of the DomSanitizer.

user_photo: SafeResourceUrl;
photo_url(data: string){
     this.user_photo = this.domSanitizer.bypassSecurityTrustResourceUrl(
       'data:image/jpeg;base64,' + data);
}


问:
Error running mysql script through Docker?
I'm trying to create a docker container that will run a mysql script which generates a database and then table. My Dockerfile looks like this:

```<code>FROM mysql:latest

WORKDIR /

ADD . /

EXPOSE 3306

CMD mysql -u "root" -proot < "schema.sql"
</code>```

However when I run it I get the following error messages:

```<code>mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
</code>```

When I run the sql script I only get the password error.  Grateful for your help!

答:
Like majority of official docker image, you can configure the container through the entrypoint.

It's documented on mysql docker page. You can use MYSQL_ROOT_PASSWORD, MYSQL_DATABASE, MYSQL_USER, MYSQL_PASSWORD to configure mysql instance.

You will set this variables through environments variables with -e with docker or environments option in docker-compose.yml file.

You can see in here that files(.sh,.sql,.sql.gz) copied in /docker-entrypoint-initdb.d/ image will be run during startup.

So you can write Dockerfile like this :

```<code>FROM mysql:latest

COPY schema.sql /docker-entrypoint-initdb.d/
# No need to override CMD default command of mysql image
</code>```

Body:
I'm trying to create a docker container that will run a mysql script which generates a database and then table. My Dockerfile looks like this:

FROM mysql:latest

WORKDIR /

ADD . /

EXPOSE 3306

CMD mysql -u "root" -proot < "schema.sql"

However when I run it I get the following error messages:

mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

When I run the sql script I only get the password error.  Grateful for your help!

Body:
Like majority of official docker image, you can configure the container through the entrypoint.

It's documented on mysql docker page. You can use MYSQL_ROOT_PASSWORD, MYSQL_DATABASE, MYSQL_USER, MYSQL_PASSWORD to configure mysql instance.

You will set this variables through environments variables with -e with docker or environments option in docker-compose.yml file.

You can see in here that files(.sh,.sql,.sql.gz) copied in /docker-entrypoint-initdb.d/ image will be run during startup.

So you can write Dockerfile like this :

FROM mysql:latest

COPY schema.sql /docker-entrypoint-initdb.d/
# No need to override CMD default command of mysql image


问:
Writing JUnit tests in Jython
I was wondering whether anyone is using Jython to write JUnit tests? The reason for this is that I try to find a neat way to test my SOAP based web services without the need to generate any code. The reason for sticking with JUnit is that I would love to eventually integrate the tests into my Ant based CI system.

I already had a look at the article http://www.devx.com/java/Article/26602/1954 which describes exactly what I need. Unfortunately, I wasn't able to get it working.

Any thoughts and experiences on this would be of great help.

Thanks,
Alex

答:
I'd rather go the other way round: write tests using python unittest to test java code from python. You could then have doctests as well to test Java code, which is neat.

Then you could attempt integration in ant by creating an ant task that e.g. runs 'nose' to find and execute the tests.

Or you can decide to use Hudson for continuous integration (which is going a long step beyond simple Ant) and never look back... ;)

A nice article with this and more (including a mention of the jython plugin for Hudson):
http://www.jython.org/jythonbook/en/1.0/TestingIntegration.html

ContentLicense: CC BY-SA 2.5

Title: Writing JUnit tests in Jython


答:
You can use aggregate functions in ORDER BY:

```<code>SELECT shops.id AS shopid -- No need to use MAX(...) here
FROM shops
LEFT JOIN expiration ON shops.id=expiration.shopid
GROUP BY shopid
ORDER BY
  MAX(shops.grade) DESC,
  MIN(expiration.startdate) ASC,
  MAX(expiration.enddate) DESC,
  shops.id
</code>```

Title: select distinct id when using left join and order by on two tables

Body:
You can use aggregate functions in ORDER BY:

SELECT shops.id AS shopid -- No need to use MAX(...) here
FROM shops
LEFT JOIN expiration ON shops.id=expiration.shopid
GROUP BY shopid
ORDER BY
  MAX(shops.grade) DESC,
  MIN(expiration.startdate) ASC,
  MAX(expiration.enddate) DESC,
  shops.id


问:
Push Pull Model in Web Development
I would like to create for myself a base core (or package) for handling interactions between the server side and client side.  My approach is this:

Set the time interval to every two seconds (arbitrarily picked)

Create a script on the PHP side.  This script will allow other PHP scripts to add functions to call (or remove them) to collect information that will be sent to the client.

Every 2 seconds, the client will call this PHP script to request the information.

When this occurs, the PHP script will call all added functions, store their data, and send all data back to the client.

The client will handle this data appropriately

I am not sure if this actually describes an implementation of the Push-Pull model, or of a similar, but different, model.  I imagine the "pushes" from the client to the server side would not need to be synchronized into this two second window.

The ultimate goal in all of this is for me to create a method in which the client side can remain up to date when displaying information that is likely to change while the browser window is open.

I would like to ask if this is a correct interpretation of the push pull model, if this is a suitable way to accomplish this goal, and if there is possibly a more suited paradigm for this goal.

答:
Push: The SERVER side actively sends information to the client (via WebSocket). Therefore, the client passively listens for messages of the server.

Pull: The CLIENT requests actively information from the server (via HTTP or WebSocket). The server processes the request and sends the requested information back.

What you want to achieve is the PUSH. Although, you try to implement this via longpolling (where the client gathers his infos actively).

If you really want to implement your approach, get yourself into WebSockets. You can see a basic example on https://socket.io/ unfortunately this is nodeJs and not PHP.

Title: Push Pull Model in Web Development


问:
WebStorm Mocha run configuration throws error, command line does not
I am trying to use Mocha (and Chai) to test my Node.js TypeScript code.

When I use WebStorm's Mocha Run Configuration it runs the following command and throws an error

```<code>/usr/local/bin/node /Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/bin/_mocha --require ts-node/register --ui bdd --reporter "/Users/george.pai/Library/Application Support/JetBrains/Toolbox/apps/WebStorm/ch-0/173.3727.108/WebStorm.app/Contents/plugins/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js" /Users/george.pai/Workspace/fd/fd-lambdas/src/test/slack.handler.spec.ts --grep "slack\.handler "
</code>```

However if I run the exact same command from the command line it works fine.

Here is my run configuration (some directory names obfuscated for privacy)

My package.json dependencies

```<code>  "dependencies": {
    "aws-lambda": "0.1.2",
    "json2csv": "^3.11.5",
    "request": "^2.83.0",
    "request-promise-native": "^1.0.5",
    "uuid": "^3.1.0"
  },
  "devDependencies": {
    "@types/aws-lambda": "0.0.19",
    "@types/chai": "^4.0.7",
    "@types/mocha": "^2.2.44",
    "@types/node": "^8.0.53",
    "@types/request": "^2.0.8",
    "@types/request-promise-native": "^1.0.10",
    "@types/uuid": "^3.4.3",
    "chai": "^4.1.2",
    "mocha": "^4.0.1",
    "mocha-typescript": "^1.1.12",
    "serverless-offline": "^3.16.0",
    "serverless-webpack": "^3.0.0",
    "ts-loader": "^2.3.7",
    "ts-node": "^3.3.0",
    "tslint": "^5.8.0",
    "tslint-config-standard": "^7.0.0",
    "typescript": "^2.5.2",
    "webpack": "^3.6.0"
  }
</code>```

My tsconfig.json

```<code>{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "lib": [
      "es6",
      "dom"
    ],
    "moduleResolution": "node",
    "rootDir": "./src",
    "sourceMap": true,
    "inlineSources": true,
    "allowJs": true,
    "noImplicitAny": true,
    "noUnusedLocals": true,
    "noImplicitThis": true,
    "strictNullChecks": true,
    "noImplicitReturns": true,
    "preserveConstEnums": true,
    "suppressImplicitAnyIndexErrors": true,
    "forceConsistentCasingInFileNames": true
  },
  "exclude": [
    "node_modules",
    "build",
    "webpack"
  ],
  "types": [
    "aws-sdk",
    "chai",
    "mocha",
    "node",
    "request",
    "request-promise-native",
    "typePatches",
    "uuid"
  ]
}
</code>```

Here is the full output of the error

```<code>/usr/local/bin/node /Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/bin/_mocha --require ts-node/register --ui bdd --reporter "/Users/george.pai/Library/Application Support/JetBrains/Toolbox/apps/WebStorm/ch-0/173.3727.108/WebStorm.app/Contents/plugins/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js" /Users/george.pai/Workspace/fd/fd-lambdas/src/test/slack.handler.spec.ts --grep "slack\.handler "

/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:307
        throw new TSError(formatDiagnostics(diagnosticList, cwd, ts, lineOffset))
              ^
TSError: ⨯ Unable to compile TypeScript
fd-lambdas/src/main/node/slack/slack.handler.ts (57,18): 'Promise' only refers to a type, but is being used as a value here. (2693)
fd-lambdas/src/main/node/slack/slack.handler.ts (69,12): 'Promise' only refers to a type, but is being used as a value here. (2693)
fd-lambdas/src/main/node/slack/slack.handler.ts (199,14): 'Promise' only refers to a type, but is being used as a value here. (2693)
fd-lambdas/src/main/node/slack/slack.handler.ts (202,14): 'Promise' only refers to a type, but is being used as a value here. (2693)
fd-lambdas/src/main/node/slack/slack.handler.ts (230,16): 'Promise' only refers to a type, but is being used as a value here. (2693)
    at getOutput (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:307:15)
    at /Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:336:16
    at Object.compile (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:498:11)
    at Module.m._compile (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:392:43)
    at Module._extensions..js (module.js:623:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:395:12)
    at Module.load (module.js:531:32)
    at tryModuleLoad (module.js:494:12)
    at Function.Module._load (module.js:486:3)
    at Module.require (module.js:556:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/george.pai/Workspace/fd/fd-lambdas/src/test/slack.handler.spec.ts:4:1)
    at Module._compile (module.js:612:30)
    at Module.m._compile (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:392:23)
    at Module._extensions..js (module.js:623:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:395:12)
    at Module.load (module.js:531:32)
    at tryModuleLoad (module.js:494:12)
    at Function.Module._load (module.js:486:3)
    at Module.require (module.js:556:17)
    at require (internal/module.js:11:18)
    at /Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/lib/mocha.js:231:27
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/lib/mocha.js:228:14)
    at Mocha.run (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/lib/mocha.js:514:10)
    at Object.<anonymous> (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/bin/_mocha:484:18)
    at Module._compile (module.js:612:30)
    at Object.Module._extensions..js (module.js:623:10)
    at Module.load (module.js:531:32)
    at tryModuleLoad (module.js:494:12)
    at Function.Module._load (module.js:486:3)
    at Function.Module.runMain (module.js:653:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

Process finished with exit code 1
</code>```

答:
Turns out the obfuscation probably hindered finding the solution. The working directory for the Mocha Run Configuration /Users/george.pai/Workspace/fd was the root of the project, but not the root of my node project /Users/george.pai/Workspace/fd/fd-lambdas

Changing the working directory to the proper directory solved this. My terminal was already in the proper directory /Users/george.pai/Workspace/fd/fd-lambdas so that is why it worked.

Body:
I am trying to use Mocha (and Chai) to test my Node.js TypeScript code.

When I use WebStorm's Mocha Run Configuration it runs the following command and throws an error

/usr/local/bin/node /Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/bin/_mocha --require ts-node/register --ui bdd --reporter "/Users/george.pai/Library/Application Support/JetBrains/Toolbox/apps/WebStorm/ch-0/173.3727.108/WebStorm.app/Contents/plugins/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js" /Users/george.pai/Workspace/fd/fd-lambdas/src/test/slack.handler.spec.ts --grep "slack\.handler "

However if I run the exact same command from the command line it works fine.

Here is my run configuration (some directory names obfuscated for privacy)

My package.json dependencies

  "dependencies": {
    "aws-lambda": "0.1.2",
    "json2csv": "^3.11.5",
    "request": "^2.83.0",
    "request-promise-native": "^1.0.5",
    "uuid": "^3.1.0"
  },
  "devDependencies": {
    "@types/aws-lambda": "0.0.19",
    "@types/chai": "^4.0.7",
    "@types/mocha": "^2.2.44",
    "@types/node": "^8.0.53",
    "@types/request": "^2.0.8",
    "@types/request-promise-native": "^1.0.10",
    "@types/uuid": "^3.4.3",
    "chai": "^4.1.2",
    "mocha": "^4.0.1",
    "mocha-typescript": "^1.1.12",
    "serverless-offline": "^3.16.0",
    "serverless-webpack": "^3.0.0",
    "ts-loader": "^2.3.7",
    "ts-node": "^3.3.0",
    "tslint": "^5.8.0",
    "tslint-config-standard": "^7.0.0",
    "typescript": "^2.5.2",
    "webpack": "^3.6.0"
  }

My tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "lib": [
      "es6",
      "dom"
    ],
    "moduleResolution": "node",
    "rootDir": "./src",
    "sourceMap": true,
    "inlineSources": true,
    "allowJs": true,
    "noImplicitAny": true,
    "noUnusedLocals": true,
    "noImplicitThis": true,
    "strictNullChecks": true,
    "noImplicitReturns": true,
    "preserveConstEnums": true,
    "suppressImplicitAnyIndexErrors": true,
    "forceConsistentCasingInFileNames": true
  },
  "exclude": [
    "node_modules",
    "build",
    "webpack"
  ],
  "types": [
    "aws-sdk",
    "chai",
    "mocha",
    "node",
    "request",
    "request-promise-native",
    "typePatches",
    "uuid"
  ]
}

Here is the full output of the error

/usr/local/bin/node /Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/bin/_mocha --require ts-node/register --ui bdd --reporter "/Users/george.pai/Library/Application Support/JetBrains/Toolbox/apps/WebStorm/ch-0/173.3727.108/WebStorm.app/Contents/plugins/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js" /Users/george.pai/Workspace/fd/fd-lambdas/src/test/slack.handler.spec.ts --grep "slack\.handler "

/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:307
        throw new TSError(formatDiagnostics(diagnosticList, cwd, ts, lineOffset))
              ^
TSError: ⨯ Unable to compile TypeScript
fd-lambdas/src/main/node/slack/slack.handler.ts (57,18): 'Promise' only refers to a type, but is being used as a value here. (2693)
fd-lambdas/src/main/node/slack/slack.handler.ts (69,12): 'Promise' only refers to a type, but is being used as a value here. (2693)
fd-lambdas/src/main/node/slack/slack.handler.ts (199,14): 'Promise' only refers to a type, but is being used as a value here. (2693)
fd-lambdas/src/main/node/slack/slack.handler.ts (202,14): 'Promise' only refers to a type, but is being used as a value here. (2693)
fd-lambdas/src/main/node/slack/slack.handler.ts (230,16): 'Promise' only refers to a type, but is being used as a value here. (2693)
    at getOutput (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:307:15)
    at /Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:336:16
    at Object.compile (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:498:11)
    at Module.m._compile (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:392:43)
    at Module._extensions..js (module.js:623:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:395:12)
    at Module.load (module.js:531:32)
    at tryModuleLoad (module.js:494:12)
    at Function.Module._load (module.js:486:3)
    at Module.require (module.js:556:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/george.pai/Workspace/fd/fd-lambdas/src/test/slack.handler.spec.ts:4:1)
    at Module._compile (module.js:612:30)
    at Module.m._compile (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:392:23)
    at Module._extensions..js (module.js:623:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/ts-node/src/index.ts:395:12)
    at Module.load (module.js:531:32)
    at tryModuleLoad (module.js:494:12)
    at Function.Module._load (module.js:486:3)
    at Module.require (module.js:556:17)
    at require (internal/module.js:11:18)
    at /Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/lib/mocha.js:231:27
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/lib/mocha.js:228:14)
    at Mocha.run (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/lib/mocha.js:514:10)
    at Object.<anonymous> (/Users/george.pai/Workspace/fd/fd-lambdas/node_modules/mocha/bin/_mocha:484:18)
    at Module._compile (module.js:612:30)
    at Object.Module._extensions..js (module.js:623:10)
    at Module.load (module.js:531:32)
    at tryModuleLoad (module.js:494:12)
    at Function.Module._load (module.js:486:3)
    at Function.Module.runMain (module.js:653:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

Process finished with exit code 1


问:
403 Forbidden ERROR with WebClient request
I understand this is a quite frequently asked question and also have many proposals and solutions. However, I tried almost all of them but still cannot fix this issue from my side, even with Fiddler's http request headers configured. I am not sure whether this is a specific one or I missed something else important. So I asked this question again, hope could get any further support from you. Thanks in advance!

Here is the code used with the link:

```<code>  Dim WC As New System.Net.WebClient
        'WC.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705Wink")
        WC.Headers.Add(HttpRequestHeader.Accept, "Text/ html, Application / xhtml + Xml, Application / Xml;q=0.9, Image / webp, Image / apng,*/*;q=0.8")
        WC.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36")
        WC.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br")
        WC.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8")
        'WC.Headers.Add(HttpRequestHeader.KeepAlive, "true")
        WC.Headers.Add(HttpRequestHeader.Host, "www.fda.gov")

        'WC.Headers.Add(HttpRequestHeader.ContentType, "")
        'WC.Headers.Add(HttpRequestHeader.ContentLength, "")

        Dim strURL As String = "https://www.fda.gov/downloads/Drugs/GuidanceComplianceRegulatoryInformation/Guidances/UCM227351.pdf"
        'Threading.Thread.Sleep(5000)
        WC.DownloadFile(strURL, "1.pdf")
</code>```

Any thoughts would be highly appreciated!

Thanks again!

Stanley

答:
First, any time you use .net to make a web request you should catch exceptions, specifically of the webexception type.  This will let you get the response from the server.  See below.

```<code>  Dim strURL As String = "https://www.fda.gov/downloads/Drugs/GuidanceComplianceRegulatoryInformation/Guidances/UCM227351.pdf"

  Try
     WC.DownloadFile(strURL, "1.pdf")
  Catch ex As Net.WebException

     If ex.Response IsNot Nothing Then
        Dim response = ex.Response
        Dim dataStream = ex.Response.GetResponseStream
        Dim reader = New StreamReader(dataStream)
        Dim errorDetails As String = reader.ReadToEnd

        '  do something with errorDetails

     End If

  End Try
</code>```

I was curious so I did the same for your URL, and found that it returns this helpful information.

This page cannot be displayed.  We're sorry for any inconvenience this issue has caused.  Make sure you are using a client that supports TLS.1.2.

To correct the error please add this code before your web request.

```<code>ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
</code>```

Body:
I understand this is a quite frequently asked question and also have many proposals and solutions. However, I tried almost all of them but still cannot fix this issue from my side, even with Fiddler's http request headers configured. I am not sure whether this is a specific one or I missed something else important. So I asked this question again, hope could get any further support from you. Thanks in advance!

Here is the code used with the link:

  Dim WC As New System.Net.WebClient
        'WC.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705Wink")
        WC.Headers.Add(HttpRequestHeader.Accept, "Text/ html, Application / xhtml + Xml, Application / Xml;q=0.9, Image / webp, Image / apng,*/*;q=0.8")
        WC.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36")
        WC.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br")
        WC.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8")
        'WC.Headers.Add(HttpRequestHeader.KeepAlive, "true")
        WC.Headers.Add(HttpRequestHeader.Host, "www.fda.gov")

        'WC.Headers.Add(HttpRequestHeader.ContentType, "")
        'WC.Headers.Add(HttpRequestHeader.ContentLength, "")

        Dim strURL As String = "https://www.fda.gov/downloads/Drugs/GuidanceComplianceRegulatoryInformation/Guidances/UCM227351.pdf"
        'Threading.Thread.Sleep(5000)
        WC.DownloadFile(strURL, "1.pdf")

Any thoughts would be highly appreciated!

Thanks again!

Stanley

Body:
First, any time you use .net to make a web request you should catch exceptions, specifically of the webexception type.  This will let you get the response from the server.  See below.

  Dim strURL As String = "https://www.fda.gov/downloads/Drugs/GuidanceComplianceRegulatoryInformation/Guidances/UCM227351.pdf"

  Try
     WC.DownloadFile(strURL, "1.pdf")
  Catch ex As Net.WebException

     If ex.Response IsNot Nothing Then
        Dim response = ex.Response
        Dim dataStream = ex.Response.GetResponseStream
        Dim reader = New StreamReader(dataStream)
        Dim errorDetails As String = reader.ReadToEnd

        '  do something with errorDetails

     End If

  End Try

I was curious so I did the same for your URL, and found that it returns this helpful information.

This page cannot be displayed.  We're sorry for any inconvenience this issue has caused.  Make sure you are using a client that supports TLS.1.2.

To correct the error please add this code before your web request.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12


问:
IEnumerable from IEnumerator
I have writen about custom IEnumerator. Whats the simplest way to make IEnumerable from it ? Ideal solution (one line of code) would be if there was some class for that purpose. Or do I have to create my own ?

答:
Pretty simple:

```<code>class Enumerate : IEnumerable
{
    private Enumerate IEnumerator it;
    public Enumerate(IEnumerator it) { this.it = it; }
    public IEnumerator GetEnumerator() { return this.it; }
}
</code>```

This also allows the user to call IEnumerator.Reset() if the enumerator you gave it supports it.

Title: IEnumerable from IEnumerator

Body:
Pretty simple:

class Enumerate : IEnumerable
{
    private Enumerate IEnumerator it;
    public Enumerate(IEnumerator it) { this.it = it; }
    public IEnumerator GetEnumerator() { return this.it; }
}

This also allows the user to call IEnumerator.Reset() if the enumerator you gave it supports it.


问:
React, Why label not firing onChange for checkbox?
I feel like I've done this a million times, but possibly not with a mapping function. I have a collection of activities that I'm creating checkboxes with the code is as follows (__map is coming from Lodash by the way):

```<code><div className="activity-blocks">
{
    __map(this.state.activities, (activity, i) => {
        return (
            <div key={ i } className="single-activity">
                <input id={ `register-activity-${ i }` }
                    type="checkbox" className="register-multiselect"
                    name="main_activity" checked={ !!activity.checked }
                    onChange={ (e) => this.toggleActivity(e, activity.id) }
                />
                <label htmlFor={ `register-activity-${ i }` }>{ activity.name }</label>
            </div>
         )
    })
 }
</code>```

My onChange handler looks like this:

```<code>toggleActivity(e, activityId) {
    let activities = { ...this.state.activities };

    __forEach(this.state.activities, (activity) => {
        if (activityId === activity.id) {
            activity = __assign(activity, { checked: e.target.checked });
            return false;
        }
    });

    this.setState({ activities: activities });
}
</code>```

The handler works just fine, it's for reference mostly. My issue is that the label is not firing the handler. I have tested only the checkbox input with no label and it fires off the handler. Does anyone know why the label is not doing so?

More info: I've had this problem before but it usually turns out to be an id mismatch or something simple like that. I don't believe so this time.

Edit
I have deleted pretty much all the code from my file and incorporated Slawa's answer below and it still doesn't behave as expected. Here is the code including all imports, the class structure and all unnecessary code stripped out, including styles:

```<code>import React from 'react';
import __forEach from 'lodash/forEach';
import __assign from 'lodash/assign';
import __map from 'lodash/map';

export default class RegisterActivities extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            activities: [
                {
                    id: 1,
                    name: 'label-1'
                },
                {
                    id: 2,
                    name: 'label-2'
                },
                {
                    id: 3,
                    name: 'label-3'
                }
            ],
        }
    }

    toggleActivity(e, activityId) {
        const { activities } = this.state;

        const updated = activities.map((activity) => {
            if (activity.id === activityId){
                return {
                    ...activity,
                    checked: e.target.checked
                }
            }

            return activity;
        });
    }

    render() {
        return (
            <div>
                <p>what do you do?</p>
                <div>
                {
                    __map(this.state.activities, (activity, i) => {
                        return (
                            <div key={ i }>
                                <input id={ `register-activity-${ i }` }
                                    type="checkbox"
                                    name="main_activity" checked={ !!activity.checked }
                                    onChange={ (e) => this.toggleActivity(e, activity.id) }
                                />
                                <label htmlFor={ `register-activity-${ i }` }>{ activity.name }</label>
                            </div>
                        )
                    })
                }
                </div>
            </div>
        );
    }
}
</code>```

Edit2
I'm playing around and decided to replce onChange with onClick and now I'm able to click the actual checkbox to hit toggleActivity. Does anyone have an idea on why onChange isn't firing?

答:
I was having this same issue. It was driving me mad, but what my team and I discovered is there must be some bug with the htmlFor they tell you to use in the docs. We removed it from our checkbox prop and now it functions as expected with no weird side effects. I'm opening up a GH issue on it. I'll edit later with the link/update

Code that didn't work:

```<code><label htmlFor={`${label}-checkbox`} className={checked ? "checked data-filter-checkbox" : "data-filter-checkbox"} >
  <input id={`${label}-checkbox`} type="checkbox" onChange={(event) => handleCheck(event)} value={label} name={label} checked={checked} />
  {label}
  <span>{count}</span>
</label>
</code>```

Code I'm using now:

```<code><label className={checked ? "checked data-filter-checkbox" : "data-filter-checkbox"} >
  <input id={`${label}-checkbox`} type="checkbox" onChange={(event) => handleCheck(event)} value={label} name={label} checked={checked} />
  {label}
  <span>{count}</span>
</label>
</code>```

Body:
I feel like I've done this a million times, but possibly not with a mapping function. I have a collection of activities that I'm creating checkboxes with the code is as follows (__map is coming from Lodash by the way):

{
    __map(this.state.activities, (activity, i) => {
        return (

                <input id={ `register-activity-${ i }` }
                    type="checkbox" className="register-multiselect"
                    name="main_activity" checked={ !!activity.checked }
                    onChange={ (e) => this.toggleActivity(e, activity.id) }
                />
                <label htmlFor={ `register-activity-${ i }` }>{ activity.name }

         )
    })
 }

My onChange handler looks like this:

toggleActivity(e, activityId) {
    let activities = { ...this.state.activities };

    __forEach(this.state.activities, (activity) => {
        if (activityId === activity.id) {
            activity = __assign(activity, { checked: e.target.checked });
            return false;
        }
    });

    this.setState({ activities: activities });
}

The handler works just fine, it's for reference mostly. My issue is that the label is not firing the handler. I have tested only the checkbox input with no label and it fires off the handler. Does anyone know why the label is not doing so?

More info: I've had this problem before but it usually turns out to be an id mismatch or something simple like that. I don't believe so this time.

Edit
I have deleted pretty much all the code from my file and incorporated Slawa's answer below and it still doesn't behave as expected. Here is the code including all imports, the class structure and all unnecessary code stripped out, including styles:

import React from 'react';
import __forEach from 'lodash/forEach';
import __assign from 'lodash/assign';
import __map from 'lodash/map';

export default class RegisterActivities extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            activities: [
                {
                    id: 1,
                    name: 'label-1'
                },
                {
                    id: 2,
                    name: 'label-2'
                },
                {
                    id: 3,
                    name: 'label-3'
                }
            ],
        }
    }

    toggleActivity(e, activityId) {
        const { activities } = this.state;

        const updated = activities.map((activity) => {
            if (activity.id === activityId){
                return {
                    ...activity,
                    checked: e.target.checked
                }
            }

            return activity;
        });
    }

    render() {
        return (

what do you do?

                {
                    __map(this.state.activities, (activity, i) => {
                        return (

                                <input id={ `register-activity-${ i }` }
                                    type="checkbox"
                                    name="main_activity" checked={ !!activity.checked }
                                    onChange={ (e) => this.toggleActivity(e, activity.id) }
                                />
                                <label htmlFor={ `register-activity-${ i }` }>{ activity.name }

                        )
                    })
                }

        );
    }
}

Edit2
I'm playing around and decided to replce onChange with onClick and now I'm able to click the actual checkbox to hit toggleActivity. Does anyone have an idea on why onChange isn't firing?

Body:
I was having this same issue. It was driving me mad, but what my team and I discovered is there must be some bug with the htmlFor they tell you to use in the docs. We removed it from our checkbox prop and now it functions as expected with no weird side effects. I'm opening up a GH issue on it. I'll edit later with the link/update

Code that didn't work:

<label htmlFor={`${label}-checkbox`} className={checked ? "checked data-filter-checkbox" : "data-filter-checkbox"} >
  <input id={`${label}-checkbox`} type="checkbox" onChange={(event) => handleCheck(event)} value={label} name={label} checked={checked} />
  {label}
  <span>{count}</span>
</label>

Code I'm using now:

<label className={checked ? "checked data-filter-checkbox" : "data-filter-checkbox"} >
  <input id={`${label}-checkbox`} type="checkbox" onChange={(event) => handleCheck(event)} value={label} name={label} checked={checked} />
  {label}
  <span>{count}</span>
</label>


问:
Add a default value to form submission in Laravel
In my controller I've got the destination columns and the origin fields for specific data entered in my create function. However, I've got a few default values in here, like below:

```<code>    $shipment->shipment_billing_status = 1;
    $shipment->created_by = $user_id;
    $shipment->cn_billtoName = request('cn_billtoName');
</code>```

As you can see $shipment->shipment_billing_status default value should always be 1. However, in extreme cases, I would like a user to be able to choose (if they need to) between two checkboxes, titled "No Settle" and "No Charge", or their values being 2 and 3.

So in those extreme cases, I want a record to absolutely go to 1 if the "No Settle" or "No Charge" checkboxes aren't selected.

答:
Let's say that the name of the check boxes input is status(single case since you're only accepting one status or none), I believe you can do something like this:

```<code>// Inside the store method.

$status = request('status') ?: 1;

$shipment->shipment_billing_status = $status;
</code>```

Hopefully this should do the trick.

Body:
In my controller I've got the destination columns and the origin fields for specific data entered in my create function. However, I've got a few default values in here, like below:

    $shipment->shipment_billing_status = 1;
    $shipment->created_by = $user_id;
    $shipment->cn_billtoName = request('cn_billtoName');

As you can see $shipment->shipment_billing_status default value should always be 1. However, in extreme cases, I would like a user to be able to choose (if they need to) between two checkboxes, titled "No Settle" and "No Charge", or their values being 2 and 3.

So in those extreme cases, I want a record to absolutely go to 1 if the "No Settle" or "No Charge" checkboxes aren't selected.

Body:
Let's say that the name of the check boxes input is status(single case since you're only accepting one status or none), I believe you can do something like this:

// Inside the store method.

$status = request('status') ?: 1;

$shipment->shipment_billing_status = $status;

Hopefully this should do the trick.