问:
Swift, Custom UIButton does not work when click
I have a custom UIButton created with xib file. When i use my custom button on my view, it does not work when i press to it.

My RoundBtn.swift file:

```<code>import UIKit

@IBDesignable class RoundBtn: UIButton {

    var nibName = "RoundBtn"

    @IBOutlet weak var btnImageView: UIImageView!
    @IBOutlet weak var btnLabel: UILabel!

    @IBInspectable var image: UIImage? {
        get {
            return btnImageView.image
        } set(image) {
            btnImageView.image = image
        }
    }

    @IBInspectable var label: String? {
        get {
            return btnLabel.text
        } set(label) {
            btnLabel.text = label
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {
        let view = loadViewFromNib()
        view.frame = self.bounds
        view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        btnImageView.layer.cornerRadius = 60/2
        btnImageView.layer.borderColor = UIColor(red: 5/255,
            green: 66/255, blue: 38/255, alpha: 1).CGColor
        btnImageView.layer.borderWidth = 2
        btnLabel.font = UIFont.boldSystemFontOfSize(14.0)
        btnImageView.userInteractionEnabled = true
        btnLabel.userInteractionEnabled = true
        view.userInteractionEnabled = true
        addSubview(view)
    }

    func loadViewFromNib() -> UIButton {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: nibName, bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIButton
        return view
    }
}
</code>```

My RoundBtn.xib file:

View where i used my custom button:

I enabled userInteractionEnabled on all view components. When i click to my custom button, it does not work. I tried by defining on click programmatically and by defining action segue (show).

```<code>@IBAction func myCartBtnPressed(sender: AnyObject) {
    print("my cart btn pressed")
}
</code>```

答:
Referring to @fdiaz's answer.
Swift 4 notation.

Conversely, if you attach some UIButton (or user interactive view) to an UIImageView, you must turn its isUserInteractionEnabled = true to let the touches go through the hierarchy up down to the UIButton.

Body:
I have a custom UIButton created with xib file. When i use my custom button on my view, it does not work when i press to it.

My RoundBtn.swift file:

import UIKit

@IBDesignable class RoundBtn: UIButton {

    var nibName = "RoundBtn"

    @IBOutlet weak var btnImageView: UIImageView!
    @IBOutlet weak var btnLabel: UILabel!

    @IBInspectable var image: UIImage? {
        get {
            return btnImageView.image
        } set(image) {
            btnImageView.image = image
        }
    }

