问:
Stripping HTML from C# program that integrates a website into Jira
I am working on a website that is integrated in Jira. The web page has a "description" section. When I write a description on the web page this looks okay, but when it gets imported into Jira , the ticket has html tags in the description:

```<code>ex: < p > this is the description < p >
</code>```

instead of simply 'this is the description'

Here is the description call in the C# code:

```<code>var ticket = new Ticket()
{
    Id = 0,
    IsActive = true,
    TicketDescription =
        string.IsNullOrEmpty(issue.Description)
            ? string.Empty
            : issue.Description.Replace(Environment.NewLine, "<br />"),
    AssignedToId = assignedToUser.SecurityUserId,
    TicketTypeId = type == 0 ? 1 : type,
};
</code>```

what would I need to add to TicketDescription so the html is always stripped ?

答:
I would create an extension method like this:

```<code>/// Strips all HTML tags from a string
public static string StripHtml(this string html)
{
    if (string.IsNullOrEmpty(html))
        return html;
    return Regex.Replace(html, @"<(.|\n)*?>", " ").Trim();
}
</code>```

You can customize the replace token at your convenience. In this case I simply used a whitespace.

Then just use it in in place of your Replace

Body:
I am working on a website that is integrated in Jira. The web page has a "description" section. When I write a description on the web page this looks okay, but when it gets imported into Jira , the ticket has html tags in the description:

ex:
 this is the description

instead of simply 'this is the description'

Here is the description call in the C# code:

var ticket = new Ticket()
{
    Id = 0,
    IsActive = true,
    TicketDescription =
        string.IsNullOrEmpty(issue.Description)
            ? string.Empty
            : issue.Description.Replace(Environment.NewLine, "
"),
    AssignedToId = assignedToUser.SecurityUserId,
    TicketTypeId = type == 0 ? 1 : type,
};

what would I need to add to TicketDescription so the html is always stripped ?

Body:
I would create an extension method like this:

/// Strips all HTML tags from a string
public static string StripHtml(this string html)
{
    if (string.IsNullOrEmpty(html))
        return html;
    return Regex.Replace(html, @"<(.|\n)*?>", " ").Trim();
}

You can customize the replace token at your convenience. In this case I simply used a whitespace.

Then just use it in in place of your Replace


来源: stackexchange

问:
How to set limit for EditText in Android?
How can I set a limit of number on EditText?

Like maximum number it's 30, from 31 set a Toast?

答:
This is an answer if you want to detect if there's more than 30 characters

First of all I recommend to you to set it on your .xml file as follows :

```<code><EditText
    android:id="@+id/someId"
    android:maxLength="30"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>
</code>```

Then in your onCreate() you have to initialize it do it as follows :

```<code>EditText eText = (EditText)findViewById(R.id.someId);
</code>```

Now you have to add Filters to it as follows:

```<code>eText.setFilters(new InputFilter[] {
    new InputFilter.LengthFilter(30)
});
</code>```

And finally you add a TextWatcher() to deal with it as follows:

```<code>    eText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(count >= 30) Toast.makeText(MainActivity.this, "Max length of EditText is "+ String.valueOf(30), Toast.LENGTH_SHORT).show();

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
</code>```

There's an answer to detect if user tries to put a number higher than n

Your question is quite difficult to understand, but yes, finally I got you, you lucky that I did something similar a year ago...

You first create this inner class called Max30TextWatcher (or whatever name)

```<code>public class Max30TextWatcher implements TextWatcher {

        private EditText et;

        Max30TextWatcher(EditText et) {
            this.et = et;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(TextUtils.isEmpty(editable.toString())){
                return;
            }
            try {
                if (Integer.valueOf(et.getText().toString()) > 30) {
                    Toast.makeText(MainActivity.this, "Max is 30 dawg", Toast.LENGTH_SHORT).show();
                    //put all the TextView ""
                    et.setText("");

                }
            }
            catch(NumberFormatException e){
                //no dots and comma accepted
                et.setText("");
            }
        }
    }
</code>```

So you change the .xml to this :

```<code><EditText
        android:id="@+id/someId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:maxLength="2" />
</code>```

And you call the new class as follows :

```<code>et = (EditText)findViewById(R.id.someId);
et.addTextChangedListener(new Max30TextWatcher(et));
</code>```

And you are done, you cannot put a number higher than 30 :)

Happy coding!

ContentLicense: CC BY-SA 3.0

Body:
This is an answer if you want to detect if there's more than 30 characters

First of all I recommend to you to set it on your .xml file as follows :

<EditText
    android:id="@+id/someId"
    android:maxLength="30"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

Then in your onCreate() you have to initialize it do it as follows :

EditText eText = (EditText)findViewById(R.id.someId);

Now you have to add Filters to it as follows:

eText.setFilters(new InputFilter[] {
    new InputFilter.LengthFilter(30)
});

And finally you add a TextWatcher() to deal with it as follows:

    eText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(count >= 30) Toast.makeText(MainActivity.this, "Max length of EditText is "+ String.valueOf(30), Toast.LENGTH_SHORT).show();

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });

There's an answer to detect if user tries to put a number higher than n

Your question is quite difficult to understand, but yes, finally I got you, you lucky that I did something similar a year ago...

You first create this inner class called Max30TextWatcher (or whatever name)

public class Max30TextWatcher implements TextWatcher {

        private EditText et;

        Max30TextWatcher(EditText et) {
            this.et = et;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(TextUtils.isEmpty(editable.toString())){
                return;
            }
            try {
                if (Integer.valueOf(et.getText().toString()) > 30) {
                    Toast.makeText(MainActivity.this, "Max is 30 dawg", Toast.LENGTH_SHORT).show();
                    //put all the TextView ""
                    et.setText("");

                }
            }
            catch(NumberFormatException e){
                //no dots and comma accepted
                et.setText("");
            }
        }
    }

So you change the .xml to this :

<EditText
        android:id="@+id/someId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:maxLength="2" />

And you call the new class as follows :

et = (EditText)findViewById(R.id.someId);
et.addTextChangedListener(new Max30TextWatcher(et));

And you are done, you cannot put a number higher than 30 :)

Happy coding!


问:
Can not convert correctly formatted CSV to JSON
I am using the Papa Parse module to convert a CSV from my local machine to JSON.

I wrote this code:

```<code> var fs = require('fs');
 var Papa = require('papaparse');
 var filePath = '../myCSVFile.csv';

 Papa.parse(filePath, {
             complete: function(results) {
                 fs.writeFile("./converted.json", JSON.stringify(results), function(err) {
                         if(err) {
                                     return console.log(err);
                          }
                         console.log("finished!");
                 });
             }
 });
</code>```

However, in converted.json, instead of getting the JSON object, I get this message.

```<code> {"data":[["../myCSVFile.csv"]],"errors":[{"type":"Delimiter","code":"UndetectableDelimiter","message":"Unable to auto-detect delimiting character; defaulted to ','"}],"meta":{"delimiter":",",          "linebreak":"\n","aborted":false,"truncated":false,"cursor":19}}
</code>```

I'm pretty sure my SV file is well formatted. Is there something wrong with my code?

答:
The API you're using sees that string you pass in (your file name) as the actual CSV content to be parsed. You have to open the file yourself, read the contents, and pass that instead.

You can tell it's doing that by the value of the "data" property: it's a two-dimensional array containing the file name. It's the only "cell" in the CSV contents you passed it.

Body:
I am using the Papa Parse module to convert a CSV from my local machine to JSON.

I wrote this code:

 var fs = require('fs');
 var Papa = require('papaparse');
 var filePath = '../myCSVFile.csv';

 Papa.parse(filePath, {
             complete: function(results) {
                 fs.writeFile("./converted.json", JSON.stringify(results), function(err) {
                         if(err) {
                                     return console.log(err);
                          }
                         console.log("finished!");
                 });
             }
 });

However, in converted.json, instead of getting the JSON object, I get this message.

 {"data":[["../myCSVFile.csv"]],"errors":[{"type":"Delimiter","code":"UndetectableDelimiter","message":"Unable to auto-detect delimiting character; defaulted to ','"}],"meta":{"delimiter":",",          "linebreak":"\n","aborted":false,"truncated":false,"cursor":19}}

I'm pretty sure my SV file is well formatted. Is there something wrong with my code?


问:
React Component with dynamic Sub-Components
I`m creating a react dynamic dialog where you can add functionality to the Dialog.

One way of doing this was with Composition, but I did not manage to do this via composition.

I`m not very experienced on React, so this was my first approach

I got my Modal component, and the modal has

```<code>export default class KneatModal extends React.Component {
constructor() {
  super();
  this.state = {
     open: false
  }
  this.components = [];
</code>```

I would add components like this

```<code>import CommentField from '../../../Modal/ModalContents/CommentField.jsx'

export default class DoApprove extends React.Component {
constructor() {
  super();
}

componentDidMount() {
 this._buildDialog();
}

_buildDialog() {
  console.log("Building the Dialog");
  this.modal.components.push(CommentField);
}
</code>```

In that modal renderer, i have

 <ModalContent components={ this.components } />

Then i the final renderer in ModalContent i try to render all attached components

```<code> render() {
  var list = this.props.components.map((Component, key) => <Component/> );
  return (
     <div className='modal-contents'>
        {list}
     </div>
 )
</code>```

}

