问:
Index of hovered element in QGraphicsPathItem
I have a QGraphicsPathItem which is drawn from a list of cartesian x,y points.

What would be the best (performance wise) method of determining when the cursor is hovered over one of these points I presently iterate through the source list and compare each point with the cursor position.

Regards

答:
Qt does not provide a built-in solution for what you want. You should reimplement QGraphicsScene::mouseMoveEvent and check in it which point (if any) is hovered (with a certain margin), i.e. determine which point is within a certain distance of the current mouse position (QGraphicsSceneMouseEvent::pos).

The most computation intensive task is determining the closest point. A naive approach is to iterate over all the points, but general optimised implementation exists:

QuadTree: 2D implementation

k-d tree: Multidimensional implementation

Nearest Neighbor Search: broad overview

Caching the last result and using the triangle inequality may be important to improve the performance of this method:

If currently the mouse hovers a point P, the next time you can just validate if it still hovers this point.

If currently no point is hovered and the nearest point from location P (the last mouse position for which you calculated the nearest point) is at a distance d, then you should not check if an hover occur if: norm(P - QGraphicsSceneMouseEvent::pos()) < d - hoverThreshold


来源: stackexchange

问:
GWT - internationalization of entity properties
I'm looking for an elegant solution for the following problem:

In my database, I have some predefined(!) entities. These entities have names and descriptions (Strings). Around the data access layer, there are some EJBs containing business logic to load/search for/etc. those entities.

Now for the frontend, we are developing a GWT application which calls the EJB methods on our backend.

The problem is, that the name and the descriptions of the entities mentioned above must be internationalized - e.g., depending on the user's locale, an entity's description must be "My cool description" (English) or "Beschreibung bla" (German) or whatever :)

My first approach was to use a resource string in the database. So entity A has a description "descriptionA", entity B has a description "descriptionB"... Later on, the GWT app (or any other client) translates this resource string into the actual description using some kind of "resource bundle". E.g.:

*resources_en.properties*:

descriptionA=Actual Description of Entity A

descriptionB=Actual Description of Entity B

*resources_de.properties*:

descriptionA=Beschreibung A

descriptionB=Beschreibung B

(Remember, the entities are predefined, so it's possible to "know" all descriptions at compile time. BUT it would be better if the resource bundle could be enhanced without having to recompile the application).

Is this possible with GWT? How can I do this? Is it better to "translate" on the server or on the client side?

Otherwise, I've to deal with all that i18n stuff on the backend side. Well, this would allow to keep data together (instead of defining the descriptions on the client side). But the big drawback is that the backend must be aware of the caller's locale.

Regards,
Frank

答:
It's mainly a decision between download time/speed vs flexibility. If you compile it GWT inlines the messages and can generate a little faster code, because no string lookup has to be done. However, if you need to make changes and don't want to recompile or want to be a able to let users dynamically alter messages you need dynamic messages.

Regarding the latter case, the Dictionary class can help you with this, see also: http://code.google.com/webtoolkit/doc/latest/DevGuideI18n.html#DevGuideDynamicStringInternationalization
With the Dictionary you generate all messages in the static page served to the user. The users locale can be found in the header Accept-Language, which is send by the browser when a page is requested.

In either case (compiled or dynamic) you might want to serve the locale set by the user in some configuration property and in that case you still need logic for both cases on the server side to serve the locale to the user.

ContentLicense: CC BY-SA 2.5


问:
Swift Image Download TableView
I'm trying to fix a problem with downloading an image asynchronously in a TableView in Swift. This is my Problem: I download the image from a url asynchronously, but if I scroll quickly the TableView my pictures begin to rotate.(The images alternate until the correct one appears).

This is my Download Async Code and imageCache

```<code>let imageCache = NSCache()

//DOWNLOAD Image ASINC
extension UIImageView {

    public func imageFromServerURL(url: String){

        if(imageCache.objectForKey(url) != nil){
            self.image = imageCache.objectForKey(url) as? UIImage
        }else{

            let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
            let task = session.dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, response, error) -> Void in
                if error == nil {

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        if let downloadedImage = UIImage(data: data!) {
                            imageCache.setObject(downloadedImage, forKey: url)
                            self.image = downloadedImage
                        }
                    })

                }
                else {
                    print(error)
                }
            })
            task.resume()
        }

    }
}
</code>```

and Which I recall in the TableView so:

```<code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("record_charts", forIndexPath: indexPath) as! myTableViewCell

            let url_img = "https://image/download.jpg"
            cell.immagine.imageFromServerURL(url_img)

        return cell
    }
</code>```

This is the gif to show you the problem better

答:
This is due to the reuse mechanism of iOS's table view.
You can make some modification to your code to fix this:

```<code>class AsyncImageView: UIImageView {

private var currentUrl: String? //Get a hold of the latest request url

public func imageFromServerURL(url: String){
    currentUrl = url
    if(imageCache.objectForKey(url) != nil){
        self.image = imageCache.objectForKey(url) as? UIImage
    }else{

        let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
        let task = session.dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, response, error) -> Void in
            if error == nil {

                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    if let downloadedImage = UIImage(data: data!) {
                        if (url == currentUrl) {//Only cache and set the image view when the downloaded image is the one from last request
                            imageCache.setObject(downloadedImage, forKey: url)
                            self.image = downloadedImage
                        }

                    }
                })

            }
            else {
                print(error)
            }
        })
        task.resume()
    }

}
}
</code>```

Note #1: I was whiteboard coding the modification, so not sure if the code has correct syntax.

Note #2: Instead of declaring a new subclass of UIImageView, you can use associated objects.

Note #3: I strongly suggest you use AlamoFireImage, it has a category for UIImageView which is exactly what you need in this case (and future cases too).

ContentLicense: CC BY-SA 3.0

Title: Swift Image Download TableView

Body:
I'm trying to fix a problem with downloading an image asynchronously in a TableView in Swift. This is my Problem: I download the image from a url asynchronously, but if I scroll quickly the TableView my pictures begin to rotate.(The images alternate until the correct one appears).

This is my Download Async Code and imageCache

let imageCache = NSCache()

//DOWNLOAD Image ASINC
extension UIImageView {

    public func imageFromServerURL(url: String){

        if(imageCache.objectForKey(url) != nil){
            self.image = imageCache.objectForKey(url) as? UIImage
        }else{

            let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
            let task = session.dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, response, error) -> Void in
                if error == nil {

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        if let downloadedImage = UIImage(data: data!) {
                            imageCache.setObject(downloadedImage, forKey: url)
                            self.image = downloadedImage
                        }
                    })

                }
                else {
                    print(error)
                }
            })
            task.resume()
        }

    }
}

and Which I recall in the TableView so:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("record_charts", forIndexPath: indexPath) as! myTableViewCell

            let url_img = "https://image/download.jpg"
            cell.immagine.imageFromServerURL(url_img)

        return cell
    }

This is the gif to show you the problem better

Body:
This is due to the reuse mechanism of iOS's table view.
You can make some modification to your code to fix this:

class AsyncImageView: UIImageView {

private var currentUrl: String? //Get a hold of the latest request url

public func imageFromServerURL(url: String){
    currentUrl = url
    if(imageCache.objectForKey(url) != nil){
        self.image = imageCache.objectForKey(url) as? UIImage
    }else{

        let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
        let task = session.dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, response, error) -> Void in
            if error == nil {

                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    if let downloadedImage = UIImage(data: data!) {
                        if (url == currentUrl) {//Only cache and set the image view when the downloaded image is the one from last request
                            imageCache.setObject(downloadedImage, forKey: url)
                            self.image = downloadedImage
                        }

                    }
                })

            }
            else {
                print(error)
            }
        })
        task.resume()
    }

}
}

Note #1: I was whiteboard coding the modification, so not sure if the code has correct syntax.

Note #2: Instead of declaring a new subclass of UIImageView, you can use associated objects.

Note #3: I strongly suggest you use AlamoFireImage, it has a category for UIImageView which is exactly what you need in this case (and future cases too).


问:
How to get props value of boolean type in react
I have created one component where I am passing two props - taskName which is string and status which is boolean. I found a way to get taskName in my App.js but it failed in case of boolean type.

Doesn't react support boolean props ?

TaskComponent.js

```<code>export default class TaskComponent extends Component {
    render() {
        var taskStatus = this.props.status;
        if(taskStatus)
            return <h1><strike>Task: {this.props.taskName}</strike></h1>
    }
}
</code>```

App.js

```<code>class App extends Component {
  render() {
    return (
      <TaskComponent taskName="Buy Milk" status={false} />
    );
  }
}

export default App;
</code>```

I am getting this error while trying to get status value.

TaskComponent.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

答:
Return a null is the taskStatus is false, thats the reason you get an error since nothing is returned is the if condition doesn't match

class App extends React.Component {
  render() {
    return (
      <TaskComponent taskName="Buy Milk" status={true} />
    );
  }
}

class TaskComponent extends React.Component {
    render() {
        var taskStatus = this.props.status;
        if(taskStatus)
            return
Task: {this.props.taskName}

        else
            return null
    }
}

ReactDOM.render(<App/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

Body:
I have created one component where I am passing two props - taskName which is string and status which is boolean. I found a way to get taskName in my App.js but it failed in case of boolean type.

Doesn't react support boolean props ?

TaskComponent.js

export default class TaskComponent extends Component {
    render() {
        var taskStatus = this.props.status;
        if(taskStatus)
            return
Task: {this.props.taskName}

    }
}

App.js

class App extends Component {
  render() {
    return (
      <TaskComponent taskName="Buy Milk" status={false} />
    );
  }
}

export default App;

I am getting this error while trying to get status value.

TaskComponent.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Body:
Return a null is the taskStatus is false, thats the reason you get an error since nothing is returned is the if condition doesn't match

class App extends React.Component {
  render() {
    return (
      <TaskComponent taskName="Buy Milk" status={true} />
    );
  }
}

class TaskComponent extends React.Component {
    render() {
        var taskStatus = this.props.status;
        if(taskStatus)
            return <h1><strike>Task: {this.props.taskName}</strike></h1>
        else
            return null
    }
}

ReactDOM.render(<App/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


问:
Android intent to check/view emails
I am looking for a way to fire the email-app on device from my app to check emails. Note: I do not want to 'send' any email, just want to 'check' emails. The following code crashes for the gmail app -

```<code>          Intent intent = new Intent(Intent.ACTION_VIEW);
          intent.setType("message/rfc822");
          startActivity(intent);
</code>```

The stack-trace being -

```<code>06-06 23:26:20.313 27703-27731/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                   Process: com.google.android.gm, PID: 27703
                                                   java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                       at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                       at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)
                                                    Caused by: java.lang.NullPointerException: uri
                                                       at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
                                                       at android.content.ContentResolver.openInputStream(ContentResolver.java:645)
                                                       at clk.a(SourceFile:8)
                                                       at clk.loadInBackground(SourceFile:74)
                                                       at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:66)
                                                       at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)
</code>```

Is there no way to fire email app just to check emails?

答:
This should work:</p>

```<code>Intent intent = new Intent(Intent.CATEGORY_APP_EMAIL);
          intent.setType("message/rfc822");
          startActivity(intent);
</code>```

Title: Android intent to check/view emails

Body:
I am looking for a way to fire the email-app on device from my app to check emails. Note: I do not want to 'send' any email, just want to 'check' emails. The following code crashes for the gmail app -

          Intent intent = new Intent(Intent.ACTION_VIEW);
          intent.setType("message/rfc822");
          startActivity(intent);

The stack-trace being -

06-06 23:26:20.313 27703-27731/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                   Process: com.google.android.gm, PID: 27703
                                                   java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                       at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                       at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)
                                                    Caused by: java.lang.NullPointerException: uri
                                                       at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
                                                       at android.content.ContentResolver.openInputStream(ContentResolver.java:645)
                                                       at clk.a(SourceFile:8)
                                                       at clk.loadInBackground(SourceFile:74)
                                                       at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69)
                                                       at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:66)
                                                       at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                       at java.lang.Thread.run(Thread.java:818)