    @IBInspectable var label: String? {
        get {
            return btnLabel.text
        } set(label) {
            btnLabel.text = label
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {
        let view = loadViewFromNib()
        view.frame = self.bounds
        view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        btnImageView.layer.cornerRadius = 60/2
        btnImageView.layer.borderColor = UIColor(red: 5/255,
            green: 66/255, blue: 38/255, alpha: 1).CGColor
        btnImageView.layer.borderWidth = 2
        btnLabel.font = UIFont.boldSystemFontOfSize(14.0)
        btnImageView.userInteractionEnabled = true
        btnLabel.userInteractionEnabled = true
        view.userInteractionEnabled = true
        addSubview(view)
    }

    func loadViewFromNib() -> UIButton {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: nibName, bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIButton
        return view
    }
}

My RoundBtn.xib file:

View where i used my custom button:

I enabled userInteractionEnabled on all view components. When i click to my custom button, it does not work. I tried by defining on click programmatically and by defining action segue (show).

@IBAction func myCartBtnPressed(sender: AnyObject) {
    print("my cart btn pressed")
}


来源: stackexchange

问:
Flutter - How to pass user data to all views
I'm new to the flutter world and mobile app development and struggling with how I should pass user data throughout my app.

I've tried several things, but none seem great and I'm sure there are best practice patterns I should be following.

Because it makes examples easier, I'm using firebase for authentication.
I currently have a separate route for logging in. Once I'm logged in I want the User model in most views for checking permissions on what to show, displaying user info in the drawer, etc...

Firebase has an await firebaseAuth.currentUser(); Is it best practice to call this everywhere you might need the user? and if so, where is the best spot to place this call?

The flutter codelab shows a great example of authenticating users before allowing writes. However, if the page needs to check auth to determine what to build, the async call can't go in the build method.

initState

One method I've tried is to override initState and kick off the call to get the user. When the future completes I call setState and update the user.

```<code>    FirebaseUser user;

    @override
    void initState() {
      super.initState();
      _getUserDetail();
    }

  Future<Null> _getUserDetail() async {
    User currentUser = await firebaseAuth.currentUser();
    setState(() => user = currentUser);
  }
</code>```

This works decent but seems like a lot of ceremony for each widget that needs it. There is also a flash when the screen loads without the user and then gets updated with the user upon the future's completion.

Pass the user through the constructor

This works too but is a lot of boilerplate to pass the user through all routes, views, and states that might need to access them. Also, we can't just do popAndPushNamed when transitioning routes because we can't pass a variable to it. We have to change routes similar to this:

```<code>Navigator.push(context, new MaterialPageRoute(
    builder: (BuildContext context) => new MyPage(user),
));
</code>```

Inherited Widgets

https://medium.com/@mehmetf_71205/inheriting-widgets-b7ac56dbbeb1

This article showed a nice pattern for using InheritedWidget.  When I place the inherited widget at the MaterialApp level, the children aren't updating when the auth state changed (I'm sure I'm doing it wrong)

```<code>  FirebaseUser user;

  Future<Null> didChangeDependency() async {
    super.didChangeDependencies();
    User currentUser = await firebaseAuth.currentUser();
    setState(() => user = currentUser);
  }

  @override
  Widget build(BuildContext context) {
    return new UserContext(
      user,
      child: new MaterialApp(
        title: 'TC Stream',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: new LoginView(title: 'TC Stream Login', analytics: analytics),
        routes: routes,
      ),
    );
  }
</code>```

FutureBuilder

FutureBuilder also seems like a decent option but seems to be a lot of work for each route. In the partial example below, _authenticateUser() is getting the user and setting state upon completion.

```<code>  @override
  Widget build(BuildContext context) {
    return new FutureBuilder<FirebaseUser>(
      future: _authenticateUser(),
      builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return _buildProgressIndicator();
        }
        if (snapshot.connectionState == ConnectionState.done) {
          return _buildPage();
        }
      },
    );
  }
</code>```

I'd appreciate any advice on best practice patterns or links to resources to use for examples.

答:
I'd recommend investigating inherited widgets further; the code below shows how to use them with asynchronously updating data:</p>

```<code>import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(new MaterialApp(
      title: 'Inherited Widgets Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Scaffold(
          appBar: new AppBar(
            title: new Text('Inherited Widget Example'),
          ),
          body: new NamePage())));
}

// Inherited widget for managing a name
class NameInheritedWidget extends InheritedWidget {
  const NameInheritedWidget({
    Key key,
    this.name,
    Widget child}) : super(key: key, child: child);

  final String name;

  @override
  bool updateShouldNotify(NameInheritedWidget old) {
    print('In updateShouldNotify');
    return name != old.name;
  }

  static NameInheritedWidget of(BuildContext context) {
    // You could also just directly return the name here
    // as there's only one field
    return context.inheritFromWidgetOfExactType(NameInheritedWidget);
  }
}

// Stateful widget for managing name data
class NamePage extends StatefulWidget {
  @override
  _NamePageState createState() => new _NamePageState();
}

// State for managing fetching name data over HTTP
class _NamePageState extends State<NamePage> {
  String name = 'Placeholder';

  // Fetch a name asynchonously over HTTP
  _get() async {
    var res = await http.get('https://jsonplaceholder.typicode.com/users');
    var name = json.decode(res.body)[0]['name'];
    setState(() => this.name = name);
  }

  @override
  void initState() {
    super.initState();
    _get();
  }

  @override
  Widget build(BuildContext context) {
    return new NameInheritedWidget(
      name: name,
      child: const IntermediateWidget()
    );
  }
}

// Intermediate widget to show how inherited widgets
// can propagate changes down the widget tree
class IntermediateWidget extends StatelessWidget {
  // Using a const constructor makes the widget cacheable
  const IntermediateWidget();

  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new Padding(
        padding: new EdgeInsets.all(10.0),
        child: const NameWidget()));
  }
}

class NameWidget extends StatelessWidget {
  const NameWidget();

  @override
  Widget build(BuildContext context) {
    final inheritedWidget = NameInheritedWidget.of(context);
    return new Text(
      inheritedWidget.name,
      style: Theme.of(context).textTheme.display1,
    );
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to the flutter world and mobile app development and struggling with how I should pass user data throughout my app.

I've tried several things, but none seem great and I'm sure there are best practice patterns I should be following.

Because it makes examples easier, I'm using firebase for authentication.
I currently have a separate route for logging in. Once I'm logged in I want the User model in most views for checking permissions on what to show, displaying user info in the drawer, etc...

Firebase has an await firebaseAuth.currentUser(); Is it best practice to call this everywhere you might need the user? and if so, where is the best spot to place this call?

The flutter codelab shows a great example of authenticating users before allowing writes. However, if the page needs to check auth to determine what to build, the async call can't go in the build method.

initState

One method I've tried is to override initState and kick off the call to get the user. When the future completes I call setState and update the user.

    FirebaseUser user;

    @override
    void initState() {
      super.initState();
      _getUserDetail();
    }

  Future<Null> _getUserDetail() async {
    User currentUser = await firebaseAuth.currentUser();
    setState(() => user = currentUser);
  }

This works decent but seems like a lot of ceremony for each widget that needs it. There is also a flash when the screen loads without the user and then gets updated with the user upon the future's completion.

Pass the user through the constructor

This works too but is a lot of boilerplate to pass the user through all routes, views, and states that might need to access them. Also, we can't just do popAndPushNamed when transitioning routes because we can't pass a variable to it. We have to change routes similar to this:

Navigator.push(context, new MaterialPageRoute(
    builder: (BuildContext context) => new MyPage(user),
));

Inherited Widgets

https://medium.com/@mehmetf_71205/inheriting-widgets-b7ac56dbbeb1

This article showed a nice pattern for using InheritedWidget.  When I place the inherited widget at the MaterialApp level, the children aren't updating when the auth state changed (I'm sure I'm doing it wrong)

  FirebaseUser user;

  Future<Null> didChangeDependency() async {
    super.didChangeDependencies();
    User currentUser = await firebaseAuth.currentUser();
    setState(() => user = currentUser);
  }

  @override
  Widget build(BuildContext context) {
    return new UserContext(
      user,
      child: new MaterialApp(
        title: 'TC Stream',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: new LoginView(title: 'TC Stream Login', analytics: analytics),
        routes: routes,
      ),
    );
  }

FutureBuilder

FutureBuilder also seems like a decent option but seems to be a lot of work for each route. In the partial example below, _authenticateUser() is getting the user and setting state upon completion.

  @override
  Widget build(BuildContext context) {
    return new FutureBuilder<FirebaseUser>(
      future: _authenticateUser(),
      builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return _buildProgressIndicator();
        }
        if (snapshot.connectionState == ConnectionState.done) {
          return _buildPage();
        }
      },
    );
  }

I'd appreciate any advice on best practice patterns or links to resources to use for examples.

Body:
I'd recommend investigating inherited widgets further; the code below shows how to use them with asynchronously updating data:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(new MaterialApp(
      title: 'Inherited Widgets Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Scaffold(
          appBar: new AppBar(
            title: new Text('Inherited Widget Example'),
          ),
          body: new NamePage())));
}

// Inherited widget for managing a name
class NameInheritedWidget extends InheritedWidget {
  const NameInheritedWidget({
    Key key,
    this.name,
    Widget child}) : super(key: key, child: child);

  final String name;

  @override
  bool updateShouldNotify(NameInheritedWidget old) {
    print('In updateShouldNotify');
    return name != old.name;
  }

  static NameInheritedWidget of(BuildContext context) {
    // You could also just directly return the name here
    // as there's only one field
    return context.inheritFromWidgetOfExactType(NameInheritedWidget);
  }
}

// Stateful widget for managing name data
class NamePage extends StatefulWidget {
  @override
  _NamePageState createState() => new _NamePageState();
}

// State for managing fetching name data over HTTP
class _NamePageState extends State<NamePage> {
  String name = 'Placeholder';

  // Fetch a name asynchonously over HTTP
  _get() async {
    var res = await http.get('https://jsonplaceholder.typicode.com/users');
    var name = json.decode(res.body)[0]['name'];
    setState(() => this.name = name);
  }

  @override
  void initState() {
    super.initState();
    _get();
  }

  @override
  Widget build(BuildContext context) {
    return new NameInheritedWidget(
      name: name,
      child: const IntermediateWidget()
    );
  }
}

// Intermediate widget to show how inherited widgets
// can propagate changes down the widget tree
class IntermediateWidget extends StatelessWidget {
  // Using a const constructor makes the widget cacheable
  const IntermediateWidget();

  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new Padding(
        padding: new EdgeInsets.all(10.0),
        child: const NameWidget()));
  }
}

class NameWidget extends StatelessWidget {
  const NameWidget();

  @override
  Widget build(BuildContext context) {
    final inheritedWidget = NameInheritedWidget.of(context);
    return new Text(
      inheritedWidget.name,
      style: Theme.of(context).textTheme.display1,
    );
  }
}


问:
In node.js, how to evaluate formulas in excel that contains reference to cells from another sheets in same workbook?
I have an excel sheet that contain multiple formulas. Formulas refer to cells from other sheets in same workbook.Is there any npm package that can evaluate formulas having references of cells from other sheets?   </p>

答:
I am trying to do the same thing right now.

My attempt includes:

xlsx - to read values and functions from the file

hot-formula-parser - to evaluate functions

This library will fire an event each time it tries to evaluate a cell reference.

See callcellvalue documentation for more information

Also see callrangevalue documentation for more when range is required

This should suffice to implement the solution.

Let me know how it works and share your work :)

I will also share mine if I get it working.

Update

So turns out the library [hot-formula-parser] does not officially support cross sheet references. See more info at this ticket

However, I opened a PR for them to support it. Currently available at my fork

I am also working on a library that will enable you to point to a cell, and it will evaluate it. So even if it points to other cells which are formulas, it will recursively evaluate them. Let me know if it is of any interest to you.

Another Small Update

I was able to finish a POC that evaluates thousands of formulas along the way using the stack mentioned above and my PR.

I required some more patches along the way, but most of them can be worked-around if you can modify the excel file (for example, the name of the tab could not have spaces).

ContentLicense: CC BY-SA 3.0


问:
Is the Mutex class safe to use within an ASP.NET request?
The Mutex documentation states:

The Mutex class enforces thread identity, so a mutex can be released
  only by the thread that acquired it. By contrast, the Semaphore class
  does not enforce thread identity. A mutex can also be passed across
  application domain boundaries.

ASP.NET implements thread agility, meaning:

... IIS is free to use more than one thread to handle a
  single request, although not in parallel.

If these two statements are true, then it must be unsafe to use the Mutex class from within an ASP.NET request, because a request can be processed by multiple threads and a mutex can only be released by the thread that acquired it.

Despite this, I can't find it written anywhere that Mutex cannot be used within an ASP.NET request.

答:
Under thread agility, ASP.NET may use a different thread for different handler calls. It's rare. But occasionally you'll see that your module's BeginRequest handler executed on a different thread from the page's OnPreRender handler, that sort of thing.

If you're using a using clause and creating and disposing of the Mutex within the same method call, you will probably be fine.

If for whatever reason the thread does switch on you, the mutex will be treated as abandoned and any other thread can acquire it (WaitOne()) at that point.


问:
How to extract leaf nodes from Oracle XMLTYPE
I want to extract only the leaf nodes from an XMLTYPE object in Oracle 10g

```<code>SELECT
    t.getStringVal() AS text
FROM
    TABLE( XMLSequence(
        XMLTYPE(
            '<xml>
                <node>
                    <one>text</one>
                </node>
                <node>
                    <two>text</two>
                </node>
                <node>
                    <three>text</three>
                </node>
            </xml>'
        ).extract( '//*' )
    ) ) t
</code>```

What should I use as the WHERE clause so this returns only these:

```<code>                    <one>text</one>
                    <two>text</two>
                    <three>text</three>
</code>```

I've tried the following but they don't work:

```<code>WHERE t.existsNode( '//*' ) = 0
WHERE t.existsNode( '/.//*' ) = 0
WHERE t.existsNode( './/*' ) = 0
</code>```

What am I missing?

答:
The XPath //*[not(*)] will get any element at level 1 or deeper that does not have any children:

SQL Fiddle

Query 1:

```<code>SELECT t.getStringVal()
FROM   TABLE(
         XMLSEQUENCE(
           XMLTYPE(
             '<xml>
             <node><one>text</one></node>
             <node><two>text</two></node>
             <node><three>text</three></node>
             </xml>'
           ).extract( '//*[not(*)]' )
         )
       ) t
</code>```

Results:

```<code>|    T.GETSTRINGVAL() |
|---------------------|
|     <one>text</one> |
|     <two>text</two> |
| <three>text</three> |
</code>```

If you want to be able to include the root element then use the XPath  (//*|/*)[not(*)]

OwnerDisplayName: kurosch

ContentLicense: CC BY-SA 2.5

Body:
I want to extract only the leaf nodes from an XMLTYPE object in Oracle 10g

SELECT
    t.getStringVal() AS text
FROM
    TABLE( XMLSequence(
        XMLTYPE(
            '<xml>
                <node>
                    <one>text</one>
                </node>
                <node>
                    <two>text</two>
                </node>
                <node>
                    <three>text</three>
                </node>
            </xml>'
        ).extract( '//*' )
    ) ) t

What should I use as the WHERE clause so this returns only these:

                    <one>text</one>
                    <two>text</two>
                    <three>text</three>

I've tried the following but they don't work:

WHERE t.existsNode( '//*' ) = 0
WHERE t.existsNode( '/.//*' ) = 0
WHERE t.existsNode( './/*' ) = 0

What am I missing?

Body:
The XPath //*[not(*)] will get any element at level 1 or deeper that does not have any children:

SQL Fiddle

Query 1:

SELECT t.getStringVal()
FROM   TABLE(
         XMLSEQUENCE(
           XMLTYPE(
             '<xml>
             <node><one>text</one></node>
             <node><two>text</two></node>
             <node><three>text</three></node>
             </xml>'
           ).extract( '//*[not(*)]' )
         )
       ) t

Results:

|    T.GETSTRINGVAL() |
|---------------------|
|     <one>text</one> |
|     <two>text</two> |
| <three>text</three> |

If you want to be able to include the root element then use the XPath  (//*|/*)[not(*)]


问:
user photo in tab navigation
In a react native project I am trying to set the user's profile photo as a tabBarIcon in tabNavigation. Below is how I am trying to retrieve the photo path and set it in the source for TabBarIcon.

First I have a token in AsyncStorage that gives me the username, email, or phonenumber of the user after login (works fine). This is in my constructor:

```<code>constructor(props) {
  super(props)

  this.state = {
    Access: []
  }

}
</code>```

I set the Access in my state to a value in my AsyncStorage with getItem('Access') which i know works fine.

Now i have a function getProfilePhoto where I use fetch to get the profile photo.

```<code>getProfilePhoto = () => {

  const { Access } = this.state.access;

  fetch('http://urltofiletogetprofilephoto', {
    method: 'POST',
    headers: {
      'Accept':'application/json',
      'Content-Type':'application/json',
    },
    body: JSON.stringify({
      Access:Access
    })
  }).then((response) => response.json())
    .then((responseJson) => {
      if(responseJson === 'NULL') {
        console.log('../Images/NoPhoto.png');
      } else {
        console.log('../' + responseJson);
      }
    })

}
</code>```

What I return from that file is:

```<code>$profilephoto = $row['ProfilePhoto'];
$profilephotoJson = json_encode($profilephoto);
echo $profilephotoJson;
</code>```

That should return something like "Images/userprofilephoto.png". Now in navigationOptions I have this:

```<code>static navigationOptions = {
    tabBarLabel: 'Profile',
    tabBarIcon: ({ tintColor }) => (
        <Image
            source = {this.getProfilePhoto}
            style={[styles.icon, {tintColor: tintColor}]}
        />
    )
}
</code>```

I thought calling the function would print the returned Image path, but when I run the app on my device I don't get an error but my tabBarIcon Image is just blank. I am new to react native and haven't worked with Json much I am hoping someone will be able to see something wrong that I am missing!

答:
You probably need to setState when your promise resolved by adding the data fetching request in the comoponentWillMount hook and make sure your image resides in the generated location relative to your component.

```<code>class UserProfile extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      Access: []
      image: null
    }

  }

  componentWillMount() {
    this.getProfilePhoto();
  }

  getProfilePhoto = () => {

    const { Access } = this.state.access;

    fetch('http://urltofiletogetprofilephoto', {
      method: 'POST',
      headers: {
        'Accept':'application/json',
        'Content-Type':'application/json',
      },
      body: JSON.stringify({
        Access:Access
      })
    }).then((response) => response.json())
      .then((responseJson) => {
        if(responseJson === 'NULL') {
          console.log("../Images/NoPhoto.png");
        } else {
          this.setState({image: responseJson})
        }
      })

  }

  render() {
    return (
       this.state.image
         ?
         <Image
           source={require(this.state.image)}
           style={this.props.style}
         />
         :
         null
    )
  }
}