But the render method does not seems to work, i`ve tryed callin Component.render() instead of the component tag, but still could not make the sub-components render. =(

Would apreciate any help. Thanks

答:
To be even more specific, this resumes on what im attempting</p>

```<code>import PropTypes from 'prop-types';
import React from 'react';
import MyComponent1 from './MyComponent1.jsx'
import MyComponent2 from './MyComponent2.jsx'

export default class KneatModalContent extends React.Component {

   constructor() {
      super();
      this.components = [MyComponent1, MyComponent2];
   }

   render() {
     return (
     <div className='modal-contents'>
        {this.components.map(function (component, i) {
           return <{ component } key= { i } />
        })}
     </div>
 )
}

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I`m creating a react dynamic dialog where you can add functionality to the Dialog.

One way of doing this was with Composition, but I did not manage to do this via composition.

I`m not very experienced on React, so this was my first approach

I got my Modal component, and the modal has

export default class KneatModal extends React.Component {
constructor() {
  super();
  this.state = {
     open: false
  }
  this.components = [];

I would add components like this

import CommentField from '../../../Modal/ModalContents/CommentField.jsx'

export default class DoApprove extends React.Component {
constructor() {
  super();
}

componentDidMount() {
 this._buildDialog();
}

_buildDialog() {
  console.log("Building the Dialog");
  this.modal.components.push(CommentField);
}

In that modal renderer, i have

 <ModalContent components={ this.components } />

Then i the final renderer in ModalContent i try to render all attached components

 render() {
  var list = this.props.components.map((Component, key) => <Component/> );
  return (

        {list}

 )

}

But the render method does not seems to work, i`ve tryed callin Component.render() instead of the component tag, but still could not make the sub-components render. =(

Would apreciate any help. Thanks

Body:
To be even more specific, this resumes on what im attempting

import PropTypes from 'prop-types';
import React from 'react';
import MyComponent1 from './MyComponent1.jsx'
import MyComponent2 from './MyComponent2.jsx'

export default class KneatModalContent extends React.Component {

   constructor() {
      super();
      this.components = [MyComponent1, MyComponent2];
   }

   render() {
     return (
     <div className='modal-contents'>
        {this.components.map(function (component, i) {
           return <{ component } key= { i } />
        })}
     </div>
 )
}

}


问:
Android permissions 6.0 and above
I am trying to create my own class of checking request permission for Marshmallow and know that there are normal and dangerous permissions. The very basic feature of the app is to block incoming call.

```<code>public class RequestPermission {

    private String[] modifyPhoneStatePermission = {Manifest.permission.MODIFY_PHONE_STATE};
    private String[] contactsPermission = {Manifest.permission.READ_CONTACTS};
    private String[] phonePermissions = {Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE};

    private Context context;

    public RequestPermission(Context context)
    {
       this.context = context;
    }

public boolean checkModifyPhoneStatePermission() {
    try
    {
        if (ContextCompat.checkSelfPermission(context, modifyPhoneStatePermission[0]) == PackageManager.PERMISSION_GRANTED) {

            return true;

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

     public void askModifyPhoneStatePermission() {
    try
    {
        ActivityCompat.requestPermissions((Activity) context, modifyPhoneStatePermission, REQUEST_CODE_PERMISSION);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}
</code>```

However, when I try this on a separate class, a dialog box does not pop up. Why is this happening? Should I include this on phonePermissions array? What is the participation of MODIFY_PHONE_STATE in blocking calls?

答:
Checkout below Code :

```<code>      private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 10001;

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

                if (platform_version >= 23) {
                    boolean permission = checkAndRequestPermissions();
                    /*if (permission)
                        Toast.makeText(this, "All permissions granted!", Toast.LENGTH_LONG).show();*/
                }

        }

        private boolean checkAndRequestPermissions() {
            int modifyPhoneStatePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_PHONE_STATE);
            int contactsPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
            int phonePermissions = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int permissionReadExternal = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);

            List<String> listPermissionsNeeded = new ArrayList<>();
            if (modifyPhoneStatePermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.MODIFY_PHONE_STATE);
            }
            if (contactsPermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.READ_CONTACTS);
            }
            if (phonePermissions != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
            }
 if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }

            return true;
        }

          @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
            Log.d(PERMISSION_TAG, "Permission callback called...");
            switch (requestCode) {
                case REQUEST_ID_MULTIPLE_PERMISSIONS: {

                    Map<String, Integer> perms = new HashMap<>();
                    // Initialize the map with both permissions

                    perms.put(Manifest.permission.MODIFY_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
                    perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
                    perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);

                    // Fill with actual results from user
                    if (grantResults.length > 0) {
                        for (int i = 0; i < permissions.length; i++)
                            perms.put(permissions[i], grantResults[i]);
                        // Check for both permissions
                        if (perms.get(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED &&
                                perms.get(Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED &&
                                perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                                perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                            Log.d(PERMISSION_TAG, "permission granted");
                            // process the normal flow
                            //else any one or both the permissions are not granted
                        } else {
                            Log.d(PERMISSION_TAG, "Some permissions are not granted ask again ");
                            //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
    //                      //shouldShowRequestPermissionRationale will return true
                            //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
                            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) && ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                showDialogOK("Permission required for this app",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                switch (which) {
                                                    case DialogInterface.BUTTON_POSITIVE:
                                                        checkAndRequestPermissions();
                                                        break;
                                                    case DialogInterface.BUTTON_NEGATIVE:
                                                        // proceed with logic by disabling the related features or quit the app.
                                                        checkAndRequestPermissions();
                                                        break;
                                                }
                                            }
                                        });
                            }
                            //permission is denied (and never ask again is  checked)
                            //shouldShowRequestPermissionRationale will return false
                            else {
                                //proceed with logic by disabling the related features or quit the app.

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

Below code will work in your case , you can use the below check in any method you want or in onCreate()

```<code>   if (platform_version >= 23) {
                boolean permission = checkAndRequestPermissions();
                /*if (permission)
                    Toast.makeText(this, "All permissions granted!", Toast.LENGTH_LONG).show();*/
            }
</code>```

Title: Android permissions 6.0 and above

Body:
I am trying to create my own class of checking request permission for Marshmallow and know that there are normal and dangerous permissions. The very basic feature of the app is to block incoming call.

public class RequestPermission {

    private String[] modifyPhoneStatePermission = {Manifest.permission.MODIFY_PHONE_STATE};
    private String[] contactsPermission = {Manifest.permission.READ_CONTACTS};
    private String[] phonePermissions = {Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE};

    private Context context;

    public RequestPermission(Context context)
    {
       this.context = context;
    }

public boolean checkModifyPhoneStatePermission() {
    try
    {
        if (ContextCompat.checkSelfPermission(context, modifyPhoneStatePermission[0]) == PackageManager.PERMISSION_GRANTED) {

            return true;

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

     public void askModifyPhoneStatePermission() {
    try
    {
        ActivityCompat.requestPermissions((Activity) context, modifyPhoneStatePermission, REQUEST_CODE_PERMISSION);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

However, when I try this on a separate class, a dialog box does not pop up. Why is this happening? Should I include this on phonePermissions array? What is the participation of MODIFY_PHONE_STATE in blocking calls?

Body:
Checkout below Code :

      private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 10001;

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

                if (platform_version >= 23) {
                    boolean permission = checkAndRequestPermissions();
                    /*if (permission)
                        Toast.makeText(this, "All permissions granted!", Toast.LENGTH_LONG).show();*/
                }

        }

        private boolean checkAndRequestPermissions() {
            int modifyPhoneStatePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_PHONE_STATE);
            int contactsPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
            int phonePermissions = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int permissionReadExternal = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);

            List<String> listPermissionsNeeded = new ArrayList<>();
            if (modifyPhoneStatePermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.MODIFY_PHONE_STATE);
            }
            if (contactsPermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.READ_CONTACTS);
            }
            if (phonePermissions != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
            }
 if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }

            return true;
        }

          @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
            Log.d(PERMISSION_TAG, "Permission callback called...");
            switch (requestCode) {
                case REQUEST_ID_MULTIPLE_PERMISSIONS: {

                    Map<String, Integer> perms = new HashMap<>();
                    // Initialize the map with both permissions

                    perms.put(Manifest.permission.MODIFY_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
                    perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
                    perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);

                    // Fill with actual results from user
                    if (grantResults.length > 0) {
                        for (int i = 0; i < permissions.length; i++)
                            perms.put(permissions[i], grantResults[i]);
                        // Check for both permissions
                        if (perms.get(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED &&
                                perms.get(Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED &&
                                perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                                perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                            Log.d(PERMISSION_TAG, "permission granted");
                            // process the normal flow
                            //else any one or both the permissions are not granted
                        } else {
                            Log.d(PERMISSION_TAG, "Some permissions are not granted ask again ");
                            //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
    //                      //shouldShowRequestPermissionRationale will return true
                            //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
                            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) && ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                showDialogOK("Permission required for this app",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                switch (which) {
                                                    case DialogInterface.BUTTON_POSITIVE:
                                                        checkAndRequestPermissions();
                                                        break;
                                                    case DialogInterface.BUTTON_NEGATIVE:
                                                        // proceed with logic by disabling the related features or quit the app.
                                                        checkAndRequestPermissions();
                                                        break;
                                                }
                                            }
                                        });
                            }
                            //permission is denied (and never ask again is  checked)
                            //shouldShowRequestPermissionRationale will return false
                            else {
                                //proceed with logic by disabling the related features or quit the app.

                            }
                        }
                    }
                }
            }
        }

Below code will work in your case , you can use the below check in any method you want or in onCreate()

   if (platform_version >= 23) {
                boolean permission = checkAndRequestPermissions();
                /*if (permission)
                    Toast.makeText(this, "All permissions granted!", Toast.LENGTH_LONG).show();*/
            }


问:
Bootstrap Select option validation not working
Here is my HTML and JavaScript code

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="staff_add" class="form-horizontal" action="#" method="post" autocomplete="off">
  <select class="selectpicker form-control" data-live-search="true" name="vender" tabindex="-1" required="required">
    <option>--Select--</option>
    <option>001</option>
    <option>002</option>
    <option>003</option>
  </select>
  <input type="text" class="form-control" name="invoicenumber" id="invoiceNo" placeholder="Invoice No" required="" />
  <button type="submit" name="add_purchase" id="submit_postcode" class="btn btn-success">Submit</button>
</form></code>```

The Select box validation is not working, the textbox validation is working correctly.

I remove select box  class selectpicker validation working but to put selectpicker class its not work

答:
For setting an option as "not valid as validation answer" you should disable it:

```<code><select class="selectpicker form-control" data-live-search="true" name="vender" tabindex="-1" required="required">
<option disabled="disabled">--Select--</option>
<option>001</option>
<option>002</option>
<option>003</option>
</code>```

Body:
Here is my HTML and JavaScript code

<form id="staff_add" class="form-horizontal" action="#" method="post" autocomplete="off">
  <select class="selectpicker form-control" data-live-search="true" name="vender" tabindex="-1" required="required">
    <option>--Select--</option>
    <option>001</option>
    <option>002</option>
    <option>003</option>
  </select>
  <input type="text" class="form-control" name="invoicenumber" id="invoiceNo" placeholder="Invoice No" required="" />
  <button type="submit" name="add_purchase" id="submit_postcode" class="btn btn-success">Submit</button>
</form>

The Select box validation is not working, the textbox validation is working correctly.

I remove select box  class selectpicker validation working but to put selectpicker class its not work

Body:
For setting an option as "not valid as validation answer" you should disable it:

<select class="selectpicker form-control" data-live-search="true" name="vender" tabindex="-1" required="required">
<option disabled="disabled">--Select--</option>
<option>001</option>
<option>002</option>
<option>003</option>


问:
How do I initialise all entries of a matrix with a specific value?
In Haskell, if I wanted to get a 10 element list which only contained the number 5, I could do something like this:

```<code>take 10 $ repeat 5
</code>```

Output:

```<code>[5,5,5,5,5,5,5,5,5,5]
</code>```

Is there anything like this in Matlab?

答:
As mentioned in other answers you can use:

```<code>>> tic; x=5*ones(10,1); toc
Elapsed time is 0.000415 seconds.
</code>```

An even faster method is:

```<code>>> tic;  x=5; x=x(ones(10,1)); toc
Elapsed time is 0.000257 seconds.
</code>```

Body:
In Haskell, if I wanted to get a 10 element list which only contained the number 5, I could do something like this:

take 10 $ repeat 5

Output:

[5,5,5,5,5,5,5,5,5,5]

Is there anything like this in Matlab?

Body:
As mentioned in other answers you can use:

>> tic; x=5*ones(10,1); toc
Elapsed time is 0.000415 seconds.

An even faster method is:

>> tic;  x=5; x=x(ones(10,1)); toc
Elapsed time is 0.000257 seconds.


问:
Emulator: Process finished with exit code -1073741819 (0xC0000005)
I'm using android studio 3.0.1, when I start my emulator I get many error messages, I've tried to solve each problem separately, I also searched a lot but nothing works for me.

```<code>12:24 م Emulator: init: Could not find wglGetExtensionsStringARB!

12:24 م Emulator: OpenGL backend 'angle' without OpenGL ES 1.x library
detected. Using GLESv2 only.

12:24 م Emulator: Failed to eglInitialize

12:24 م Emulator: Could not initialize emulated framebuffer

12:24 م Emulator: Warning: requested RAM 1024M too high for your system.
Reducing to maximum supported size 512M

12:25 م Emulator: emulator: ERROR: Could not initialize OpenglES emulation,
use '-gpu off' to disable it.

12:25 م Emulator: Process finished with exit code -1073741819 (0xC0000005)
</code>```

I also tried this

答:
Make sure your graphics driver is updated

Go to tools

Go to Android

Select AVD Manager.

click on the pencil icon in under Action

Click Advanced Settings button.

In Emulated Performance row change Graphics to Software GLES 2.0

In Memory, row change RAM field to 512(minimum).

Body:
I'm using android studio 3.0.1, when I start my emulator I get many error messages, I've tried to solve each problem separately, I also searched a lot but nothing works for me.

12:24 م Emulator: init: Could not find wglGetExtensionsStringARB!

12:24 م Emulator: OpenGL backend 'angle' without OpenGL ES 1.x library
detected. Using GLESv2 only.

12:24 م Emulator: Failed to eglInitialize

12:24 م Emulator: Could not initialize emulated framebuffer

12:24 م Emulator: Warning: requested RAM 1024M too high for your system.
Reducing to maximum supported size 512M

12:25 م Emulator: emulator: ERROR: Could not initialize OpenglES emulation,
use '-gpu off' to disable it.

12:25 م Emulator: Process finished with exit code -1073741819 (0xC0000005)

I also tried this


问:
I am stuck on my Java homework Parsing Strings
I am somewhat lost on what to do.

There are 4 parts.

Prompt the user for a string that contains two strings separated by a comma.

Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.

Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings.

Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit.

Final outcome should print out as follows:

```<code>Enter input string: Jill, Allen
First word: Jill
Second word: Allen

Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey

Enter input string: Washington,DC
First word: Washington
Second word: DC

Enter input string: q
</code>```

I've figured out everything out but can't figure out the second part. I don't exactly know how to do the code for does not contain comma.

Here's my code:

```<code>import java.util.Scanner;

public class ParseStrings {

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    String lineString = "";
    int commaLocation = 0;
    String firstWord = "";
    String secondWord = "";
    boolean inputDone = false;

    while (!inputDone) {
        System.out.println("Enter input string: ");
        lineString = scnr.nextLine();

        if (lineString.equals("q")) {
            inputDone = true;
        }

        else {
        commaLocation = lineString.indexOf(',');
        firstWord = lineString.substring(0, commaLocation);
        secondWord = lineString.substring(commaLocation + 1, lineString.length());

        System.out.println("First word: " + firstWord);
        System.out.println("Second word:" + secondWord);
        System.out.println();
        System.out.println();
        }
    }

    return;
    }
}
</code>```

答:
You can use :</p>

```<code>if (input.matches("[^,]+,[^,]+")) {//If the input match two strings separated by a comma

    //split using this regex \s*,\s* zero or more spaces separated by comman
    String[] results = input.split("\\s*,\\s*");

    System.out.println("First word: " + results[0]);
    System.out.println("Second word: " + results[1]);
} else {
    //error, there are no two strings separated by a comma
}
</code>```

Body:
I am somewhat lost on what to do.

There are 4 parts.

Prompt the user for a string that contains two strings separated by a comma.

Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.

Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings.

Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit.

Final outcome should print out as follows:

Enter input string: Jill, Allen
First word: Jill
Second word: Allen

Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey

Enter input string: Washington,DC
First word: Washington
Second word: DC

Enter input string: q

I've figured out everything out but can't figure out the second part. I don't exactly know how to do the code for does not contain comma.

Here's my code:

import java.util.Scanner;

public class ParseStrings {

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    String lineString = "";
    int commaLocation = 0;
    String firstWord = "";
    String secondWord = "";
    boolean inputDone = false;

    while (!inputDone) {
        System.out.println("Enter input string: ");
        lineString = scnr.nextLine();

        if (lineString.equals("q")) {
            inputDone = true;
        }

        else {
        commaLocation = lineString.indexOf(',');
        firstWord = lineString.substring(0, commaLocation);
        secondWord = lineString.substring(commaLocation + 1, lineString.length());

        System.out.println("First word: " + firstWord);
        System.out.println("Second word:" + secondWord);
        System.out.println();
        System.out.println();
        }
    }

    return;
    }
}

Body:
You can use :

if (input.matches("[^,]+,[^,]+")) {//If the input match two strings separated by a comma

    //split using this regex \s*,\s* zero or more spaces separated by comman
    String[] results = input.split("\\s*,\\s*");

    System.out.println("First word: " + results[0]);
    System.out.println("Second word: " + results[1]);
} else {
    //error, there are no two strings separated by a comma
}


问:
HQL to query records between two dates
I am trying to query all customers records using HQL in my Spring/ Hibernate app that have DateAdded between Date1 and Date2 OR LastSeen between Date1 and Date2, so I've build this HQL query in the Repository/ DAO class:

```<code>sessionfactory.getCurrentSession().createQuery("from Customer c where c.dateAdded BETWEEN '"+startDate+"' AND '"+endDate+"' OR c.lastSeenDate BETWEEN  '"+startDate+"' AND '"+endDate+"'").list();
</code>```

I've debugged the app to check the startDate and endDate and found that they are sent as:

startDate: Wed Jan 22 01:16:57 HKT 2014

endDate: Wed Jan 29 01:16:57 HKT 2014

In DB, I am 100% sure there is one record at least meeting this query, as this record DateAdded and LastSeen are as follows:

2014-01-23 15:33:38

2014-01-25 15:33:38

So can someone please tell me what I am doing wrong / missing here?

答:
I had similar issue. When we use end date (Wed Jan 29), the system looks for Wed Jan 29 00:00:00, which is just like choosing Jan 28. In order to avoid such case, we can add one day to the end date. This also explains why we do not have issue with the start date.

Surprisingly, this issue does not exist when we use hibernate criteria.

Title: HQL to query records between two dates

Body:
I am trying to query all customers records using HQL in my Spring/ Hibernate app that have DateAdded between Date1 and Date2 OR LastSeen between Date1 and Date2, so I've build this HQL query in the Repository/ DAO class:

sessionfactory.getCurrentSession().createQuery("from Customer c where c.dateAdded BETWEEN '"+startDate+"' AND '"+endDate+"' OR c.lastSeenDate BETWEEN  '"+startDate+"' AND '"+endDate+"'").list();

I've debugged the app to check the startDate and endDate and found that they are sent as:

startDate: Wed Jan 22 01:16:57 HKT 2014

endDate: Wed Jan 29 01:16:57 HKT 2014

In DB, I am 100% sure there is one record at least meeting this query, as this record DateAdded and LastSeen are as follows:

2014-01-23 15:33:38

2014-01-25 15:33:38

So can someone please tell me what I am doing wrong / missing here?


问:
Can boost::smart_ptr be used in polymorphism?
Can boost::smart_ptr such as scoped_ptr and shared_ptr be used in polymorphism?</p>

```<code>class SomeClass
{
public:
    SomeClass()
    {
        a_ptr.reset(new SubClass);
    }
private:
    boost::scoped_ptr<SuperClass> a_ptr;
}
</code>```

答:
Yes:

```<code>#include <string>
#include <iostream>
using namespace std;
#include <boost\shared_ptr.hpp>
using namespace boost;

class Foo
{
public:
    virtual string speak() const { return "Foo"; }
    virtual ~Foo() {};
};

class Bar : public Foo
{
public:
    string speak() const { return "Bar"; }
};

int main()
{
    boost::shared_ptr<Foo> my_foo(new Bar);
    cout << my_foo->speak();
}
</code>```

Output is: Bar

ContentLicense: CC BY-SA 2.5

Body:
Can boost::smart_ptr such as scoped_ptr and shared_ptr be used in polymorphism?

class SomeClass
{
public:
    SomeClass()
    {
        a_ptr.reset(new SubClass);
    }
private:
    boost::scoped_ptr<SuperClass> a_ptr;
}

Body:
Yes:

#include <string>
#include <iostream>
using namespace std;
#include <boost\shared_ptr.hpp>
using namespace boost;

class Foo
{
public:
    virtual string speak() const { return "Foo"; }
    virtual ~Foo() {};
};

class Bar : public Foo
{
public:
    string speak() const { return "Bar"; }
};

int main()
{
    boost::shared_ptr<Foo> my_foo(new Bar);
    cout << my_foo->speak();
}

Output is: Bar


问:
create trigger when I use area code outside of a specific state
I am creating a Trigger that lets me know when I enter a phone number outside of CA. This is what I have so far, but I think this will always generate a trigger message each time a phone number is entered regardless of the area code/state.

Not sure if I need to specify more in my customerphone table or not, if so what am I missing if anything?

Here is my code I have thus far...

```<code>Create Trigger NumberOutsideCA
On CustomerPhone
After Insert, Update as
    Print 'Phone Number is Outside CA'
Return
</code>```

答:
You can use the magic table "inserted" to check whether the phone number is outside CA and can log that record some where.</p>

```<code>CREATE TRIGGER NumberOutsideCA ON CustomerPhone
AFTER INSERT, UPDATE
AS
BEGIN
    -- Here i have user CustomerPhoneLog table to log the record. You can make your own table
    INSERT INTO CustomerPhoneLog (CustomerPhoneID,Message)
    SELECT CustomerPhoneID
        , 'This phone number doest not belongs to CA State'
    FROM INSERTED
    WHERE STATE != 'CA' -- Here you have to user proper condition to check the phone number outside CA
END
</code>```

Body:
I am creating a Trigger that lets me know when I enter a phone number outside of CA. This is what I have so far, but I think this will always generate a trigger message each time a phone number is entered regardless of the area code/state.

Not sure if I need to specify more in my customerphone table or not, if so what am I missing if anything?

Here is my code I have thus far...

Create Trigger NumberOutsideCA
On CustomerPhone
After Insert, Update as
    Print 'Phone Number is Outside CA'
Return

Body:
You can use the magic table "inserted" to check whether the phone number is outside CA and can log that record some where.

CREATE TRIGGER NumberOutsideCA ON CustomerPhone
AFTER INSERT, UPDATE
AS
BEGIN
    -- Here i have user CustomerPhoneLog table to log the record. You can make your own table
    INSERT INTO CustomerPhoneLog (CustomerPhoneID,Message)
    SELECT CustomerPhoneID
        , 'This phone number doest not belongs to CA State'
    FROM INSERTED
    WHERE STATE != 'CA' -- Here you have to user proper condition to check the phone number outside CA
END


问:
CASE in Eloquent Laravel not running the function
The following is my query and the CASE part is not executing:

```<code>$deposit = CurrentTransaction::select('current_transaction.id', 'user.name', 'current_transaction.amount', 'current_transaction.status', 'current_transaction.type', 'current_transaction.refer_id', 'current_transaction.msg', 'current_transaction.remarks', 'current_transaction.created_by', 'current_transaction.created_at')
->join('user', 'current_transaction.user_id', '=', 'user.id')
->where('current_transaction.amount', '>', '0')
->where(function ($query) {
    $query->select(DB::raw('CASE WHEN current_transaction.created_by = current_transaction.user_id THEN "true" ELSE "false" END AS "result"'))->where('result', 'false');
})->get();
</code>```

and the syntax error around where('result', 'false') part.

Update

The structure of database:

```<code>Schema::create('current_transaction', function (Blueprint $table){
        $table->increments('id');
        $table->integer('user_id');
        $table->decimal('amount', 30, 8);
        $table->boolean('status')->default(1);
        $table->integer('type')->default(1);
        $table->integer('refer_id');
        $table->integer('created_by');
        $table->integer('updated_by');
        $table->timestamps();
    });
</code>```

I want to find out the rows where created_by is not equal to user_id
join the user table, and get the user.name with user_id
and amount more than 0.

答:
You can update your query like this:</p>

```<code>$deposit = CurrentTransaction::join('user', 'current_transaction.user_id', '=', 'user.id')
            ->where('amount', '>', '0')
            ->where('created_by' , '!=', 'user_id')
            ->select('current_transaction.id',
                     'user.name', 'current_transaction.amount',
                     'current_transaction.status',
                     'current_transaction.type',
                     'current_transaction.refer_id',
                     'current_transaction.msg',
                     'current_transaction.remarks',
                     'current_transaction.created_by',
                     'current_transaction.created_at')
            ->get();
</code>```

Body:
The following is my query and the CASE part is not executing:

$deposit = CurrentTransaction::select('current_transaction.id', 'user.name', 'current_transaction.amount', 'current_transaction.status', 'current_transaction.type', 'current_transaction.refer_id', 'current_transaction.msg', 'current_transaction.remarks', 'current_transaction.created_by', 'current_transaction.created_at')
->join('user', 'current_transaction.user_id', '=', 'user.id')
->where('current_transaction.amount', '>', '0')
->where(function ($query) {
    $query->select(DB::raw('CASE WHEN current_transaction.created_by = current_transaction.user_id THEN "true" ELSE "false" END AS "result"'))->where('result', 'false');
})->get();

and the syntax error around where('result', 'false') part.

Update

The structure of database:

Schema::create('current_transaction', function (Blueprint $table){
        $table->increments('id');
        $table->integer('user_id');
        $table->decimal('amount', 30, 8);
        $table->boolean('status')->default(1);
        $table->integer('type')->default(1);
        $table->integer('refer_id');
        $table->integer('created_by');
        $table->integer('updated_by');
        $table->timestamps();
    });

I want to find out the rows where created_by is not equal to user_id
join the user table, and get the user.name with user_id
and amount more than 0.

Body:
You can update your query like this:

$deposit = CurrentTransaction::join('user', 'current_transaction.user_id', '=', 'user.id')
            ->where('amount', '>', '0')
            ->where('created_by' , '!=', 'user_id')
            ->select('current_transaction.id',
                     'user.name', 'current_transaction.amount',
                     'current_transaction.status',
                     'current_transaction.type',
                     'current_transaction.refer_id',
                     'current_transaction.msg',
                     'current_transaction.remarks',
                     'current_transaction.created_by',
                     'current_transaction.created_at')
            ->get();


问:
Concurrently check if stack is empty
How do you ensure that between subsequent calls to !stack.isEmpty() and stack.pop() the stack is not accessed by different threads?

```<code>executor.submit(()->{
    File currentDirectory;
    while(!directoryToSearch.isEmpty()) {
        currentDirectory = directoryToSearch.pop();
        ....
    }
}
</code>```

Wrapping:

```<code>while ((currentDirectory = directoryToSearch.pop()) != null)
</code>```

in a try and catch block or creating a lock for an already synchronized data structure simply does not feel like a good solution.

The stack is filled before releasing n threads on it and does not get filled up again. The issue I am seeing is that at the last object multiple threads might pass the stack.isEmpty() check before one of the threads is able to pop one element resulting in an exception for all other threads.

答:
I suggest using ConcurrentLinkedQueue.  It should be quicker than synchronizing and future proof (if you DID later decide to add items in a thread while you pulled them out it would just work).

Second choice: Just catch the exception and continue as though the stack had been empty.

This is faster than Synchronized because synchronized has a fairly serious penalty whenever you enter a synchronized block but exceptions only cause a speed problem when they are hit (which will only happen on threads that are not doing anything interesting anyway).

Exceptions may be a little quicker than the ConcurrentLinkedQueue but only a little.

Title: Concurrently check if stack is empty

Body:
How do you ensure that between subsequent calls to !stack.isEmpty() and stack.pop() the stack is not accessed by different threads?

executor.submit(()->{
    File currentDirectory;
    while(!directoryToSearch.isEmpty()) {
        currentDirectory = directoryToSearch.pop();
        ....
    }
}

Wrapping:

while ((currentDirectory = directoryToSearch.pop()) != null)

in a try and catch block or creating a lock for an already synchronized data structure simply does not feel like a good solution.

The stack is filled before releasing n threads on it and does not get filled up again. The issue I am seeing is that at the last object multiple threads might pass the stack.isEmpty() check before one of the threads is able to pop one element resulting in an exception for all other threads.


问:
Multiple Permission at once not working in android
I am trying to get 2 permissions at once but Iam unable to do so.

```<code>if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(context, Array<String>(2) {
            Manifest.permission.READ_CONTACTS;
            Manifest.permission.WRITE_EXTERNAL_STORAGE},
        1);
    }
}
</code>```

It only asks for WRITE_EXTERNAL_STORAGE permission and not READ_CONTACTS. Actually, If I write WRITE_EXTERNAL_STORAGE one first and READ_CONTACTS after that then it will only ask for contact and not WRITE_EXTERNAL_STORAGE.

答:
```<code>Array(size: Int, init: (Int) -> T)
</code>```

is the constructor for the Array class which takes the number of elements it should contain, and an init function which maps the index to an actual array element.

Here is what your code does, written in a more verbose way

```<code>val a = Array<String>(size = 2, init = { index: Int ->
    Manifest.permission.READ_CONTACTS; // nothing
    Manifest.permission.WRITE_EXTERNAL_STORAGE // returned by the lambda for each index
})
</code>```

Result:

[Manifest.permission.WRITE_EXTERNAL_STORAGE,
  Manifest.permission.WRITE_EXTERNAL_STORAGE]

So, you would be better of using the arrayOf function in this case, since you don't want to genereate your array elements but rather specify them explicitely.

Body:
I am trying to get 2 permissions at once but Iam unable to do so.

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(context, Array<String>(2) {
            Manifest.permission.READ_CONTACTS;
            Manifest.permission.WRITE_EXTERNAL_STORAGE},
        1);
    }
}

It only asks for WRITE_EXTERNAL_STORAGE permission and not READ_CONTACTS. Actually, If I write WRITE_EXTERNAL_STORAGE one first and READ_CONTACTS after that then it will only ask for contact and not WRITE_EXTERNAL_STORAGE.

Body:
Array(size: Int, init: (Int) -> T)

is the constructor for the Array class which takes the number of elements it should contain, and an init function which maps the index to an actual array element.

Here is what your code does, written in a more verbose way

val a = Array<String>(size = 2, init = { index: Int ->
    Manifest.permission.READ_CONTACTS; // nothing
    Manifest.permission.WRITE_EXTERNAL_STORAGE // returned by the lambda for each index
})

Result:

[Manifest.permission.WRITE_EXTERNAL_STORAGE,
  Manifest.permission.WRITE_EXTERNAL_STORAGE]

So, you would be better of using the arrayOf function in this case, since you don't want to genereate your array elements but rather specify them explicitely.


问:
l[:] performance problem
Recently I was debugging a code like following

```<code>def getList():
    #query db and return a list
    total_list = Model.objects.all()
    result = list()
    for item in total_list:
        if item.attr1:
            result.append(item)
    return result

# in main code
org_list = getList()
list = orgList[:]#this line cause cpu problems.

if len(org_list)>0 and org_list[0].is_special:
    my_item = org_list[0]

for i in list:
    print_item(i)

doSomethingelse(list[0])
</code>```

In order to simplify the code I change most of it but the main part is here.

In getList method we query db and get 20~30 rows. Then we create a python list from it and return it.
in main method we get org_list variable from getList method
and slice it with orgList[:]

and loop over this list and call spesific elements on it like list[0]

The problem here is that this code runs on a really busy server and unfortunaletty it uses most of the cpu and eventually locks our servers.
Problem here is the line that we slice list varibale with list[:]
if we dont do that and just use org_list variable instead our servers does not have a problem. Does anybosy have any idea why that might happen. is slicing uses alot of cpu or when we use a sliced list. does it uses alot of cpu?

答:
I would like to know:

what is the type of total_list ? Please do print type(total_list)

what are the types of the elements of total_list ?

have you an idea of the sizes of these elements ?

what is the number of elements in the list returned by getList() ? 20-30 ?

Remarks:

-giving the keyword "list" as a name for a list isn't a good idea (in list = orgList[:] )

-your getList function can be written :

```<code>def getList():
    #query db and return a list
    total_list = Model.objects.all()
    return [ item for item in total_list if item.attr1 ]
</code>```

Title: l[:] performance problem

Body:
Recently I was debugging a code like following

def getList():
    #query db and return a list
    total_list = Model.objects.all()
    result = list()
    for item in total_list:
        if item.attr1:
            result.append(item)
    return result

# in main code
org_list = getList()
list = orgList[:]#this line cause cpu problems.

if len(org_list)>0 and org_list[0].is_special:
    my_item = org_list[0]

for i in list:
    print_item(i)

doSomethingelse(list[0])

In order to simplify the code I change most of it but the main part is here.

In getList method we query db and get 20~30 rows. Then we create a python list from it and return it.
in main method we get org_list variable from getList method
and slice it with orgList[:]

and loop over this list and call spesific elements on it like list[0]

The problem here is that this code runs on a really busy server and unfortunaletty it uses most of the cpu and eventually locks our servers.
Problem here is the line that we slice list varibale with list[:]
if we dont do that and just use org_list variable instead our servers does not have a problem. Does anybosy have any idea why that might happen. is slicing uses alot of cpu or when we use a sliced list. does it uses alot of cpu?

Body:
I would like to know:

what is the type of total_list ? Please do print type(total_list)

what are the types of the elements of total_list ?

have you an idea of the sizes of these elements ?

what is the number of elements in the list returned by getList() ? 20-30 ?

Remarks:

-giving the keyword "list" as a name for a list isn't a good idea (in list = orgList[:] )

-your getList function can be written :

def getList():
    #query db and return a list
    total_list = Model.objects.all()
    return [ item for item in total_list if item.attr1 ]


问:
split strings into two columns
I am working with someone else's data with a column for which possible values are "short" and "long". Unfortunately, the data creator also added letters and question marks after those words to annotate certain things, that I want to split into a separate column. Here's some fake data to work with:

```<code>vars <- c('long','short','longG','short?','short?F','long?G')
species <- c('sp1','sp2','sp3','sp4','sp5','sp6')
testdf <- cbind(vars, species)
</code>```

I would like to split the vars column into the actual value long or short, and a new column with just the annotated characters. I can get halfway there with the following, which correctly produces a new column with just the annotating characters:

```<code>testdf %>% mutate(notes = gsub('long|short',"",vars)
</code>```

But I can't figure out how to split or subset var such that I get a column that just says short or long.

Thanks in advance for the help, SO community! ^_^

答:
testdf in the question is a matrix so convert it to a data frame with one of these two alternatives:

1) sub  a  mutate with two sub invocations with the same pattern pat but with different replacements.

```<code>pat <- "(long|short)(.*)"
testdf %>%
       as.data.frame %>%
       mutate(notes = sub(pat, "\\2", vars),
              vars = sub(pat, "\\1", vars))
</code>```

giving:

```<code>   vars  species notes
1  long      sp1
2 short      sp2
3  long      sp3     G
4 short      sp4     ?
5 short      sp5    ?F
6  long      sp6    ?G
</code>```

2) separate Insert a semicolon (or other character) after long or short and then use separate from tidyr.  Note that this works even if the notes contain a semicolon since it only splits at the first semicolon.

```<code>library(tidyr)

testdf %>%
       as.data.frame %>%
       mutate(vars = sub("(long|short)", "\\1;", vars)) %>%
       separate(vars, c("vars", "notes"), sep = ";", extra = "merge")
</code>```

giving:

```<code>   vars notes  species
1  long            sp1
2 short            sp2
3  long     G      sp3
4 short     ?      sp4
5 short    ?F      sp5
6  long    ?G      sp6
</code>```

Note that if there is always a ? separating the notes then it could be reduced to:

```<code>testdf %>%
       as.data.frame %>%
       separate(vars, c("vars", "notes"), sep = "\\?", extra = "merge")
</code>```

Title: split strings into two columns

Body:
I am working with someone else's data with a column for which possible values are "short" and "long". Unfortunately, the data creator also added letters and question marks after those words to annotate certain things, that I want to split into a separate column. Here's some fake data to work with:

vars <- c('long','short','longG','short?','short?F','long?G')
species <- c('sp1','sp2','sp3','sp4','sp5','sp6')
testdf <- cbind(vars, species)

I would like to split the vars column into the actual value long or short, and a new column with just the annotated characters. I can get halfway there with the following, which correctly produces a new column with just the annotating characters:

testdf %>% mutate(notes = gsub('long|short',"",vars)

But I can't figure out how to split or subset var such that I get a column that just says short or long.

Thanks in advance for the help, SO community! ^_^

Body:
testdf in the question is a matrix so convert it to a data frame with one of these two alternatives:

1) sub  a  mutate with two sub invocations with the same pattern pat but with different replacements.

pat <- "(long|short)(.*)"
testdf %>%
       as.data.frame %>%
       mutate(notes = sub(pat, "\\2", vars),
              vars = sub(pat, "\\1", vars))

giving:

   vars  species notes
1  long      sp1
2 short      sp2
3  long      sp3     G
4 short      sp4     ?
5 short      sp5    ?F
6  long      sp6    ?G

2) separate Insert a semicolon (or other character) after long or short and then use separate from tidyr.  Note that this works even if the notes contain a semicolon since it only splits at the first semicolon.

library(tidyr)

testdf %>%
       as.data.frame %>%
       mutate(vars = sub("(long|short)", "\\1;", vars)) %>%
       separate(vars, c("vars", "notes"), sep = ";", extra = "merge")

giving:

   vars notes  species
1  long            sp1
2 short            sp2
3  long     G      sp3
4 short     ?      sp4
5 short    ?F      sp5
6  long    ?G      sp6

Note that if there is always a ? separating the notes then it could be reduced to:

testdf %>%
       as.data.frame %>%
       separate(vars, c("vars", "notes"), sep = "\\?", extra = "merge")


问:
To be assigned value as variable in jq
json processor jq for a package.json

```<code>{
  "someparent" : {
    "somechild" : "oldvalue"
  }
}
</code>```

If I run the following command (to change oldvalue to somevalue):

```<code>jq '.someparent["somechild"] = "somevalue" "$aDirection/package.json"'
</code>```

It is successfully changed. However, if I give a variable instead of someValue:

```<code> aVar="anotherValue"
 jq '.someparent["somechild"] = "$aVar" "$aDirection/package.json"'
</code>```

It is not working.
What I already tried:

```<code>["aVar"] #interpreted as string
["$aVar"] #interpreted as string
"$aVar" # aVar is not defined
$avar #aVar is not defined
</code>```

答:
Just to be clear: using the OP's approach can be made to work, e.g.

```<code>jq '.someparent["somechild"] = "'"$aVar"'"' "$aDirection/package.json"
</code>```

but using --arg (for strings) and/or --argjson is far better.  An additional option for environment variables is to use the jq function env.

Title: To be assigned value as variable in jq

Body:
json processor jq for a package.json

{
  "someparent" : {
    "somechild" : "oldvalue"
  }
}

If I run the following command (to change oldvalue to somevalue):

jq '.someparent["somechild"] = "somevalue" "$aDirection/package.json"'

It is successfully changed. However, if I give a variable instead of someValue:

 aVar="anotherValue"
 jq '.someparent["somechild"] = "$aVar" "$aDirection/package.json"'

It is not working.
What I already tried:

["aVar"] #interpreted as string
["$aVar"] #interpreted as string
"$aVar" # aVar is not defined
$avar #aVar is not defined

Body:
Just to be clear: using the OP's approach can be made to work, e.g.

jq '.someparent["somechild"] = "'"$aVar"'"' "$aDirection/package.json"

but using --arg (for strings) and/or --argjson is far better.  An additional option for environment variables is to use the jq function env.


问:
R, dplyr: Looping over a subset of columns by name and applying mutate?
My current setup uses R 3.4.2 and tidyverse 1.1.1.

My aim is to transform data in the manner of this answer but to do so in a way that is extensible, so that I can easily change the set of variables that I wish to perform this operation with.

For the sake of definiteness, let us take the following data:

```<code>library(tidyverse)

df = tibble(
  id = seq(1,8),
  hair.colour = c("red", "blonde", "brown", "black", "red", "blonde", "brown", "black"),
  eye.colour = c("blue", "brown", "blue", "brown", "blue", "brown", "blue", "brown"),
  gender = c("male", "male", "male", "male", "female", "female", "female",
             "female"))
</code>```

Code such as this works as desired:

```<code>df2 = df %>%
  mutate(value = 1,
         hair.colour = paste("hair.colour", hair.colour, sep = ".")) %>%
  spread(hair.colour, value, fill = 0)
</code>```

Naively attempting to wrap this in a loop, e.g.

```<code>factors = c("hair.colour", "eye.colour", "gender")
for (factor in factors) {
    df = df %>%
        mutate(value = 1, factor = paste(toString(factor), factor, sep = ".")) %>%
        spread(factor, value, fill = 0)
}
</code>```

does not work. I imagine there's a clever way using quo(), !!, etc., but I'm new to R, and my searches have yielded nothing that I can use.

Does anyone have any advice, both within the tidyverse (especially if it finds a way to use the same code as in the second block) and outside of it?

答:
You could do it this way:

```<code>factors = c("hair.colour", "eye.colour", "gender")
for (factor in factors) {
  df = df %>%
    mutate(value = 1, x = paste(factor,.[[factor]], sep = ".")) %>%
    select_(paste0("-",factor)) %>%
    spread(x, "value", fill = 0)
}
</code>```

The dot . is a shortcut for the left hand side when using pipes, so when typing .[[factor]] I could have written df[[factor]] just the same, so i'm pasting the value of your factor string to the value of the relevant column.

select_ is a variant of select using standard evaluation (basically you feed it strings), dplyr and tidyr functions usually have one. for more: ?select_

result:

```<code># # A tibble: 8 x 9
#      id hair.colour.black hair.colour.blonde hair.colour.brown hair.colour.red eye.colour.blue eye.colour.brown gender.female gender.male
# * <int>             <dbl>              <dbl>             <dbl>           <dbl>           <dbl>            <dbl>         <dbl>       <dbl>
# 1     1                 0                  0                 0               1               1                0             0           1
# 2     2                 0                  1                 0               0               0                1             0           1
# 3     3                 0                  0                 1               0               1                0             0           1
# 4     4                 1                  0                 0               0               0                1             0           1
# 5     5                 0                  0                 0               1               1                0             1           0
# 6     6                 0                  1                 0               0               0                1             1           0
# 7     7                 0                  0                 1               0               1                0             1           0
# 8     8                 1                  0                 0               0               0                1             1           0
</code>```

Body:
My current setup uses R 3.4.2 and tidyverse 1.1.1.

My aim is to transform data in the manner of this answer but to do so in a way that is extensible, so that I can easily change the set of variables that I wish to perform this operation with.

For the sake of definiteness, let us take the following data:

library(tidyverse)

df = tibble(
  id = seq(1,8),
  hair.colour = c("red", "blonde", "brown", "black", "red", "blonde", "brown", "black"),
  eye.colour = c("blue", "brown", "blue", "brown", "blue", "brown", "blue", "brown"),
  gender = c("male", "male", "male", "male", "female", "female", "female",
             "female"))

Code such as this works as desired:

df2 = df %>%
  mutate(value = 1,
         hair.colour = paste("hair.colour", hair.colour, sep = ".")) %>%
  spread(hair.colour, value, fill = 0)

Naively attempting to wrap this in a loop, e.g.

factors = c("hair.colour", "eye.colour", "gender")
for (factor in factors) {
    df = df %>%
        mutate(value = 1, factor = paste(toString(factor), factor, sep = ".")) %>%
        spread(factor, value, fill = 0)
}

does not work. I imagine there's a clever way using quo(), !!, etc., but I'm new to R, and my searches have yielded nothing that I can use.

Does anyone have any advice, both within the tidyverse (especially if it finds a way to use the same code as in the second block) and outside of it?

Body:
You could do it this way:

factors = c("hair.colour", "eye.colour", "gender")
for (factor in factors) {
  df = df %>%
    mutate(value = 1, x = paste(factor,.[[factor]], sep = ".")) %>%
    select_(paste0("-",factor)) %>%
    spread(x, "value", fill = 0)
}

The dot . is a shortcut for the left hand side when using pipes, so when typing .[[factor]] I could have written df[[factor]] just the same, so i'm pasting the value of your factor string to the value of the relevant column.

select_ is a variant of select using standard evaluation (basically you feed it strings), dplyr and tidyr functions usually have one. for more: ?select_

result:

# # A tibble: 8 x 9
#      id hair.colour.black hair.colour.blonde hair.colour.brown hair.colour.red eye.colour.blue eye.colour.brown gender.female gender.male
# * <int>             <dbl>              <dbl>             <dbl>           <dbl>           <dbl>            <dbl>         <dbl>       <dbl>
# 1     1                 0                  0                 0               1               1                0             0           1
# 2     2                 0                  1                 0               0               0                1             0           1
# 3     3                 0                  0                 1               0               1                0             0           1
# 4     4                 1                  0                 0               0               0                1             0           1
# 5     5                 0                  0                 0               1               1                0             1           0
# 6     6                 0                  1                 0               0               0                1             1           0
# 7     7                 0                  0                 1               0               1                0             1           0
# 8     8                 1                  0                 0               0               0                1             1           0


问:
Is it worth creating an interface for a trivial return type?
Consider the following interfaces:

```<code>public interface IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id);
}