Is there no way to fire email app just to check emails?

Body:
This should work:

Intent intent = new Intent(Intent.CATEGORY_APP_EMAIL);
          intent.setType("message/rfc822");
          startActivity(intent);


问:
Laravel json response not showing custom object data
I have the following class:

```<code><?php
namespace App\Libraries;

use Illuminate\Contracts\Support\Arrayable;

class ErrorResponse implements Arrayable {

    private $error;

    function __construct($code, $message) {
        $this->error = array('code' => $code, 'message' => $message);
    }

    function toArray() {
        return $this->error;
    }

}
</code>```

Then on the controller I have as a response:

```<code>$data['message'] = 'hello';
$data['error'] = new ErrorResponse($code, 'Something is bad');
return response()->json($data, $code);
</code>```

On the response I get the following result:

```<code>{
  "error": {},
  "message": "hello"
}
</code>```

But I was expecting

```<code>{
  "error": {
       "code": 422,
       "message": "Something is bad"
  },
  "message": "hello"
}
</code>```

Any idea on how to make Laravel responds the contents of the nested object (ErrorResponse)?

答:
Since you give a pure array to json(), Laravel just passes it straight to json_encode. You will either need to:

give the json() call an Arrayable or JsonSerializable object to have Laravel recursively expand the value,

make the $error a public so json_decode can use it, or

do it yourself, given how simple your example is:

$data['error'] = (new ErrorResponse($code, 'Something is bad'))->toArray();

Body:
I have the following class:

<?php
namespace App\Libraries;

use Illuminate\Contracts\Support\Arrayable;

class ErrorResponse implements Arrayable {

    private $error;

    function __construct($code, $message) {
        $this->error = array('code' => $code, 'message' => $message);
    }

    function toArray() {
        return $this->error;
    }

}

Then on the controller I have as a response:

$data['message'] = 'hello';
$data['error'] = new ErrorResponse($code, 'Something is bad');
return response()->json($data, $code);

On the response I get the following result:

{
  "error": {},
  "message": "hello"
}

But I was expecting

{
  "error": {
       "code": 422,
       "message": "Something is bad"
  },
  "message": "hello"
}

Any idea on how to make Laravel responds the contents of the nested object (ErrorResponse)?


问:
Rows in a Multi Column ListView are not properly ordered while Scrolling: Android
I've populated the data into a multi column ListView from firebase database.

I've extended BaseAdapter class for getting getting this view as shown in below figures.

Why does the item positions change while scrolling ?

Rows are getting aligned up and down when scrolled. This is the scenario:

Scrolled a bit down... ( Looks fine! )

Scrolling...

( The records were not displayed in the order, as you can see they are getting changed every time I scroll through the list. )

What can be the reason for this? Can anyone explain?

Code for Adapter class:

```<code>    public class ReportAdapter extends BaseAdapter {

    public ArrayList<HashMap<String, String>> list;
    Activity activity;
    TextView childOneNameColumn, childTwoNameColumn, childThreeNameColumn;
    TextView checkInColumn;
    TextView parentCheckInColumn;
    TextView checkOutColumn;
    TextView parentCheckOutColumn;
    TextView familyNameColumn;

    public ReportAdapter(Activity activity, ArrayList<HashMap<String, String>> list) {
        super();
        this.activity = activity;
        this.list = list;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder;

        LayoutInflater inflater = activity.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.column_row, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        HashMap<String, String> map = list.get(position);
        familyNameColumn.setText(map.get(FAMILY_NAME_COLUMN));
        childOneNameColumn.setText(map.get(CHILD_ONE_NAME_COLUMN));
        childTwoNameColumn.setText(map.get(CHILD_TWO_NAME_COLUMN));
        childThreeNameColumn.setText(map.get(CHILD_THREE_NAME_COLUMN));
        checkInColumn.setText(map.get(CHECKIN_COLUMN));
        parentCheckInColumn.setText(map.get(PARENT_CHECKIN_COLUMN));
        checkOutColumn.setText(map.get(CHECKOUT_COLUMN));
        parentCheckOutColumn.setText(map.get(PARENT_CHECKOUT_COLUMN));

        return convertView;
    }

    private class ViewHolder {

        public ViewHolder(View view) {
            childOneNameColumn = (TextView) view.findViewById(R.id.child1NameColumn);
            childTwoNameColumn = (TextView) view.findViewById(R.id.child2NameColumn);
            childThreeNameColumn = (TextView) view.findViewById(R.id.child3NameColumn);
            checkInColumn = (TextView) view.findViewById(R.id.checkInColumn);
            parentCheckInColumn = (TextView) view.findViewById(R.id.parentCheckInColumn);
            checkOutColumn = (TextView) view.findViewById(R.id.checkOutColumn);
            parentCheckOutColumn = (TextView) view.findViewById(R.id.parentCheckOutColumn);
            familyNameColumn = (TextView) view.findViewById(R.id.familyNameColumn);
        }
    }
}
</code>```

Layout column_row.xml:

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <LinearLayout
        android:id="@+id/linearLayout5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="30dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/familyNameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:textColor="@color/colorBlack" />

        <TextView
            android:id="@+id/child1NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/child2NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/child3NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/checkInColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="@color/colorGreen" />

        <TextView
            android:id="@+id/parentCheckInColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.7" />

        <TextView
            android:id="@+id/checkOutColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="@color/colorGreen" />

        <TextView
            android:id="@+id/parentCheckOutColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.7" />

    </LinearLayout>
</RelativeLayout>
</code>```

ListView properties:

```<code><ListView
    android:id="@+id/reportListView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="40dp"
    android:transcriptMode="alwaysScroll" />
