问:
Deployment of NPAPI plugin with minimal user steps
Situation: I've already written an ActiveX control for my IE users which works perfectly.  I build the .ocx, CAB it up, sign it, and put it on the site with an EMBED tag.  Users load the page, the yellow bar shows up asking if they want to install it: all they have to do is click it, and we're off.

Now I need to build support for FF, Chrome, and Safari (on Mac).  From my research, NPAPI is the way to do this, and Firebreath is supposed to make it easier.  But from what I have read, deployment is not so easy.  Windows users would have to run "regsvr32" on a DLL (which none of my web users would actually do).  I have no idea what would happen on a Mac.  I believe the user has to copy it to a directory like /Library/Internet\ Plugins/, which is also a non-starter for deployment.  Firefox users would download/run an .xpi.  Chrome is supposed to run a .crx.

Does anyone out there have experience with this?  How do you do a easy-for-users-to-run deployment of an NPAPI plugin for the other big 3 browsers?

答:
I'm not aware of any way to install a plugin from within Safari.

Also, keep in mind that while you may think of the extension-style deployment as easier for users, it's not all that uncommon for Mac users to use more than one browser. If you make them re-install your plugin in each browser they will be confused (since that's not how browser plugins are generally deployed on the Mac) and annoyed. An installer or a manual drag-and-drop installation are the standard ways of deploying plugins on the Mac.


来源: stackexchange

问:
How to set data in recyclerView with Retrofit in Android
I want to show some data into recyclerview and for this I am using the code displayed below.

When I run the application, it's not showing me any data into recyclerview and ListData.size() is 0, but in PostMan

I write below code for set into recyclerView :

```<code>InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<CommentResponse> call = api.getComments(sendData);

call.enqueue(new Callback<CommentResponse>() {
    @Override
    public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
        if (response.body().getData() != null) {
            commentModel.clear();
            commentModel.addAll(response.body().getData());
            commentsListAdapter.notifyDataSetChanged();
            content_newsCommentsRecyclerView.setAdapter(commentsListAdapter);
        }
    }

    @Override
    public void onFailure(Call<CommentResponse> call, Throwable t) {

    }
});
</code>```

My Adapter codes:

```<code>public class CommentsListAdapter extends RecyclerView.Adapter<CommentsListAdapter.ViewHolder> {

    private Context context;
    private List<CommentData> model;

    public CommentsListAdapter(Context context, List<CommentData> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public CommentsListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_comment, parent, false);

        return new CommentsListAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final CommentsListAdapter.ViewHolder holder, final int position) {

        holder.row_commentNameTxt.setText(Html.fromHtml(model.get(position).getOwner().getName()));
        holder.row_commentCommentTxt.setText(Html.fromHtml(model.get(position).getText()));
        Glide.with(context)
                .load(model.get(position).getOwner().getImageUrl())
                .placeholder(R.drawable.default_image)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.row_commentProfileImage);
        holder.row_commentLikeTxt.setText(model.get(position).getLikeCount() + "");
        holder.row_commentReplayTxt.setText(model.get(position).getRepliesCount() + "");
        holder.row_commentDateTxt.setText(model.get(position).getSubmitDate() + " " + model.get(position).getSubmitTime());
    }

    @Override
    public int getItemCount() {
        return model.size();
    }

    public void addNewItem(List<CommentData> newContent) {
        int start = this.model.size();
        int end = newContent.size();
        model.addAll(newContent);
        notifyDataSetChanged();
    }

    public void clear() {
        model.clear();
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private CircleImageView row_commentProfileImage;
        private TextView row_commentNameTxt, row_commentCommentTxt, row_commentLikeTxt, row_commentReplayTxt, row_commentDateTxt;

        public ViewHolder(View itemView) {
            super(itemView);

            row_commentProfileImage = (CircleImageView) itemView.findViewById(R.id.row_commentProfileImage);
            row_commentNameTxt = (TextView) itemView.findViewById(R.id.row_commentNameTxt);
            row_commentCommentTxt = (TextView) itemView.findViewById(R.id.row_commentCommentTxt);
            row_commentLikeTxt = (TextView) itemView.findViewById(R.id.row_commentLikeTxt);
            row_commentReplayTxt = (TextView) itemView.findViewById(R.id.row_commentReplayTxt);
            row_commentDateTxt = (TextView) itemView.findViewById(R.id.row_commentDateTxt);

        }
    }
}
</code>```

How can I display the data into recyclerView?

答:
Before the API call initialize the Adapter

```<code>mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRVCommentList.setLayoutManager(mLayoutManager);
CommentsListAdapter commentsListAdapter= new CommentsListAdapter(this)
mRVCommentList.setAdapter(commentsListAdapter)
</code>```

Then call the API

```<code>public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
        if (response.body().getData() != null) {
            List<CommentData> list= response.body().getData().getCommentData();
            commentsListAdapter.setData(list);
         }
    }
</code>```

Small changes in Adapter Class

```<code>private List<CommentData> commentData;

 public CommentsListAdapter(Context context) {
        this.context = context;
        this.commentData = new ArrayList<>();
    }

 public void setData(List<CommentData> commentData) {
        this.commentData= commentData;
        notifyDataSetChanged();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to show some data into recyclerview and for this I am using the code displayed below.

When I run the application, it's not showing me any data into recyclerview and ListData.size() is 0, but in PostMan

I write below code for set into recyclerView :

InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<CommentResponse> call = api.getComments(sendData);

call.enqueue(new Callback<CommentResponse>() {
    @Override
    public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
        if (response.body().getData() != null) {
            commentModel.clear();
            commentModel.addAll(response.body().getData());
            commentsListAdapter.notifyDataSetChanged();
            content_newsCommentsRecyclerView.setAdapter(commentsListAdapter);
        }
    }

    @Override
    public void onFailure(Call<CommentResponse> call, Throwable t) {

    }
});

My Adapter codes:

public class CommentsListAdapter extends RecyclerView.Adapter<CommentsListAdapter.ViewHolder> {

    private Context context;
    private List<CommentData> model;

    public CommentsListAdapter(Context context, List<CommentData> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public CommentsListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_comment, parent, false);

        return new CommentsListAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final CommentsListAdapter.ViewHolder holder, final int position) {

        holder.row_commentNameTxt.setText(Html.fromHtml(model.get(position).getOwner().getName()));
        holder.row_commentCommentTxt.setText(Html.fromHtml(model.get(position).getText()));
        Glide.with(context)
                .load(model.get(position).getOwner().getImageUrl())
                .placeholder(R.drawable.default_image)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.row_commentProfileImage);
        holder.row_commentLikeTxt.setText(model.get(position).getLikeCount() + "");
        holder.row_commentReplayTxt.setText(model.get(position).getRepliesCount() + "");
        holder.row_commentDateTxt.setText(model.get(position).getSubmitDate() + " " + model.get(position).getSubmitTime());
    }

    @Override
    public int getItemCount() {
        return model.size();
    }

    public void addNewItem(List<CommentData> newContent) {
        int start = this.model.size();
        int end = newContent.size();
        model.addAll(newContent);
        notifyDataSetChanged();
    }

    public void clear() {
        model.clear();
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private CircleImageView row_commentProfileImage;
        private TextView row_commentNameTxt, row_commentCommentTxt, row_commentLikeTxt, row_commentReplayTxt, row_commentDateTxt;

        public ViewHolder(View itemView) {
            super(itemView);

            row_commentProfileImage = (CircleImageView) itemView.findViewById(R.id.row_commentProfileImage);
            row_commentNameTxt = (TextView) itemView.findViewById(R.id.row_commentNameTxt);
            row_commentCommentTxt = (TextView) itemView.findViewById(R.id.row_commentCommentTxt);
            row_commentLikeTxt = (TextView) itemView.findViewById(R.id.row_commentLikeTxt);
            row_commentReplayTxt = (TextView) itemView.findViewById(R.id.row_commentReplayTxt);
            row_commentDateTxt = (TextView) itemView.findViewById(R.id.row_commentDateTxt);

        }
    }
}

How can I display the data into recyclerView?

Body:
Before the API call initialize the Adapter

mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRVCommentList.setLayoutManager(mLayoutManager);
CommentsListAdapter commentsListAdapter= new CommentsListAdapter(this)
mRVCommentList.setAdapter(commentsListAdapter)

Then call the API

public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
        if (response.body().getData() != null) {
            List<CommentData> list= response.body().getData().getCommentData();
            commentsListAdapter.setData(list);
         }
    }

Small changes in Adapter Class

private List<CommentData> commentData;

 public CommentsListAdapter(Context context) {
        this.context = context;
        this.commentData = new ArrayList<>();
    }

 public void setData(List<CommentData> commentData) {
        this.commentData= commentData;
        notifyDataSetChanged();
    }


问:
Need to insert Script tag in angular 2
I've already done a bit of reading and searching and pretty much everything I find points to that a script tag cannot be included in a template in Angular 2.

we are removing  tags from templates on purpose as you
  shouldn't use those to load code on demand.
  https://github.com/angular/angular/issues/4903 [2015]

However - there is a function bypassSecurityTrustScript

I'd like to know when and how bypassSecurityTrustScript in Angular 2 is intended to be used?

I know a similar question has been asked:
Angular2 dynamically insert script tag - though no one answered their question of how to use bypassSecurityTrustScript, and I'm not sure how the provided answer to that question could even work as it appears to use JavaScript within a template.

答:
Having scripts in your views is usually a bad practice. If you insist on doing this you can use this component:

scripthack.component.html:

```<code><div #script style.display="none">
  <ng-content></ng-content>
</div>
</code>```

scripthack.component.ts:

```<code>import { Component, ElementRef, ViewChild, Input } from '@angular/core';

@Component({
    selector: 'script-hack',
    templateUrl: './scripthack.component.html'
})
export class ScriptHackComponent {

    @Input()
    src: string;

    @Input()
    type: string;

    @ViewChild('script') script: ElementRef;