static navigationOptions = {
    tabBarLabel: 'Profile',
    tabBarIcon: ({ tintColor }) => (
        <UserProfile
            style={[styles.icon, {tintColor: tintColor}]}
        />
    )
}
</code>```

Title: user photo in tab navigation

Body:
In a react native project I am trying to set the user's profile photo as a tabBarIcon in tabNavigation. Below is how I am trying to retrieve the photo path and set it in the source for TabBarIcon.

First I have a token in AsyncStorage that gives me the username, email, or phonenumber of the user after login (works fine). This is in my constructor:

constructor(props) {
  super(props)

  this.state = {
    Access: []
  }

}

I set the Access in my state to a value in my AsyncStorage with getItem('Access') which i know works fine.

Now i have a function getProfilePhoto where I use fetch to get the profile photo.

getProfilePhoto = () => {

  const { Access } = this.state.access;

  fetch('http://urltofiletogetprofilephoto', {
    method: 'POST',
    headers: {
      'Accept':'application/json',
      'Content-Type':'application/json',
    },
    body: JSON.stringify({
      Access:Access
    })
  }).then((response) => response.json())
    .then((responseJson) => {
      if(responseJson === 'NULL') {
        console.log('../Images/NoPhoto.png');
      } else {
        console.log('../' + responseJson);
      }
    })

}

What I return from that file is:

$profilephoto = $row['ProfilePhoto'];
$profilephotoJson = json_encode($profilephoto);
echo $profilephotoJson;

That should return something like "Images/userprofilephoto.png". Now in navigationOptions I have this:

static navigationOptions = {
    tabBarLabel: 'Profile',
    tabBarIcon: ({ tintColor }) => (
        <Image
            source = {this.getProfilePhoto}
            style={[styles.icon, {tintColor: tintColor}]}
        />
    )
}

I thought calling the function would print the returned Image path, but when I run the app on my device I don't get an error but my tabBarIcon Image is just blank. I am new to react native and haven't worked with Json much I am hoping someone will be able to see something wrong that I am missing!

Body:
You probably need to setState when your promise resolved by adding the data fetching request in the comoponentWillMount hook and make sure your image resides in the generated location relative to your component.

class UserProfile extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      Access: []
      image: null
    }

  }

  componentWillMount() {
    this.getProfilePhoto();
  }

  getProfilePhoto = () => {

    const { Access } = this.state.access;

    fetch('http://urltofiletogetprofilephoto', {
      method: 'POST',
      headers: {
        'Accept':'application/json',
        'Content-Type':'application/json',
      },
      body: JSON.stringify({
        Access:Access
      })
    }).then((response) => response.json())
      .then((responseJson) => {
        if(responseJson === 'NULL') {
          console.log("../Images/NoPhoto.png");
        } else {
          this.setState({image: responseJson})
        }
      })

  }

  render() {
    return (
       this.state.image
         ?
         <Image
           source={require(this.state.image)}
           style={this.props.style}
         />
         :
         null
    )
  }
}

static navigationOptions = {
    tabBarLabel: 'Profile',
    tabBarIcon: ({ tintColor }) => (
        <UserProfile
            style={[styles.icon, {tintColor: tintColor}]}
        />
    )
}


问:
Replacing callbacks with promises in Node.js
I have a simple node module which connects to a database and has several functions to receive data, for example this function:

dbConnection.js:

```<code>import mysql from 'mysql';

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'db'
});

export default {
  getUsers(callback) {
    connection.connect(() => {
      connection.query('SELECT * FROM Users', (err, result) => {
        if (!err){
          callback(result);
        }
      });
    });
  }
};
</code>```

The module would be called this way from a different node module:

app.js:

```<code>import dbCon from './dbConnection.js';

dbCon.getUsers(console.log);
</code>```

I would like to use promises instead of callbacks in order to return the data.
So far I've read about nested promises in the following thread: Writing Clean Code With Nested Promises, but I couldn't find any solution that is simple enough for this use case.
What would be the correct way to return result using a promise?

答:
Node.js version 8.0.0+:

You don't have to use bluebird to promisify the node API methods anymore. Because, from version 8+ you can use native util.promisify:

```<code>const util = require('util');

const connectAsync = util.promisify(connection.connectAsync);
const queryAsync = util.promisify(connection.queryAsync);

exports.getUsersAsync = function () {
    return connectAsync()
        .then(function () {
            return queryAsync('SELECT * FROM Users')
        });
};
</code>```

Now, don't have to use any 3rd party lib to do the promisify.

Body:
I have a simple node module which connects to a database and has several functions to receive data, for example this function:

dbConnection.js:

import mysql from 'mysql';

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'db'
});

export default {
  getUsers(callback) {
    connection.connect(() => {
      connection.query('SELECT * FROM Users', (err, result) => {
        if (!err){
          callback(result);
        }
      });
    });
  }
};

The module would be called this way from a different node module:

app.js:

import dbCon from './dbConnection.js';

dbCon.getUsers(console.log);

I would like to use promises instead of callbacks in order to return the data.
So far I've read about nested promises in the following thread: Writing Clean Code With Nested Promises, but I couldn't find any solution that is simple enough for this use case.
What would be the correct way to return result using a promise?

Body:
Node.js version 8.0.0+:

You don't have to use bluebird to promisify the node API methods anymore. Because, from version 8+ you can use native util.promisify:

const util = require('util');

const connectAsync = util.promisify(connection.connectAsync);
const queryAsync = util.promisify(connection.queryAsync);

exports.getUsersAsync = function () {
    return connectAsync()
        .then(function () {
            return queryAsync('SELECT * FROM Users')
        });
};

Now, don't have to use any 3rd party lib to do the promisify.


问:
com.android.tools.build:gradle 3.0.0 and platformBuildVersionName
I have been investigating an issue with platformBuildVersionName and platformBuildVersionCode not present in AndroidManifest that is embedded into output .apk file. From what I have found when using com.android.tools.build:gradle:2.3.3 those fields are in the output manifest but when switching to com.android.tools.build:gradle:3.0.0 they are gone.

platformBuildVersionName and platformBuildVersionCode fields seem to be very vaguely documented, most things that I could find were user questions, not official documentation. It seems that in general I shouldn't care if those fields exist or not at all. They didn't bother me until today actually.

I am stuck with this problem as AirWatch is using those fields for something and it seems crucial for them. My guess here is not to use undocumented stuff like that in your software but I'm not in the position to tell them that.

Anyone had experience with those fields added during apk build time with Gradle 3.0.0?

答:
I'm having the exact same issue with AirWatch!  From an open support ticket with AirWatch, they say the following:

We found a feature request associated with this behavior and the gradle build version.
The reference ID is PR-195117.
There are 2 workarounds.
1. Build the apk using the gradle plugin 2.3.3
2. Upload the apk built using gradle plugin 3.x as a separate app on the console. Define App/ID version code manually and deploy.

They recommend downgrading to gradle 2.3.3

I tried to manually add those attributes to the AndroidManifest.xml file.   Was able to add them to the built apk, but AirWatch still wasn't happy.


问:
fig.caption stops r markdown to docx when using bookdown::word_document2
I am trying to create an article for publication with graphs, tables, cross-referencing and references.

The publishers require the articles to be in docx/doc format.

I have used bookdown::word_document2 and previously had no problem compiling the document.

Suddenly the document has stopped compiling and produces an error.

I have reproduced the problem with an MWE:

```<code>---
title: "MWE"
author: "JEB"
date: "13th November 2017"
output:
    bookdown::word_document2:
      fig_caption: true