public interface IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}
</code>```

and the associated implementations:

```<code>public class PlayerRepository : IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id)
  {
    // read from external data store
    return new PlayerInfo();
  }
}

public class PlayerInfo : IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}
</code>```

Is there any value in having the separate IPlayerInfo interface, given that the class only exists as a collection of properties to be returned by this method?  Would it be preferable to just have the IPlayerRepository.GetPlayerInfo method return a concrete PlayerInfo object?

答: IMO.  Don't try to write code for a type that you haven't thought of yet.  I find it's always easier to write code that makes sense, and isn't overly abstracted or overly complicated.  You can always refactor it when you get to the point where your requirements change and you have more than one type of PlayerInfo that will require a different implementation.  </p>

Body:
Consider the following interfaces:

public interface IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id);
}

public interface IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}

and the associated implementations:

public class PlayerRepository : IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id)
  {
    // read from external data store
    return new PlayerInfo();
  }
}

public class PlayerInfo : IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}

Is there any value in having the separate IPlayerInfo interface, given that the class only exists as a collection of properties to be returned by this method?  Would it be preferable to just have the IPlayerRepository.GetPlayerInfo method return a concrete PlayerInfo object?


问:
Json.Net not deserializing derived object that hides base property when posting with form data
I have a WebApi Controller method that accepts a derived class:

```<code>    //Controller Method
    public IHttpActionResult Test(DerivedClass m)
    {
        return Ok(true);
    }

    //base class
    public class BaseClass
    {
        public int Id{ get; set; }
    }

    //derived class
    public class DerivedClass : BaseClass
    {
        public new int? Id { get; set; }
    }