    convertToScript() {
        var element = this.script.nativeElement;
        var script = document.createElement("script");
        script.type = this.type ? this.type : "text/javascript";
        if (this.src) {
            script.src = this.src;
        }
        if (element.innerHTML) {
            script.innerHTML = element.innerHTML;
        }
        var parent = element.parentElement;
        parent.parentElement.replaceChild(script, parent);
    }

    ngAfterViewInit() {
        this.convertToScript();
    }
}
</code>```

usage (inline):

```<code><script-hack>alert('hoi');</script-hack>
</code>```

usage (external):

```<code><script-hack src="//platform.twitter.com/widgets.js" type="text/javascript"></script-hack>
</code>```

Title: Need to insert Script tag in angular 2

Body:
Having scripts in your views is usually a bad practice. If you insist on doing this you can use this component:

scripthack.component.html:

<div #script style.display="none">
  <ng-content></ng-content>
</div>

scripthack.component.ts:

import { Component, ElementRef, ViewChild, Input } from '@angular/core';

@Component({
    selector: 'script-hack',
    templateUrl: './scripthack.component.html'
})
export class ScriptHackComponent {

    @Input()
    src: string;

    @Input()
    type: string;

    @ViewChild('script') script: ElementRef;

    convertToScript() {
        var element = this.script.nativeElement;
        var script = document.createElement("script");
        script.type = this.type ? this.type : "text/javascript";
        if (this.src) {
            script.src = this.src;
        }
        if (element.innerHTML) {
            script.innerHTML = element.innerHTML;
        }
        var parent = element.parentElement;
        parent.parentElement.replaceChild(script, parent);
    }

    ngAfterViewInit() {
        this.convertToScript();
    }
}

usage (inline):

<script-hack>alert('hoi');</script-hack>

usage (external):

<script-hack src="//platform.twitter.com/widgets.js" type="text/javascript"></script-hack>


问:
Why would you set `null: false, default: ""` on a required DB column?
I'm building a Rails app with Devise for authentication, and its default DB migration sets the following columns:

```<code>## Database authenticatable
t.string :email,              null: false, default: ""
t.string :encrypted_password, null: false, default: ""
</code>```

What is the purpose of setting null: false and default: "" at the same time?

My understanding is that null: false effectively makes a value required: i.e., trying to save a record with a NULL value in that column will fail on the database level, without depending any validations on the model.

But then default: "" basically undoes that by simply converting NULL values to empty strings before saving.

I understand that for an optional column, you want to reject NULL values just to make sure that all data within that column is of the same type. However, in this case, email and password are decidedly not optional attributes on a user authentication model. I'm sure there are validations in the model to make sure you can't create a user with an empty email address, but why would you set default: "" here in the first place? Does it serve some benefit or prevent some edge case that I haven't considered?

答:
There is a difference in the insertion type. For example, let say you have a new_table table such that:

```<code>CREATE TABLE IF NOT EXISTS `new_table` (
  `col1` VARCHAR(10) NOT NULL,
  `col2` VARCHAR(10) NOT NULL DEFAULT '',
  `col3` VARCHAR(10) NULL DEFAULT '');
</code>```

When you use explicit insert of NULL you'll get the NULL:

```<code>INSERT INTO new_table(col1,col2,col3) VALUES('a','b',NULL);
</code>```

```<code>'a','b',NULL
</code>```

for col2 same trick will result in error:

```<code>INSERT INTO new_table(col1,col2,col3) VALUES('a',NULL,'c');
</code>```

But when you use implicit insert of NULL you'll get the default value:

```<code>INSERT INTO new_table(col1,col2) VALUES('a','b');
</code>```

```<code>'a','b',''
</code>```

meaning that setting a default value is not preventing NULL assertion to this column, but only used when the value is not explicitly given.

Body:
I'm building a Rails app with Devise for authentication, and its default DB migration sets the following columns:

## Database authenticatable
t.string :email,              null: false, default: ""
t.string :encrypted_password, null: false, default: ""

What is the purpose of setting null: false and default: "" at the same time?

My understanding is that null: false effectively makes a value required: i.e., trying to save a record with a NULL value in that column will fail on the database level, without depending any validations on the model.

But then default: "" basically undoes that by simply converting NULL values to empty strings before saving.

I understand that for an optional column, you want to reject NULL values just to make sure that all data within that column is of the same type. However, in this case, email and password are decidedly not optional attributes on a user authentication model. I'm sure there are validations in the model to make sure you can't create a user with an empty email address, but why would you set default: "" here in the first place? Does it serve some benefit or prevent some edge case that I haven't considered?

Body:
There is a difference in the insertion type. For example, let say you have a new_table table such that:

CREATE TABLE IF NOT EXISTS `new_table` (
  `col1` VARCHAR(10) NOT NULL,
  `col2` VARCHAR(10) NOT NULL DEFAULT '',
  `col3` VARCHAR(10) NULL DEFAULT '');

When you use explicit insert of NULL you'll get the NULL:

INSERT INTO new_table(col1,col2,col3) VALUES('a','b',NULL);

'a','b',NULL

for col2 same trick will result in error:

INSERT INTO new_table(col1,col2,col3) VALUES('a',NULL,'c');

But when you use implicit insert of NULL you'll get the default value:

INSERT INTO new_table(col1,col2) VALUES('a','b');

'a','b',''

meaning that setting a default value is not preventing NULL assertion to this column, but only used when the value is not explicitly given.


问:
How to do https communication by using boost::asio::ssl on Mac OS 10.12
I am trying to call a REST API via HTTPS by using boost::asio::ssl in my Xcode Project. I couldn't find a way to link against OpenSSL in Xcode. Possibly I am not compiling OpenSSL properly. Can you give me hints on:

How to install and link against OpenSSL (version?) in Xcode (8.3.2) on Mac OS X (10.12.3)?

How to add library in my Xcode project means in source tree (openssl lib or path?) and its header search path?

答:
How install openssl library on Mac OS 10.12 and link in Xcdoe 8.3.2 for boost https connection ...steps are
1.Download openssl-1.0.2k from curl --remote-name https://www.openssl.org/source/openssl-1.0.2k.tar.gz into /usr/local/src folder ,please create src if not there.
2.Extract the archive and move into the folder.
tar -xzvf penssl-1.0.2k.tar.gz
cd penssl-1.0.2k
3.On terminal go sudo ./Configure darwin64-x86_64-cc
4.sudo make
5.sudo make test
6.sudo make install
7.export PATH="/usr/local/ssl/bin:$PATH"
8./usr/local/ssl/bin/openssl version
You will get OpenSSL 1.0.2k  26 Jan 2017
Now add /usr/local/ssl/lib in your xcode project setting Library Search Path and /usr/local/ssl/include in Header search path .
And finally add libssl.a and libcrypto.a in to xcode project from /usr/local/ssl/lib folder. Thats it.
Thanks & Regards
Qamar</p>


问:
Defining a duplicate row by the first 20 characters of a cell
I am running a basic de-duplication script for a Google spreadsheet and have hit  roadblock. I want to base whether or not a row is a duplicate on only the first 20 characters in the columns I have defined, not the entire contents of the column.

I ran multiple searches and haven't found anything even close. I keep coming up with ways to remove the first X characters, but that doesn't do me any good.

Any help is greatly appreciated.

function removeDuplicates() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var newData = new Array();
  for(i in data){
    var row = data[i];
    var duplicate = false;
    for(j in newData){
      if(row[0] == newData[j][0] && row[4] == newData[j][4]){
  duplicate = true;
}
    }
    if(!duplicate){
      newData.push(row);
    }
  }
  sheet.clearContents();
  sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}```

答:
First, you want an array with the first 20 characters of all the values in the specified column

```<code>var columnNumber = 2
var values = data.map(function(el){
    return /^.{0,20}/.exec(el[columnNumber + 1]).toString()
})
</code>```

Then, you want to go through the array and see if there is a duplicate

```<code>for (var row = 1; row < values.length; row++){
    var dupIndex = values.indexOf(values[row],row + 1)
    if (~dupIndex)
    {
        Browser.msgBox("Row " + (row + 1) + " and Row " + (dupIndex + 1) + " are identical")
        // Act on the duplicate rows here
    }
}
</code>```

I hope this at least gives a good starting point, good luck!

Body:
First, you want an array with the first 20 characters of all the values in the specified column

var columnNumber = 2
var values = data.map(function(el){
    return /^.{0,20}/.exec(el[columnNumber + 1]).toString()
})

Then, you want to go through the array and see if there is a duplicate

for (var row = 1; row < values.length; row++){
    var dupIndex = values.indexOf(values[row],row + 1)
    if (~dupIndex)
    {
        Browser.msgBox("Row " + (row + 1) + " and Row " + (dupIndex + 1) + " are identical")
        // Act on the duplicate rows here
    }
}

I hope this at least gives a good starting point, good luck!


问:
Get Specific class with Jquery/ JavaScript
I have got a div containing some html elements. They all have a class named

class="fileItem read write".

But there could be an Element with

class="fileItem read write selected".

Now I want to get this element with the additional 'selected' tag and edit this. Currently I have an in JQuery

```<code>$(".fileItem").click(function(){
    // Code
});
</code>```

which detect an click on one of these fileItems.

Here I want to edit style tag of the element with 'selected' tag. So is there something where I can say get all by class and select the on with "selected"?

答:
As far as I know you should be able to combine the two classnames:</p>

```<code>$(".fileItem.selected").click(function() {
//your actions
});
</code>```

Body:
I have got a div containing some html elements. They all have a class named

class="fileItem read write".

But there could be an Element with

class="fileItem read write selected".

Now I want to get this element with the additional 'selected' tag and edit this. Currently I have an in JQuery

$(".fileItem").click(function(){
    // Code
});

which detect an click on one of these fileItems.

Here I want to edit style tag of the element with 'selected' tag. So is there something where I can say get all by class and select the on with "selected"?

Body:
As far as I know you should be able to combine the two classnames:

$(".fileItem.selected").click(function() {
//your actions
});


问:
MongoDB C# - How can I update elements in an array
Let's assume this structure

```<code>class A
{
  string Id;
  int value
  ...
}
</code>```

and

```<code>class B
{
    int sum;
    List<A> L;
    some stuff
}
</code>```

I have a Mongo table with objects B

What I need to do is the following, in pseudo code:

```<code>if (any A item of B has Id == XXX)
{
  if (A.value > X)
  {
    B.Sum += A.Value;
    A.Value = 0;
  }
}
</code>```

in one (atomic) operation.

The B.sum += A.Value and the A.Value = 0 need to be atomic.

I have absolutely no clue on how to implement that.

Has anyone done something similar with MongoDB before?

答:
As you probability know Mongo does not have transaction.
But in your case I think it is easy to work around if you use a noSql approach. All you need to so is have a single table of B object where the A objects are included inside the array:

a B object
    { sum: 0, listA: [ {id: A1, value: 1}, {id: A2, value:2 }], some stuff }

Then you query for A object do:
   db.B.find({"listA.id":"XXX"})

You do calculations on B object and then you only need to update one B record - and that is atomic

This is better explained here How to work around the lack of transactions in MongoDB?.

Body:
Let's assume this structure

class A
{
  string Id;
  int value
  ...
}

and

class B
{
    int sum;
    List L;
    some stuff
}

I have a Mongo table with objects B

What I need to do is the following, in pseudo code:

if (any A item of B has Id == XXX)
{
  if (A.value > X)
  {
    B.Sum += A.Value;
    A.Value = 0;
  }
}

in one (atomic) operation.

The B.sum += A.Value and the A.Value = 0 need to be atomic.

I have absolutely no clue on how to implement that.

Has anyone done something similar with MongoDB before?


问:
Tab bar is also moving when i scroll the table view
I have written the code programmatically  for my tab bar in my table view.The problem whenever i am scrolling the table view,the tab bar is also moving.The tab bar created in one cell,so it is also scrolling.How to keep that in static.Please help me in this.
Thanks in advance</p>

答:
If you're creating the tab bar as one of the cells, this will always happen. (It's the expected behaviour for the table cell.)

Why on earth are you using this approach, rather than simply putting the tab bar above or below the UITableView?

ContentLicense: CC BY-SA 2.5


问:
Where/how do you store application secrets(password, API KEY) in Spring Boot application
I want to encrypt sensitive data in application properties. I will use AES algorithm to encrypt/decrypt data. The key to decrypt will be stored in ENV variables, accessing this key requires the same privileges as modifying production application.

What do you think about this approach?

How do you protect sensitive data?

答:
There are many ways:

Spring Cloud Config

Spring Cloud Config Vault

Not store them at all and provide them via environment variables/files/whatever at run time

I'm sure there are other ways

This is really too broad of a topic for Stackoverflow and is not really specific to Spring Boot or anything in particular.


问:
Wildcard not expanded in recursive cp using execvp()
Though there are multiple files under path "/home/abhijit/Documents/LINUX/editor/" , but I am not getting desired output in "temp" (which should copied all files from editor folder) folder instead output is coming error as : "cp: cannot stat ‘/home/abhijit/Documents/LINUX/editor/*’: No such file or directory".

```<code>#include <stdio.h>
#include <unistd.h>

int main( void )
{
    char* argv1[10] = { "cp", "-rf", "/home/abhijit/Documents/LINUX/editor/*", "/home/abhijit/Documents/LINUX/temp", 0 };
    execvp( argv1[0], argv1 );
}
</code>```

But if i say as below , it works fine.

```<code> char* argv1[MAX_ARGS] = { "cp", "-rf", "/home/abhijit/Documents/LINUX/editor/", "/home/abhijit/Documents/LINUX/temp", 0 };
</code>```

答:
The asterisk pattern * is expanded by the shell and not by the cp command itself.

You could make it work if you run the cp command through a shell, either by invoking a shell with the -c option through exec or by using the system function instead of exec.

Body:
Though there are multiple files under path "/home/abhijit/Documents/LINUX/editor/" , but I am not getting desired output in "temp" (which should copied all files from editor folder) folder instead output is coming error as : "cp: cannot stat ‘/home/abhijit/Documents/LINUX/editor/*’: No such file or directory".

#include <stdio.h>
#include <unistd.h>

int main( void )
{
    char* argv1[10] = { "cp", "-rf", "/home/abhijit/Documents/LINUX/editor/*", "/home/abhijit/Documents/LINUX/temp", 0 };
    execvp( argv1[0], argv1 );
}

But if i say as below , it works fine.

 char* argv1[MAX_ARGS] = { "cp", "-rf", "/home/abhijit/Documents/LINUX/editor/", "/home/abhijit/Documents/LINUX/temp", 0 };


问:
Laravel 5 - Use 'isAdmin' role check method when querying a model
I have implemented a basic role system that uses a table 'role_user'.

On my user model I have a few methods that check the roles, one of them is:

```<code>public function isStaff()
{
    foreach ($this->roles()->get() as $role)
    {
        if ($role->id == 3)
        {
            return true;
        }
    }

    return false;
}
</code>```

How can I use this method when I am querying users?

This query here:

```<code>return User::where('name', 'like', "%".$request->name."%")
    ->orWhere('email', 'like', "%".$request->name."%")
    ->whereDoesntHave('Teams', function ($query) use($teamId) {
        $query->whereId($teamId);
    })
    ->with('teams')
    ->get();
</code>```

Currently returns all users, but I only wish to return users that have a role of 3 (isStaff)

答:
it's better to do condition

```<code>return User::where('name', 'like', "%".$request->name."%")
->orWhere('email', 'like', "%".$request->name."%")
->whereDoesntHave('Teams', function ($query) use($teamId) {
    $query->whereId($teamId);
})
->whereHas('roles', function($q) use ($role_id){
    $q->where('id',$role_id);
})
->with('teams')
->get();
</code>```

or also you can create a method for above query and based on param reurn result

Body:
I have implemented a basic role system that uses a table 'role_user'.

On my user model I have a few methods that check the roles, one of them is:

public function isStaff()
{
    foreach ($this->roles()->get() as $role)
    {
        if ($role->id == 3)
        {
            return true;
        }
    }

    return false;
}

How can I use this method when I am querying users?

This query here:

return User::where('name', 'like', "%".$request->name."%")
    ->orWhere('email', 'like', "%".$request->name."%")
    ->whereDoesntHave('Teams', function ($query) use($teamId) {
        $query->whereId($teamId);
    })
    ->with('teams')
    ->get();

Currently returns all users, but I only wish to return users that have a role of 3 (isStaff)

Body:
it's better to do condition

return User::where('name', 'like', "%".$request->name."%")
->orWhere('email', 'like', "%".$request->name."%")
->whereDoesntHave('Teams', function ($query) use($teamId) {
    $query->whereId($teamId);
})
->whereHas('roles', function($q) use ($role_id){
    $q->where('id',$role_id);
})
->with('teams')
->get();

or also you can create a method for above query and based on param reurn result


问:
Changing the bounds of a UIView once a UIPinchGestureRecognizer is called
I have noticed an issue where I resize a View, but the bounds do not appear to change (so after pinching a view you have to use the edge of a UIView to pinch further)

```<code>@IBAction private func handlePinch(_ sender: UIPinchGestureRecognizer) {
    if let view = sender.view {
        view.transform = view.transform.scaledBy(x: sender.scale, y: sender.scale)
        sender.scale = 1
    }
}
</code>```

I found a likely stackoverflow answer iphone uiview - resize frame to fit subviews that gave an extension to resize to fit subviews, but there is no observable difference in the behavior of the objects.

```<code>@IBAction private func handlePinch(_ sender: UIPinchGestureRecognizer) {
    if let view = sender.view {
        view.transform = view.transform.scaledBy(x: sender.scale, y: sender.scale)
        sender.scale = 1
    }
    self.resizeToFitSubviews()
}

extension UIView {
func resizeToFitSubviews() {
    let subviewsRect = subviews.reduce(CGRect.zero) {
        $0.union($1.frame)
    }
    let fix = subviewsRect.origin
    subviews.forEach {
        $0.frame.offsetBy(dx: -fix.x, dy: -fix.y)
    }
    frame.offsetBy(dx: fix.x, dy: fix.y)
    frame.size = subviewsRect.size
}
</code>```

How can I make the pinch (and ultimately the handleRotate function with the same issue) work to adjust the bounds correctly?

答:
Changing the transform does not change bounds.

Please refer to the answer here:
Does the bounds of a uiview change when a pinch gesture is used on it?

Body:
I have noticed an issue where I resize a View, but the bounds do not appear to change (so after pinching a view you have to use the edge of a UIView to pinch further)

@IBAction private func handlePinch(_ sender: UIPinchGestureRecognizer) {
    if let view = sender.view {
        view.transform = view.transform.scaledBy(x: sender.scale, y: sender.scale)
        sender.scale = 1
    }
}

I found a likely stackoverflow answer iphone uiview - resize frame to fit subviews that gave an extension to resize to fit subviews, but there is no observable difference in the behavior of the objects.

@IBAction private func handlePinch(_ sender: UIPinchGestureRecognizer) {
    if let view = sender.view {
        view.transform = view.transform.scaledBy(x: sender.scale, y: sender.scale)
        sender.scale = 1
    }
    self.resizeToFitSubviews()
}

extension UIView {
func resizeToFitSubviews() {
    let subviewsRect = subviews.reduce(CGRect.zero) {
        $0.union($1.frame)
    }
    let fix = subviewsRect.origin
    subviews.forEach {
        $0.frame.offsetBy(dx: -fix.x, dy: -fix.y)
    }
    frame.offsetBy(dx: fix.x, dy: fix.y)
    frame.size = subviewsRect.size
}

How can I make the pinch (and ultimately the handleRotate function with the same issue) work to adjust the bounds correctly?


问:
Angular-cli showing error when importing rxjs
I get this error in angular-cli when I import rxjs, and do not know what is the source of the problem.

angular-cli error

The path which I wrote is correct, double checked. I am new to the Angular, so feeling stuck.
Here is the source code link https://github.com/EgomortIncognitus/bookstore

books.service.ts:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator.map';

@Injectable()
export class BooksService {