---

## Including Plots

You can also embed plots, for example \@ref(fig:pressure)

```{r pressure, echo=FALSE, fig.cap="Test caption"}
plot(pressure)
```
</code>```

If I include fig.cap="Test caption" I get the following error:

Error in parse_fig_labels(x, global) :
   There are multiple labels on one line: (#fig:pressure), (#fig:pressure)
  Calls:  ...  -> process_markdown -> parse_fig_labels
  Execution halted

If I remove the fig.cap="Test caption", I get the following:

Output created: test.docx
  Warning message:
  The label(s) fig:pressure not found

Is this a bug or am I doing something wrong?

[EDIT] Here is my sessionInfo()

```<code>sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Arch Linux

Matrix products: default
BLAS: /usr/lib/libblas.so.3.7.1
LAPACK: /usr/lib/liblapack.so.3.7.1

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C
LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8
 [5] LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_GB.UTF-8
LC_PAPER=en_GB.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] bindrcpp_0.2        ez_4.4-0            knitr_1.17
reshape2_1.4.2      pastecs_1.3-18
 [6] boot_1.3-20         car_2.1-5           compute.es_0.2-4
gridExtra_2.3       ggplot2_2.2.1
[11] xtable_1.8-2        data.table_1.10.4-3 dplyr_0.7.4

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.13       highr_0.6          compiler_3.4.2     nloptr_1.0.4       plyr_1.8.4
 [6] bindr_0.1          tools_3.4.2        digest_0.6.12      lme4_1.1-14        evaluate_0.10.1
[11] tibble_1.3.4       gtable_0.2.0       nlme_3.1-131       lattice_0.20-35    mgcv_1.8-22
[16] pkgconfig_2.0.1    rlang_0.1.4        Matrix_1.2-11      yaml_2.1.14        parallel_3.4.2
[21] SparseM_1.77       stringr_1.2.0      MatrixModels_0.4-1 rprojroot_1.2      nnet_7.3-12
[26] glue_1.2.0         R6_2.2.2           bookdown_0.5       rmarkdown_1.7      minqa_1.2.4
[31] magrittr_1.5       backports_1.1.1    htmltools_0.3.6    scales_0.5.0       MASS_7.3-47
[36] splines_3.4.2      assertthat_0.2.0   pbkrtest_0.4-7     colorspace_1.3-2   labeling_0.3
[41] quantreg_5.34      stringi_1.1.5      lazyeval_0.2.1     munsell_0.4.3
</code>```

答: This was because you were using Pandoc 2.0, and bookdown was not fully compatible with this new version of Pandoc yet. I just pushed a fix on Github, and you can install the development version with devtools::install_github("rstudio/bookdown").

Body:
I am trying to create an article for publication with graphs, tables, cross-referencing and references.

The publishers require the articles to be in docx/doc format.

I have used bookdown::word_document2 and previously had no problem compiling the document.

Suddenly the document has stopped compiling and produces an error.

I have reproduced the problem with an MWE:

---
title: "MWE"
author: "JEB"
date: "13th November 2017"
output:
    bookdown::word_document2:
      fig_caption: true
---

## Including Plots

You can also embed plots, for example \@ref(fig:pressure)

```{r pressure, echo=FALSE, fig.cap="Test caption"}
plot(pressure)
```

If I include fig.cap="Test caption" I get the following error:

Error in parse_fig_labels(x, global) :
   There are multiple labels on one line: (#fig:pressure), (#fig:pressure)
  Calls:  ...  -> process_markdown -> parse_fig_labels
  Execution halted

If I remove the fig.cap="Test caption", I get the following:

Output created: test.docx
  Warning message:
  The label(s) fig:pressure not found

Is this a bug or am I doing something wrong?

[EDIT] Here is my sessionInfo()

sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Arch Linux

Matrix products: default
BLAS: /usr/lib/libblas.so.3.7.1
LAPACK: /usr/lib/liblapack.so.3.7.1

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C
LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8
 [5] LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_GB.UTF-8
LC_PAPER=en_GB.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] bindrcpp_0.2        ez_4.4-0            knitr_1.17
reshape2_1.4.2      pastecs_1.3-18
 [6] boot_1.3-20         car_2.1-5           compute.es_0.2-4
gridExtra_2.3       ggplot2_2.2.1
[11] xtable_1.8-2        data.table_1.10.4-3 dplyr_0.7.4

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.13       highr_0.6          compiler_3.4.2     nloptr_1.0.4       plyr_1.8.4
 [6] bindr_0.1          tools_3.4.2        digest_0.6.12      lme4_1.1-14        evaluate_0.10.1
[11] tibble_1.3.4       gtable_0.2.0       nlme_3.1-131       lattice_0.20-35    mgcv_1.8-22
[16] pkgconfig_2.0.1    rlang_0.1.4        Matrix_1.2-11      yaml_2.1.14        parallel_3.4.2
[21] SparseM_1.77       stringr_1.2.0      MatrixModels_0.4-1 rprojroot_1.2      nnet_7.3-12
[26] glue_1.2.0         R6_2.2.2           bookdown_0.5       rmarkdown_1.7      minqa_1.2.4
[31] magrittr_1.5       backports_1.1.1    htmltools_0.3.6    scales_0.5.0       MASS_7.3-47
[36] splines_3.4.2      assertthat_0.2.0   pbkrtest_0.4-7     colorspace_1.3-2   labeling_0.3
[41] quantreg_5.34      stringi_1.1.5      lazyeval_0.2.1     munsell_0.4.3


问:
Parsing POSTed multipart/form-data in Rails 4.2
I am trying to implement a simple AJAX image uploader with multiple selection support using a standard HTML input with type="file". The JS uploading code looks like:

```<code>var files = document.getElementById("txtFiles").files;
var formData = new FormData();

for (var file = 0; file < files.length; file++) {
  formData.append("userimage", files[file], name)
}

//throw up a loading bar while we're uploading
util.loaderShow("Uploading, please wait...");