</code>```

I am posting with Id = 1

If I POST to this controller method with JSON data type it works fine (I get an object with Id=1), but if I send x-www-form-urlencoded data then the object is null.

Now, if I change the controller method to accept the BaseClass and use x-www-form-urlencoded data then the object is not null (Id=1).  Also, if I modify the Derived class and remove the new int? property it works fine as well.

This is leading me to believe there is an issue with Json.Net not deserializing x-www-form-urlencoded data to objects that hide derived class properties. Any suggestions on how to resolve?

答: One thing to consider is that the nullable int property will have a different signature from non-nullable, so you may not be actually overriding the property if that was your intention.</p>

Body:
I have a WebApi Controller method that accepts a derived class:

    //Controller Method
    public IHttpActionResult Test(DerivedClass m)
    {
        return Ok(true);
    }

    //base class
    public class BaseClass
    {
        public int Id{ get; set; }
    }

    //derived class
    public class DerivedClass : BaseClass
    {
        public new int? Id { get; set; }
    }

I am posting with Id = 1

If I POST to this controller method with JSON data type it works fine (I get an object with Id=1), but if I send x-www-form-urlencoded data then the object is null.

Now, if I change the controller method to accept the BaseClass and use x-www-form-urlencoded data then the object is not null (Id=1).  Also, if I modify the Derived class and remove the new int? property it works fine as well.

This is leading me to believe there is an issue with Json.Net not deserializing x-www-form-urlencoded data to objects that hide derived class properties. Any suggestions on how to resolve?


问:
Pass whole script as argument to powershell.exe
I once found a script to easily change my Wallpaper if I use multiple ones.

```<code>set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys("^ ")
WshShell.SendKeys("+{F10}")
WshShell.SendKeys("n")
WshShell.SendKeys("{ENTER}")
</code>```

However I need a separate link that calls the script.
Now I wonder if I can pass these multiple lines of code as parameter to powershell.exe directly.

I did read that I can allign multiple lines using ; and tried building the one-liner, however it doesn't run...or rather it does run, there is no feedback, nothing changes. If I paste the command line into a running powershell instance it just exits.

```<code>%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -windowstyle hidden -Command "set WshShell = WScript.CreateObject('WScript.Shell'); WshShell.SendKeys('^ '); WshShell.SendKeys('+{F10}'); WshShell.SendKeys('n'); WshShell.SendKeys('{ENTER}')"
</code>```

I basically just concatenated them and replaced the double quotes with single quotes to escape the special characters, so why does it not work as the separate script?

答:
In PowerShell:

```<code>$WSH = New-Object -ComObject 'WScript.Shell'
$WSH.SendKeys('^ ')
$WSH.SendKeys('+{F10}')
$WSH.SendKeys('n')
$WSH.SendKeys('{ENTER}')
</code>```

Save this as a script (Filename.ps1), and call it from a .bat or .cmd file:

```<code>%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe -File "path\filename.ps1"
</code>```

Alternatively, as a one-liner in a command file:

```<code>%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "$WSH = New-Object -ComObject 'WScript.Shell';$WSH.SendKeys('\^ ');$WSH.SendKeys('+{F10}');$WSH.SendKeys('n');$WSH.SendKeys('{ENTER}')"
</code>```

Body:
I once found a script to easily change my Wallpaper if I use multiple ones.

set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys("^ ")
WshShell.SendKeys("+{F10}")
WshShell.SendKeys("n")
WshShell.SendKeys("{ENTER}")

However I need a separate link that calls the script.
Now I wonder if I can pass these multiple lines of code as parameter to powershell.exe directly.

I did read that I can allign multiple lines using ; and tried building the one-liner, however it doesn't run...or rather it does run, there is no feedback, nothing changes. If I paste the command line into a running powershell instance it just exits.

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -windowstyle hidden -Command "set WshShell = WScript.CreateObject('WScript.Shell'); WshShell.SendKeys('^ '); WshShell.SendKeys('+{F10}'); WshShell.SendKeys('n'); WshShell.SendKeys('{ENTER}')"

I basically just concatenated them and replaced the double quotes with single quotes to escape the special characters, so why does it not work as the separate script?

Body:
In PowerShell:

$WSH = New-Object -ComObject 'WScript.Shell'
$WSH.SendKeys('^ ')
$WSH.SendKeys('+{F10}')
$WSH.SendKeys('n')
$WSH.SendKeys('{ENTER}')

Save this as a script (Filename.ps1), and call it from a .bat or .cmd file:

%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe -File "path\filename.ps1"

Alternatively, as a one-liner in a command file:

%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "$WSH = New-Object -ComObject 'WScript.Shell';$WSH.SendKeys('\^ ');$WSH.SendKeys('+{F10}');$WSH.SendKeys('n');$WSH.SendKeys('{ENTER}')"


问:
Excel VBA Bolding red text in a string
I'm working on an Excel macro that will loop through cells and bold all text within each that is already formatted as red. Each cell contains a string with automatic black text except for keywords which are highlighted as red. I just want those red keywords to also be bolded.

The way I have it set up now, it iterates through each character individually, which although not the fastest, is fine for my purposes, since it will only be run on a few cells at a time.
I initially had it coded as this:

```<code>Sub redTxtBold2()
Dim i As Integer

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        For i = 1 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then
                currentCell.Characters(i, 1).Font.Bold = True
            End If
        Next i
    End If