  constructor(private http: Http) { }

  getAllBooks() {
    return this.http.get('data/books.json').map(res => res.json());
  }
}```

答: I believe it should be import 'rxjs/add/operator/map'; not import 'rxjs/add/operator.map';


问:
Why does: string st = "" + 12; work in c# without conversion?
This is super dumb, but I've googled and checked references and I just cannot find an answer... Why can an int or float etc be added as part of a string without converstion but not on it's own? that is:

while this work fine:

```<code> string st = "" + 12;
</code>```

this doesn't (of course):

```<code> string st = 12;
</code>```

Where is the magic here? I know it works I just want to know WHY it works and how I control HOW the conversion is done?

答:
String concats in .NET ultimately resolve to calls to one of the overloads of the static  String.Concat methods. This is an optimization to reduce the number of temporary strings that would otherwise be created when mutliple concatenations occur in a single statement.

In short the reason this works is because a number of the String.Concat overloads will accept object in the argument list and since an int, float etc. are in essence objects they can be passed to the Concat overload that accepts one or more object parameters. Internally Concat of basically does a .ToString() on the incomming object therefore turning your int into it's string representation.

In your specific example

```<code>string st = "" + 12;
</code>```

The compiler will reconize that the first string is empty and simply call the String.Concat(object) overload. Which will convert the integer 12 to a string and assign it to st.

This overload is called because the integer can be implicitly boxed to fit into the object type and therefore satisfy the method overload selection.

Body:
This is super dumb, but I've googled and checked references and I just cannot find an answer... Why can an int or float etc be added as part of a string without converstion but not on it's own? that is:

while this work fine:

 string st = "" + 12;

this doesn't (of course):

 string st = 12;

Where is the magic here? I know it works I just want to know WHY it works and how I control HOW the conversion is done?

Body:
String concats in .NET ultimately resolve to calls to one of the overloads of the static  String.Concat methods. This is an optimization to reduce the number of temporary strings that would otherwise be created when mutliple concatenations occur in a single statement.

In short the reason this works is because a number of the String.Concat overloads will accept object in the argument list and since an int, float etc. are in essence objects they can be passed to the Concat overload that accepts one or more object parameters. Internally Concat of basically does a .ToString() on the incomming object therefore turning your int into it's string representation.

In your specific example

string st = "" + 12;

The compiler will reconize that the first string is empty and simply call the String.Concat(object) overload. Which will convert the integer 12 to a string and assign it to st.

This overload is called because the integer can be implicitly boxed to fit into the object type and therefore satisfy the method overload selection.


问:
Drop down List from Viewbag not following selected property
I have a dropdownList that will be populated by a viewbag carrying a List values containing "Text" and "Value" property that is set by a loop.

```<code>      List<SelectListItem> year = new List<SelectListItem>();

        for (var i = 1990; i <= DateTime.Now.Year; i++)
        {
            year.Add(new SelectListItem
            {
                Text = i.ToString(),
                Value = i.ToString()
            });
        }

       ViewBag.Year = year;
</code>```

And in my view:

```<code>@Html.DropDownListFor(model => model.Year, new SelectList(ViewBag.Year, "Value", "Text", Model.Birthday.Year), htmlAttributes: new { @class = "form-control", style = "width: 80px" })
</code>```

Nothing happens.

答:
Try

```<code>@Html.DropDownListFor(model => model.Year, new SelectList(@ViewBag.Year, "Value", "Text", Model.Birthday.Year), new { @class = "form-control", style = "width: 80px" })
</code>```

It will work as expected.

Body:
I have a dropdownList that will be populated by a viewbag carrying a List values containing "Text" and "Value" property that is set by a loop.

      List<SelectListItem> year = new List<SelectListItem>();

        for (var i = 1990; i <= DateTime.Now.Year; i++)
        {
            year.Add(new SelectListItem
            {
                Text = i.ToString(),
                Value = i.ToString()
            });
        }

       ViewBag.Year = year;

And in my view:

@Html.DropDownListFor(model => model.Year, new SelectList(ViewBag.Year, "Value", "Text", Model.Birthday.Year), htmlAttributes: new { @class = "form-control", style = "width: 80px" })

Nothing happens.

Body:
Try

@Html.DropDownListFor(model => model.Year, new SelectList(@ViewBag.Year, "Value", "Text", Model.Birthday.Year), new { @class = "form-control", style = "width: 80px" })

It will work as expected.


问:
I want to set actionbar color and title in a fragment class which is in tablayout
This is my tabhost Activity and i want to set each fragment title at actionbar.My tabs are at bottom in xml and i want each tab title at top in actionbar.Can we write code in this tabhostActivity?Or can write any code in each fragment.Can anyone suggest any option for this?</p>

```<code>public class TabHostActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
        R.drawable.hm_icon,
        R.drawable.a_icon,
        R.drawable.user_icon_white,
        R.drawable.gear,
        R.drawable.mail_icon_white
};
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tabs);

    toolbar = (Toolbar) findViewById(R.id.toolbar);

   /* setSupportActionBar(toolbar);*/
    /*getSupportActionBar().setDisplayHomeAsUpEnabled(true);*/

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();

    permissionCheck = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_CONTACTS);

    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CONTACTS}, REQUEST_READ_PHONE_STATE);

    }
}
private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
    tabLayout.getTabAt(3).setIcon(tabIcons[3]);
    tabLayout.getTabAt(4).setIcon(tabIcons[4]);

}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new HomeMain(), "");
    adapter.addFrag(new ChooseDefault(), "");
    adapter.addFrag(new MyAccountActivity(), "");
    adapter.addFrag(new UtitlityFragment(), "");
    adapter.addFrag(new SMSFragment(), "");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
</code>```

答:
You can try something like this to get your desired outcome.</p>

```<code>YourTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int pos = tab.getPosition();
        String title = YourFragmentTitle.get(pos);
        YourActionBarObject.setTitle(title);
    }
}
</code>```

Body:
This is my tabhost Activity and i want to set each fragment title at actionbar.My tabs are at bottom in xml and i want each tab title at top in actionbar.Can we write code in this tabhostActivity?Or can write any code in each fragment.Can anyone suggest any option for this?

public class TabHostActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
        R.drawable.hm_icon,
        R.drawable.a_icon,
        R.drawable.user_icon_white,
        R.drawable.gear,
        R.drawable.mail_icon_white
};
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tabs);

    toolbar = (Toolbar) findViewById(R.id.toolbar);

   /* setSupportActionBar(toolbar);*/
    /*getSupportActionBar().setDisplayHomeAsUpEnabled(true);*/

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();

    permissionCheck = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_CONTACTS);

    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CONTACTS}, REQUEST_READ_PHONE_STATE);

    }
}
private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
    tabLayout.getTabAt(3).setIcon(tabIcons[3]);
    tabLayout.getTabAt(4).setIcon(tabIcons[4]);

}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new HomeMain(), "");
    adapter.addFrag(new ChooseDefault(), "");
    adapter.addFrag(new MyAccountActivity(), "");
    adapter.addFrag(new UtitlityFragment(), "");
    adapter.addFrag(new SMSFragment(), "");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

Body:
You can try something like this to get your desired outcome.

YourTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int pos = tab.getPosition();
        String title = YourFragmentTitle.get(pos);
        YourActionBarObject.setTitle(title);
    }
}


问:
Flip barplot axes
How can I to turn vertically the names "fast" and "slow" through 'barplot()' ?

```<code>barplot(table(mode))
</code>```

Title: Flip barplot axes

Body:
How can I to turn vertically the names "fast" and "slow" through 'barplot()' ?

barplot(table(mode))

Body:
Just write :

barplot(table(x), las = 2)

where x is your vector of data :

x <- c("1.3.43.33", "2.2.43.33", "1.3.43.33", "66.3.43.33")


问:
Does Android really exist on other platforms than ARM?
I want to port an aplication written in C++ to android. Converting the application from C++ to Java will take a lot of work that I would prefer to use on making the application better for that platform instead of fixing convertion bugs and solving refactoring problems.

The NDK seems a good route to take but actually I don't want to miss a platform(if it is a considerable % of the market) just because the NDK doesn't or won't support it.

Android claims to support MIPS, ARM, X86 and others ... but actually all the implementations I have seen are only on ARM (or arm compatible).
I checked that on this site:
http://www.pdadb.net/

Would it be a bad desision to use the NDK?

Are there any non ARM devices that run or will run Android?

Where can I find more information about this?

Thanks in advance!

答:
At this point the problem is not that you would not lose market share due to CPU architecture, as there are very few non-ARM Android devices at the moment, the problem is that you may lose market share due to requiring users to run Android 2.3 or later, which you would have to use in order to create a fully native application with access to the window, sensor, and input subsystems.

Avoiding rewriting code is a good goal but you would likely have to rewrite portions of the code anyway due to Android's dissimilar Window and life-cycle APIs. Now you would have to rewrite some important parts of the code in C++ rather than in Java.

You could try a hybrid approach where you write most of the UI in Java, then make calls to your existing C++ code.

Are you making a game? Then you'll probably want to deal with these issues and press on with the NDK. If not, try implementing as much of the program as possible in Java and use the NDK for the complex, tested parts of your code that need to be fast.


答:
add the "las" parameter to change the orientation of the labels</p>

```<code>barplot(table(mode), las=2)
</code>```

Title: Flip barplot axes

Body:
add the "las" parameter to change the orientation of the labels

barplot(table(mode), las=2)


答:
You need to create a style function to handle such cases.

So make your style function:

```<code> var styleFunction = function(feature) {
       console.log(feature);
     //now you can use any property of your feature to identify the different colors
     //I am using the ID property of your data just to demonstrate
      var color;
      if (feature.get("ID")==1){
      color = "red";
      } else if (feature.get("ID")==2){
      color = "green";
      } else {
     color = "black";
      }

      var retStyle =   new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: color,
            width: 5
          })
        });
       return retStyle;

      };