</code>```

答:
Better use a ViewHolder for long lists.

Anyway, you wrongly set views. In a ListView you should manage both branches, whether convertView == null or not. When convertView != null you also have to set views.

So, if you don't want to create a ViewHolder, write:

```<code>if (convertView == null) {
    convertView = inflater.inflate(R.layout.column_row, parent, false);
}
childOneNameColumn = (TextView) convertView.findViewById(R.id.child1NameColumn);
childTwoNameColumn = (TextView) convertView.findViewById(R.id.child2NameColumn);
...
</code>```

Also try to name variables with lowercase.

Body:
I've populated the data into a multi column ListView from firebase database.

I've extended BaseAdapter class for getting getting this view as shown in below figures.

Why does the item positions change while scrolling ?

Rows are getting aligned up and down when scrolled. This is the scenario:

Scrolled a bit down... ( Looks fine! )

Scrolling...

( The records were not displayed in the order, as you can see they are getting changed every time I scroll through the list. )

What can be the reason for this? Can anyone explain?

Code for Adapter class:

    public class ReportAdapter extends BaseAdapter {

    public ArrayList<HashMap<String, String>> list;
    Activity activity;
    TextView childOneNameColumn, childTwoNameColumn, childThreeNameColumn;
    TextView checkInColumn;
    TextView parentCheckInColumn;
    TextView checkOutColumn;
    TextView parentCheckOutColumn;
    TextView familyNameColumn;

    public ReportAdapter(Activity activity, ArrayList<HashMap<String, String>> list) {
        super();
        this.activity = activity;
        this.list = list;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder;

        LayoutInflater inflater = activity.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.column_row, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        HashMap<String, String> map = list.get(position);
        familyNameColumn.setText(map.get(FAMILY_NAME_COLUMN));
        childOneNameColumn.setText(map.get(CHILD_ONE_NAME_COLUMN));
        childTwoNameColumn.setText(map.get(CHILD_TWO_NAME_COLUMN));
        childThreeNameColumn.setText(map.get(CHILD_THREE_NAME_COLUMN));
        checkInColumn.setText(map.get(CHECKIN_COLUMN));
        parentCheckInColumn.setText(map.get(PARENT_CHECKIN_COLUMN));
        checkOutColumn.setText(map.get(CHECKOUT_COLUMN));
        parentCheckOutColumn.setText(map.get(PARENT_CHECKOUT_COLUMN));

        return convertView;
    }

    private class ViewHolder {

        public ViewHolder(View view) {
            childOneNameColumn = (TextView) view.findViewById(R.id.child1NameColumn);
            childTwoNameColumn = (TextView) view.findViewById(R.id.child2NameColumn);
            childThreeNameColumn = (TextView) view.findViewById(R.id.child3NameColumn);
            checkInColumn = (TextView) view.findViewById(R.id.checkInColumn);
            parentCheckInColumn = (TextView) view.findViewById(R.id.parentCheckInColumn);
            checkOutColumn = (TextView) view.findViewById(R.id.checkOutColumn);
            parentCheckOutColumn = (TextView) view.findViewById(R.id.parentCheckOutColumn);
            familyNameColumn = (TextView) view.findViewById(R.id.familyNameColumn);
        }
    }
}

Layout column_row.xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <LinearLayout
        android:id="@+id/linearLayout5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="30dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/familyNameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:textColor="@color/colorBlack" />

        <TextView
            android:id="@+id/child1NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/child2NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/child3NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/checkInColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="@color/colorGreen" />

        <TextView
            android:id="@+id/parentCheckInColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.7" />

        <TextView
            android:id="@+id/checkOutColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="@color/colorGreen" />

        <TextView
            android:id="@+id/parentCheckOutColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.7" />

    </LinearLayout>
</RelativeLayout>

ListView properties:

<ListView
    android:id="@+id/reportListView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="40dp"
    android:transcriptMode="alwaysScroll" />

Body:
Better use a ViewHolder for long lists.

Anyway, you wrongly set views. In a ListView you should manage both branches, whether convertView == null or not. When convertView != null you also have to set views.

So, if you don't want to create a ViewHolder, write:

if (convertView == null) {
    convertView = inflater.inflate(R.layout.column_row, parent, false);
}
childOneNameColumn = (TextView) convertView.findViewById(R.id.child1NameColumn);
childTwoNameColumn = (TextView) convertView.findViewById(R.id.child2NameColumn);
...

Also try to name variables with lowercase.


问:
I'm getting problem when setting the height of label dynamically
I'm setting the tableView cells height dynamically according to labels height and labels height according to text. It is working fine when I had given text with spaces (ex: This is Question for stackoverflow). But when I'm entering text of length two lines without spaces(ex ThisisQuestionforstackoverflow) . It is taking two lines and the text is starting from second line and cutting at the end.It taking first line full space and second line like(ThisisQuestionfor.....).

I'm using methods

+(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width:(UILineBreakMode)lineBreakMode

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

In cellForRowAtIndexPath

```<code>float productNameHeight = [DetailsViewController calculateHeightOfTextFromWidth:warObj1.productName :valueFont : valueWidth :UILineBreakModeWordWrap];
UILabel *productNameValue = [[UILabel alloc] initWithFrame:CGRectMake(xCoordinateStartLocatioForValue,yCoordinateStartLocation,valueWidth,productNameHeight)];
</code>```

Can u plz help me quickly.Thanks in advance

答:
What's the line break mode for the label and how many lines are you allowing it to have?

You might be correctly setting the height of the label but then telling to draw all the text on one line :)

You should check that the number of lines in the label is 0 (which means as many as needed) and the line break mode is set to character break. (It sounds like it's set to truncate end at the moment).

Body:
I'm setting the tableView cells height dynamically according to labels height and labels height according to text. It is working fine when I had given text with spaces (ex: This is Question for stackoverflow). But when I'm entering text of length two lines without spaces(ex ThisisQuestionforstackoverflow) . It is taking two lines and the text is starting from second line and cutting at the end.It taking first line full space and second line like(ThisisQuestionfor.....).

I'm using methods

+(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width:(UILineBreakMode)lineBreakMode

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

In cellForRowAtIndexPath

float productNameHeight = [DetailsViewController calculateHeightOfTextFromWidth:warObj1.productName :valueFont : valueWidth :UILineBreakModeWordWrap];
UILabel *productNameValue = [[UILabel alloc] initWithFrame:CGRectMake(xCoordinateStartLocatioForValue,yCoordinateStartLocation,valueWidth,productNameHeight)];

Can u plz help me quickly.Thanks in advance


问:
Rails flash message
I am building an application on Rails where a user creates a Test, goes to the show view for that test and fills in a form with an answer to a question. If the answer to the question matches the "correct_answer" (defined in the controller), there will be flash message that the answer was correct and a button to continue to the root_path will appear. If the answer is wrong, the flash says "Wrong answer."

My problem is that the flash message will say wrong answer even if no answer has been given. I ONLY want that message to appear AFTER the user has submitted the form. I understand why this is happening, I just am unsure about how to fix it. Here is the show view for a test:

```<code><div class="col-md-8 col-md-push-2">
        <h4>Current Score: <%= @test.score %></h4>
        <br /><br />

        <div class="form_group">
        <%= form_tag test_path(@test), :method=> 'get' do %>
            <h4>What is my first name?</h4>
            <div class="form-group">
                <%= text_field_tag :answer, params[:answer], class: 'form-control' %>
            </div>
            <% if !flash[:success] %>
            <div class="form-group">
                <%= submit_tag "Submit", class: "btn btn-primary" %>
            </div>
            <% end %>
        <% end %>
        </div>

        <% if flash[:success] %>
            <%= link_to "Continue", root_path, class: "btn btn-success pull-right" %>
        <% end %>
    </div>
</code>```

Here is the controller for tests, which contains the offending show action:

```<code> class TestsController < ApplicationController

def index
    @test = Test.new
    @tests = Test.all
end

def show
    @test = Test.find(params[:id])
    correct_answer = "jack"
    user_answer = params[:answer]
    if user_answer == correct_answer
        flash.now[:success] = "That is correct!"
        new_score = @test.score += 1
        @test.update(score: new_score)
    elsif params[:answer] != correct_answer
        flash.now[:danger] = "Wrong answer"
    end
end

def create
    @test = Test.create(test_params)
    if @test.save
        redirect_to test_path(@test)
        flash[:success] = "Test created"
    else
        flash[:danger] = "There was a problem"
        render "index"
    end
end

def destroy
    @test = Test.find(params[:id])
    if @test.destroy
        flash[:success] = "Your test was removed"
        redirect_to root_path
    end
end

private

    def test_params
        params.require(:test).permit(:score, :user_id)
    end
end
</code>```

Is there a better way to do this? If not, can I somehow stop the flash message from appearing on the initial load? I ONLY want it to appear once the form has been submitted. Thanks in advance.

答:
So your flash is triggered because params[:answer] is undefined and not == to jack.

You say:

My problem is that the flash message will say wrong answer even if no answer has been given.

But your logic is off for this outcome, your code says that params[:answer] is defined, which it can't be since the form is not rendered yet.

Maybe your condition should be:

```<code>elsif params[:answer].present? && params[:answer] != correct_answer
  flash.now[:danger] = "Wrong answer"
end
</code>```

Traditionally, the showing of the form and POST to a form are separete actions, which is why you're seeing this flash before anything even happens.

Title: Rails flash message

Body:
I am building an application on Rails where a user creates a Test, goes to the show view for that test and fills in a form with an answer to a question. If the answer to the question matches the "correct_answer" (defined in the controller), there will be flash message that the answer was correct and a button to continue to the root_path will appear. If the answer is wrong, the flash says "Wrong answer."

My problem is that the flash message will say wrong answer even if no answer has been given. I ONLY want that message to appear AFTER the user has submitted the form. I understand why this is happening, I just am unsure about how to fix it. Here is the show view for a test:

Current Score: <%= @test.score %>

        <%= form_tag test_path(@test), :method=> 'get' do %>

What is my first name?

                <%= text_field_tag :answer, params[:answer], class: 'form-control' %>

            <% if !flash[:success] %>

                <%= submit_tag "Submit", class: "btn btn-primary" %>

            <% end %>
        <% end %>

        <% if flash[:success] %>
            <%= link_to "Continue", root_path, class: "btn btn-success pull-right" %>
        <% end %>

Here is the controller for tests, which contains the offending show action:

 class TestsController < ApplicationController

def index
    @test = Test.new
    @tests = Test.all
end

def show
    @test = Test.find(params[:id])
    correct_answer = "jack"
    user_answer = params[:answer]
    if user_answer == correct_answer
        flash.now[:success] = "That is correct!"
        new_score = @test.score += 1
        @test.update(score: new_score)
    elsif params[:answer] != correct_answer
        flash.now[:danger] = "Wrong answer"
    end
end

def create
    @test = Test.create(test_params)
    if @test.save
        redirect_to test_path(@test)
        flash[:success] = "Test created"
    else
        flash[:danger] = "There was a problem"
        render "index"
    end
end

def destroy
    @test = Test.find(params[:id])
    if @test.destroy
        flash[:success] = "Your test was removed"
        redirect_to root_path
    end
end

private

    def test_params
        params.require(:test).permit(:score, :user_id)
    end
end

Is there a better way to do this? If not, can I somehow stop the flash message from appearing on the initial load? I ONLY want it to appear once the form has been submitted. Thanks in advance.

Body:
So your flash is triggered because params[:answer] is undefined and not == to jack.

You say:

My problem is that the flash message will say wrong answer even if no answer has been given.

But your logic is off for this outcome, your code says that params[:answer] is defined, which it can't be since the form is not rendered yet.

Maybe your condition should be:

elsif params[:answer].present? && params[:answer] != correct_answer
  flash.now[:danger] = "Wrong answer"
end

Traditionally, the showing of the form and POST to a form are separete actions, which is why you're seeing this flash before anything even happens.


问:
help, stored procedures and cursors
i have to write a stored procedure, where you give the month, and a credit card number, and it calulates 1%  for each transaction made in the first 10 days of the month, 2% for transactions between 10 and 20, and 3% for transactions above 20.
And i must use cursors.

i wrote this code, but i get some errors when i try to run the precedure

```<code>   create procedure cardP
   /* month ex 1,3,5 etc*/
   @minas int,
   @cardNo bigint

as
/* creating the cursor*/
DECLARE sinallages CURSOR
FOR SELECT cc_number,day([DateTime]),charged_amount FROM transactions
where cc_number=@cardNo and month([DateTime])=@minas

/* declaring local variables*/
declare @poso int,@karta bigint,@mera int,@pos float,@pos2 float,@pos3 float,
@count int,@counter int

open sinallages

set @count=(select count(cc_number) from transactions where cc_number=@cardNo and month([DateTime])=@minas )
/* get 1st row*/
fetch sinallages into @karta,@mera,@poso
while (/*@@sqlstatus != 2*/@counter<@count)
  begin
    if day(@mera)<=10
    set @pos =@poso+ @poso * 0.01
    else
    if day(@mera)>10 and day(@mera)<=20
    set @pos2 =@poso+ @poso * 0.02
    else
    if day(@mera) > 20
    set @pos3 =@poso+ @poso * 0.03
    fetch sinallages into @karta,@mera,@poso
  set @counter=@counter+1
  end

close sinallages

return
</code>```

when i call the procedure i get

EXEC cardP @minas = 5, @cardNo =4929569752542450

```<code>Msg 16915, Level 16, State 1, Procedure cardP, Line 20
A cursor with the name 'sinallages' already exists.
Msg 16922, Level 16, State 1, Procedure cardP, Line 31
</code>```

Cursor Fetch: Implicit conversion from data type datetime to int is not allowed.

thank you :) i now deallocate the cursor at the end of the stored procedure and removed the day(). Now i want to print the pos+pos2+pos3. I use print  pos+pos2+pos3  but it doesnt print anything. why is that ??

```<code>    ................
      set @counter=@counter+1
  end
print @pos+@pos2+@pos3
close sinallages