Next currentCell
End Sub
</code>```

The problem I ran into here was that, although it worked fine for most cells, in cases where the first character in a cell was red, it would bold that character and remove the red text formatting in the rest of the cell. Figuring out why it does this and preventing it would be the best solution, but I came up with a workaround:

```<code>Sub redTxtBold1()
Dim i, tstart As Integer
Dim redTxt As String
Dim BoldText As String

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        For i = 1 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then
                redTxt = redTxt & currentCell.Characters(i, 1).Text
                Debug.Print redTxt
            End If
        Next i
    End If
    tstart = InStr(currentCell.Text, redTxt)
    Debug.Print tstart
    currentCell.Characters(tstart, Len(redTxt)).Font.Bold = True
    redTxt = ""
Next currentCell
End Sub
</code>```

The problem now with this one is that if the string contains multiple red keywords spaced throughout, redTxt collects and merges them together, causing InStr to not find the substring. The macro thus bolds the first few characters for Len(redTxt) regardless of which are red or not.

I've only been experimenting with VBA for a couple months now, so my skills are still fairly limited. How can I code this better so it bolds all red, and only red characters?

答:
This is possibly a longstanding bug e.g. see here. This workaround, an adaptation of your first go should resolve it even if it is rather inelegant.</p>

```<code>Sub redTxtBold2()