$.ajax({

  url: '#{upload_alert_image_url}',

  data: formData,
  processData: false,
  contentType: 'multipart/form-data',
  type: 'POST',

  success: function() {
    util.loaderHide();
    alert("Got success!");
    finish_upload();
  },

  error: function(e) {
    util.loaderHide()
    alert("Upload failed: "+e);
  },

  complete: function() {
    util.loaderHide();
  }

})
</code>```

On the Rails side of things, right now request.body is simply saved to a temporary file, and inside that temp file is the body of the request from the above JS snippet, as expected.

What is the correct way to get at that data without having to write a multipart/form-data parser myself? Is there a function somewhere that takes this raw data and spits out some sort of hash or array with the included uploads?

I've been Googling and searching SO and Rails docs for an hour or two trying to find an answer. There are a variety of gems that handle file uploading (most of which have way too other cruft I don't want) as well as the multipart-parser, and I have checked these out... but given that multipart/form-data is old and useful, I have a hard time believing there isn't in-the-box support someplace I'm not looking. Rack::Middleware claims to have an .extract_multipart class method, according to its docs, but I can't figure out how to access it.

So... how is one supposed to receive POST'd multipart/form-data?

Thanks

Tom

答:
There are a number of gems that handle this for you, as you've mentioned. The reason they exist is because

There isn't anything built in to rails* simplify handling multipart form data

Doing it yourself isn't easy

*Rails 5.2 will finally introduce ActiveStorage, built-in polish for handling file uploads.

As an aside, file uploads tie up a server process. If the file is large, this could be really painful for other users trying to access your app as they could get timed out. The general consensus is to upload your files client-side to the cloud storage provider of your choice instead of to your rails server. ActiveStorage will support this as well.

Body:
I am trying to implement a simple AJAX image uploader with multiple selection support using a standard HTML input with type="file". The JS uploading code looks like:

var files = document.getElementById("txtFiles").files;
var formData = new FormData();

for (var file = 0; file < files.length; file++) {
  formData.append("userimage", files[file], name)
}

//throw up a loading bar while we're uploading
util.loaderShow("Uploading, please wait...");

$.ajax({

  url: '#{upload_alert_image_url}',

  data: formData,
  processData: false,
  contentType: 'multipart/form-data',
  type: 'POST',

  success: function() {
    util.loaderHide();
    alert("Got success!");
    finish_upload();
  },

  error: function(e) {
    util.loaderHide()
    alert("Upload failed: "+e);
  },

  complete: function() {
    util.loaderHide();
  }

})

On the Rails side of things, right now request.body is simply saved to a temporary file, and inside that temp file is the body of the request from the above JS snippet, as expected.

What is the correct way to get at that data without having to write a multipart/form-data parser myself? Is there a function somewhere that takes this raw data and spits out some sort of hash or array with the included uploads?

I've been Googling and searching SO and Rails docs for an hour or two trying to find an answer. There are a variety of gems that handle file uploading (most of which have way too other cruft I don't want) as well as the multipart-parser, and I have checked these out... but given that multipart/form-data is old and useful, I have a hard time believing there isn't in-the-box support someplace I'm not looking. Rack::Middleware claims to have an .extract_multipart class method, according to its docs, but I can't figure out how to access it.

So... how is one supposed to receive POST'd multipart/form-data?

Thanks

Tom


问:
best practice to add git workflow on existing websites
Up until now I worked on my websites alone and without any kind of version control right on my server (basically opened and modified files stored in each /var/www/vhosts/domain.tld/httpdocs-Folder directly over sftp with an IDE/over ssh) since it was sufficient for my needs.

Now I'm searching for the best way to collaborate with other developers and use git for all of these already existing websites.

Is it recommendable to create multiple bare repositories like

/home/git/domain_1.git,   /home/git/domain_2.git, ...

with e.g. git init --bare domain_1.git in some folder like /home/git/
with my root-Account and then somehow** add each already existing /var/www/vhosts/domain/httpdocs-Folder to each of these bare git repos and then add an hook (post-receive?) to each repo to overwrite it's specific /var/www/vhosts/domain.tld/httpdocs-Folder at every push. And then give every developer access via the git-User with URL like ssh://git@1.2.3.4:/home/git/domain_1.git for each single repo.

If that way should be fine: Is there any kind of walkthrough out there? I couldn't find anything and I'm searching for a proper solution since days, no kidding...

Or is there any better/best practice to solve this kind of issue?

** = (how?! since no git command like git add works on these bare repos...)

答:
First thing congratulations on deciding on to use a version control system to manage your codebase.
Second thing you don't need multiple bare repositories to maintain multiple folders in your source control.
Since you have asked for the best practices I will directly get into what you need to do to set yourself up with a source control.

You need a DVCS tool ---> GIT
One repository to host your source code---->Github/Bitbucket Cloud
Once you have the repository created in the above Source Control Management Tool create and empty repo and pull all your code inside that repo. Follow this for how to?

Next you need to design a branching strategy so that other developers can keep developing on the same codebase. I would start with something simple like one master branch(to maintain different release versions)  and one integration branch named develop. Your developers need to create feature branches to implement new features. You can review them and merge them on to integration and then on to master.
To learn more you can follow https://git-scm.com/book/en/v2/Git-Branching-Branching-Workflows


问:
Multithreading not working - Create thread per loop index Java
I wrote the below code trying to run two threads for calling a function in a for loop, but the results have the same time as if I ran it sequentially without multiple threads. Any thoughts why the multithreading here is not working? Is there a better way to do it? Like for example if I wanted to have 10 threads, using my code this will mean I have to create 10 duplicate run() functions when creating the thread, I wonder if there is an easier way to set the number of threads? Also is it possible to create a number of threads depending on the loop counter so that each loop a thread is created to finish it so if I had 10 loops then 10 threads will run concurrently to finish the processing very fast?</p>

```<code>   private Thread t1 = new Thread(){
   public void run(){

            for (int i = 0; i < 2; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    };

    private Thread t2 = new Thread(){
        public void run(){

            for (int i = 2; i < 4; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            }
    };

 public Results getResults() throws IOException, SocketTimeoutException {

        t1.start();
        t2.start();
        try {
            t1.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            t2.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
</code>```

答:
You don't need to copy your threads / loop 10 times, just take the logic and use it appropriately.</p>

```<code>public class ExampleThread extends Thread {
  private final int start, iterations;
  public ExampleThread(int start, int iterations) {
    this.start = start;
    this.iterations = iterations;
  }
  @Override public void run() {
    for (int i = 0; i < iterations; i++) {
      myfn(start + i);
    }
  }
}

int iterations = 2;
List<Thread> threads = new ArrayList<>();
for (int threadId = 0; threadId < 10; threadId++) {
  threads.add(new ExampleThread(threadId * iterations, iterations));
}
threads.forEach(Thread::start);
threads.forEach(t -> {
  try {
    t.join(0);
  } catch (Exception e) {
    e.printStackTrace(System.err);
  }
});
</code>```

Body:
I wrote the below code trying to run two threads for calling a function in a for loop, but the results have the same time as if I ran it sequentially without multiple threads. Any thoughts why the multithreading here is not working? Is there a better way to do it? Like for example if I wanted to have 10 threads, using my code this will mean I have to create 10 duplicate run() functions when creating the thread, I wonder if there is an easier way to set the number of threads? Also is it possible to create a number of threads depending on the loop counter so that each loop a thread is created to finish it so if I had 10 loops then 10 threads will run concurrently to finish the processing very fast?

   private Thread t1 = new Thread(){
   public void run(){

            for (int i = 0; i < 2; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    };

    private Thread t2 = new Thread(){
        public void run(){

            for (int i = 2; i < 4; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            }
    };

 public Results getResults() throws IOException, SocketTimeoutException {

        t1.start();
        t2.start();
        try {
            t1.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            t2.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

Body:
You don't need to copy your threads / loop 10 times, just take the logic and use it appropriately.

public class ExampleThread extends Thread {
  private final int start, iterations;
  public ExampleThread(int start, int iterations) {
    this.start = start;
    this.iterations = iterations;
  }
  @Override public void run() {
    for (int i = 0; i < iterations; i++) {
      myfn(start + i);
    }
  }
}

int iterations = 2;
List<Thread> threads = new ArrayList<>();
for (int threadId = 0; threadId < 10; threadId++) {
  threads.add(new ExampleThread(threadId * iterations, iterations));
}
threads.forEach(Thread::start);
threads.forEach(t -> {
  try {
    t.join(0);
  } catch (Exception e) {
    e.printStackTrace(System.err);
  }
});


问:
Plot Pandas groupby dataframe
I am having some problems with plotting a Pandas dataframe that was created from a groupby() and now has a RangeIndex.

For example, here is my input data with four columns:

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df.head()
#     A   B   C   D
# 0  83  99  55  83
# 1  91  42  14  27
# 2  44   4  30   9
# 3  96  46  92  73
# 4  91  73  17  36
</code>```

I then apply a groupby() to get two columns: A and the mean of B.

```<code>gb = df.groupby(pd.cut(df.A, 10)).B.mean()
gb
# A
# (-0.099, 9.9]    38.272727
# (9.9, 19.8]      49.800000
# (19.8, 29.7]     55.000000
# (29.7, 39.6]     50.454545
# (39.6, 49.5]     46.285714
# (49.5, 59.4]     44.800000
# (59.4, 69.3]     48.500000
# (69.3, 79.2]     55.615385
# (79.2, 89.1]     45.500000
# (89.1, 99]       51.866667
# Name: B, dtype: float64

gb_df = gb.to_frame().reset_index()
gb_df
#                A          B
# 0  (-0.099, 9.9]  38.272727
# 1    (9.9, 19.8]  49.800000
# 2   (19.8, 29.7]  55.000000
# 3   (29.7, 39.6]  50.454545
# 4   (39.6, 49.5]  46.285714
# 5   (49.5, 59.4]  44.800000
# 6   (59.4, 69.3]  48.500000
# 7   (69.3, 79.2]  55.615385
# 8   (79.2, 89.1]  45.500000
# 9     (89.1, 99]  51.866667
</code>```

Now, when I try to plot A and B, I get an error because column A is of RangeIndex.

```<code>plt.scatter(x=gb_df.A, y=gb_df.B)

# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# ValueError: could not convert string to float: (89.1, 99]
</code>```

Ideally, I would like to plot the lower bound of the A column's RangeIndex as the X-axis. So data like this would be great:

```<code>#         A          B
# 0  -0.099  38.272727
# 1     9.9  49.800000
# 2    19.8  55.000000
</code>```

Thanks for any help.

Title: Plot Pandas groupby dataframe

Body:
I am having some problems with plotting a Pandas dataframe that was created from a groupby() and now has a RangeIndex.

For example, here is my input data with four columns:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df.head()
#     A   B   C   D
# 0  83  99  55  83
# 1  91  42  14  27
# 2  44   4  30   9
# 3  96  46  92  73
# 4  91  73  17  36

I then apply a groupby() to get two columns: A and the mean of B.

gb = df.groupby(pd.cut(df.A, 10)).B.mean()
gb
# A
# (-0.099, 9.9]    38.272727
# (9.9, 19.8]      49.800000
# (19.8, 29.7]     55.000000
# (29.7, 39.6]     50.454545
# (39.6, 49.5]     46.285714
# (49.5, 59.4]     44.800000
# (59.4, 69.3]     48.500000
# (69.3, 79.2]     55.615385
# (79.2, 89.1]     45.500000
# (89.1, 99]       51.866667
# Name: B, dtype: float64

gb_df = gb.to_frame().reset_index()
gb_df
#                A          B
# 0  (-0.099, 9.9]  38.272727
# 1    (9.9, 19.8]  49.800000
# 2   (19.8, 29.7]  55.000000
# 3   (29.7, 39.6]  50.454545
# 4   (39.6, 49.5]  46.285714
# 5   (49.5, 59.4]  44.800000
# 6   (59.4, 69.3]  48.500000
# 7   (69.3, 79.2]  55.615385
# 8   (79.2, 89.1]  45.500000
# 9     (89.1, 99]  51.866667

Now, when I try to plot A and B, I get an error because column A is of RangeIndex.

plt.scatter(x=gb_df.A, y=gb_df.B)

# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# ValueError: could not convert string to float: (89.1, 99]

Ideally, I would like to plot the lower bound of the A column's RangeIndex as the X-axis. So data like this would be great:

#         A          B
# 0  -0.099  38.272727
# 1     9.9  49.800000
# 2    19.8  55.000000

Thanks for any help.

Body:
By using left to get the leftbreak.

gb_df['New_A']=gb_df.A.apply(lambda x : x.left).astype('float')
gb_df.plot.scatter(x = 'New_A', y='B')

Data Info:

gb_df
               A          B   New_A
0  (-0.099, 9.9]  39.928571  -0.099
1    (9.9, 19.8]  33.090909   9.900
2   (19.8, 29.7]  41.900000  19.800
3   (29.7, 39.6]  46.500000  29.700
4   (39.6, 49.5]  52.454545  39.600
5   (49.5, 59.4]  37.866667  49.500
6   (59.4, 69.3]  60.600000  59.400
7   (69.3, 79.2]  71.300000  69.300
8   (79.2, 89.1]  42.714286  79.200
9   (89.1, 99.0]  52.545455  89.100


问:
Kubernetes service with clustered PODs in active/standby
Apologies for not keeping this short, as any such attempt would make me miss-out on some important details of my problem.

I have a legacy Java application which works in a active/standby mode in a clustered environment to expose certain RESTful WebServices via a predefined port.

If there are two nodes in my app cluster, at any point in time only one would be in Active mode, and the other in Passive mode, and the requests are always served by the node with app running in Active mode. 'Active' and 'Passive' are just roles, the app as such would be running on both nodes. The Active and Passive instances communicate with each other through this same predetermined port.

Suppose I have a two node cluster with one instance of my application running on each node, then one of the instance would initially be active and the other will be passive. If for some reason the active node goes for a toss for some reason, the app instance in other node identifies this using some heartbeat mechanism, takes over the control and becomes the new active. When the old active comes back up it detects the other guy has owned up the new Active role, hence it goes into Passive mode.

The application manages to provide RESTful webservices on the same endpoint IP irrespective of which node is running the app in 'Active' mode by using a cluster IP, which piggy-backs on the active instance, so the cluster IP switches over to whichever node is running the app in Active mode.

I am trying to containerize this app and run this in a Kubernetes cluster for scale and ease of deployment. I am able to containerize and able to deploy it as a POD in a Kubernetes cluster.

In order to bring in the Active/Passive role here, I am running two instances of this POD, each pinned to a separate K8S nodes using node affinity (each node is labeled as either active or passive, and POD definitions pin on these labels), and clustering them up using my app's clustering mechanism whereas only one will be active and the other will be passive.

I am exposing the REST service externally using K8S Service semantics by making use of the NodePort, and exposing the REST WebService via a NodePort on the master node.

Here's my yaml file content:

```<code>apiVersion: v1
kind: Service
metadata:
  name: myapp-service
  labels:
    app: myapp-service
spec:
  type: NodePort
  ports:
    - port: 8443
      nodePort: 30403
  selector:
    app: myapp

---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: active
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: myapp
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: nodetype
                operator: In
                values:
                - active
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
           claimName: active-pv-claim
      containers:
      - name: active
        image: myapp:latest
        imagePullPolicy: Never
        securityContext:
           privileged: true
        ports:
         - containerPort: 8443
        volumeMounts:
        - mountPath: "/myapptmp"
          name: task-pv-storage

---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: passive
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: myapp
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: nodetype
                operator: In
                values:
                - passive
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
           claimName: active-pv-claim
      containers:
      - name: passive
        image: myapp:latest
        imagePullPolicy: Never
        securityContext:
           privileged: true
        ports:
         - containerPort: 8443
        volumeMounts:
        - mountPath: "/myapptmp"
          name: task-pv-storage
</code>```

Everything seems working fine, except that since both PODs are exposing the web service via same port, the K8S Service is routing the incoming requests to one of these PODS in a random fashion. Since my REST WebService endpoints work only on Active node, the service requests work via K8S Service resource only when the request is getting routed to the POD with app in Active role. If at any point in time the K8S Service happens to route the incoming request to POD with app in passive role, the service is inaccessible/not served.

How do I make this work in such a way that the K8S service always routes the requests to POD with app in Active role? Is this something doable in Kubernetes or I'm aiming for too much?

Thank you for your time!

答:
One way to achieve this is add label tag in the pod as active and standby. then select the active pod in your service. this will send the traffic to pod labeled as active.

https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#service-and-replicationcontroller

you can find another example on this document.

https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/

Body:
Apologies for not keeping this short, as any such attempt would make me miss-out on some important details of my problem.

I have a legacy Java application which works in a active/standby mode in a clustered environment to expose certain RESTful WebServices via a predefined port.

If there are two nodes in my app cluster, at any point in time only one would be in Active mode, and the other in Passive mode, and the requests are always served by the node with app running in Active mode. 'Active' and 'Passive' are just roles, the app as such would be running on both nodes. The Active and Passive instances communicate with each other through this same predetermined port.

Suppose I have a two node cluster with one instance of my application running on each node, then one of the instance would initially be active and the other will be passive. If for some reason the active node goes for a toss for some reason, the app instance in other node identifies this using some heartbeat mechanism, takes over the control and becomes the new active. When the old active comes back up it detects the other guy has owned up the new Active role, hence it goes into Passive mode.

The application manages to provide RESTful webservices on the same endpoint IP irrespective of which node is running the app in 'Active' mode by using a cluster IP, which piggy-backs on the active instance, so the cluster IP switches over to whichever node is running the app in Active mode.

I am trying to containerize this app and run this in a Kubernetes cluster for scale and ease of deployment. I am able to containerize and able to deploy it as a POD in a Kubernetes cluster.

In order to bring in the Active/Passive role here, I am running two instances of this POD, each pinned to a separate K8S nodes using node affinity (each node is labeled as either active or passive, and POD definitions pin on these labels), and clustering them up using my app's clustering mechanism whereas only one will be active and the other will be passive.

I am exposing the REST service externally using K8S Service semantics by making use of the NodePort, and exposing the REST WebService via a NodePort on the master node.

Here's my yaml file content:

apiVersion: v1
kind: Service
metadata:
  name: myapp-service
  labels:
    app: myapp-service
spec:
  type: NodePort
  ports:
    - port: 8443
      nodePort: 30403
  selector:
    app: myapp

---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: active
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: myapp
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: nodetype
                operator: In
                values:
                - active
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
           claimName: active-pv-claim
      containers:
      - name: active
        image: myapp:latest
        imagePullPolicy: Never
        securityContext:
           privileged: true
        ports:
         - containerPort: 8443
        volumeMounts:
        - mountPath: "/myapptmp"
          name: task-pv-storage

---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: passive
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: myapp
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: nodetype
                operator: In
                values:
                - passive
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
           claimName: active-pv-claim
      containers:
      - name: passive
        image: myapp:latest
        imagePullPolicy: Never
        securityContext:
           privileged: true
        ports:
         - containerPort: 8443
        volumeMounts:
        - mountPath: "/myapptmp"
          name: task-pv-storage

Everything seems working fine, except that since both PODs are exposing the web service via same port, the K8S Service is routing the incoming requests to one of these PODS in a random fashion. Since my REST WebService endpoints work only on Active node, the service requests work via K8S Service resource only when the request is getting routed to the POD with app in Active role. If at any point in time the K8S Service happens to route the incoming request to POD with app in passive role, the service is inaccessible/not served.

How do I make this work in such a way that the K8S service always routes the requests to POD with app in Active role? Is this something doable in Kubernetes or I'm aiming for too much?

Thank you for your time!


答:
For running the same task across multiple threads, you're probably looking for a thread pool. Java provides a ThreadPoolExecutor for this.

Here is an introduction to Java concurrency with the following example:

```<code>ExecutorService executor = Executors.newFixedThreadPool(1);

Future<Integer> future = executor.submit(() -> {
    try {
        TimeUnit.SECONDS.sleep(2);
        return 123;
    }
    catch (InterruptedException e) {
        throw new IllegalStateException("task interrupted", e);
    }
});

future.get(1, TimeUnit.SECONDS);
</code>```

That example specifically creates a pool with only a single thread, but the parameter to Executors.newFixedThreadPool controls how many threads will be used.

I'm not sure from your original question why you think two threads aren't being utilized.

Title: Multithreading not working - Create thread per loop index Java

Body:
For running the same task across multiple threads, you're probably looking for a thread pool. Java provides a ThreadPoolExecutor for this.

Here is an introduction to Java concurrency with the following example:

ExecutorService executor = Executors.newFixedThreadPool(1);

Future<Integer> future = executor.submit(() -> {
    try {
        TimeUnit.SECONDS.sleep(2);
        return 123;
    }
    catch (InterruptedException e) {
        throw new IllegalStateException("task interrupted", e);
    }
});

future.get(1, TimeUnit.SECONDS);

That example specifically creates a pool with only a single thread, but the parameter to Executors.newFixedThreadPool controls how many threads will be used.

I'm not sure from your original question why you think two threads aren't being utilized.


问:
Can a Scan (build & tests) be reused in Gym (build) when creating an archive?
I have a project which builds and tests in 10 minutes. If the Fastlane Scan does not throw an error then I build an archive with the Fastlane Gym.

In total it takes almost 18 minutes.

I would like to decrease a delivery time for an app build and the first idea is to reuse a build from Scan in Gym. Is it possible?

答:
I'm not entirely certain, but I don't think it's possible. I think Xcode always does a full build, not an incremental build, when archiving, so it doesn't matter what's already there. Also, usually you test with the Debug configuration and archive with the Release configuration. You can pass a configuration parameter to scan telling it to do a Release build. If you look at the scheme in your project or workspace, it's probably set up to test with Debug (when you use cmd-U in Xcode). You may or may not have issues unit testing with Release, depending on your codebase. At least you might have to modify some tests.

There are ways to speed up your build with Xcode. Maybe something here will help:

https://developer.apple.com/library/content/technotes/tn2190/_index.html


问:
Unable to connect to Google Cloud SQL with eclipse
I'm having trouble connecting to my database from eclipse. The mysql java connector & the mysql socket factory connector jar files are included in the build path. I'm not sure what is causing the NoClassDefFound error. The credentials are correct and omitted in the code.

My code:

```<code>import java.sql.*;

public class TestConnect {

private static String instanceConnectionName = "sampleInstanceName";
private static String databaseName = "sampleDatabaseName";
private static Connection connection = null;
private static String userName="sampleUserName";
private static String password="samplePassword";
private static String dbURL = String.format("jdbc:mysql://google/%s?cloudSqlInstance=%s&"
                                + "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
                                databaseName, instanceConnectionName);

public static void main(String[] args) {
    // TODO Auto-generated method stub
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (Exception e) {
                System.out.println("Where is your MySQL JDBC Driver?");
                e.printStackTrace();
                return;
            }
            System.out.println("MySQL JDBC Driver Registered!");
            CreateConnection();
    }

    public static void CreateConnection() {
            try {
            // connect
                connection = DriverManager.getConnection(dbURL,userName, password);
            } catch (SQLException ex) {
                System.out.println("Connection Failed! Check output console");
                ex.printStackTrace();
            }
        }

}
</code>```

Here is the pom.xml:

```<code>  <dependencies>
<!-- https://mvnrepository.com/artifact/com.google.cloud.sql/mysql-socket-factory -->
<dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>mysql-socket-factory</artifactId>
    <version>1.0.4</version>
</dependency>
<dependency>                        <!-- http://dev.mysql.com/doc/connector-j/en/ -->
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.44</version>
</dependency>

  </dependencies>
</project>
</code>```

And here is the error message:

```<code>java.sql.SQLException: java.lang.NoClassDefFoundError: com/mysql/cj/api/io/SocketFactory
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:877)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:873)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:443)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at TestConnect.CreateConnection(TestConnect.java:32)
    at TestConnect.main(TestConnect.java:26)
Caused by: java.lang.NoClassDefFoundError: com/mysql/cj/api/io/SocketFactory
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at com.mysql.jdbc.MysqlIO.createSocketFactory(MysqlIO.java:3328)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:296)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2189)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2222)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2017)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    ... 6 more
Caused by: java.lang.ClassNotFoundException: com.mysql.cj.api.io.SocketFactory
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 32 more
</code>```

UPDATE

I updated the jar files and removed the unnecessary ones and updated the pom file accordingly.

Here is the new pom file:

```<code>  <dependencies>
<!-- https://mvnrepository.com/artifact/com.google.cloud.sql/mysql-socket-factory-connector-j-6 -->
<dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>mysql-socket-factory-connector-j-6</artifactId>
    <version>1.0.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.cloud.sql/jdbc-socket-factory-core -->
<dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>jdbc-socket-factory-core</artifactId>
    <version>1.0.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>
  </dependencies>
</code>```

And here is the new error message:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/base/Preconditions
    at com.google.cloud.sql.mysql.SocketFactory.connect(SocketFactory.java:41)
    at com.mysql.cj.mysqla.io.MysqlaSocketConnection.connect(MysqlaSocketConnection.java:57)
    at com.mysql.cj.mysqla.MysqlaSession.connect(MysqlaSession.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1726)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1596)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:633)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:347)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:219)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at TestConnect.CreateConnection(TestConnect.java:30)
    at TestConnect.main(TestConnect.java:24)
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Preconditions
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 12 more
</code>```

答:
com.mysql.cj.api.io.SocketFactory is part of the MySQL Connector/J version 6. This is used by the SocketFactory in the mysql-socket-factory-connector-j-6. However the pom.xml you shared, uses mysql-socket-factory which is the version 5 packet and shouldn't use it.

Is it possible that you used mysql-socket-factory-connector-j-6 previously and it is in your libraries from that? This could allow the v6 SocketFactory to be loaded by mistake, causing this issue. If so try mvn clean to get rid of the old jar file and try running again.

Body:
I'm having trouble connecting to my database from eclipse. The mysql java connector & the mysql socket factory connector jar files are included in the build path. I'm not sure what is causing the NoClassDefFound error. The credentials are correct and omitted in the code.

My code:

import java.sql.*;

public class TestConnect {

private static String instanceConnectionName = "sampleInstanceName";
private static String databaseName = "sampleDatabaseName";
private static Connection connection = null;
private static String userName="sampleUserName";
private static String password="samplePassword";
private static String dbURL = String.format("jdbc:mysql://google/%s?cloudSqlInstance=%s&"
                                + "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
                                databaseName, instanceConnectionName);

public static void main(String[] args) {
    // TODO Auto-generated method stub
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (Exception e) {
                System.out.println("Where is your MySQL JDBC Driver?");
                e.printStackTrace();
                return;
            }
            System.out.println("MySQL JDBC Driver Registered!");
            CreateConnection();
    }

    public static void CreateConnection() {
            try {
            // connect
                connection = DriverManager.getConnection(dbURL,userName, password);
            } catch (SQLException ex) {
                System.out.println("Connection Failed! Check output console");
                ex.printStackTrace();
            }
        }

}

Here is the pom.xml:

  <dependencies>

<dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>mysql-socket-factory</artifactId>
    <version>1.0.4</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.44</version>
</dependency>

  </dependencies>
</project>

And here is the error message:

java.sql.SQLException: java.lang.NoClassDefFoundError: com/mysql/cj/api/io/SocketFactory
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:877)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:873)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:443)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at TestConnect.CreateConnection(TestConnect.java:32)
    at TestConnect.main(TestConnect.java:26)
Caused by: java.lang.NoClassDefFoundError: com/mysql/cj/api/io/SocketFactory
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at com.mysql.jdbc.MysqlIO.createSocketFactory(MysqlIO.java:3328)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:296)
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2189)
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2222)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2017)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    ... 6 more
Caused by: java.lang.ClassNotFoundException: com.mysql.cj.api.io.SocketFactory
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 32 more

UPDATE

I updated the jar files and removed the unnecessary ones and updated the pom file accordingly.

Here is the new pom file:

  <dependencies>

<dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>mysql-socket-factory-connector-j-6</artifactId>
    <version>1.0.4</version>
</dependency>

<dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>jdbc-socket-factory-core</artifactId>
    <version>1.0.4</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>
  </dependencies>

And here is the new error message:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/base/Preconditions
    at com.google.cloud.sql.mysql.SocketFactory.connect(SocketFactory.java:41)
    at com.mysql.cj.mysqla.io.MysqlaSocketConnection.connect(MysqlaSocketConnection.java:57)
    at com.mysql.cj.mysqla.MysqlaSession.connect(MysqlaSession.java:122)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1726)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1596)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:633)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:347)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:219)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at TestConnect.CreateConnection(TestConnect.java:30)
    at TestConnect.main(TestConnect.java:24)
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Preconditions
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 12 more


问:
R - Match based on minimum difference between column in data.frame
I have the following two dataframes:

```<code>df1 <- data.frame(Subject=c("S1","S1","S2","S2","S2","S3","S3"),
       SampleTime=c(1,2,1,2.1,3,0.9,2), Value=c(3,4,3,2,2,4,5))

df2 <- data.frame(Subject=c("S1","S1","S1","S2","S2","S2","S2","S3","S3"),
       SampleTime=c(0.99, 2.01,2.99, 0,1.01,2,3,1.2,2.02), Conc=c(4.7,5.2,8,5,2,1,3,4,6))
</code>```

My goal is to add the column df2$Conc to df1 where the difference between SampleTime in df1 and df2 is smallest per subject. In addition, I would like to add a column that shows the difference between SampleTime.

Desired output:

```<code>output <- data.frame(Subject=c("S1","S1","S2","S2","S2","S3","S3"),
                     SampleTime=c(1,2,1,2.1,3,0.9,2), Value=c(3,4,3,2,2,4,5),
                     SampleTime_df2=c(0.99,2.01,1.01,2,3,1.20,2.02), Conc=c(4.7,5.2,2,1,3,4,6))
</code>```

So far, I'm able to it per subject, like this for Subject S2:

```<code>     Indices <- sapply(df1$SampleTime[df1$Subject=="S2"], FUN=function(x,y) which.min(abs(y - x)), y=df2$SampleTime[df2$Subject=="S2"])
     df1$SampleTime_df2[df1$Subject=="S2"] <- df2$SampleTime[df2$Subject=="S2"][Indices]
     df1$Conc[df1$Subject=="S2"] <- df2$Conc[df2$Subject=="S2"][Indices]
</code>```

The code doesn't look very nice and I would like to do it for all subjects at once. In my real data, there aren't any ties (i.e. two sample times in df2 that are equally closest to one sample time in df1), but let's say that in that case I would like to keep the first.

I hope my question is clear. Thank you for your help!

答:
I think this is what you're looking for? Do an inner join, and then take the absolute difference, sort it and slice. This is all using dplyr</p>

```<code>require(dplyr)

df3 <- df1 %>%
         rename(ST1 = SampleTime) %>%
         inner_join(df2, by = "Subject") %>%
         group_by(Subject, ST1) %>%
         mutate(diff = abs(ST1 - SampleTime)) %>%
         arrange(diff) %>%
         slice(1) %>%
         ungroup()
</code>```

Body:
I have the following two dataframes:

df1 <- data.frame(Subject=c("S1","S1","S2","S2","S2","S3","S3"),
       SampleTime=c(1,2,1,2.1,3,0.9,2), Value=c(3,4,3,2,2,4,5))

df2 <- data.frame(Subject=c("S1","S1","S1","S2","S2","S2","S2","S3","S3"),
       SampleTime=c(0.99, 2.01,2.99, 0,1.01,2,3,1.2,2.02), Conc=c(4.7,5.2,8,5,2,1,3,4,6))

My goal is to add the column df2$Conc to df1 where the difference between SampleTime in df1 and df2 is smallest per subject. In addition, I would like to add a column that shows the difference between SampleTime.

Desired output:

output <- data.frame(Subject=c("S1","S1","S2","S2","S2","S3","S3"),
                     SampleTime=c(1,2,1,2.1,3,0.9,2), Value=c(3,4,3,2,2,4,5),
                     SampleTime_df2=c(0.99,2.01,1.01,2,3,1.20,2.02), Conc=c(4.7,5.2,2,1,3,4,6))

So far, I'm able to it per subject, like this for Subject S2:

     Indices <- sapply(df1$SampleTime[df1$Subject=="S2"], FUN=function(x,y) which.min(abs(y - x)), y=df2$SampleTime[df2$Subject=="S2"])
     df1$SampleTime_df2[df1$Subject=="S2"] <- df2$SampleTime[df2$Subject=="S2"][Indices]
     df1$Conc[df1$Subject=="S2"] <- df2$Conc[df2$Subject=="S2"][Indices]

The code doesn't look very nice and I would like to do it for all subjects at once. In my real data, there aren't any ties (i.e. two sample times in df2 that are equally closest to one sample time in df1), but let's say that in that case I would like to keep the first.

I hope my question is clear. Thank you for your help!

Body:
I think this is what you're looking for? Do an inner join, and then take the absolute difference, sort it and slice. This is all using dplyr

require(dplyr)

df3 <- df1 %>%
         rename(ST1 = SampleTime) %>%
         inner_join(df2, by = "Subject") %>%
         group_by(Subject, ST1) %>%
         mutate(diff = abs(ST1 - SampleTime)) %>%
         arrange(diff) %>%
         slice(1) %>%
         ungroup()


问:
Daemon using MSAL to MSGraph
I'm getting the error AADSTS70002: Error validating credentials. AADSTS50012: Client assertion audience claim does not match Realm issuer

when running this code.

```<code>    string[] scopes = new string[]{"https://graph.microsoft.com/.default"};
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
var cert = certStore.Certificates.Cast<X509Certificate2>().First(c => c.Thumbprint == "XXX-XXX etc");
var cas = new ClientAssertionCertificate(cert);
var cc = new Microsoft.Identity.Client.ClientCredential(cas);
var client = new Microsoft.Identity.Client.ConfidentialClientApplication("XX-XXX etc", "http://localhost", cc, new TokenCache(), new TokenCache() );
var authResult = await client.AcquireTokenForClientAsync(scopes);
var dap = new DelegateAuthenticationProvider(rm =>
{
    rm.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", authResult.AccessToken);
    return Task.FromResult(0);
});
var gClient = new GraphServiceClient(dap);
gClient.Me.Dump();
</code>```

Error occurrs on the call to AcquireTokenForClientAsync() method.

I can not find any online documentation for MSAL and Daemon clients where no user authentication is possible.

Suggestions ?

答:
Found the problem. I needed to use the second overload of the ConfidentialClientApplication constructor, and supply the authorisation like this.

```<code>string authorityFormat = "https://login.microsoftonline.com/{0}/v2.0";
string tennantId = "xxx-xx-xx";
</code>```

then

var client = new Microsoft.Identity.Client.ConfidentialClientApplication("xxx-x-xx etc", string.Format(authorityFormat, tennantId), "http://localhost", cc, new TokenCache(), new TokenCache() );

The code Here pointed me in the right direction.

Title: Daemon using MSAL to MSGraph

Body:
I'm getting the error AADSTS70002: Error validating credentials. AADSTS50012: Client assertion audience claim does not match Realm issuer

when running this code.

    string[] scopes = new string[]{"https://graph.microsoft.com/.default"};
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
var cert = certStore.Certificates.Cast<X509Certificate2>().First(c => c.Thumbprint == "XXX-XXX etc");
var cas = new ClientAssertionCertificate(cert);
var cc = new Microsoft.Identity.Client.ClientCredential(cas);
var client = new Microsoft.Identity.Client.ConfidentialClientApplication("XX-XXX etc", "http://localhost", cc, new TokenCache(), new TokenCache() );
var authResult = await client.AcquireTokenForClientAsync(scopes);
var dap = new DelegateAuthenticationProvider(rm =>
{
    rm.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", authResult.AccessToken);
    return Task.FromResult(0);
});
var gClient = new GraphServiceClient(dap);
gClient.Me.Dump();

Error occurrs on the call to AcquireTokenForClientAsync() method.

I can not find any online documentation for MSAL and Daemon clients where no user authentication is possible.

Suggestions ?

Body:
Found the problem. I needed to use the second overload of the ConfidentialClientApplication constructor, and supply the authorisation like this.

string authorityFormat = "https://login.microsoftonline.com/{0}/v2.0";
string tennantId = "xxx-xx-xx";

then

var client = new Microsoft.Identity.Client.ConfidentialClientApplication("xxx-x-xx etc", string.Format(authorityFormat, tennantId), "http://localhost", cc, new TokenCache(), new TokenCache() );

The code Here pointed me in the right direction.


问:
ellipse detection in opencv python
My image is here:

i'm looking for a better solution or algorithm to detect the ellipse part (dish) in this photo and mask it in an other photo in Opencv.
could you please give me some advice or solution.
and my code is :

```<code> circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1.2, 1, param1=128, minRadius=200, maxRadius=600)
    # draw detected circles on image
    circles = circles.tolist()
    for cir in circles:
        for x, y, r in cir:
            x, y, r = int(x), int(y), int(r)
            cv2.circle(img, (x, y), r, (0, 255, 0), 4)

    # show the output image
    cv2.imshow("output", cv2.resize(img, (500, 500)))