return
DEALLOCATE sinallages;
</code>```

it seems like hte variables po,pos2,pos3 are left null??

答:
Yes, you need to deallocate the cursor after closing it. Besides, if your query had an error before closing the cursor, it may have stayed open, so i recommend you execute the CLOSE and DEALLOCATE before executing your procedure again. For your second error, you are using the function DAY() over a variable of type INT, change if day(@mera)<=10 with if @mera<=10.
Update: Now that you fixed the problems you had, when you add each @pos variable, following your logic, one of them is always null, so you should add them like this:
Print isnull(@pos1,0)+isnull(@pos2,0)+isnull(@pos3,0)

Title: help, stored procedures and cursors

Body:
i have to write a stored procedure, where you give the month, and a credit card number, and it calulates 1%  for each transaction made in the first 10 days of the month, 2% for transactions between 10 and 20, and 3% for transactions above 20.
And i must use cursors.

i wrote this code, but i get some errors when i try to run the precedure

   create procedure cardP
   /* month ex 1,3,5 etc*/
   @minas int,
   @cardNo bigint

as
/* creating the cursor*/
DECLARE sinallages CURSOR
FOR SELECT cc_number,day([DateTime]),charged_amount FROM transactions
where cc_number=@cardNo and month([DateTime])=@minas

/* declaring local variables*/
declare @poso int,@karta bigint,@mera int,@pos float,@pos2 float,@pos3 float,
@count int,@counter int

open sinallages

set @count=(select count(cc_number) from transactions where cc_number=@cardNo and month([DateTime])=@minas )
/* get 1st row*/
fetch sinallages into @karta,@mera,@poso
while (/*@@sqlstatus != 2*/@counter<@count)
  begin
    if day(@mera)<=10
    set @pos =@poso+ @poso * 0.01
    else
    if day(@mera)>10 and day(@mera)<=20
    set @pos2 =@poso+ @poso * 0.02
    else
    if day(@mera) > 20
    set @pos3 =@poso+ @poso * 0.03
    fetch sinallages into @karta,@mera,@poso
  set @counter=@counter+1
  end

close sinallages

return

when i call the procedure i get

EXEC cardP @minas = 5, @cardNo =4929569752542450

Msg 16915, Level 16, State 1, Procedure cardP, Line 20
A cursor with the name 'sinallages' already exists.
Msg 16922, Level 16, State 1, Procedure cardP, Line 31

Cursor Fetch: Implicit conversion from data type datetime to int is not allowed.

thank you :) i now deallocate the cursor at the end of the stored procedure and removed the day(). Now i want to print the pos+pos2+pos3. I use print  pos+pos2+pos3  but it doesnt print anything. why is that ??

    ................
      set @counter=@counter+1
  end
print @pos+@pos2+@pos3
close sinallages

return
DEALLOCATE sinallages;

it seems like hte variables po,pos2,pos3 are left null??


问:
java attach file from virtual filesystem to email
I am using a virtual filesystem and I'd like to attach a file from it to an email. However, the MimeBodyPart object only takes Files, which don't work on a default filesystem like jimfs. See my code below, where I get an UnsupportedOperation exception when I try to convert to file.</p>

```<code>public Email attach(Path file){
    MimeBodyPart attachment = new MimeBodyPart()
    attachment.attachFile(file.toFile())
    attachments.add(attachment)
    return this
}
</code>```

答:
Whatever this MimeBodyPart API is really ought to have an option to use a Path so that you could just use the Jimfs file directly, but since the java.nio.file APIs require Java 7 and don't work on Android yet many libraries unfortunately don't support Path yet.

toFile() can never work for a Jimfs file, or for any file that isn't on the default file system, because the File class can only represent files on the default file system. So yeah, you'd need to copy the Jimfs file to the real file system to use this attachFile method.

If the MimeBodyPart API had an option for using a URL or URI for the attachment, you would probably be able to use that plus file.toUri()[.toURL()]. Or if it could use, say, an InputStream you could obviously get one of those from the file and use it instead.

Body:
I am using a virtual filesystem and I'd like to attach a file from it to an email. However, the MimeBodyPart object only takes Files, which don't work on a default filesystem like jimfs. See my code below, where I get an UnsupportedOperation exception when I try to convert to file.

public Email attach(Path file){
    MimeBodyPart attachment = new MimeBodyPart()
    attachment.attachFile(file.toFile())
    attachments.add(attachment)
    return this
}


问:
Sum attributes from XML file
I am having issue knowing how to sum multiple instances of the same attribute in a XML file. My first thought was to build an array to hold the values then sum them together. Unfortunately my c# code knowledge is not where it should be.

```<code>double customerRate = Convert.ToDouble(
    import.Elements("PriceSheets")
        .Elements("PriceSheet")
        .Where(priceSheet => priceSheet.Attribute("type").Value == "Cost"
            && priceSheet.Attribute("isAllocated").Value == "true"
            && priceSheet.Attribute("isSelected").Value == "true")
        .First()
        .Element("Total"));
</code>```

Below is the XML file I read from that has the repeating attribute of Total

```<code><Enterprises>
 <PriceSheets>
    <PriceSheet type="Cost"
        chargeModel="NORMALIZED_MANUAL" isSelected="true" isAllocated="true"
        currencyCode="USD" createDate="05/25/2017 15:03"
        updateDate="05/25/2017 15:18" internalId="5099262823">
    <AccessorialTotal>222.80</AccessorialTotal>
    <SubTotal>780.69</SubTotal>
    <Total>1003.49</Total>
    </PriceSheet>
 </PriceSheets>
</Enterprises>
</code>```

答:
Easy; you had most of it right:</p>

```<code>var sum =
    import
    .Elements("Enterprises")
    .Elements("PriceSheets")
    .Elements("PriceSheet")
    .Where(priceSheet => priceSheet.Attribute("type").Value == "Cost"
        && priceSheet.Attribute("isAllocated").Value == "true"
        && priceSheet.Attribute("isSelected").Value == "true")
    //  Now you're working with a sequence of all the allocated and selected "Cost" price
    //  sheets. You got this far.
    //  So just grab their "Total" elements...
    .Elements("Total")
    //  And sum their values.
    .Sum(total => Convert.ToDouble(total.Value));