Dim i As Integer, currentCell As Range, SearchString As String, b As Boolean

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        For i = 2 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then
                currentCell.Characters(i, 1).Font.Bold = True
            End If
        Next i
    End If
    If currentCell.Characters(1, 1).Font.ColorIndex = 3 Then
        currentCell.Characters(1, 1).Font.Bold = True
    End If
Next currentCell

End Sub
</code>```

Title: Excel VBA Bolding red text in a string

Body:
I'm working on an Excel macro that will loop through cells and bold all text within each that is already formatted as red. Each cell contains a string with automatic black text except for keywords which are highlighted as red. I just want those red keywords to also be bolded.

The way I have it set up now, it iterates through each character individually, which although not the fastest, is fine for my purposes, since it will only be run on a few cells at a time.
I initially had it coded as this:

Sub redTxtBold2()
Dim i As Integer

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        For i = 1 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then
                currentCell.Characters(i, 1).Font.Bold = True
            End If
        Next i
    End If
Next currentCell
End Sub

The problem I ran into here was that, although it worked fine for most cells, in cases where the first character in a cell was red, it would bold that character and remove the red text formatting in the rest of the cell. Figuring out why it does this and preventing it would be the best solution, but I came up with a workaround:

Sub redTxtBold1()
Dim i, tstart As Integer
Dim redTxt As String
Dim BoldText As String

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        For i = 1 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then
                redTxt = redTxt & currentCell.Characters(i, 1).Text
                Debug.Print redTxt
            End If
        Next i
    End If
    tstart = InStr(currentCell.Text, redTxt)
    Debug.Print tstart
    currentCell.Characters(tstart, Len(redTxt)).Font.Bold = True
    redTxt = ""
Next currentCell
End Sub

The problem now with this one is that if the string contains multiple red keywords spaced throughout, redTxt collects and merges them together, causing InStr to not find the substring. The macro thus bolds the first few characters for Len(redTxt) regardless of which are red or not.

I've only been experimenting with VBA for a couple months now, so my skills are still fairly limited. How can I code this better so it bolds all red, and only red characters?

Body:
This is possibly a longstanding bug e.g. see here. This workaround, an adaptation of your first go should resolve it even if it is rather inelegant.

Sub redTxtBold2()

Dim i As Integer, currentCell As Range, SearchString As String, b As Boolean

For Each currentCell In Selection
    SearchString = currentCell.Value
    If IsNull(currentCell.Font.ColorIndex) Then
        For i = 2 To Len(SearchString)
            If currentCell.Characters(i, 1).Font.ColorIndex = 3 Then
                currentCell.Characters(i, 1).Font.Bold = True
            End If
        Next i
    End If
    If currentCell.Characters(1, 1).Font.ColorIndex = 3 Then
        currentCell.Characters(1, 1).Font.Bold = True
    End If
Next currentCell

End Sub


问:
Adding a dictionary to a list python - ValueError: dictionary update sequence element #0 has length 1; 2 is required
I keep getting a "ValueError: dictionary update sequence element #0 has length 1; 2 is required" when i try to post a new comment into the comments list </p>

```<code># import the Flask class from the flask module
from flask import Flask, render_template, request