</code>```

And then assign this function to the style of your vector layer

```<code>var vector = new ol.layer.Vector({
            source: new ol.source.Vector({
                format: new ol.format.GeoJSON(),
                url: 'http://localhost/joggo_wp/percorsi.geojson'
            }),
            style: styleFunction
        });
</code>```

here is a fiddle

Title: Different colors for each feature of a collection of features

Body:
I've uploaded a geojson file in my map with openlayers 3. The geojson file is a FeatureCollection with 5 features of type LineString.
How can I color each feature differently to distinguish my paths?
If I add the color to the style of the geojson file this is not read and if I add color to stroke, all the features are colored in a single color.

Below I add the code.

Thanks.

var vector = new ol.layer.Vector({
            source: new ol.source.Vector({
                format: new ol.format.GeoJSON(),
                url: 'http://localhost/joggo_wp/percorsi.geojson'
            }),
            style: new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: "#ff000",
                    width: 2.5,
                })
            }),
        });

FILE GEOJSON:

{

"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4326" } },
"features": [
{ "type": "Feature", "properties": { "ID": 1.0, "LUNGH_M": 1970.0, "NOME": "Percorso 1", "PARTENZA": "Via del Poggio Imperiale 4", "ARRIVO": "Via di S. Leonardo 59n", "LUNGHEZZA": "1,97 km" }, "style": { "color": "#ff0000" }, "geometry": { "type": "LineString", "coordinates": [ [ 11.24203700040032, 43.759969754752376 ], [ 11.247204649917521, 43.750208064502473 ], [ 11.247446659153409, 43.750240561464494 ], [ 11.247746238597509, 43.750179530458503 ], [ 11.247960306028226, 43.750118937742307 ], [ 11.248108264989046, 43.749966781403657 ], [ 11.248240378523741, 43.749814084940027 ], [ 11.248897533371567, 43.75006527742493 ], [ 11.249140299088037, 43.750277668555015 ], [ 11.250198620263028, 43.751078552926899 ], [ 11.250259518649738, 43.751623211022611 ], [ 11.250562891152564, 43.751940055106814 ], [ 11.250844806161599, 43.752116454510677 ], [ 11.250976903611187, 43.752184285854881 ], [ 11.251025276742347, 43.752394633135999 ], [ 11.251095944135562, 43.752551715399683 ], [ 11.252075754111447, 43.753064192693351 ], [ 11.252260569522404, 43.753162663730734 ], [ 11.252298216347477, 43.753302788154329 ], [ 11.252042422884459, 43.753607171300693 ], [ 11.252089750740879, 43.754005360713535 ], [ 11.252046702595303, 43.754152945071198 ], [ 11.251940462780629, 43.754342861090443 ], [ 11.251887408111035, 43.754762904036816 ] ] } },
.........

Body:
You need to create a style function to handle such cases.

So make your style function:

 var styleFunction = function(feature) {
       console.log(feature);
     //now you can use any property of your feature to identify the different colors
     //I am using the ID property of your data just to demonstrate
      var color;
      if (feature.get("ID")==1){
      color = "red";
      } else if (feature.get("ID")==2){
      color = "green";
      } else {
     color = "black";
      }

      var retStyle =   new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: color,
            width: 5
          })
        });
       return retStyle;

      };

And then assign this function to the style of your vector layer

var vector = new ol.layer.Vector({
            source: new ol.source.Vector({
                format: new ol.format.GeoJSON(),
                url: 'http://localhost/joggo_wp/percorsi.geojson'
            }),
            style: styleFunction
        });

here is a fiddle


问:
Django-datatable-view X-editable internal server error
I have been struggling with this one for a couple of days now.
I would like to use django-datatable-view's xeditable columns integration. My code loads the datatable correctly (see here) but whenever I specify the columns to make_xeditable, I get an 500 Internal Server error. I have looked at the few pages (Can't post links due to not enough rep...)  that discuss django-datatable-view but none of them discuss the x-editable option.

Using the snippets from the live demo online (here) (version 0.7) just doesn't do anything. The table loads but the column isn't editable.

```<code>class PriceListDataTableView(XEditableDatatableView):
    model = PriceList
    datatable_options = {
        'columns': [
            'id',
            'date',
            'product',
            'unit',
            ("Price", 'price', helpers.make_xeditable),
        ]
}
</code>```

I got the latest version (0.9) running on my localhost, and their example works! But I can't get it to work in my own app. Both setups run django 1.8

Here is my model:

```<code>class PriceList(models.Model):

    # Fields
    date =    models.DateField(verbose_name="Price list date")
    product = models.CharField(verbose_name="Product name", max_length=100)
    unit =    models.CharField(verbose_name="Unit", max_length=6)
    price =   models.DecimalField(verbose_name="Price", decimal_places=2,
              max_digits=10)
</code>```

Here is my template:

```<code>{% extends "agrichem/base.html" %}
{% block content %}

<script>
$(document).ready(function() {
    <!-- Initialization for x-editable tables -->
    $.fn.editable.defaults.mode = 'inline';
    $(function(){
        var xeditable_options = {};
        datatableview.initialize($('.datatable'), {
               fnRowCallback: datatableview.make_xeditable(xeditable_options),
        });

    });
});
</script>

{{ datatable }}

{% endblock %}
</code>```

Here is my view:

```<code>class PriceListDataTableView(XEditableDatatableView):
    model = PriceList

    class datatable_class(Datatable):
        class Meta:
            columns = ['id', 'date', 'product', 'unit', 'price']
            processors = {
                'price': helpers.make_xeditable,

            }
</code>```

If I remove the processors block, my table loads, but not editable. With it in, I get a pop-up that says:

DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see datatables.net/tn/7

This pop-up error is sent whenever the server doesn't return a 2xx code, so it basically happens because of the following bit:

In the console I get a 500 Internal Server error(sabotaged coz of link count):

jquery.min.js:4 GET ht__tp://127.0.0.1:8000/pricelist/?draw=1&columns%5B0%5D%5Bdata%5D=0&columns%art=0&length=25&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1497779941842 500 (INTERNAL SERVER ERROR)

I am going in circles now, I need some help. Anybody got this working?

Edit:
I have now downgraded django-datatable-view to version 0.8, and used the syntax suggested suggested below, and I get the SAME 500 Internal Server error for this too. I suspect I am missing some essential setup step somewhere, but the documentation, such as it is, doesn't say what.

答:
After much frustration and going in circles I gave up on django-datatable-view. I could not get it to work for inline editing, which was my primary requirement.

I then found django-inplaceedit. It works a charm and is everything I need.

I render my table in the template like so:

```<code>{% extends "site_base.html" %}

{% block more_extra_script %}

    {% load inplace_edit %}
    {% inplace_css 0 %}
    {% inplace_js 1 0 %}

{% endblock more_extra_script %}

{% block content %}

<div class="container-fluid">
    <p><a class="btn btn-default" href="{% url 'pricelist_list' %}">PriceList Listing</a></p>

    <h2>Pricelist for {{ pricelist_date }}</h2>
    <p>Double-click a price to edit it</p>

    <table class="table table-responsive table-striped .table-bordered .table_hover">
      <thead class="info">
          <th>Product</th>
          <th>Unit</th>
          <th>Price</th>
      </thead>
      <tbody>
          {% for prod in products %}
              <tr>
                  <td>{{prod.product}}</td>
                  <td>{{prod.unit}}</td>
                  <td>{% inplace_edit "prod.price" %}</td>
              </tr>
          {% endfor %}
      </tbody>
    </table>