</code>```

Title: Sum attributes from XML file

Body:
I am having issue knowing how to sum multiple instances of the same attribute in a XML file. My first thought was to build an array to hold the values then sum them together. Unfortunately my c# code knowledge is not where it should be.

double customerRate = Convert.ToDouble(
    import.Elements("PriceSheets")
        .Elements("PriceSheet")
        .Where(priceSheet => priceSheet.Attribute("type").Value == "Cost"
            && priceSheet.Attribute("isAllocated").Value == "true"
            && priceSheet.Attribute("isSelected").Value == "true")
        .First()
        .Element("Total"));

Below is the XML file I read from that has the repeating attribute of Total

<Enterprises>
 <PriceSheets>
    <PriceSheet type="Cost"
        chargeModel="NORMALIZED_MANUAL" isSelected="true" isAllocated="true"
        currencyCode="USD" createDate="05/25/2017 15:03"
        updateDate="05/25/2017 15:18" internalId="5099262823">
    <AccessorialTotal>222.80</AccessorialTotal>
    <SubTotal>780.69</SubTotal>
    <Total>1003.49</Total>
    </PriceSheet>
 </PriceSheets>
</Enterprises>

Body:
Easy; you had most of it right:

var sum =
    import
    .Elements("Enterprises")
    .Elements("PriceSheets")
    .Elements("PriceSheet")
    .Where(priceSheet => priceSheet.Attribute("type").Value == "Cost"
        && priceSheet.Attribute("isAllocated").Value == "true"
        && priceSheet.Attribute("isSelected").Value == "true")
    //  Now you're working with a sequence of all the allocated and selected "Cost" price
    //  sheets. You got this far.
    //  So just grab their "Total" elements...
    .Elements("Total")
    //  And sum their values.
    .Sum(total => Convert.ToDouble(total.Value));


Title: Replacing values based on multiple column values and conditions in pandas dataframe

Body:
I have the following dataframe:

     TIME   PREC    ET   PET  YIELD       date  year  intensity
0        1   1.21  0.02  0.02   0.00 1991-01-01  1991          1
1        2   0.00  0.03  0.04   0.00 1991-01-02  1991          1
2        3   0.00  0.03  0.05   0.00 1991-01-03  1991          1
3        4   0.00  0.04  0.05   0.00 1991-01-04  1991          1
4        5   0.00  0.05  0.07   0.00 1991-01-05  1991          1
5        6   0.00  0.03  0.05   0.00 1991-01-06  1991          1
6        7   0.00  0.02  0.04   0.00 1991-01-07  1991          1
7        8   1.14  0.03  0.04   0.00 1991-01-08  1991          1
8        9   0.10  0.02  0.03   0.00 1991-01-09  1991          1
9       10   0.00  0.03  0.04   0.00 1991-01-10  1991          1
10      11   0.10  0.05  0.11   0.00 1991-01-11  1991          1
11      12   0.00  0.06  0.15   0.00 1991-01-12  1991          1
12      13   2.30  0.14  0.44   0.00 1991-01-13  1991          1
13      14   0.17  0.09  0.29   0.00 1991-01-14  1991          1
14      15   0.00  0.13  0.35   0.00 1991-01-15  1991          1
15      16   0.00  0.14  0.39   0.00 1991-01-16  1991          1
16      17   0.00  0.10  0.31   0.00 1991-01-17  1991          1
17      18   0.00  0.15  0.51   0.00 1991-01-18  1991          1
18      19   0.00  0.22  0.58   0.00 1991-01-19  1991          1
19      20   0.10  0.04  0.09   0.00 1991-01-20  1991          1
20      21   0.00  0.04  0.06   0.00 1991-01-21  1991          1
21      22   0.27  0.13  0.43   0.00 1991-01-22  1991          1
22      23   0.00  0.10  0.25   0.00 1991-01-23  1991          1
23      24   0.00  0.03  0.04   0.00 1991-01-24  1991          1
24      25   0.00  0.04  0.05   0.00 1991-01-25  1991          1
25      26   0.43  0.04  0.15   0.00 1991-01-26  1991          1
26      27   0.17  0.06  0.23   0.00 1991-01-27  1991          1
27      28   0.50  0.02  0.04   0.00 1991-01-28  1991          1
28      29   0.00  0.03  0.04   0.00 1991-01-29  1991          1
29      30   0.00  0.04  0.08   0.00 1991-01-30  1991          1
   ...    ...   ...   ...    ...        ...   ...        ...
7275   336   0.00  0.04  0.06   0.03 2010-12-02  2010          1
7276   337   0.30  0.05  0.08   0.02 2010-12-03  2010          1
7277   338   1.62  0.08  0.12   0.02 2010-12-04  2010          1
7278   339   0.00  0.10  0.15   0.02 2010-12-05  2010          1
7279   340   0.00  0.09  0.15   0.02 2010-12-06  2010          1
7280   341   0.00  0.04  0.06   0.02 2010-12-07  2010          1
7281   342   0.00  0.04  0.06   0.02 2010-12-08  2010          1
7282   343   0.00  0.16  0.25   0.02 2010-12-09  2010          1
7283   344   0.00  0.22  0.35   0.02 2010-12-10  2010          1
7284   345   0.04  0.04  0.06   0.02 2010-12-11  2010          1
7285   346   0.01  0.02  0.03   0.02 2010-12-12  2010          1
7286   347   0.04  0.02  0.03   0.02 2010-12-13  2010          1
7287   348   0.00  0.05  0.08   0.02 2010-12-14  2010          1
7288   349   0.37  0.08  0.13   0.02 2010-12-15  2010          1
7289   350  13.19  0.08  0.13   0.02 2010-12-16  2010          1
7290   351   1.33  0.06  0.10   0.02 2010-12-17  2010          1
7291   352   0.00  0.08  0.12   0.02 2010-12-18  2010          1
7292   353   0.01  0.05  0.08   0.02 2010-12-19  2010          1
7293   354   0.00  0.03  0.04   0.02 2010-12-20  2010          1
7294   355   9.70  0.07  0.12   0.02 2010-12-21  2010          1
7295   356   0.00  0.06  0.11   0.02 2010-12-22  2010          1
7296   357   0.00  0.07  0.12   0.02 2010-12-23  2010          1
7297   358   0.13  0.08  0.13   0.02 2010-12-24  2010          1
7298   359   0.10  0.09  0.15   0.02 2010-12-25  2010          1
7299   360   0.00  0.07  0.12   0.02 2010-12-26  2010          1
7300   361   0.00  0.08  0.14   0.02 2010-12-27  2010          1
7301   362   0.61  0.18  0.32   0.02 2010-12-28  2010          1
7302   363   0.00  0.15  0.26   0.02 2010-12-29  2010          1
7303   364   3.95  0.10  0.18   0.02 2010-12-30  2010          1
7304   365   0.10  0.10  0.18   0.01 2010-12-31  2010          1

I would like to categorize the data based on the values in PREC and year columns. Here's the template of the code that I have:

for y in range(1991,2011):
    for i in df.loc[df.year == y, 'PREC']:
        if i <= np.percentile(df.loc[df.year == y, 'PREC'], 10):
            df.loc[df.PREC.isin([i]), 'intensity'] = 'light'

However, this code categorize intensity in the whole dataframe, but I need to categorize  PREC for each year. So, how to do this?

Body:
Consider the following approach:

In [202]: pctl = df.groupby('year').PREC.quantile(.10).reset_index(name='pctl')

In [203]: pctl
Out[203]:
   year  pctl
0  1991   0.0
1  2010   0.0

In [204]: df.loc[df.reset_index()
                   .merge(pctl)
                   .query('PREC <= pctl', inplace=False)['index'],
                 'intensity'] = 'light'

In [205]: df
Out[205]:
      TIME  PREC    ET   PET  YIELD       date  year intensity
0        1  1.21  0.02  0.02   0.00 1991-01-01  1991         1
1        2  0.00  0.03  0.04   0.00 1991-01-02  1991     light
2        3  0.00  0.03  0.05   0.00 1991-01-03  1991     light
3        4  0.00  0.04  0.05   0.00 1991-01-04  1991     light
4        5  0.00  0.05  0.07   0.00 1991-01-05  1991     light
5        6  0.00  0.03  0.05   0.00 1991-01-06  1991     light
6        7  0.00  0.02  0.04   0.00 1991-01-07  1991     light
7        8  1.14  0.03  0.04   0.00 1991-01-08  1991         1
8        9  0.10  0.02  0.03   0.00 1991-01-09  1991         1
9       10  0.00  0.03  0.04   0.00 1991-01-10  1991     light
...    ...   ...   ...   ...    ...        ...   ...       ...
7295   356  0.00  0.06  0.11   0.02 2010-12-22  2010     light
7296   357  0.00  0.07  0.12   0.02 2010-12-23  2010     light
7297   358  0.13  0.08  0.13   0.02 2010-12-24  2010         1
7298   359  0.10  0.09  0.15   0.02 2010-12-25  2010         1
7299   360  0.00  0.07  0.12   0.02 2010-12-26  2010     light
7300   361  0.00  0.08  0.14   0.02 2010-12-27  2010     light
7301   362  0.61  0.18  0.32   0.02 2010-12-28  2010         1
7302   363  0.00  0.15  0.26   0.02 2010-12-29  2010     light
7303   364  3.95  0.10  0.18   0.02 2010-12-30  2010         1
7304   365  0.10  0.10  0.18   0.01 2010-12-31  2010         1

[60 rows x 8 columns]

Step by step:

In [208]: df.reset_index().merge(pctl)
Out[208]:
    index  TIME  PREC    ET   PET  YIELD       date  year intensity  pctl
0       0     1  1.21  0.02  0.02   0.00 1991-01-01  1991         1   0.0
1       1     2  0.00  0.03  0.04   0.00 1991-01-02  1991     light   0.0
2       2     3  0.00  0.03  0.05   0.00 1991-01-03  1991     light   0.0
3       3     4  0.00  0.04  0.05   0.00 1991-01-04  1991     light   0.0
4       4     5  0.00  0.05  0.07   0.00 1991-01-05  1991     light   0.0
5       5     6  0.00  0.03  0.05   0.00 1991-01-06  1991     light   0.0
6       6     7  0.00  0.02  0.04   0.00 1991-01-07  1991     light   0.0
7       7     8  1.14  0.03  0.04   0.00 1991-01-08  1991         1   0.0
8       8     9  0.10  0.02  0.03   0.00 1991-01-09  1991         1   0.0
9       9    10  0.00  0.03  0.04   0.00 1991-01-10  1991     light   0.0
..    ...   ...   ...   ...   ...    ...        ...   ...       ...   ...
50   7295   356  0.00  0.06  0.11   0.02 2010-12-22  2010     light   0.0
51   7296   357  0.00  0.07  0.12   0.02 2010-12-23  2010     light   0.0
52   7297   358  0.13  0.08  0.13   0.02 2010-12-24  2010         1   0.0
53   7298   359  0.10  0.09  0.15   0.02 2010-12-25  2010         1   0.0
54   7299   360  0.00  0.07  0.12   0.02 2010-12-26  2010     light   0.0
55   7300   361  0.00  0.08  0.14   0.02 2010-12-27  2010     light   0.0
56   7301   362  0.61  0.18  0.32   0.02 2010-12-28  2010         1   0.0
57   7302   363  0.00  0.15  0.26   0.02 2010-12-29  2010     light   0.0
58   7303   364  3.95  0.10  0.18   0.02 2010-12-30  2010         1   0.0
59   7304   365  0.10  0.10  0.18   0.01 2010-12-31  2010         1   0.0

[60 rows x 10 columns]

In [209]: df.reset_index().merge(pctl).query('PREC <= pctl', inplace=False)
Out[209]:
    index  TIME  PREC    ET   PET  YIELD       date  year intensity  pctl
1       1     2   0.0  0.03  0.04   0.00 1991-01-02  1991     light   0.0
2       2     3   0.0  0.03  0.05   0.00 1991-01-03  1991     light   0.0
3       3     4   0.0  0.04  0.05   0.00 1991-01-04  1991     light   0.0
4       4     5   0.0  0.05  0.07   0.00 1991-01-05  1991     light   0.0
5       5     6   0.0  0.03  0.05   0.00 1991-01-06  1991     light   0.0
6       6     7   0.0  0.02  0.04   0.00 1991-01-07  1991     light   0.0
9       9    10   0.0  0.03  0.04   0.00 1991-01-10  1991     light   0.0
11     11    12   0.0  0.06  0.15   0.00 1991-01-12  1991     light   0.0
14     14    15   0.0  0.13  0.35   0.00 1991-01-15  1991     light   0.0
15     15    16   0.0  0.14  0.39   0.00 1991-01-16  1991     light   0.0
..    ...   ...   ...   ...   ...    ...        ...   ...       ...   ...
37   7282   343   0.0  0.16  0.25   0.02 2010-12-09  2010     light   0.0
38   7283   344   0.0  0.22  0.35   0.02 2010-12-10  2010     light   0.0
42   7287   348   0.0  0.05  0.08   0.02 2010-12-14  2010     light   0.0
46   7291   352   0.0  0.08  0.12   0.02 2010-12-18  2010     light   0.0
48   7293   354   0.0  0.03  0.04   0.02 2010-12-20  2010     light   0.0
50   7295   356   0.0  0.06  0.11   0.02 2010-12-22  2010     light   0.0
51   7296   357   0.0  0.07  0.12   0.02 2010-12-23  2010     light   0.0
54   7299   360   0.0  0.07  0.12   0.02 2010-12-26  2010     light   0.0
55   7300   361   0.0  0.08  0.14   0.02 2010-12-27  2010     light   0.0
57   7302   363   0.0  0.15  0.26   0.02 2010-12-29  2010     light   0.0

[34 rows x 10 columns]

In [210]: df.reset_index().merge(pctl).query('PREC <= pctl', inplace=False)['index']
Out[210]:
1        1
2        2
3        3
4        4
5        5
6        6
9        9
11      11
14      14
15      15
      ...
37    7282
38    7283
42    7287
46    7291
48    7293
50    7295
51    7296
54    7299
55    7300
57    7302
Name: index, dtype: int64


问:
In PHP, replace a number with "string" depending on ranges?
I need a php function to convert some numbers into a "string" (using quotation marks because of not sure if it's the proper name) according to some ranges.

Problem

In my web, I have different numbers (in different fields that may change) which I want to modify

I need a function which change the numbers into a "string" depending on a range

Information

Numbers

Numbers can be from 0 to 5000

My ranges

From 0 to 150

From 151 to 300

From 301 to 500

Up to 501

Range - string relation

From 0 to 150 --> "Less than 150 m2"

From 151 to 300 --> "150 - 300 m2"

From 301 to 500 --> "300 - 500 m2"

Up to 501 --> "Up to 500 m2"

Examples

Number: 180 -- (this number is <300 and > 151) --> Output: "150 - 300 m2"

Number: 524 -- (this number is > 501) --> Output: "Up to 500 m2"

What I've achieved
I'm looking for a better way to do this. Any documentation is also welcomed.

```<code><?php
function my_map_field($data) {
    $map = array(
        '0' => 'Less than 150 m2',
        '1' => 'Less than 150 m2',
        '2' => 'Less than 150 m2',
        '3' => 'Less than 150 m2',
        '4' => 'Less than 150 m2', /*Imagine all the numbers*/
        '151' => '150 - 300 m2',  /*Imagine all the numbers*/
        '301' => '300 - 500 m2',  /*Imagine all the numbers*/
    );

    return isset( $map[$data] ) ? $map[$data] : $data;
}
?>
</code>```

答:
Find the numbers with regex then str_replace them.

Regex pattern \d+ finds numbers.

```<code>function replace_numbers($str) {

 Preg_match_all("/(\d+)/", $str, $arr);
 //Var_dump($arr);
 For ($i=0; $i<count($arr[0]);$i++){
     If($arr[0][$i]>=0 && $arr[0][$i]<=150) $str = str_replace($arr[0][$i], "less than 150 m2", $str);
     If($arr[0][$i]>=151 && $arr[0][$i]<=300) $str = str_replace($arr[0][$i], "151 - 300 m2", $str);
     If($arr[0][$i]>=301 && $arr[0][$i]<=500) $str = str_replace($arr[0][$i], "301 - 500 m2", $str);
     If($arr[0][$i]>=501 && $arr[0][$i]<=5000) $str = str_replace($arr[0][$i], "up to 500 m2", $str);

 }

Return $str;
}