</code>```

答:
There is an alternative for it in skimage made by Xie, Yonghong, and Qiang Ji and published as...

“A new efficient ellipse detection method.” Pattern Recognition, 2002.
Proceedings. 16th International Conference on. Vol. 2. IEEE, 2002.

Their Ellipse detection code is relatively slow and the example takes about 70 seconds; compared to website claimed "28 seconds".

If you have conda or pip: "name" install scikit-image and give it a shot...

Their code can be found here or as copy/pasted below:

```<code>import matplotlib.pyplot as plt

from skimage import data, color, img_as_ubyte
from skimage.feature import canny
from skimage.transform import hough_ellipse
from skimage.draw import ellipse_perimeter

# Load picture, convert to grayscale and detect edges
image_rgb = data.coffee()[0:220, 160:420]
image_gray = color.rgb2gray(image_rgb)
edges = canny(image_gray, sigma=2.0,
              low_threshold=0.55, high_threshold=0.8)

# Perform a Hough Transform
# The accuracy corresponds to the bin size of a major axis.
# The value is chosen in order to get a single high accumulator.
# The threshold eliminates low accumulators
result = hough_ellipse(edges, accuracy=20, threshold=250,
                       min_size=100, max_size=120)
result.sort(order='accumulator')

# Estimated parameters for the ellipse
best = list(result[-1])
yc, xc, a, b = [int(round(x)) for x in best[1:5]]
orientation = best[5]