# create the application object
app = Flask(__name__)

posts=[]

@app.route('/index')
def index():
user = {'nickname': 'Miguel'}
posts = [
    {'author': {'nickname': 'John'}, 'body': 'Beautiful day in Portland!'},
    {'author': {'nickname': 'Susan'}, 'body': 'The Avengers movie was so
cool!'}
]
return render_template("index.html", title='Home', user=user, posts=posts)

@app.route('/postAnonComment', methods=['POST'])
def SaveDetails():
userName = request.form['user_name']
userMail = request.form['user_mail']
userMessage = request.form['user_message']

newDictionaryItem = newDictionaryItem = "{'author': {'nickname': '{}'},
'body': '{}'}".format(userName, userMessage)
posts.append(dict(newDictionaryItem))

return render_template('index.html', user=userName, posts=posts)

# start the server with the 'run()' method
if __name__ == '__main__':
app.run(debug=True)
</code>```

答:
Making a string representation of dict and trying to make dict out of it is inefficient, when you can directly do it.

```<code>newDictionaryItem = {
    'author': {'nickname': userName},
    'body': userMessage,
}
posts.append(newDictionaryItem)
</code>```

Body:
I keep getting a "ValueError: dictionary update sequence element #0 has length 1; 2 is required" when i try to post a new comment into the comments list

# import the Flask class from the flask module
from flask import Flask, render_template, request

# create the application object
app = Flask(__name__)

posts=[]

@app.route('/index')
def index():
user = {'nickname': 'Miguel'}
posts = [
    {'author': {'nickname': 'John'}, 'body': 'Beautiful day in Portland!'},
    {'author': {'nickname': 'Susan'}, 'body': 'The Avengers movie was so
cool!'}
]
return render_template("index.html", title='Home', user=user, posts=posts)

@app.route('/postAnonComment', methods=['POST'])
def SaveDetails():
userName = request.form['user_name']
userMail = request.form['user_mail']
userMessage = request.form['user_message']

newDictionaryItem = newDictionaryItem = "{'author': {'nickname': '{}'},
'body': '{}'}".format(userName, userMessage)
posts.append(dict(newDictionaryItem))

return render_template('index.html', user=userName, posts=posts)

# start the server with the 'run()' method
if __name__ == '__main__':
app.run(debug=True)

Body:
Making a string representation of dict and trying to make dict out of it is inefficient, when you can directly do it.

newDictionaryItem = {
    'author': {'nickname': userName},
    'body': userMessage,
}
posts.append(newDictionaryItem)


问:
nchor Link to Local File? (DEAD LINK not working in FireFox but in IE)
This Java code,

```<code>"<a href='file:///" + curBP.get_build_path() + "'>" + curBP.get_build_path() + "</a>"
</code>```

is outputted to the browser.

On the page, the HTML is:

```<code><a href="file:///\\path\to\shared\file">Shared File</a>
</code>```

However, it does not open the file. I've tried countless other combinations of slashes, but to no avail. In FireFox, it acts like a dead link and does not open the file. In IE, it works.

Any idea as to how to make it work in FireFox? Thanks!

答:
Bad news: Firefox has closed a security hole:

http://www.techlifeweb.com/firefox/2006/07/how-to-open-file-links-in-firefox-15.html

It requires the user to modify a local file to allow file:// urls.

Body:
This Java code,

"" + curBP.get_build_path() + ""

is outputted to the browser.

On the page, the HTML is:

Shared File

However, it does not open the file. I've tried countless other combinations of slashes, but to no avail. In FireFox, it acts like a dead link and does not open the file. In IE, it works.

Any idea as to how to make it work in FireFox? Thanks!


问:
Translate (curve path) + Scale animation Android

I want to translate a imageview in a curve while scaling it as it translates.

Ive gone through
Multiple posts like
https://stackoverflow.com/a/30254927/3518278
where i cant figure out how to compute my path variable

also
its mentioned here that android 5 provides basic curves in interpolars
https://stackoverflow.com/a/26591870/3518278
but they seem to have no effect.

My current code is

```<code>View view;
        ValueAnimator animator = ValueAnimator.ofFloat(0, 1); // values from 0 to 1
        animator.setDuration(5000); // 5 seconds duration from 0 to 1
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
        {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = ((Float) (animation.getAnimatedValue()))
                        .floatValue();
                // Set translation of your view here. Position can be calculated
                // out of value. This code should move the view in a half circle.
                img_fullscreen_drone.setTranslationX((float)(150.0 * Math.sin(value*Math.PI)));
                img_fullscreen_drone.setTranslationY((float)(150.0 * Math.cos(value*Math.PI)));
                img_fullscreen_drone.setScaleType(ImageView.ScaleType.CENTER);
                img_fullscreen_drone.animate().scaleX(0.5f).scaleY(0.5f).setDuration(5000).start();

            }
        });

        animator.start();