$str ="Number: 180, Number: 524";  // the string that needs attention
$newstr = replace_numbers($str); // newstr is the old string but with replaced numbers
</code>```

I have not included anything that takes care of numbers above 5000.

Also since you have not given much examples it will not work strings like "I'm 30 years old and my house is 400 m2" because it will replace 30 also.

Body:
I need a php function to convert some numbers into a "string" (using quotation marks because of not sure if it's the proper name) according to some ranges.

Problem

In my web, I have different numbers (in different fields that may change) which I want to modify

I need a function which change the numbers into a "string" depending on a range

Information

Numbers

Numbers can be from 0 to 5000

My ranges

From 0 to 150

From 151 to 300

From 301 to 500

Up to 501

Range - string relation

From 0 to 150 --> "Less than 150 m2"

From 151 to 300 --> "150 - 300 m2"

From 301 to 500 --> "300 - 500 m2"

Up to 501 --> "Up to 500 m2"

Examples

Number: 180 -- (this number is <300 and > 151) --> Output: "150 - 300 m2"

Number: 524 -- (this number is > 501) --> Output: "Up to 500 m2"

What I've achieved
I'm looking for a better way to do this. Any documentation is also welcomed.

<?php
function my_map_field($data) {
    $map = array(
        '0' => 'Less than 150 m2',
        '1' => 'Less than 150 m2',
        '2' => 'Less than 150 m2',
        '3' => 'Less than 150 m2',
        '4' => 'Less than 150 m2', /*Imagine all the numbers*/
        '151' => '150 - 300 m2',  /*Imagine all the numbers*/
        '301' => '300 - 500 m2',  /*Imagine all the numbers*/
    );

    return isset( $map[$data] ) ? $map[$data] : $data;
}
?>

Body:
Find the numbers with regex then str_replace them.

Regex pattern \d+ finds numbers.

function replace_numbers($str) {

 Preg_match_all("/(\d+)/", $str, $arr);
 //Var_dump($arr);
 For ($i=0; $i<count($arr[0]);$i++){
     If($arr[0][$i]>=0 && $arr[0][$i]<=150) $str = str_replace($arr[0][$i], "less than 150 m2", $str);
     If($arr[0][$i]>=151 && $arr[0][$i]<=300) $str = str_replace($arr[0][$i], "151 - 300 m2", $str);
     If($arr[0][$i]>=301 && $arr[0][$i]<=500) $str = str_replace($arr[0][$i], "301 - 500 m2", $str);
     If($arr[0][$i]>=501 && $arr[0][$i]<=5000) $str = str_replace($arr[0][$i], "up to 500 m2", $str);

 }

Return $str;
}

$str ="Number: 180, Number: 524";  // the string that needs attention
$newstr = replace_numbers($str); // newstr is the old string but with replaced numbers

I have not included anything that takes care of numbers above 5000.

Also since you have not given much examples it will not work strings like "I'm 30 years old and my house is 400 m2" because it will replace 30 also.


问:
Neo4J : Get all nodes who are connected to at least K nodes with a path length <= 2
With this use case I am finding it to hard with Cypher query. Do I need to write stored procedure for it ?</p>

答:
Here is a query that will return every node that is connected via paths up to length 2 to at least k distinct nodes. k is assumed to be passed as a parameter.

```<code>MATCH (n)-[*..2]-(m)
WITH n, COUNT(DISTINCT m) AS ms
WHERE ms > $k
RETURN n, ms;
</code>```

Body:
Here is a query that will return every node that is connected via paths up to length 2 to at least k distinct nodes. k is assumed to be passed as a parameter.

MATCH (n)-[*..2]-(m)
WITH n, COUNT(DISTINCT m) AS ms
WHERE ms > $k
RETURN n, ms;


问:
Creating a user profile with SoftLayer_User_Customer REST API
I am trying to create a new user profile and the JSON fields passed in are ignored.

The following is the URL with method POST

```<code>https://api.softlayer.com/rest/v3/SoftLayer_User_Customer.json
</code>```

The JSON payload is:

```<code>{
"parameters" : [
    {
      "address1" : "1101 Kitchawan Road",
      "city" : "Yorktown Heights",
      "companyName" : "IBM - www Account",
      "state" : "NY",
      "country" : "US",
      "postalCode" : "10598",
      "firstName" : "hello",
      "lastName" : "thisguy",
      "email" : "thisguy@nn.ibm.com",
      "permissionSystemVersion" : "1",
      "timezoneId" : "117",
      "username" : "286900_thisguy@nn.ibm.com",
      "secondaryPasswordTimeoutDays" : 90,
      "managedByOpenIdConnectFlag" : false,
      "userStatusId" : 1001,
      "sslVpnAllowedFlag" : true
   },
  "xxxxxxxx!",
  "xxxxxxxx!"
 ]
}
</code>```

The JSON returned from the create is:

```<code>      'userStatusId' => 1001,
      'timezoneId' => 117,
      'accountId' => 286900,
      'statusDate' => undef,
      'userLinks' => [],
      'locale' => {
                    'friendlyName' => 'English',
                    'name' => 'English',
                    'id' => 1,
                    'languageTag' => 'en-US'
                  },
      'state' => 'NY',
      'secondaryLoginRequiredFlag' => undef,
      'msn' => '',
      'managedByOpenIdConnectFlag' => bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' ),
      'email' => 'thisguy@nn.ibm.com',
      'permissionSystemVersion' => 2,
      'vpnManualConfig' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
      'id' => 6713227,
      'secondaryPasswordTimeoutDays' => 0,
      'yahoo' => '',
      'denyAllResourceAccessOnCreateFlag' => $VAR1->{'vpnManualConfig'},
      'secondaryLoginManagementFlag' => undef,
      'localeId' => 1,
      'firstName' => hello',
      'timezone' => {
                      'longName' => '(GMT-05:00) America/New York - EST',
                      'name' => 'America/New_York',
                      'id' => 117,
                      'shortName' => 'EST',
                      'offset' => '-0500'
                    },
      'sslVpnAllowedFlag' => $VAR1->{'vpnManualConfig'},
      'companyName' => 'IBM - www Account',
      'isMasterUserFlag' => $VAR1->{'vpnManualConfig'},
      'username' => '286900_thisguy@nn.ibm.com',
      'pptpVpnAllowedFlag' => $VAR1->{'vpnManualConfig'},
      'userStatus' => {
                        'name' => 'Active',
                        'id' => 1001,
                        'keyName' => 'ACTIVE'
                      },
      'passwordExpireDate' => undef,
      'address1' => '1101 Kitchawan Road',
      'sms' => '',
      'daylightSavingsTimeFlag' => $VAR1->{'vpnManualConfig'},
      'officePhone' => '',
      'city' => 'Yorktown Heights',
      'icq' => '',
      'createDate' => '2017-06-06T08:46:54-04:00',
      'savedId' => '6713227',
      'lastName' => 'thisguy',
      'displayName' => 'CarlosF',
      'secondaryPasswordModifyDate' => '2017-06-06T08:46:55-04:00',
      'country' => 'US',
      'modifyDate' => '2017-06-06T08:46:55-04:00',
      'alternatePhone' => '',
      'forumPasswordHash' => '._staIj7diist1',
      'aim' => '',
      'managedByFederationFlag' => $VAR1->{'vpnManualConfig'},
      'address2' => '',
      'parentId' => 151785,
      'postalCode' => '10598'
    };
</code>```

This all looks good, except for the fiedl 'displayName'

I now issue the URL with a GET request:

```<code>https://api.softlayer.com/rest/v3/SoftLayer_Account/getUsers/6713227.json?objectMask=mask[virtualGuestCount,virtualGuests.id,virtualGuests.hostname,virtualGuests.status,hardwareCount,hardware.id,hardware.hostname,hardware.hardwareStatus,userStatus,apiAuthenticationKeyCount,apiAuthenticationKeys,loginAttemptCount,successfulLoginCount,unsuccessfulLoginCount]
</code>```

The JSON payload returned is:

```<code>'userStatusId' => 1001,
'timezoneId' => 113,
'accountId' => 286900,
'permissions' => [
]
'state' => 'NY',
'secondaryLoginRequiredFlag' => undef,
'managedByOpenIdConnectFlag' => bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' ),
'email' => 'thisguy@nn.ibm.com',
'actionCount' => 25,
'permissionSystemVersion' => 2,
'vpnManualConfig' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
'id' => 6713227,
'secondaryPasswordTimeoutDays' => 0,
'denyAllResourceAccessOnCreateFlag' => $VAR1->{'vpnManualConfig'},
'secondaryLoginManagementFlag' => undef,
'firstName' => 'hello',
'localeId' => 1,
'parent' => {
]
'timezone' => {
     'longName' => '(GMT-06:00) America/Chicago - CST',
     'name' => 'America/Chicago',
     'id' => 113,
     'shortName' => 'CST',
     'offset' => '-0600'
    },