</div>
{% endblock %}
</code>```

The beauty of this app is that it handles all the server-side stuff transparently. You double-click the field, change it, press enter, and the value gets updated in the database.

Body:
I have been struggling with this one for a couple of days now.
I would like to use django-datatable-view's xeditable columns integration. My code loads the datatable correctly (see here) but whenever I specify the columns to make_xeditable, I get an 500 Internal Server error. I have looked at the few pages (Can't post links due to not enough rep...)  that discuss django-datatable-view but none of them discuss the x-editable option.

Using the snippets from the live demo online (here) (version 0.7) just doesn't do anything. The table loads but the column isn't editable.

class PriceListDataTableView(XEditableDatatableView):
    model = PriceList
    datatable_options = {
        'columns': [
            'id',
            'date',
            'product',
            'unit',
            ("Price", 'price', helpers.make_xeditable),
        ]
}

I got the latest version (0.9) running on my localhost, and their example works! But I can't get it to work in my own app. Both setups run django 1.8

Here is my model:

class PriceList(models.Model):

    # Fields
    date =    models.DateField(verbose_name="Price list date")
    product = models.CharField(verbose_name="Product name", max_length=100)
    unit =    models.CharField(verbose_name="Unit", max_length=6)
    price =   models.DecimalField(verbose_name="Price", decimal_places=2,
              max_digits=10)

Here is my template:

{% extends "agrichem/base.html" %}
{% block content %}

{{ datatable }}

{% endblock %}

Here is my view:

class PriceListDataTableView(XEditableDatatableView):
    model = PriceList

    class datatable_class(Datatable):
        class Meta:
            columns = ['id', 'date', 'product', 'unit', 'price']
            processors = {
                'price': helpers.make_xeditable,

            }

If I remove the processors block, my table loads, but not editable. With it in, I get a pop-up that says:

DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see datatables.net/tn/7

This pop-up error is sent whenever the server doesn't return a 2xx code, so it basically happens because of the following bit:

In the console I get a 500 Internal Server error(sabotaged coz of link count):

jquery.min.js:4 GET ht__tp://127.0.0.1:8000/pricelist/?draw=1&columns%5B0%5D%5Bdata%5D=0&columns%art=0&length=25&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1497779941842 500 (INTERNAL SERVER ERROR)

I am going in circles now, I need some help. Anybody got this working?

Edit:
I have now downgraded django-datatable-view to version 0.8, and used the syntax suggested suggested below, and I get the SAME 500 Internal Server error for this too. I suspect I am missing some essential setup step somewhere, but the documentation, such as it is, doesn't say what.

Body:
After much frustration and going in circles I gave up on django-datatable-view. I could not get it to work for inline editing, which was my primary requirement.

I then found django-inplaceedit. It works a charm and is everything I need.

I render my table in the template like so:

{% extends "site_base.html" %}

{% block more_extra_script %}

    {% load inplace_edit %}
    {% inplace_css 0 %}
    {% inplace_js 1 0 %}

{% endblock more_extra_script %}

{% block content %}

<div class="container-fluid">
    <p><a class="btn btn-default" href="{% url 'pricelist_list' %}">PriceList Listing</a></p>

    <h2>Pricelist for {{ pricelist_date }}</h2>
    <p>Double-click a price to edit it</p>

    <table class="table table-responsive table-striped .table-bordered .table_hover">
      <thead class="info">
          <th>Product</th>
          <th>Unit</th>
          <th>Price</th>
      </thead>
      <tbody>
          {% for prod in products %}
              <tr>
                  <td>{{prod.product}}</td>
                  <td>{{prod.unit}}</td>
                  <td>{% inplace_edit "prod.price" %}</td>
              </tr>
          {% endfor %}
      </tbody>
    </table>

</div>
{% endblock %}

The beauty of this app is that it handles all the server-side stuff transparently. You double-click the field, change it, press enter, and the value gets updated in the database.


问:
Get values of 2 columns as single value when separated with '|'
I want to have the values of two columns as a single value but separated with '|' and to also skip the hyphen if values are not present in the particular column.

For example:

The output should be like below,

```<code>1|2
2
1|2
2
1|2
</code>```

答:
To concatenate strings you can use "||". For example:</p>

```<code>SELECT CASE
         WHEN column1 IS NULL THEN column2
         WHEN column2 IS NULL THEN column1
         ELSE column1 || "|" || column2
       END
  FROM someTable
</code>```

Body:
I want to have the values of two columns as a single value but separated with '|' and to also skip the hyphen if values are not present in the particular column.

For example:

The output should be like below,

1|2
2
1|2
2
1|2

Body:
To concatenate strings you can use "||". For example:

SELECT CASE
         WHEN column1 IS NULL THEN column2
         WHEN column2 IS NULL THEN column1
         ELSE column1 || "|" || column2
       END
  FROM someTable


问:
Python's alphabetical sort file error
i'm new to python & here is my question:
Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

This is the file:

But soft what light through yonder window breaks

It is the east and Juliet is the sun

Arise fair sun and kill the envious moon

Who is already sick and pale with grief

Desired Output:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

This is my code:

```<code>fname = raw_input("Enter file name: ")
fh = open(fname)

lst = list()

#loop through the text to get the lines
for line in fh:

    line = line.rstrip()

    #loop through the line to get the words
    for word in line:
        words = line.split()

        #if a word is not in the empty list, append it
        if not word in lst: lst.append(word)

lst.sort()
print lst
</code>```

My output:

[' ', 'A', 'B', 'I', 'J', 'W', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'v', 'w', 'y']

If you could tell me what is wrong (to get only the first letters of the words with a space in the beginning instead of the whole words), it would be great..

Note: I want the code using these instructions, not other advanced instructions (to keep my learning sequence)

Thank you

答:
just small thing you are missing is this line

```<code>for word in line.split():    #split() gives you list of word seprated by space
</code>```

by doing this you are making line => list of words

right now it is list of char(a simple string). try to print word in your example and print word after using line.split() you will get better idea.

Checkout this link > how to use split

Title: Python's alphabetical sort file error

Body:
i'm new to python & here is my question:
Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

This is the file:

But soft what light through yonder window breaks

It is the east and Juliet is the sun

Arise fair sun and kill the envious moon

Who is already sick and pale with grief

Desired Output:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

This is my code:

fname = raw_input("Enter file name: ")
fh = open(fname)

lst = list()

#loop through the text to get the lines
for line in fh:

    line = line.rstrip()

    #loop through the line to get the words
    for word in line:
        words = line.split()

        #if a word is not in the empty list, append it
        if not word in lst: lst.append(word)

lst.sort()
print lst

My output:

[' ', 'A', 'B', 'I', 'J', 'W', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'v', 'w', 'y']

If you could tell me what is wrong (to get only the first letters of the words with a space in the beginning instead of the whole words), it would be great..

Note: I want the code using these instructions, not other advanced instructions (to keep my learning sequence)

Thank you

Body:
just small thing you are missing is this line

for word in line.split():    #split() gives you list of word seprated by space

by doing this you are making line => list of words

right now it is list of char(a simple string). try to print word in your example and print word after using line.split() you will get better idea.

Checkout this link > how to use split


问:
FIPS Compliant Algorithm for Encrypting Passwords using Jasypt in a Property File
My application connects to the database by reading passwords from a property file. Can you suggest a suitable algorithm for encrypting these passwords?

EDIT: I went through a bunch of documents on nist.gov and realized that AES 128 and SHA 256 are compliant. Now, I am considering PBEWITHSHA256AND128BITAES-CBC-BC as the encryption method. Is this method FIPS compliant?

PS: I just want to encrypt the property values, not the whole file.

答:
sha-256 is good enough for this task.

MessageDigest md=MessageDigest.getInstance("SHA-256");
md.update(pass.getBytes());
byte byteData[]=md.digest();
StringBuffer sb=new StringBuffer();
for(int i=0;i<byteData.length;i++)
    sb.append(Integer.toString((byteData[i] & 0xFF) + 0x100, 16).substring(1));
BufferedWriter output=new BufferedWriter(new FileWriter("passwords.txt",true));
output.write(userTF.getText()+" "+sb.toString()+"\n");
output.close();
```


问:
stackoverflow exception was unhandled
In the code below it should multiply 2 numbers. It works for 3 and less than 3 digits numbers but when I give numbers with 4 digits or bigger it gives runtime error: stackoverflow exception was unhandled. I've commented where the problem is. I thought the problem is for defining variables in int and changed them in long but the problem still exists. Where is the mistake?

edited:
now,whats do you think about the problem?it doesnt do anything

```<code>        public long Prod2(long u, long v)
    {
        var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
        int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1),(int)Math.Floor(Math.Log10(v) + 1));
        int threshold = 3;

        if (u == 0 || v == 0)
        {
            return 0;
        }
        else if (n <= threshold)
        {
            return u * v;
        }
        else
        {
            int m = (int)Math.Ceiling(n / 2.0);

            int x = (int)(u / Math.Pow(10, m));
            int y = (int)(u % Math.Pow(10, m));
            int w = (int)(u / Math.Pow(10, m));
            int z = (int)(v % Math.Pow(10, m));

            long r = Prod2(x + y, w + z);
            long p = Prod2(x, w);
            long q = Prod2(y, z);

            return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
            long result = Prod2(numbers[0], numbers[1]);
            textBox1.Text = result.ToString();
        }
    }
</code>```

答:
EDIT: I've completely translated the algorithm described in the book for you:

```<code>public long Prod2(long u, long v)
{
    int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1), (int)Math.Floor(Math.Log10(v) + 1));
    int threshold = 3;

    if(u == 0 || v == 0)
    {
        return 0;
    }
    else if(n <= threshold)
    {
        return u * v;
    }
    else
    {
        int m = (int)Math.Ceiling(n / 2.0);

        int x = (int)(u / Math.Pow(10, m));
        int y = (int)(u % Math.Pow(10, m));
        int w = (int)(u / Math.Pow(10, m));
        int z = (int)(v % Math.Pow(10, m));

        long r = Prod2(x + y, w + z);
        long p = Prod2(x, w);
        long q = Prod2(y, z);

        return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
    }
}
</code>```

To get the right result, you'd call this method from some other method like this:

```<code>void Main()
{

    // Call the method and store the result in variable 'r'.
    long r = Prod2(1234, 5678);
    Console.WriteLine(r);

    /////////////////////////////////
    //
    // OR - In your case read from textBox7 and then store the result in textBox1
    //
    /////////////////////////////////
    var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
    long result = prod2(numbers[0], numbers[1]);
    textBox1.Text = result.ToString();
}
</code>```

So in your event handler, for example for button1, you'd do this to make the call:

```<code>public void button1_Click()
{
    var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
    long result = prod2(numbers[0], numbers[1]);
    textBox1.Text = result.ToString();
}
</code>```

Don't modify the Prod2 that I have, and just paste it with your code. This way, Prod2 does the calculation and then your button1_Click controls the input and what to do with the output.

Title: stackoverflow exception was unhandled

Body:
In the code below it should multiply 2 numbers. It works for 3 and less than 3 digits numbers but when I give numbers with 4 digits or bigger it gives runtime error: stackoverflow exception was unhandled. I've commented where the problem is. I thought the problem is for defining variables in int and changed them in long but the problem still exists. Where is the mistake?

edited:
now,whats do you think about the problem?it doesnt do anything

        public long Prod2(long u, long v)
    {
        var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
        int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1),(int)Math.Floor(Math.Log10(v) + 1));
        int threshold = 3;

        if (u == 0 || v == 0)
        {
            return 0;
        }
        else if (n <= threshold)
        {
            return u * v;
        }
        else
        {
            int m = (int)Math.Ceiling(n / 2.0);

            int x = (int)(u / Math.Pow(10, m));
            int y = (int)(u % Math.Pow(10, m));
            int w = (int)(u / Math.Pow(10, m));
            int z = (int)(v % Math.Pow(10, m));

            long r = Prod2(x + y, w + z);
            long p = Prod2(x, w);
            long q = Prod2(y, z);

            return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
            long result = Prod2(numbers[0], numbers[1]);
            textBox1.Text = result.ToString();
        }
    }