</code>```

this translates my view in a arc but after translation is complete scale starts,i want scale and translate along curve to happen toghether.

Any help will be appreicated

Thanks in Advance

答:
After fiddling with Joel's answer, I found out you could also use a ViewPropertyAnimator and write it all at once this way:

```<code>img_fullscreen_drone.setScaleType(ImageView.ScaleType.CENTER);
img_fullscreen_drone.animate()
  .setUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        float value = ((Float) (animation.getAnimatedValue()));
        // Set translation of your view here. Position can be calculated
        // out of value. This code should move the view in a half circle.
        img_fullscreen_drone.setTranslationX((float)(150.0 * Math.sin(value*Math.PI)));
        img_fullscreen_drone.setTranslationY((float)(150.0 * Math.cos(value*Math.PI)));
    }})
  .scaleX(0f).scaleY(0f)
  .setDuration(5000)
  .start();
</code>```

Not tested by I think it should work just fine.

Body:
I want to translate a imageview in a curve while scaling it as it translates.

Ive gone through
Multiple posts like
https://stackoverflow.com/a/30254927/3518278
where i cant figure out how to compute my path variable

also
its mentioned here that android 5 provides basic curves in interpolars
https://stackoverflow.com/a/26591870/3518278
but they seem to have no effect.

My current code is

View view;
        ValueAnimator animator = ValueAnimator.ofFloat(0, 1); // values from 0 to 1
        animator.setDuration(5000); // 5 seconds duration from 0 to 1
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
        {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = ((Float) (animation.getAnimatedValue()))
                        .floatValue();
                // Set translation of your view here. Position can be calculated
                // out of value. This code should move the view in a half circle.
                img_fullscreen_drone.setTranslationX((float)(150.0 * Math.sin(value*Math.PI)));
                img_fullscreen_drone.setTranslationY((float)(150.0 * Math.cos(value*Math.PI)));
                img_fullscreen_drone.setScaleType(ImageView.ScaleType.CENTER);
                img_fullscreen_drone.animate().scaleX(0.5f).scaleY(0.5f).setDuration(5000).start();

            }
        });

        animator.start();

this translates my view in a arc but after translation is complete scale starts,i want scale and translate along curve to happen toghether.

Any help will be appreicated

Thanks in Advance

Body:
After fiddling with Joel's answer, I found out you could also use a ViewPropertyAnimator and write it all at once this way:

img_fullscreen_drone.setScaleType(ImageView.ScaleType.CENTER);
img_fullscreen_drone.animate()
  .setUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        float value = ((Float) (animation.getAnimatedValue()));
        // Set translation of your view here. Position can be calculated
        // out of value. This code should move the view in a half circle.
        img_fullscreen_drone.setTranslationX((float)(150.0 * Math.sin(value*Math.PI)));
        img_fullscreen_drone.setTranslationY((float)(150.0 * Math.cos(value*Math.PI)));
    }})
  .scaleX(0f).scaleY(0f)
  .setDuration(5000)
  .start();

Not tested by I think it should work just fine.