'sslVpnAllowedFlag' => $VAR1->{'vpnManualConfig'},
'companyName' => 'IBM - www Account',
'isMasterUserFlag' => $VAR1->{'vpnManualConfig'},
'username' => '286900_thisguy@us.ibm.com',
'pptpVpnAllowedFlag' => $VAR1->{'vpnManualConfig'},
'userStatus' => {
                        'name' => 'Active',
                        'id' => 1001,
                        'keyName' => 'ACTIVE'
                      },
 'apiAuthenticationKeys' => [
 ]
 'passwordExpireDate' => undef,
 'loginAttemptCount' => 0,
 'address1' => '2455 South Rd',
 'openIdConnectUserName' => 'thisguy@nn.ibm.com',
 'actions' => [
 ]
 'daylightSavingsTimeFlag' => $VAR1->{'vpnManualConfig'},
      'unsuccessfulLoginCount' => 0,
      'successfulLoginCount' => 0,
      'city' => 'Poughkeepsie',
      'createDate' => '2017-06-06T08:46:54-04:00',
      'savedId' => '6713227',
      'lastName' => 'thisguy',
      'displayName' => 'hellog',
      'country' => 'US',
      'secondaryPasswordModifyDate' => '2017-06-06T08:46:55-04:00',
      'modifyDate' => '2017-06-06T08:46:55-04:00',
      'apiAuthenticationKeyCount' => 1,
      'forumPasswordHash' => '._staIj7diist1',
      'managedByFederationFlag' => $VAR1->{'vpnManualConfig'},
      'parentId' => 151785,
      'postalCode' => '12601-5400'

    }