Body:
EDIT: I've completely translated the algorithm described in the book for you:

public long Prod2(long u, long v)
{
    int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1), (int)Math.Floor(Math.Log10(v) + 1));
    int threshold = 3;

    if(u == 0 || v == 0)
    {
        return 0;
    }
    else if(n <= threshold)
    {
        return u * v;
    }
    else
    {
        int m = (int)Math.Ceiling(n / 2.0);

        int x = (int)(u / Math.Pow(10, m));
        int y = (int)(u % Math.Pow(10, m));
        int w = (int)(u / Math.Pow(10, m));
        int z = (int)(v % Math.Pow(10, m));

        long r = Prod2(x + y, w + z);
        long p = Prod2(x, w);
        long q = Prod2(y, z);

        return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
    }
}

To get the right result, you'd call this method from some other method like this:

void Main()
{

    // Call the method and store the result in variable 'r'.
    long r = Prod2(1234, 5678);
    Console.WriteLine(r);

    /////////////////////////////////
    //
    // OR - In your case read from textBox7 and then store the result in textBox1
    //
    /////////////////////////////////
    var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
    long result = prod2(numbers[0], numbers[1]);
    textBox1.Text = result.ToString();
}

So in your event handler, for example for button1, you'd do this to make the call:

public void button1_Click()
{
    var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
    long result = prod2(numbers[0], numbers[1]);
    textBox1.Text = result.ToString();
}

Don't modify the Prod2 that I have, and just paste it with your code. This way, Prod2 does the calculation and then your button1_Click controls the input and what to do with the output.


问:
Access values in boxed nested struct
I am fairly new to Rust and want to implement an AVL-Tree.

I am using the following enum to represent my tree:

```<code>enum AvlTree<T> {
    Leaf,
    Node {
        left: Box<AvlTree<T>>,
        right: Box<AvlTree<T>>,
        value: T
    }
}
</code>```

When implementing one of the balance-functions, I'm facing some problems with ownership and borrowing.

I am trying to write a function, which takes an AvlTree<T> and returns another AvlTree<T>. My first attempt was something like this:

```<code>fn balance_ll(tree: AvlTree<T>) -> AvlTree<T> {
    if let AvlTree::Node {left: t, right: u, value: v} = tree {
        if let AvlTree::Node {left: ref tl, right: ref ul, value: ref vl} = *t {
            AvlTree::Leaf // Return a new AvlTree here
        } else {
            tree
        }
    } else {
        tree
    }
}
</code>```

Even with this minimal example, the compiler is returning an error:

```<code>error[E0382]: use of partially moved value: `tree`
  --> avl.rs:67:17
   |
63 |         if let AvlTree::Node {left: t, right: u, value: v} = tree {
   |                                     - value moved here
...
67 |                 tree
   |                 ^^^^ value used here after move
   |
   = note: move occurs because `(tree:AvlTree::Node).left` has type `std::boxed::Box<AvlTree<T>>`, which does not implement the `Copy` trait
</code>```

I think, I'm understanding the error message correctly, in that destructuring the AvlTree::Node will take away the ownership of the tree example. How can I prevent this from happening? I already tried various things and (de-)referencing the tree-variable only to face more errors.

Additionally, I want to use some of the extracted values like u, tl and vl in the new struct. Is this possible and could you maybe provide a minimal example doing exactly that? I don't need access to the old tree after executing the function.

答:
I think, I'm understanding the error message correctly, in that destructuring the AvlTree::Node will take away the ownership of the tree example.

Yes. If you still need to be able to use tree afterwards, you will either need to make a copy of it:

```<code>#[derive(Clone)]
enum AvlTree<T> {...}

fn balance_ll<T: Clone>(tree: AvlTree<T>) -> AvlTree<T> {
    let copy = tree.clone();

    if let AvlTree::Node { left: t, right: u, value: v } = tree {
        if let AvlTree::Node { left: ref tl, right: ref ul, value: ref vl } = *t {
            AvlTree::Leaf // Return a new AvlTree here
        } else {
            copy
        }
    } else {
        tree
    }
}
</code>```

or use a helper function that quickly releases its ownership - but I don't think it is possible without box patterns:

```<code>#![feature(box_patterns)]

impl<T> AvlTree<T> {
    fn is_left_node(&self) -> bool {
        if let &AvlTree::Node { left: ref t, right: ref u, value: ref v } = self {
            if let &box AvlTree::Node { left: ref tl, right: ref ul, value: ref vl } = t {
                true
            } else {
                false
            }
        } else {
            false
        }
    }
}

fn balance_ll<T>(tree: AvlTree<T>) -> AvlTree<T> {
    if tree.is_left_node() {
        AvlTree::Leaf
    } else {
        tree
    }
}
</code>```

Since you possibly want to use the destructured values you will probably prefer the clone variant, but maybe the other one will give you some extra ideas.

Title: Access values in boxed nested struct

Body:
I am fairly new to Rust and want to implement an AVL-Tree.

I am using the following enum to represent my tree:

enum AvlTree<T> {
    Leaf,
    Node {
        left: Box<AvlTree<T>>,
        right: Box<AvlTree<T>>,
        value: T
    }
}

When implementing one of the balance-functions, I'm facing some problems with ownership and borrowing.

I am trying to write a function, which takes an AvlTree<T> and returns another AvlTree<T>. My first attempt was something like this:

fn balance_ll(tree: AvlTree<T>) -> AvlTree<T> {
    if let AvlTree::Node {left: t, right: u, value: v} = tree {
        if let AvlTree::Node {left: ref tl, right: ref ul, value: ref vl} = *t {
            AvlTree::Leaf // Return a new AvlTree here
        } else {
            tree
        }
    } else {
        tree
    }
}

Even with this minimal example, the compiler is returning an error:

error[E0382]: use of partially moved value: `tree`
  --> avl.rs:67:17
   |