# Draw the ellipse on the original image
cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
image_rgb[cy, cx] = (0, 0, 255)
# Draw the edge (white) and the resulting ellipse (red)
edges = color.gray2rgb(img_as_ubyte(edges))
edges[cy, cx] = (250, 0, 0)

fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4), sharex=True,
                                sharey=True,
                                subplot_kw={'adjustable':'box'})

ax1.set_title('Original picture')
ax1.imshow(image_rgb)

ax2.set_title('Edge (white) and result (red)')
ax2.imshow(edges)

plt.show()
</code>```

Title: ellipse detection in opencv python

Body:
My image is here:

i'm looking for a better solution or algorithm to detect the ellipse part (dish) in this photo and mask it in an other photo in Opencv.
could you please give me some advice or solution.
and my code is :

 circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1.2, 1, param1=128, minRadius=200, maxRadius=600)
    # draw detected circles on image
    circles = circles.tolist()
    for cir in circles:
        for x, y, r in cir:
            x, y, r = int(x), int(y), int(r)
            cv2.circle(img, (x, y), r, (0, 255, 0), 4)

    # show the output image
    cv2.imshow("output", cv2.resize(img, (500, 500)))

Body:
There is an alternative for it in skimage made by Xie, Yonghong, and Qiang Ji and published as...

“A new efficient ellipse detection method.” Pattern Recognition, 2002.
Proceedings. 16th International Conference on. Vol. 2. IEEE, 2002.

Their Ellipse detection code is relatively slow and the example takes about 70 seconds; compared to website claimed "28 seconds".

If you have conda or pip: "name" install scikit-image and give it a shot...

Their code can be found here or as copy/pasted below:

import matplotlib.pyplot as plt

from skimage import data, color, img_as_ubyte
from skimage.feature import canny
from skimage.transform import hough_ellipse
from skimage.draw import ellipse_perimeter

# Load picture, convert to grayscale and detect edges
image_rgb = data.coffee()[0:220, 160:420]
image_gray = color.rgb2gray(image_rgb)
edges = canny(image_gray, sigma=2.0,
              low_threshold=0.55, high_threshold=0.8)

# Perform a Hough Transform
# The accuracy corresponds to the bin size of a major axis.
# The value is chosen in order to get a single high accumulator.
# The threshold eliminates low accumulators
result = hough_ellipse(edges, accuracy=20, threshold=250,
                       min_size=100, max_size=120)
result.sort(order='accumulator')

# Estimated parameters for the ellipse
best = list(result[-1])
yc, xc, a, b = [int(round(x)) for x in best[1:5]]
orientation = best[5]

# Draw the ellipse on the original image
cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
image_rgb[cy, cx] = (0, 0, 255)
# Draw the edge (white) and the resulting ellipse (red)
edges = color.gray2rgb(img_as_ubyte(edges))
edges[cy, cx] = (250, 0, 0)

fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4), sharex=True,
                                sharey=True,
                                subplot_kw={'adjustable':'box'})

ax1.set_title('Original picture')
ax1.imshow(image_rgb)

ax2.set_title('Edge (white) and result (red)')
ax2.imshow(edges)

plt.show()