</code>```

Notice that th4e address is not the same as returned from the create and the timezone is wrong. The create ignored certain fields passed in on the create.

答:
This is an issue for accounts with bluemix and it is already reported. Some values like address and time zone are saved with data of master account.

You can try to update/change those values by editing the user with the method SoftLayer_User_Customer::editObject.

Also you can submit a ticket in order to get further assistance with this bug.

About displayName

If you don't set this value in the JSON request, it is automatically set with the firstName and first character of lastName.

Body:
I am trying to create a new user profile and the JSON fields passed in are ignored.

The following is the URL with method POST

https://api.softlayer.com/rest/v3/SoftLayer_User_Customer.json

The JSON payload is:

{
"parameters" : [
    {
      "address1" : "1101 Kitchawan Road",
      "city" : "Yorktown Heights",
      "companyName" : "IBM - www Account",
      "state" : "NY",
      "country" : "US",
      "postalCode" : "10598",
      "firstName" : "hello",
      "lastName" : "thisguy",
      "email" : "thisguy@nn.ibm.com",
      "permissionSystemVersion" : "1",
      "timezoneId" : "117",
      "username" : "286900_thisguy@nn.ibm.com",
      "secondaryPasswordTimeoutDays" : 90,
      "managedByOpenIdConnectFlag" : false,
      "userStatusId" : 1001,
      "sslVpnAllowedFlag" : true
   },
  "xxxxxxxx!",
  "xxxxxxxx!"
 ]
}

The JSON returned from the create is:

      'userStatusId' => 1001,
      'timezoneId' => 117,
      'accountId' => 286900,
      'statusDate' => undef,
      'userLinks' => [],
      'locale' => {
                    'friendlyName' => 'English',
                    'name' => 'English',
                    'id' => 1,
                    'languageTag' => 'en-US'
                  },
      'state' => 'NY',
      'secondaryLoginRequiredFlag' => undef,
      'msn' => '',
      'managedByOpenIdConnectFlag' => bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' ),
      'email' => 'thisguy@nn.ibm.com',
      'permissionSystemVersion' => 2,
      'vpnManualConfig' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
      'id' => 6713227,
      'secondaryPasswordTimeoutDays' => 0,
      'yahoo' => '',
      'denyAllResourceAccessOnCreateFlag' => $VAR1->{'vpnManualConfig'},
      'secondaryLoginManagementFlag' => undef,
      'localeId' => 1,
      'firstName' => hello',
      'timezone' => {
                      'longName' => '(GMT-05:00) America/New York - EST',
                      'name' => 'America/New_York',
                      'id' => 117,
                      'shortName' => 'EST',
                      'offset' => '-0500'
                    },
      'sslVpnAllowedFlag' => $VAR1->{'vpnManualConfig'},
      'companyName' => 'IBM - www Account',
      'isMasterUserFlag' => $VAR1->{'vpnManualConfig'},
      'username' => '286900_thisguy@nn.ibm.com',
      'pptpVpnAllowedFlag' => $VAR1->{'vpnManualConfig'},
      'userStatus' => {
                        'name' => 'Active',
                        'id' => 1001,
                        'keyName' => 'ACTIVE'
                      },
      'passwordExpireDate' => undef,
      'address1' => '1101 Kitchawan Road',
      'sms' => '',
      'daylightSavingsTimeFlag' => $VAR1->{'vpnManualConfig'},
      'officePhone' => '',
      'city' => 'Yorktown Heights',
      'icq' => '',
      'createDate' => '2017-06-06T08:46:54-04:00',
      'savedId' => '6713227',
      'lastName' => 'thisguy',
      'displayName' => 'CarlosF',
      'secondaryPasswordModifyDate' => '2017-06-06T08:46:55-04:00',
      'country' => 'US',
      'modifyDate' => '2017-06-06T08:46:55-04:00',
      'alternatePhone' => '',
      'forumPasswordHash' => '._staIj7diist1',
      'aim' => '',
      'managedByFederationFlag' => $VAR1->{'vpnManualConfig'},
      'address2' => '',
      'parentId' => 151785,
      'postalCode' => '10598'
    };

This all looks good, except for the fiedl 'displayName'

I now issue the URL with a GET request:

https://api.softlayer.com/rest/v3/SoftLayer_Account/getUsers/6713227.json?objectMask=mask[virtualGuestCount,virtualGuests.id,virtualGuests.hostname,virtualGuests.status,hardwareCount,hardware.id,hardware.hostname,hardware.hardwareStatus,userStatus,apiAuthenticationKeyCount,apiAuthenticationKeys,loginAttemptCount,successfulLoginCount,unsuccessfulLoginCount]

The JSON payload returned is:

'userStatusId' => 1001,
'timezoneId' => 113,
'accountId' => 286900,
'permissions' => [
]
'state' => 'NY',
'secondaryLoginRequiredFlag' => undef,
'managedByOpenIdConnectFlag' => bless( do{\(my $o = 1)}, 'JSON::PP::Boolean' ),
'email' => 'thisguy@nn.ibm.com',
'actionCount' => 25,
'permissionSystemVersion' => 2,
'vpnManualConfig' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
'id' => 6713227,
'secondaryPasswordTimeoutDays' => 0,
'denyAllResourceAccessOnCreateFlag' => $VAR1->{'vpnManualConfig'},
'secondaryLoginManagementFlag' => undef,
'firstName' => 'hello',
'localeId' => 1,
'parent' => {
]
'timezone' => {
     'longName' => '(GMT-06:00) America/Chicago - CST',
     'name' => 'America/Chicago',
     'id' => 113,
     'shortName' => 'CST',
     'offset' => '-0600'
    },
'sslVpnAllowedFlag' => $VAR1->{'vpnManualConfig'},
'companyName' => 'IBM - www Account',
'isMasterUserFlag' => $VAR1->{'vpnManualConfig'},
'username' => '286900_thisguy@us.ibm.com',
'pptpVpnAllowedFlag' => $VAR1->{'vpnManualConfig'},
'userStatus' => {
                        'name' => 'Active',
                        'id' => 1001,
                        'keyName' => 'ACTIVE'
                      },
 'apiAuthenticationKeys' => [
 ]
 'passwordExpireDate' => undef,
 'loginAttemptCount' => 0,
 'address1' => '2455 South Rd',
 'openIdConnectUserName' => 'thisguy@nn.ibm.com',
 'actions' => [
 ]
 'daylightSavingsTimeFlag' => $VAR1->{'vpnManualConfig'},
      'unsuccessfulLoginCount' => 0,
      'successfulLoginCount' => 0,
      'city' => 'Poughkeepsie',
      'createDate' => '2017-06-06T08:46:54-04:00',
      'savedId' => '6713227',
      'lastName' => 'thisguy',
      'displayName' => 'hellog',
      'country' => 'US',
      'secondaryPasswordModifyDate' => '2017-06-06T08:46:55-04:00',
      'modifyDate' => '2017-06-06T08:46:55-04:00',
      'apiAuthenticationKeyCount' => 1,
      'forumPasswordHash' => '._staIj7diist1',
      'managedByFederationFlag' => $VAR1->{'vpnManualConfig'},
      'parentId' => 151785,
      'postalCode' => '12601-5400'

    }

Notice that th4e address is not the same as returned from the create and the timezone is wrong. The create ignored certain fields passed in on the create.


问:
DateTime parsing problem (DateTime.ParseExact)
[Please vote to close this - see my last comment.]

Hi,

Something like this:

```<code>DateTime.ParseExact("25/12/2008 00:00:00", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
</code>```

works fine on my development machine but not after deployment (server).

I guess it has to do with some time zone configuration. I have tried:

```<code><%@ ... UICulture="en" Culture="en-US" %>
</code>```

with no avail. Any suggestions on a postcard please. Thanks.

Christian

PS: Exception:

String was not recognized as a valid DateTime

PPS: I have updated the question. I actually feed in the time bit. sorry about that!

PPPS:
I have now realised that all this has to do with Excel and oledb. The string 25/12/2008 looks like this "12/25/2008 12:00:00 AM" on the server and like this "25/12/2008 00:00:00" on the developement machine. I adjusted the time zone of the server to UK without avail. What else can I do? Thank and sorry about all this confusion!!!

答:
try </p>

```<code>DateTime.ParseExact("25/12/2008", "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
</code>```

Body:
[Please vote to close this - see my last comment.]

Hi,

Something like this:

DateTime.ParseExact("25/12/2008 00:00:00", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

works fine on my development machine but not after deployment (server).

I guess it has to do with some time zone configuration. I have tried:

<%@ ... UICulture="en" Culture="en-US" %>

with no avail. Any suggestions on a postcard please. Thanks.

Christian

PS: Exception:

String was not recognized as a valid DateTime

PPS: I have updated the question. I actually feed in the time bit. sorry about that!

PPPS:
I have now realised that all this has to do with Excel and oledb. The string 25/12/2008 looks like this "12/25/2008 12:00:00 AM" on the server and like this "25/12/2008 00:00:00" on the developement machine. I adjusted the time zone of the server to UK without avail. What else can I do? Thank and sorry about all this confusion!!!

Body:
try

DateTime.ParseExact("25/12/2008", "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);


问:
Is it possible to use a table in an array statement?
I'm trying to reference a table in an array to eventually use in process in a data step. Here is the code:

```<code>proc sql;
create table claims.iterations
    as select Allowed_Claims, Px1
    from simulation
    order by Allowed_Claims, Px1;
quit;
data simulation_iterations;
    array Members {24} _temporary_ (5 6 8 10 12 15 20 25 30 40 50 60 70 80
                                    90 100 125 150 175 200 250 300 400 500);
    array ****** ;
    do i = 1 to 24;
    do j = 1 to Members{i}-1;
        Px2 = rand('Uniform',0,1);
        if Px2 > 0.5 then Px2=Px2;
        output;
        end;
    output;
    end;
run;
</code>```

is it possible to do so? Although it isn't shown, I want to use the table as in an attempt to linearly interpolate for the values in the "Members" array.

Edit:

I want to interpolate for Allowed_Claims based on a randomly generated value (from 0 to 1). The condensed table that I'm basing my linearly interpolation off of is listed below.

```<code>Allowed_Claims  Px1
25.224545313    0.0008129708
34.767797696    0.0014747668
35.367278291    0.0015210493
42.616660238    0.0021191153
52.495185148    0.0030343735
52.652599162    0.0030497846
53.26904904     0.0031103676
57.183442582    0.0035034118
</code>```

For example, let's call this Process A, if Px2 = rand('Uniform',0,1) yields .0010, I want it to interpolate between the Allowed_Claims values where Px1 = 0.0008129708 and Px1 = 0.0014747668.

The role of the array is that it dictates how many iterations of Process A I want. The array is

```<code>Members {24} _temporary_ (5 6 8 10 12 15 20 25 30 40 50 60 70 80
                                    90 100 125 150 175 200 250 300 400 500);
</code>```

So when the loop starts, it will perform 5 iterations of Process A, thereby producing 5 interpolated "allowed_claims" values. I want the average of these five claims.

Then, the loop will continue and perform 6 iterations of Process A and produce 6 interpolated "allowed_claims" values. Again, I want the average of these 6 claims.

I want the output table to look like:

`

```<code>Member[i]    Average_Expected_Claims
   5              (average of 5 interpolated claims)
   6              (average of 6 interpolated claims)
   8              (average of 8 interpolated claims)
</code>```

答:
Here's the example of how to do this with a hash table.  It's very similar to an array in this usage - since there's no "lookup key", we just load it up and create an iterator, then loop over the iterator, just like an array (except you can't grab the exact position).  Sadly there's no VLOOKUP-type functionality that will give you the closest match - you have to iterate until you find your correct one.

This isn't the absolute most efficient process, in particular I make exactly one more iterator call than I need to (as I could store the last seen allowed claims in a variable).  I don't bother because frankly it's not worth it, just calling the iterator one more time doesn't make much difference, but I suppose for efficiency you might want to do it differently if this takes a long time on your machine.  I doubt it will.

```<code>*Just setting up the example iterations dataset;
data iterations;
  call streaminit(7);
  retain allowed_claims 20;
  do px1 = 0.05 to 1 by 0.05;
    allowed_claims + rand('Uniform')*5;
    output;
  end;
run;

data simulated_iterations2;
  call streaminit(8);      *init the random generator;
  array Members [5] _temporary_ (5 6 8 10 12);  *any number of members here is fine;
  if _n_ eq 1  then do;            *initialize the hash tables;
    if 0 then set iterations;      *defines the variables used;
    declare hash _iter(dataset:'iterations', ordered:'a');  *ordered = ascending - do not need a sort first;
    _iter.defineKey('px1');                    * key is artificial, but has to exist;
    _iter.defineData('px1','allowed_Claims');  * data variables to retrieve;
    _iter.defineDone();
    declare hiter hi_iter('_iter');            * the iterator object;

  end;

  do _i_member = 1 to dim(members);            * iterate over members array;
    call missing(claims_simulated);
    do _i_simul = 1 to members[_i_member];     * iterate for the member value;

      rand_value = rand('Uniform');            * the number to interpolate;
      do rc= hi_iter.first() by 0 until (hi_iter.next() ne 0 or px1 gt rand_value );
         *do nothing;                          * here we are doing the work in the DO statement, looping until we find the value greater than the rand value;
      end;
      ac_max = allowed_claims;                 * your 'max' interpolation value;
      rc = hi_iter.prev();                     * back up one;
      ac_min = allowed_claims;                 * your 'min' interpolation value;
      claims_simulated + (mean(ac_min,ac_max))/members[_i_member];  *add the mean of the two interpolation values divided by the total number we are going to do to the total - avoids us having to do another array to store these and get mean of;
      put rand_value= claims_simulated=;       *just for logging;
    end;
    putlog;
    output;
  end;

  stop;

run;
</code>```

Body:
I'm trying to reference a table in an array to eventually use in process in a data step. Here is the code:

proc sql;
create table claims.iterations
    as select Allowed_Claims, Px1
    from simulation
    order by Allowed_Claims, Px1;
quit;
data simulation_iterations;
    array Members {24} _temporary_ (5 6 8 10 12 15 20 25 30 40 50 60 70 80
                                    90 100 125 150 175 200 250 300 400 500);
    array ****** ;
    do i = 1 to 24;
    do j = 1 to Members{i}-1;
        Px2 = rand('Uniform',0,1);
        if Px2 > 0.5 then Px2=Px2;
        output;
        end;
    output;
    end;
run;

is it possible to do so? Although it isn't shown, I want to use the table as in an attempt to linearly interpolate for the values in the "Members" array.

Edit:

I want to interpolate for Allowed_Claims based on a randomly generated value (from 0 to 1). The condensed table that I'm basing my linearly interpolation off of is listed below.

Allowed_Claims  Px1
25.224545313    0.0008129708
34.767797696    0.0014747668
35.367278291    0.0015210493
42.616660238    0.0021191153
52.495185148    0.0030343735
52.652599162    0.0030497846
53.26904904     0.0031103676
57.183442582    0.0035034118

For example, let's call this Process A, if Px2 = rand('Uniform',0,1) yields .0010, I want it to interpolate between the Allowed_Claims values where Px1 = 0.0008129708 and Px1 = 0.0014747668.

The role of the array is that it dictates how many iterations of Process A I want. The array is

Members {24} _temporary_ (5 6 8 10 12 15 20 25 30 40 50 60 70 80
                                    90 100 125 150 175 200 250 300 400 500);

So when the loop starts, it will perform 5 iterations of Process A, thereby producing 5 interpolated "allowed_claims" values. I want the average of these five claims.

Then, the loop will continue and perform 6 iterations of Process A and produce 6 interpolated "allowed_claims" values. Again, I want the average of these 6 claims.

I want the output table to look like:

`

Member[i]    Average_Expected_Claims
   5              (average of 5 interpolated claims)
   6              (average of 6 interpolated claims)
   8              (average of 8 interpolated claims)

Body:
Here's the example of how to do this with a hash table.  It's very similar to an array in this usage - since there's no "lookup key", we just load it up and create an iterator, then loop over the iterator, just like an array (except you can't grab the exact position).  Sadly there's no VLOOKUP-type functionality that will give you the closest match - you have to iterate until you find your correct one.

This isn't the absolute most efficient process, in particular I make exactly one more iterator call than I need to (as I could store the last seen allowed claims in a variable).  I don't bother because frankly it's not worth it, just calling the iterator one more time doesn't make much difference, but I suppose for efficiency you might want to do it differently if this takes a long time on your machine.  I doubt it will.

*Just setting up the example iterations dataset;
data iterations;
  call streaminit(7);
  retain allowed_claims 20;
  do px1 = 0.05 to 1 by 0.05;
    allowed_claims + rand('Uniform')*5;
    output;
  end;
run;

data simulated_iterations2;
  call streaminit(8);      *init the random generator;
  array Members [5] _temporary_ (5 6 8 10 12);  *any number of members here is fine;
  if _n_ eq 1  then do;            *initialize the hash tables;
    if 0 then set iterations;      *defines the variables used;
    declare hash _iter(dataset:'iterations', ordered:'a');  *ordered = ascending - do not need a sort first;
    _iter.defineKey('px1');                    * key is artificial, but has to exist;
    _iter.defineData('px1','allowed_Claims');  * data variables to retrieve;
    _iter.defineDone();
    declare hiter hi_iter('_iter');            * the iterator object;

  end;

  do _i_member = 1 to dim(members);            * iterate over members array;
    call missing(claims_simulated);
    do _i_simul = 1 to members[_i_member];     * iterate for the member value;

      rand_value = rand('Uniform');            * the number to interpolate;
      do rc= hi_iter.first() by 0 until (hi_iter.next() ne 0 or px1 gt rand_value );
         *do nothing;                          * here we are doing the work in the DO statement, looping until we find the value greater than the rand value;
      end;
      ac_max = allowed_claims;                 * your 'max' interpolation value;
      rc = hi_iter.prev();                     * back up one;
      ac_min = allowed_claims;                 * your 'min' interpolation value;
      claims_simulated + (mean(ac_min,ac_max))/members[_i_member];  *add the mean of the two interpolation values divided by the total number we are going to do to the total - avoids us having to do another array to store these and get mean of;
      put rand_value= claims_simulated=;       *just for logging;
    end;
    putlog;
    output;
  end;

  stop;

run;


问:
How can I access a controller's data in another controller in Angular js?
```<code>var app = angular.module("myApp",[]);

app.controller("CTRL1", function($scope){
    $scope.data = [{'name':'Prateek'},{'name':'Agarwal'},{'name': 'Ketan'}];
})

app.controller("CTRL2", function($scope){
    $scope.data = [{'name':'Hari'}];
})
</code>```

I have two controllers - CTRL1 and CTRL2. How can I access data from one controller in another?

答:
You can use $emit and $on functions for this, These will send data in any controll on spectfic event named.</p>

```<code><div ng-app="myApp" ng-controller="myCtrl">

    <button ng-click="sendData();"></button>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    function sendData($scope) {
        var arrayData = [1,2,3];
        $scope.$emit('someEvent', arrayData);
    }

});
app.controller('yourCtrl', function($scope, $http) {
    $scope.$on('someEvent', function(event, data) {
        console.log(data);
    });
});
</script>
</code>```

Body:
var app = angular.module("myApp",[]);

app.controller("CTRL1", function($scope){
    $scope.data = [{'name':'Prateek'},{'name':'Agarwal'},{'name': 'Ketan'}];
})

app.controller("CTRL2", function($scope){
    $scope.data = [{'name':'Hari'}];
})

I have two controllers - CTRL1 and CTRL2. How can I access data from one controller in another?

Body:
You can use $emit and $on functions for this, These will send data in any controll on spectfic event named.

<div ng-app="myApp" ng-controller="myCtrl">

    <button ng-click="sendData();"></button>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    function sendData($scope) {
        var arrayData = [1,2,3];
        $scope.$emit('someEvent', arrayData);
    }

});
app.controller('yourCtrl', function($scope, $http) {
    $scope.$on('someEvent', function(event, data) {
        console.log(data);
    });
});
</script>