63 |         if let AvlTree::Node {left: t, right: u, value: v} = tree {
   |                                     - value moved here
...
67 |                 tree
   |                 ^^^^ value used here after move
   |
   = note: move occurs because `(tree:AvlTree::Node).left` has type `std::boxed::Box<AvlTree<T>>`, which does not implement the `Copy` trait

I think, I'm understanding the error message correctly, in that destructuring the AvlTree::Node will take away the ownership of the tree example. How can I prevent this from happening? I already tried various things and (de-)referencing the tree-variable only to face more errors.

Additionally, I want to use some of the extracted values like u, tl and vl in the new struct. Is this possible and could you maybe provide a minimal example doing exactly that? I don't need access to the old tree after executing the function.

Body:
I think, I'm understanding the error message correctly, in that destructuring the AvlTree::Node will take away the ownership of the tree example.

Yes. If you still need to be able to use tree afterwards, you will either need to make a copy of it:

#[derive(Clone)]
enum AvlTree<T> {...}

fn balance_ll<T: Clone>(tree: AvlTree<T>) -> AvlTree<T> {
    let copy = tree.clone();

    if let AvlTree::Node { left: t, right: u, value: v } = tree {
        if let AvlTree::Node { left: ref tl, right: ref ul, value: ref vl } = *t {
            AvlTree::Leaf // Return a new AvlTree here
        } else {
            copy
        }
    } else {
        tree
    }
}

or use a helper function that quickly releases its ownership - but I don't think it is possible without box patterns:

#![feature(box_patterns)]

impl<T> AvlTree<T> {
    fn is_left_node(&self) -> bool {
        if let &AvlTree::Node { left: ref t, right: ref u, value: ref v } = self {
            if let &box AvlTree::Node { left: ref tl, right: ref ul, value: ref vl } = t {
                true
            } else {
                false
            }
        } else {
            false
        }
    }
}

fn balance_ll<T>(tree: AvlTree<T>) -> AvlTree<T> {
    if tree.is_left_node() {
        AvlTree::Leaf
    } else {
        tree
    }
}

Since you possibly want to use the destructured values you will probably prefer the clone variant, but maybe the other one will give you some extra ideas.


答:
You can using Scopes With Laravel instead of multiple methods to check for different methods.

```<code>public function scopeRole($query, $flag)
{
        return $query->where('role', $flag);
}
</code>```

and then

```<code>$users= User::role(3)->get();
</code>```

check the reference tutorial for Creating Dynamic Scopes

Title: Laravel 5 - Use 'isAdmin' role check method when querying a model

Body:
I have implemented a basic role system that uses a table 'role_user'.

On my user model I have a few methods that check the roles, one of them is:

public function isStaff()
{
    foreach ($this->roles()->get() as $role)
    {
        if ($role->id == 3)
        {
            return true;
        }
    }

    return false;
}

How can I use this method when I am querying users?

This query here:

return User::where('name', 'like', "%".$request->name."%")
    ->orWhere('email', 'like', "%".$request->name."%")
    ->whereDoesntHave('Teams', function ($query) use($teamId) {
        $query->whereId($teamId);
    })
    ->with('teams')
    ->get();

Currently returns all users, but I only wish to return users that have a role of 3 (isStaff)

Body:
You can using Scopes With Laravel instead of multiple methods to check for different methods.

public function scopeRole($query, $flag)
{
        return $query->where('role', $flag);
}

and then

$users= User::role(3)->get();

check the reference tutorial for Creating Dynamic Scopes


问:
Scala remove characters from String following a sequence
I have written a sample program to convert xml to json. But I want to remove a characters followed by sequence. How to achieve it.

In below example I want to remove "tns:" in the String if it comes after "<" character.

```<code>object example {
def main(args: Array[String]): Unit = {
  val xmldata :String = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tns:createGroup xmlns:tns=\"http://www.emirates.com/schemas/loyalty/customer/group/v1.0/2017/05\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.emirates.com/schemas/loyalty/customer/group/v1.0/2017/05 sample.xsd \">\n  <tns:customerGroup>\n    <tns:groupTypeCode>100</tns:groupTypeCode>\n    <tns:groupTypeDescription>sampleGroup</tns:groupTypeDescription>\n    <tns:groupAccountNumber>100100234</tns:groupAccountNumber>\n    <tns:groupName>sampleName</tns:groupName>\n    <tns:status>open</tns:status>\n    <tns:memberCountThreshold>3</tns:memberCountThreshold>\n    <tns:guestCountThreshold>4</tns:guestCountThreshold>\n    <tns:creatorDetails>\n      <tns:membershipNumber>00800934564</tns:membershipNumber>\n      <tns:mediaCode>400</tns:mediaCode>\n    </tns:creatorDetails>\n    <tns:createdDate>03JUL2017</tns:createdDate>\n    <tns:MilesSummary/>\n  </tns:customerGroup>\n  <tns:error>\n    <tns:errorRecord>noerror</tns:errorRecord>\n  </tns:error>\n</tns:createGroup>\n"
  val loyaltyGroupMessageXML = scala.xml.XML.loadString(xmldata)
  val miles = (loyaltyGroupMessageXML \\ "customerGroup")
  //print(miles)
  val json = toJson(miles)
  //val parsed = parse(json)
  //print(parsed)
  print(pretty(render(json)))
  }
}
</code>```

答:
You can use replace function

```<code>xmldata.replace("<tns:", "<")
</code>```

you can use it in your code as

```<code>val loyaltyGroupMessageXML = scala.xml.XML.loadString(xmldata.replace("<tns:", "<"))
</code>```

You still need to replace the ending </tns: to </. For that you can do

```<code>xmldata.replace("<tns:", "<").replace("</tns:", "</")
</code>```

In your code

```<code>val loyaltyGroupMessageXML = scala.xml.XML.loadString(xmldata.replace("<tns:", "<").replace("</tns:", "</"))
</code>```

Body:
I have written a sample program to convert xml to json. But I want to remove a characters followed by sequence. How to achieve it.

In below example I want to remove "tns:" in the String if it comes after "<" character.

object example {
def main(args: Array[String]): Unit = {
  val xmldata :String = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tns:createGroup xmlns:tns=\"http://www.emirates.com/schemas/loyalty/customer/group/v1.0/2017/05\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.emirates.com/schemas/loyalty/customer/group/v1.0/2017/05 sample.xsd \">\n  <tns:customerGroup>\n    <tns:groupTypeCode>100</tns:groupTypeCode>\n    <tns:groupTypeDescription>sampleGroup</tns:groupTypeDescription>\n    <tns:groupAccountNumber>100100234</tns:groupAccountNumber>\n    <tns:groupName>sampleName</tns:groupName>\n    <tns:status>open</tns:status>\n    <tns:memberCountThreshold>3</tns:memberCountThreshold>\n    <tns:guestCountThreshold>4</tns:guestCountThreshold>\n    <tns:creatorDetails>\n      <tns:membershipNumber>00800934564</tns:membershipNumber>\n      <tns:mediaCode>400</tns:mediaCode>\n    </tns:creatorDetails>\n    <tns:createdDate>03JUL2017</tns:createdDate>\n    <tns:MilesSummary/>\n  </tns:customerGroup>\n  <tns:error>\n    <tns:errorRecord>noerror</tns:errorRecord>\n  </tns:error>\n</tns:createGroup>\n"
  val loyaltyGroupMessageXML = scala.xml.XML.loadString(xmldata)
  val miles = (loyaltyGroupMessageXML \\ "customerGroup")
  //print(miles)
  val json = toJson(miles)
  //val parsed = parse(json)
  //print(parsed)
  print(pretty(render(json)))
  }
}

Body:
You can use replace function

xmldata.replace("<tns:", "<")

you can use it in your code as

val loyaltyGroupMessageXML = scala.xml.XML.loadString(xmldata.replace("<tns:", "<"))

You still need to replace the ending </tns: to </. For that you can do

xmldata.replace("<tns:", "<").replace("</tns:", "</")

In your code

val loyaltyGroupMessageXML = scala.xml.XML.loadString(xmldata.replace("<tns:", "<").replace("</tns:", "</"))


问:
Having problems with background image using Styles
having problem with background image with css on Mac Os.
if we change the resolution of browser it turn to look bad.i need look like same in every resol and also on Mac os.

There is 2 section have bg image

using Mac os

http://i.imgur.com/UmGGBA4.jpg

using window os

https://i.imgur.com/QjXNxag.jpg

I want to look like window os image on MAC.

code

.section-about {
    background: url("http://i.imgur.com/NlczAVu.jpg") top right/cover no-repeat;
    min-height: 545px;
  }

  /* line 180, ../sass/screen.scss */
  .section-experinece {
    background: url("http://i.imgur.com/eAeB5ci.jpg") top right/cover no-repeat;
    min-height: 1130px;
  }

  h1 {
  margin: 0;
  }

  .one {
  color: #fff;
    margin: 0;
  }

  p {
      margin: 0;

  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="about" class="section-about">
    <h1>section1</h1>
                        <p clas="one">Lorem ipsum doeqw sitqwewqe amet, consectetur adipiscing elit. Phasellus porta massa sit amet magna luctus euismod. Maurn malesuada nunc.  <span class="bold">Lorem ipsum dolor sit amet.</span></p>
 <p clas="one">Lorem ipsum doeqw sitqwewqe amet, consectetur adipiscing elit. Phasellus porta massa sit amet magna luctus euismod. Maurn malesuada nunc.  <span class="bold">Lorem ipsum dolor sit amet.</span></p>
</section>

<section id="experinece" class="experinece-sec section-experinece">
    <h1>section2</h1>
             <p>Lorem ipsum doeqw sitqwewqe amet, consectetur adipiscing elit. Phasellus porta massa sit amet magna luctus euismod. Maurn malesuada nunc.  <span class="bold">Lorem ipsum dolor sit amet.</span></p>
                      <p>Lorem ipsum doeqw sitqwewqe amet, consectetur adipiscing elit. Phasellus porta massa sit amet magna luctus euismod. Maurn malesuada nunc.  <span class="bold">Lorem ipsum dolor sit amet.</span></p>
</section></code>```

thanks.

答:
It looks like your problem is not the  OS you are on, but the screen resolution you are viewing on.

Check the page on a windows machine and make the view as wide as you can.

Body:
having problem with background image with css on Mac Os.
if we change the resolution of browser it turn to look bad.i need look like same in every resol and also on Mac os.

There is 2 section have bg image

using Mac os

http://i.imgur.com/UmGGBA4.jpg

using window os

https://i.imgur.com/QjXNxag.jpg

I want to look like window os image on MAC.

code

.section-about {
    background: url("http://i.imgur.com/NlczAVu.jpg") top right/cover no-repeat;
    min-height: 545px;
  }

  /* line 180, ../sass/screen.scss */
  .section-experinece {
    background: url("http://i.imgur.com/eAeB5ci.jpg") top right/cover no-repeat;
    min-height: 1130px;
  }

  h1 {
  margin: 0;
  }

  .one {
  color: #fff;
    margin: 0;
  }

  p {
      margin: 0;

  }

section1

Lorem ipsum doeqw sitqwewqe amet, consectetur adipiscing elit. Phasellus porta massa sit amet magna luctus euismod. Maurn malesuada nunc.  Lorem ipsum dolor sit amet.

Lorem ipsum doeqw sitqwewqe amet, consectetur adipiscing elit. Phasellus porta massa sit amet magna luctus euismod. Maurn malesuada nunc.  Lorem ipsum dolor sit amet.

section2

Lorem ipsum doeqw sitqwewqe amet, consectetur adipiscing elit. Phasellus porta massa sit amet magna luctus euismod. Maurn malesuada nunc.  Lorem ipsum dolor sit amet.

Lorem ipsum doeqw sitqwewqe amet, consectetur adipiscing elit. Phasellus porta massa sit amet magna luctus euismod. Maurn malesuada nunc.  Lorem ipsum dolor sit amet.

thanks.


问:
Git: branching?
I got a local script of which I want to have 2 version. So I went to the directory of the script and did this:

```<code>git init
git add myscript.py
git commit -m "initial"
git checkout -b test_branch
</code>```

After that I opened the script in an editor and wrote "foobar" at the end of the file. Then I went back to console and wrote:

```<code>git checkout master
</code>```

So basically I switched from my test_branch back to master. I opened the script and there was still the "foobar" at the end. I was expecting it not to appear since I wrote it into the file when I was in the test_branch?

答:
After you checkout to test_branch and you do some changes there, then before you checkout your master branch, you first need to commit all the changes made to the test_branch.

So it would be like:

```<code>git init                      #initializing
git add myscript.py           #added a file, ready to commit
git commit -m "initial"       #initial commit made to master

git checkout -b test_branch   #created and checked out a new branch
git add myscript.py           #add a file, ready to commit to test_branch
git commit -m 'other version' #commit the changes made to test_branch
git checkout master           #checkout master again
</code>```

Title: Git: branching?

Body:
I got a local script of which I want to have 2 version. So I went to the directory of the script and did this:

git init
git add myscript.py
git commit -m "initial"
git checkout -b test_branch

After that I opened the script in an editor and wrote "foobar" at the end of the file. Then I went back to console and wrote:

git checkout master

So basically I switched from my test_branch back to master. I opened the script and there was still the "foobar" at the end. I was expecting it not to appear since I wrote it into the file when I was in the test_branch?

Body:
After you checkout to test_branch and you do some changes there, then before you checkout your master branch, you first need to commit all the changes made to the test_branch.

So it would be like:

git init                      #initializing
git add myscript.py           #added a file, ready to commit
git commit -m "initial"       #initial commit made to master

git checkout -b test_branch   #created and checked out a new branch
git add myscript.py           #add a file, ready to commit to test_branch
git commit -m 'other version' #commit the changes made to test_branch
git checkout master           #checkout master again