问:
Date Filter Not Works on First Day of Month
```<code>I have one dropdown and two textbox on my page. Now i have to bind the value
based on dropdown value.

My question is when i am select This Week from dropdown that time it will
display wrong date when first date of month on second textbox.
</code>```

Look at the below example. It is working fine on other date of month but when
   select '07/01/2017' then it's display like this '01/06/2017' rather then
   '01/07/2017' on second textbox when we select This Week.

$(document).on("change","#selectDates",function() {
            var dropValue = document.getElementById('selectDates').value;
            //All
            if (dropValue == "1") {
                $('#txtDateFrom').val('');
                $('#txtDateTo').val('');
            }
                //Today
            else if (dropValue == "2") {
                var back_GTM = new Date();
                $('#txtDateFrom').val(Back_date(back_GTM));
                $('#txtDateTo').val(Back_date(back_GTM));

            }
                //This Week
            else if (dropValue == "3") {
                //var curr = new Date; // get current date
                var curr = new Date('07/01/2017'); // get current date
                var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
                var last = first + 6; // last day is the first day + 6

                var firstday = new Date(curr.setDate(first));
                var lastday = new Date(curr.setDate(last));

                $('#txtDateFrom').val(Back_date(firstday));
                $('#txtDateTo').val(Back_date(lastday));

            }
            });

            function Back_date(back_GTM) {
            var b_dd = back_GTM.getDate();
            var b_mm = back_GTM.getMonth() + 1;
            var b_yyyy = back_GTM.getFullYear();
            if (b_dd < 10) {
                b_dd = '0' + b_dd
            }
            if (b_mm < 10) {
                b_mm = '0' + b_mm
            }
            return back_date = b_dd + '/' + b_mm + '/' + b_yyyy;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-style">
                <select id="selectDates">
                    <option value="1" selected>All</option>
                    <option value="2">Today</option>
                    <option value="3">This Week</option>
                     </select>
            </div>
            <br />            <br />

            <div class="input-group input-large" data-date="13/07/2013" data-date-format="dd/mm/yyyy">
                <span class="input-group-addon">From</span>
                <input type="text" id="txtDateFrom" class="form-control dpd1" name="from">
                <span class="input-group-addon">To</span>
                <input type="text" id="txtDateTo" class="form-control dpd2" name="to">
            </div></code>```

答:
You should create two date objects for the cases where a week overlaps 2 months.

Because when you set the date to -5, from july 1st, 2017, it correctly calculates the date to sunday june 25th.

But now, the month has changed!

When you set the date to the last day of the week, which is 1, the month stays to june in the date object.

So having two different date objects to manipulate the dates separately is the fix.

$(document).on("change","#selectDates",function() {
  var dropValue = document.getElementById('selectDates').value;
  //All
  if (dropValue == "1") {
    $('#txtDateFrom').val('');
    $('#txtDateTo').val('');
  }
  //Today
  else if (dropValue == "2") {
    var back_GTM = new Date();
    $('#txtDateFrom').val(Back_date(back_GTM));
    $('#txtDateTo').val(Back_date(back_GTM));

  }
  //This Week
  else if (dropValue == "3") {
    //var curr = new Date; // get current date
    var curr = new Date('07/01/2017'); // get current date
    var curr2 = new Date('07/01/2017'); // get current date - Second date object.

    var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
    var last = first + 6; // last day is the first day + 6

    var firstday = new Date(curr.setDate(first));
    var lastday = new Date(curr2.setDate(last));

    $('#txtDateFrom').val(Back_date(firstday));
    $('#txtDateTo').val(Back_date(lastday));

  }
});

function Back_date(back_GTM) {
  var b_dd = back_GTM.getDate();
  var b_mm = back_GTM.getMonth() + 1;
  var b_yyyy = back_GTM.getFullYear();
  if (b_dd < 10) {
    b_dd = '0' + b_dd
  }
  if (b_mm < 10) {
    b_mm = '0' + b_mm
  }
  return back_date = b_dd + '/' + b_mm + '/' + b_yyyy;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="select-style">
  <select id="selectDates">
    <option value="1" selected>All</option>
    <option value="2">Today</option>
    <option value="3">This Week</option>
  </select>
</div>
<br />            <br />

<div class="input-group input-large" data-date="13/07/2013" data-date-format="dd/mm/yyyy">
  <span class="input-group-addon">From</span>
  <input type="text" id="txtDateFrom" class="form-control dpd1" name="from">
  <span class="input-group-addon">To</span>
  <input type="text" id="txtDateTo" class="form-control dpd2" name="to">
</div></code>```

Body:
I have one dropdown and two textbox on my page. Now i have to bind the value
based on dropdown value.

My question is when i am select This Week from dropdown that time it will
display wrong date when first date of month on second textbox.

Look at the below example. It is working fine on other date of month but when
   select '07/01/2017' then it's display like this '01/06/2017' rather then
   '01/07/2017' on second textbox when we select This Week.

$(document).on("change","#selectDates",function() {
            var dropValue = document.getElementById('selectDates').value;
            //All
            if (dropValue == "1") {
                $('#txtDateFrom').val('');
                $('#txtDateTo').val('');
            }
                //Today
            else if (dropValue == "2") {
                var back_GTM = new Date();
                $('#txtDateFrom').val(Back_date(back_GTM));
                $('#txtDateTo').val(Back_date(back_GTM));

            }
                //This Week
            else if (dropValue == "3") {
                //var curr = new Date; // get current date
                var curr = new Date('07/01/2017'); // get current date
                var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
                var last = first + 6; // last day is the first day + 6

                var firstday = new Date(curr.setDate(first));
                var lastday = new Date(curr.setDate(last));

                $('#txtDateFrom').val(Back_date(firstday));
                $('#txtDateTo').val(Back_date(lastday));

            }
            });

            function Back_date(back_GTM) {
            var b_dd = back_GTM.getDate();
            var b_mm = back_GTM.getMonth() + 1;
            var b_yyyy = back_GTM.getFullYear();
            if (b_dd < 10) {
                b_dd = '0' + b_dd
            }
            if (b_mm < 10) {
                b_mm = '0' + b_mm
            }
            return back_date = b_dd + '/' + b_mm + '/' + b_yyyy;
        }

                <select id="selectDates">
                    <option value="1" selected>All</option>
                    <option value="2">Today</option>
                    <option value="3">This Week</option>
                     </select>

                From
                <input type="text" id="txtDateFrom" class="form-control dpd1" name="from">
                To
                <input type="text" id="txtDateTo" class="form-control dpd2" name="to">

Body:
You should create two date objects for the cases where a week overlaps 2 months.

Because when you set the date to -5, from july 1st, 2017, it correctly calculates the date to sunday june 25th.

But now, the month has changed!

When you set the date to the last day of the week, which is 1, the month stays to june in the date object.

So having two different date objects to manipulate the dates separately is the fix.

$(document).on("change","#selectDates",function() {
  var dropValue = document.getElementById('selectDates').value;
  //All
  if (dropValue == "1") {
    $('#txtDateFrom').val('');
    $('#txtDateTo').val('');
  }
  //Today
  else if (dropValue == "2") {
    var back_GTM = new Date();
    $('#txtDateFrom').val(Back_date(back_GTM));
    $('#txtDateTo').val(Back_date(back_GTM));

  }
  //This Week
  else if (dropValue == "3") {
    //var curr = new Date; // get current date
    var curr = new Date('07/01/2017'); // get current date
    var curr2 = new Date('07/01/2017'); // get current date - Second date object.

    var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
    var last = first + 6; // last day is the first day + 6

    var firstday = new Date(curr.setDate(first));
    var lastday = new Date(curr2.setDate(last));

    $('#txtDateFrom').val(Back_date(firstday));
    $('#txtDateTo').val(Back_date(lastday));

  }
});

function Back_date(back_GTM) {
  var b_dd = back_GTM.getDate();
  var b_mm = back_GTM.getMonth() + 1;
  var b_yyyy = back_GTM.getFullYear();
  if (b_dd < 10) {
    b_dd = '0' + b_dd
  }
  if (b_mm < 10) {
    b_mm = '0' + b_mm
  }
  return back_date = b_dd + '/' + b_mm + '/' + b_yyyy;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="select-style">
  <select id="selectDates">
    <option value="1" selected>All</option>
    <option value="2">Today</option>
    <option value="3">This Week</option>
  </select>
</div>
<br />            <br />

<div class="input-group input-large" data-date="13/07/2013" data-date-format="dd/mm/yyyy">
  <span class="input-group-addon">From</span>
  <input type="text" id="txtDateFrom" class="form-control dpd1" name="from">
  <span class="input-group-addon">To</span>
  <input type="text" id="txtDateTo" class="form-control dpd2" name="to">
</div>


来源: stackexchange

问:
Syntax highlighting for .ctp files with Netbeans+ Cakephp in Mac OS
I code Cakephp with Netbeans in Mac Os. My syntaxs in .ctp file doesn't highlighted(colored). I found the answer but only for Windows :( . How can I do for Mac? Tks!</p>

答:
Go to Tools > Options > Miscellaneous > Files

Select File Extension = 'ctp' - (create one from the new button if the extension doesn't exist in the drop down list already)

Select Associated File Type (MIME) = PHP files

Hope that it will work for you.

ContentLicense: CC BY-SA 3.0


问:
Installing Miniconda2 Non-Interactively
Is it possible to send multiple responses in sequence to an installation script? Specifically if the install script wants you to press enter, then Q, then yes, like in this post: install miniconda.

I tried piping stuff together, but since I'm pretty unfamiliar with bash scripting, I probably just messed it up or took the wrong approach.

EDIT:

I tried to write an expect script, but it hangs as shown in the picture below the script.

```<code>#!/usr/bin/expect -f
spawn ~/Miniconda-latest-Linux-x86_64.sh
set timeout -1
expect "$ "
send "\r"
expect "Welcome "
send "Q"
expect "? "
send "yes"
</code>```

答:
You're looking for expect:

Expect is a program that "talks" to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be. An interpreted language provides branching and high-level control structures to direct the dialogue. In addition, the user can take control and interact directly when desired, afterward returning control to the script.

Edit: Looking at the screenshot it's asking you to "press ENTER to continue" which I don't see in your script. You have send "\r" but that's not normally what Enter sends. On Windows it would send /r/n and on Linux it sends /n. Give that a try.

Title: Installing Miniconda2 Non-Interactively

Body:
Is it possible to send multiple responses in sequence to an installation script? Specifically if the install script wants you to press enter, then Q, then yes, like in this post: install miniconda.

I tried piping stuff together, but since I'm pretty unfamiliar with bash scripting, I probably just messed it up or took the wrong approach.

EDIT:

I tried to write an expect script, but it hangs as shown in the picture below the script.

#!/usr/bin/expect -f
spawn ~/Miniconda-latest-Linux-x86_64.sh
set timeout -1
expect "$ "
send "\r"
expect "Welcome "
send "Q"
expect "? "
send "yes"


问:
How to create unique entry in database for new userId?
I have customer table where I wanted to store a customer with a cusomerNumber Like

customers table:

```<code>name   cusomerNumber
john   3456
doe    3457
russel 3458
mathew 3459
</code>```

Now if John comes again instead of giving new cusomerNumber i will assign the old one means 3456
and for the new one should be 3460
But if i go increment process like for new entry cusomerNumber + 1

for new customer after john would be assign as 3457 but which has already in database. How do i make it possible to set 3460 instead of 3457 ..

I have followed the following process which usually increment with 1 with the existing one.

```<code>    $customerId = DB::table('customers')
                    ->select('customers.*')
                    ->orderBy('id', 'desc')->first();
    $customer = new Customer();
    $customer->cusomerNumber = $request->Input(['cusomerNumber']) ?: $customerId->cusomerNumber+1;
</code>```

答:
If your uniqueID field is set as auto-increment, you don't have to worry about it. Let the table create the IDs on it's own, don't do it with code. What I've described is the standard practice.

Also, it's generally accepted that the uniqueID field is the first field and you should just call it 'id'

Body:
I have customer table where I wanted to store a customer with a cusomerNumber Like

customers table:

name   cusomerNumber
john   3456
doe    3457
russel 3458
mathew 3459

Now if John comes again instead of giving new cusomerNumber i will assign the old one means 3456
and for the new one should be 3460
But if i go increment process like for new entry cusomerNumber + 1

for new customer after john would be assign as 3457 but which has already in database. How do i make it possible to set 3460 instead of 3457 ..

I have followed the following process which usually increment with 1 with the existing one.

    $customerId = DB::table('customers')
                    ->select('customers.*')
                    ->orderBy('id', 'desc')->first();
    $customer = new Customer();
    $customer->cusomerNumber = $request->Input(['cusomerNumber']) ?: $customerId->cusomerNumber+1;


问:
MVC .NET using Html.EditorFor in my controller
I'm using Custom Editor Templates in my view, and I would to know if is possible to obtain the same result from my controller.

```<code><%: Html.EditorFor(model => model.Book) %>
</code>```

Does anyone knows if it's possible?

答:
I found a possible solution:

add an user control and call Html.EditorFor(model => model.Book) inside.
Then in my controller I just have to call View(usercontrol,model)

Does anyone have a better idea?

ContentLicense: CC BY-SA 2.5

Body:
I'm using Custom Editor Templates in my view, and I would to know if is possible to obtain the same result from my controller.

<%: Html.EditorFor(model => model.Book) %>

Does anyone knows if it's possible?


问:
I need user input to tell the program which list to use?
So i'm pretty new to python and i'm making a hangman program.  Here is the code I have so far.

```<code>import random
print('Welcome to hangman')
print('Type one of the following categories')
Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Storms']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']
print('Animal, Clothing, Weather, Colors')

category=input()
randomwordindex=random.randint(1,7)
</code>```

Where it says category=input() I want the user input to be one of the lists I have above.  Then I can use category with an random integer to pick a random word to start the game.  How do I get the input() to be the list and not a string value?

Edit: Okay I got it thanks guys.

Here is the code that I have currently.  I'll probably add a for loop eventually and clean up my while loop so it's one line.

```<code>import random

print('Welcome to hangman')
print('Type one of the following categories')

Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Stormy']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']

print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')

category=int(input())

while category > 4:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

while category == 0:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

if category == 1: secretword=random.choice(Animal)
if category == 2: secretword=random.choice(Clothing)
if category == 3: secretword=random.choice(Weather)
if category == 4: secretword=random.choice(Colors)
</code>```

now the variable secretword stores the word that is randomly chosen from the list.

答:
You can use a dictionary to map your lists to specific values. That way, you can accesses a category, programaticlly:

```<code>>>> categories = {
    'animal': ['Cat','Dog','Bird','Cow','Fish','Lizard'],
    'clothing': ['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf'],
    'weather': ['Rain','Snow','Sunny','Sleet','Windy','Storms'],
    'colors': ['Red','Blue','Green','Purple','Yellow','Grey'],
    }
>>>
>>> catagory = input()
animal
>>> categories[catagory]
['Cat', 'Dog', 'Bird', 'Cow', 'Fish', 'Lizard']
>>>
</code>```

Also, you should use random.choice() instead to get a random element from the list:

```<code>>>> from random import choice
>>> choice(categories[catagory])
'Fish'
>>>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So i'm pretty new to python and i'm making a hangman program.  Here is the code I have so far.

import random
print('Welcome to hangman')
print('Type one of the following categories')
Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Storms']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']
print('Animal, Clothing, Weather, Colors')

category=input()
randomwordindex=random.randint(1,7)

Where it says category=input() I want the user input to be one of the lists I have above.  Then I can use category with an random integer to pick a random word to start the game.  How do I get the input() to be the list and not a string value?

Edit: Okay I got it thanks guys.

Here is the code that I have currently.  I'll probably add a for loop eventually and clean up my while loop so it's one line.

import random

print('Welcome to hangman')
print('Type one of the following categories')

Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Stormy']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']

print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')

category=int(input())

while category > 4:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

while category == 0:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

if category == 1: secretword=random.choice(Animal)
if category == 2: secretword=random.choice(Clothing)
if category == 3: secretword=random.choice(Weather)
if category == 4: secretword=random.choice(Colors)

now the variable secretword stores the word that is randomly chosen from the list.

Body:
You can use a dictionary to map your lists to specific values. That way, you can accesses a category, programaticlly:

>>> categories = {
    'animal': ['Cat','Dog','Bird','Cow','Fish','Lizard'],
    'clothing': ['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf'],
    'weather': ['Rain','Snow','Sunny','Sleet','Windy','Storms'],
    'colors': ['Red','Blue','Green','Purple','Yellow','Grey'],
    }
>>>
>>> catagory = input()
animal
>>> categories[catagory]
['Cat', 'Dog', 'Bird', 'Cow', 'Fish', 'Lizard']
>>>

Also, you should use random.choice() instead to get a random element from the list:

>>> from random import choice
>>> choice(categories[catagory])
'Fish'
>>>


问:
summernote icons not showing in line
i work with sommernote editor. i getting problem with sommernote icons.
here is the image.

i want all icon in one line.

here is my code

```<code>$('.summernote').summernote({
    toolbar: [
        // [groupName, [list of button]]
        ['style', ['bold', 'italic', 'underline', 'clear']],
        ['fontsize', ['fontsize']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['insert', ['link','hr']],
        ['Misc',['fullscreen','help']]
    ]
    });
</code>```

答: the problem is bootstrap.css and summurnote.css is overriding.</p>

Title: summernote icons not showing in line

Body:
i work with sommernote editor. i getting problem with sommernote icons.
here is the image.

i want all icon in one line.

here is my code

$('.summernote').summernote({
    toolbar: [
        // [groupName, [list of button]]
        ['style', ['bold', 'italic', 'underline', 'clear']],
        ['fontsize', ['fontsize']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['insert', ['link','hr']],
        ['Misc',['fullscreen','help']]
    ]
    });


问:
AppInviteReferral is deprecated. Is there an alternative?
I am following the Firebase invite tutorial from https://developers.google.com/android/reference/com/google/android/gms/appinvite/AppInviteInvitation.IntentBuilder

A lot of code is relying on deprecated classes. Is there a alternative 'new' classes and apis.

答:
You just have to take a look at the docs:

This class was deprecated.

Use FirebaseAppInvite, returned by
  getInvitation(com.google.firebase.dynamiclinks.PendingDynamicLinkData),
  which holds the deep link and invitation id.


问:
How do I check for token expiration and logout user?
The user can logout himself when he/she clicks on the logout button but if the token is expired he/she cant logout because in my application, the token is used in both server side and front end. When user clicks on the logout button, the token from both server and browser is cleared if token is valid. There is a chance that when user does not log out and his/her token expires but is not being cleared in the browser. For addressing this situation, how do I check for token expiration every time the user visits in my app so if the token is expired, clear the token from the browser?

I tried in saga which watches in the background every time the user refreshes in the page or switch to another page. I don't think this is an efficient way. I reckon middleware comes into play.

```<code>function* loadInitialActions() {
  var dateNow = new Date();
  console.log(jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat);
  const token =
    JSON.parse(localStorage.getItem("user")) &&
    JSON.parse(localStorage.getItem("user"))["token"];
  if (
    token &&
    jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat
  ) {
    yield put(LOGOUT_SUCCESS);
  }
}

function* initialize() {
  const watcher = yield fork(loadInitialActions);
  yield take([INITIALIZE_ERROR, INITIALIZE_SUCCESS]);
  yield cancel(watcher);
}

function* rootSaga() {
  console.log("rootSaga");
  yield takeLatest(INITIALIZE, initialize);
}
</code>```

So my question is how do I use the token expiration logic and logout user if token is expired from the middleware?

答:
You need to wrap the Main component with a HOC. The HOC will validate the token and if OK allow the component to display. If the token is invalid, the login page is redirected to. </p>

```<code>const authChecker = (Component) => {
  return class extends React.Component {
    state = {
      show: false;
    }

    componentWillReceiveProps(nextProps) {
      if (nextProps.children !== this.props.children) {
        this.checkAuth();
      }
    }

    componentDidMount() {
      this.checkAuth();
    }

    checkAuth() {
      Api.checkAuth()
      .then(result => {
        if (result.success) {
          this.setState({ show: true });
        } else {
          // logout since token expired
          API.logout();
        }
      });
    }

    render() {
      return this.state.show && <Component {...this.props} />
    }
  }
}

export default authChecker(Main);
</code>```

Body:
The user can logout himself when he/she clicks on the logout button but if the token is expired he/she cant logout because in my application, the token is used in both server side and front end. When user clicks on the logout button, the token from both server and browser is cleared if token is valid. There is a chance that when user does not log out and his/her token expires but is not being cleared in the browser. For addressing this situation, how do I check for token expiration every time the user visits in my app so if the token is expired, clear the token from the browser?

I tried in saga which watches in the background every time the user refreshes in the page or switch to another page. I don't think this is an efficient way. I reckon middleware comes into play.

function* loadInitialActions() {
  var dateNow = new Date();
  console.log(jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat);
  const token =
    JSON.parse(localStorage.getItem("user")) &&
    JSON.parse(localStorage.getItem("user"))["token"];
  if (
    token &&
    jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat
  ) {
    yield put(LOGOUT_SUCCESS);
  }
}

function* initialize() {
  const watcher = yield fork(loadInitialActions);
  yield take([INITIALIZE_ERROR, INITIALIZE_SUCCESS]);
  yield cancel(watcher);
}

function* rootSaga() {
  console.log("rootSaga");
  yield takeLatest(INITIALIZE, initialize);
}

So my question is how do I use the token expiration logic and logout user if token is expired from the middleware?

Body:
You need to wrap the Main component with a HOC. The HOC will validate the token and if OK allow the component to display. If the token is invalid, the login page is redirected to.

const authChecker = (Component) => {
  return class extends React.Component {
    state = {
      show: false;
    }

    componentWillReceiveProps(nextProps) {
      if (nextProps.children !== this.props.children) {
        this.checkAuth();
      }
    }

    componentDidMount() {
      this.checkAuth();
    }

    checkAuth() {
      Api.checkAuth()
      .then(result => {
        if (result.success) {
          this.setState({ show: true });
        } else {
          // logout since token expired
          API.logout();
        }
      });
    }

    render() {
      return this.state.show && <Component {...this.props} />
    }
  }
}

export default authChecker(Main);


问:
jquery autocomplete: works for first value, how to enable it for next?
I'm using autocomplete so user can easly enter data on inputs, like this:

```<code> <?
$a = new etiqueta(0, '');
$b = $a->autocomplete_etiquetas();
?>
<script type="text/javascript">
    function cargar_autocomplete_etiquetas(){
        $("#tags").autocomplete({
            source: [<? echo $b; ?>]
        });
    }
</script>
</code>```

$a =  $b its an  array  with a result like:  'help','please',i','need','to,'be able to', 'select next item',' with autocomplete';

and i checked the ui documentation, but it doesn't fith with my source method.. any idea?
I'm trying like this (edited with Bugai13 aportation):

```<code> <?
$a = new etiqueta(0, '');
$b = $a->autocomplete_etiquetas();
?>
<script type="text/javascript">
    function cargar_autocomplete_etiquetas(){
    $("#tags").autocomplete({
        source: [<? echo $b; ?>],
        multiple: true,
        multipleSeparator: ", ",
        matchContains: true
    });
}

</script>
</code>```

but i don't know how to do it.. any idea? are .push and .pop functions from the autocomplete? or shall i define, them?

thanks again!

PS: i'm getting adicted to this site!
PS: come on dudes, i think the answer will be very usefull for many people
PS: is it allowed to offer paypal reward?

答:
I've use following to get work multiple autocomplete for tags with ',' separator, hope this help your:

It's full my code that work. In my case in parse function items it just json array, try to  add parse method:

```<code>   $("#txtTags").autocomplete(UrlFactory.TAGS_AUTOCOMPLETE_URL, {
    matchContains: true,
    width: 320,
    max: 10,
    highlight: false,
    multiple: true,
    multipleSeparator: ", ",
    scroll: true,
    scrollHeight: 300,
    dataType: "json",
    parse: function (data) {
        var result = Result.fromJson(data);

        var items = result.getJson("Tags");
        var arr;
        if (items != null)
            arr = items.split(",");
        return $.map(arr, function (row, i) {
            return {
                data: row,
                value: row,
                result: row
            }
        });
    },
    onItemSelect: function () {

    },
    formatItem: function (data, i, n, value) {
        if (value != null) {
            value = ltrim(value);
            value = rtrim(value);
        }
        return value;
    }
});
</code>```

So, you need something like this:

```<code>function cargar_autocomplete_etiquetas(){
    $("#tags").autocomplete({
        source: [<? echo $b; ?>],
        multiple: true,
        multipleSeparator: ", ",
        matchContains: true
    });
}
</code>```

Body:
I'm using autocomplete so user can easly enter data on inputs, like this:

 <?
$a = new etiqueta(0, '');
$b = $a->autocomplete_etiquetas();
?>

$a =  $b its an  array  with a result like:  'help','please',i','need','to,'be able to', 'select next item',' with autocomplete';

and i checked the ui documentation, but it doesn't fith with my source method.. any idea?
I'm trying like this (edited with Bugai13 aportation):

 <?
$a = new etiqueta(0, '');
$b = $a->autocomplete_etiquetas();
?>

but i don't know how to do it.. any idea? are .push and .pop functions from the autocomplete? or shall i define, them?

thanks again!

PS: i'm getting adicted to this site!
PS: come on dudes, i think the answer will be very usefull for many people
PS: is it allowed to offer paypal reward?

Body:
I've use following to get work multiple autocomplete for tags with ',' separator, hope this help your:

It's full my code that work. In my case in parse function items it just json array, try to  add parse method:

   $("#txtTags").autocomplete(UrlFactory.TAGS_AUTOCOMPLETE_URL, {
    matchContains: true,
    width: 320,
    max: 10,
    highlight: false,
    multiple: true,
    multipleSeparator: ", ",
    scroll: true,
    scrollHeight: 300,
    dataType: "json",
    parse: function (data) {
        var result = Result.fromJson(data);

        var items = result.getJson("Tags");
        var arr;
        if (items != null)
            arr = items.split(",");
        return $.map(arr, function (row, i) {
            return {
                data: row,
                value: row,
                result: row
            }
        });
    },
    onItemSelect: function () {

    },
    formatItem: function (data, i, n, value) {
        if (value != null) {
            value = ltrim(value);
            value = rtrim(value);
        }
        return value;
    }
});

So, you need something like this:

function cargar_autocomplete_etiquetas(){
    $("#tags").autocomplete({
        source: [<? echo $b; ?>],
        multiple: true,
        multipleSeparator: ", ",
        matchContains: true
    });
}


问:
How can I reset the NSUserDefaults data in the iPhone simulator?
I've added NSUserDefaults data retrieval to my app, which is pretty nice. But for testing I would like to reset all the data I added to the defaults database, so that everything is in the state when the user launches the app the first time.

I tried to call:

```<code>[NSUserDefaults resetStandardUserDefaults];
</code>```

but that doesn't do anything. The defaults are still saved and can be retrieved.

答:
If you're doing this in a unittest, you may want to keep the state of your app in the current simulator instead of inadvertently wiping it every time you also run your unittests. One way to do this is to simply hang on to the old values for your app domain in setUp() and then restore them in tearDown():

```<code>class MyClass_Tests: XCTestCase {
    static let domainName = Bundle.main.bundleIdentifier!
    static var oldUserDefaults: [String : Any]?

    override class func setUp() {
        super.setUp()
        // Hang onto this so we don't inadvertently wipe the app's state while running tests.
        oldUserDefaults = UserDefaults.standard.persistentDomain(forName: domainName)
    }

    override class func tearDown() {
        // Restore the old values.
        UserDefaults.standard.setPersistentDomain(oldUserDefaults!, forName: domainName)
        super.tearDown()
    }

    override func setUp() {
        super.setUp()
        // Wipe the state for each test.
        UserDefaults.standard.removePersistentDomain(forName: MyClass_Tests.domainName)
    }

    override func tearDown() {
        super.tearDown()
    }
}
</code>```

Body:
I've added NSUserDefaults data retrieval to my app, which is pretty nice. But for testing I would like to reset all the data I added to the defaults database, so that everything is in the state when the user launches the app the first time.

I tried to call:

[NSUserDefaults resetStandardUserDefaults];

but that doesn't do anything. The defaults are still saved and can be retrieved.

Body:
If you're doing this in a unittest, you may want to keep the state of your app in the current simulator instead of inadvertently wiping it every time you also run your unittests. One way to do this is to simply hang on to the old values for your app domain in setUp() and then restore them in tearDown():

class MyClass_Tests: XCTestCase {
    static let domainName = Bundle.main.bundleIdentifier!
    static var oldUserDefaults: [String : Any]?

    override class func setUp() {
        super.setUp()
        // Hang onto this so we don't inadvertently wipe the app's state while running tests.
        oldUserDefaults = UserDefaults.standard.persistentDomain(forName: domainName)
    }

    override class func tearDown() {
        // Restore the old values.
        UserDefaults.standard.setPersistentDomain(oldUserDefaults!, forName: domainName)
        super.tearDown()
    }

    override func setUp() {
        super.setUp()
        // Wipe the state for each test.
        UserDefaults.standard.removePersistentDomain(forName: MyClass_Tests.domainName)
    }

    override func tearDown() {
        super.tearDown()
    }
}


问:
Remove border area in apache poi bar chart in excel
I created bar chart in excel file using apache poi. How can I remove border/margin outside the plotarea? The blue border area in the following image.

I added the blue part by editing the created excel file. Before the edit, it was white. Here is the function code that creates this graph:

```<code>    public void createBarChart(double[] values, boolean[] passed, String[] labels,
                           int Dx1, int Dy1, int Dx2, int Dy2,
                           int row1, int col1, int row2, int col2){
    Drawing drawing = sheet.createDrawingPatriarch();
    ClientAnchor anchor = drawing.createAnchor(Dx1, Dy1, Dx2, Dy2, col1, row1, col2, row2);
    Chart chart = drawing.createChart(anchor);

    CTChart ctChart = ((XSSFChart)chart).getCTChart();

    CTPlotArea ctPlotArea = ctChart.getPlotArea();
    CTBarChart ctBarChart = ctPlotArea.addNewBarChart();
    //CTBoolean ctBoolean = ctBarChart.addNewVaryColors();
    //ctBoolean.setVal(false);
    ctBarChart.addNewBarDir().setVal(STBarDir.COL);

    // Add the bars
    int length = values.length;
    for (int s = 0; s < length; s++) {
        CTBarSer ctBarSer = ctBarChart.addNewSer();
        CTSerTx ctSerTx = ctBarSer.addNewTx();
        ctSerTx.setV(labels[s]);
        ctBarSer.addNewIdx().setVal(s);

        CTNumDataSource ctNumDataSource = ctBarSer.addNewVal();
        CTNumData ctNumData = ctNumDataSource.addNewNumLit();
        ctNumData.addNewPtCount().setVal(1);
        CTNumVal ctNumVal = ctNumData.addNewPt();
        ctNumVal.setIdx(0);
        ctNumVal.setV("" + values[s]);

        //at least the border lines in Libreoffice Calc ;-)
        CTShapeProperties ctShapeProperties = ctBarSer.addNewSpPr();
        if(passed[s]) {
            // bar color, green: passed
            ctShapeProperties.addNewSolidFill().addNewSrgbClr().setVal(new byte[]{0, (byte)128, 0});
        }
        else {
            // bar color, red: failed
            ctShapeProperties.addNewSolidFill().addNewSrgbClr().setVal(new byte[]{(byte) 255, 0, 0});
        }
        //ctShapeProperties.addNewLn().addNewSolidFill().addNewSrgbClr().setVal(new byte[]{0, 0, 0}); // black
        ctShapeProperties.addNewLn().addNewSolidFill().addNewSrgbClr().setVal(new byte[]{(byte)255, (byte)255, (byte)255}); // white
    }

    //telling the BarChart that it has axes and giving them Ids

    ctBarChart.addNewAxId().setVal(123456);
    ctBarChart.addNewAxId().setVal(123457);

    //cat axis
    CTCatAx ctCatAx = ctPlotArea.addNewCatAx();
    ctCatAx.addNewAxId().setVal(123456); //id of the cat axis
    CTScaling ctScaling = ctCatAx.addNewScaling();
    ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX);
    ctCatAx.addNewDelete().setVal(true);
    ctCatAx.addNewAxPos().setVal(STAxPos.B);
    ctCatAx.addNewCrossAx().setVal(123457); //id of the val axis
    ctCatAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO);

    //val axis
    CTValAx ctValAx = ctPlotArea.addNewValAx();
    ctValAx.addNewAxId().setVal(123457); //id of the val axis
    ctScaling = ctValAx.addNewScaling();
    ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX);
    ctValAx.addNewDelete().setVal(true);
    ctValAx.addNewAxPos().setVal(STAxPos.L);
    ctValAx.addNewCrossAx().setVal(123456); //id of the cat axis
    ctValAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO);

    // Remove rounded corner
    if (((XSSFChart)chart).getCTChartSpace().getRoundedCorners() == null){
        ((XSSFChart)chart).getCTChartSpace().addNewRoundedCorners();
    }

    ((XSSFChart)chart).getCTChartSpace().getRoundedCorners().setVal(false);
    //chart area (chartspace) without border line
    ((XSSFChart)chart).getCTChartSpace().addNewSpPr().addNewLn().addNewNoFill();

}
</code>```

答:
At first, I suspect you are creating a XSSFChart.

How have you set this thick blue border? Normally there is a thin blue border having rounded corners by default. How get rid of the rounded corners is answered already: Changing the shape of chart generated by apache poi for excel sheet.

But if you wants to format the border, then you need to know that the CTChartSpace has CTShapeProperties.

So:

```<code>...
        Drawing drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 8, 20);

        Chart chart = drawing.createChart(anchor);

//chart area (chartspace) without border line
((XSSFChart)chart).getCTChartSpace().addNewSpPr().addNewLn().addNewNoFill();
...
</code>```

Maybe the border around the plot area and the gap between plot area and chart area shall be removed, then:

```<code>...
        CTPlotArea ctPlotArea = ctChart.getPlotArea();
ctPlotArea.addNewSpPr().addNewLn().addNewNoFill();
org.openxmlformats.schemas.drawingml.x2006.chart.CTManualLayout ctManualLayout = ctPlotArea.getLayout().addNewManualLayout();
ctManualLayout.addNewX().setVal(0);
ctManualLayout.addNewY().setVal(0);
ctManualLayout.addNewW().setVal(1);
ctManualLayout.addNewH().setVal(1);
...
</code>```

Body:
I created bar chart in excel file using apache poi. How can I remove border/margin outside the plotarea? The blue border area in the following image.

I added the blue part by editing the created excel file. Before the edit, it was white. Here is the function code that creates this graph:

    public void createBarChart(double[] values, boolean[] passed, String[] labels,
                           int Dx1, int Dy1, int Dx2, int Dy2,
                           int row1, int col1, int row2, int col2){
    Drawing drawing = sheet.createDrawingPatriarch();
    ClientAnchor anchor = drawing.createAnchor(Dx1, Dy1, Dx2, Dy2, col1, row1, col2, row2);
    Chart chart = drawing.createChart(anchor);

    CTChart ctChart = ((XSSFChart)chart).getCTChart();

    CTPlotArea ctPlotArea = ctChart.getPlotArea();
    CTBarChart ctBarChart = ctPlotArea.addNewBarChart();
    //CTBoolean ctBoolean = ctBarChart.addNewVaryColors();
    //ctBoolean.setVal(false);
    ctBarChart.addNewBarDir().setVal(STBarDir.COL);

    // Add the bars
    int length = values.length;
    for (int s = 0; s < length; s++) {
        CTBarSer ctBarSer = ctBarChart.addNewSer();
        CTSerTx ctSerTx = ctBarSer.addNewTx();
        ctSerTx.setV(labels[s]);
        ctBarSer.addNewIdx().setVal(s);

        CTNumDataSource ctNumDataSource = ctBarSer.addNewVal();
        CTNumData ctNumData = ctNumDataSource.addNewNumLit();
        ctNumData.addNewPtCount().setVal(1);
        CTNumVal ctNumVal = ctNumData.addNewPt();
        ctNumVal.setIdx(0);
        ctNumVal.setV("" + values[s]);

        //at least the border lines in Libreoffice Calc ;-)
        CTShapeProperties ctShapeProperties = ctBarSer.addNewSpPr();
        if(passed[s]) {
            // bar color, green: passed
            ctShapeProperties.addNewSolidFill().addNewSrgbClr().setVal(new byte[]{0, (byte)128, 0});
        }
        else {
            // bar color, red: failed
            ctShapeProperties.addNewSolidFill().addNewSrgbClr().setVal(new byte[]{(byte) 255, 0, 0});
        }
        //ctShapeProperties.addNewLn().addNewSolidFill().addNewSrgbClr().setVal(new byte[]{0, 0, 0}); // black
        ctShapeProperties.addNewLn().addNewSolidFill().addNewSrgbClr().setVal(new byte[]{(byte)255, (byte)255, (byte)255}); // white
    }

    //telling the BarChart that it has axes and giving them Ids

    ctBarChart.addNewAxId().setVal(123456);
    ctBarChart.addNewAxId().setVal(123457);

    //cat axis
    CTCatAx ctCatAx = ctPlotArea.addNewCatAx();
    ctCatAx.addNewAxId().setVal(123456); //id of the cat axis
    CTScaling ctScaling = ctCatAx.addNewScaling();
    ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX);
    ctCatAx.addNewDelete().setVal(true);
    ctCatAx.addNewAxPos().setVal(STAxPos.B);
    ctCatAx.addNewCrossAx().setVal(123457); //id of the val axis
    ctCatAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO);

    //val axis
    CTValAx ctValAx = ctPlotArea.addNewValAx();
    ctValAx.addNewAxId().setVal(123457); //id of the val axis
    ctScaling = ctValAx.addNewScaling();
    ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX);
    ctValAx.addNewDelete().setVal(true);
    ctValAx.addNewAxPos().setVal(STAxPos.L);
    ctValAx.addNewCrossAx().setVal(123456); //id of the cat axis
    ctValAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO);

    // Remove rounded corner
    if (((XSSFChart)chart).getCTChartSpace().getRoundedCorners() == null){
        ((XSSFChart)chart).getCTChartSpace().addNewRoundedCorners();
    }

    ((XSSFChart)chart).getCTChartSpace().getRoundedCorners().setVal(false);
    //chart area (chartspace) without border line
    ((XSSFChart)chart).getCTChartSpace().addNewSpPr().addNewLn().addNewNoFill();

}

Body:
At first, I suspect you are creating a XSSFChart.

How have you set this thick blue border? Normally there is a thin blue border having rounded corners by default. How get rid of the rounded corners is answered already: Changing the shape of chart generated by apache poi for excel sheet.

But if you wants to format the border, then you need to know that the CTChartSpace has CTShapeProperties.

So:

...
        Drawing drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 8, 20);

        Chart chart = drawing.createChart(anchor);

//chart area (chartspace) without border line
((XSSFChart)chart).getCTChartSpace().addNewSpPr().addNewLn().addNewNoFill();
...

Maybe the border around the plot area and the gap between plot area and chart area shall be removed, then:

...
        CTPlotArea ctPlotArea = ctChart.getPlotArea();
ctPlotArea.addNewSpPr().addNewLn().addNewNoFill();
org.openxmlformats.schemas.drawingml.x2006.chart.CTManualLayout ctManualLayout = ctPlotArea.getLayout().addNewManualLayout();
ctManualLayout.addNewX().setVal(0);
ctManualLayout.addNewY().setVal(0);
ctManualLayout.addNewW().setVal(1);
ctManualLayout.addNewH().setVal(1);
...


问:
How to only build one directory in a Jenkins multi-branch pipeline job?
I have a github repo called multibranch-test with two sub-directories Project1, Project2.

PS C:\Repos\multibranch-test> tree .
Folder PATH listing for volume Windows
Volume serial number is 2085-6D3D
C:\REPOS\MULTIBRANCH-TEST
├───Project1
└───Project2

Each sub-directory has a Jenkinsfile and the code for that project.

In Jenkins I have two multibranch pipeline jobs - one for Project1 and one for Project2. In the configuration for Project1 I don't want a push notification or polling to build Project1 if a commit was pushed in sub-directory for Project2.

So in Project1 I have configured Additional Behaviours:

Advanced clone behaviours: Shallow clone is checked

Sparse checkout path is set to Project1#

Polling ignores commits in certain paths

Included Regions: Project1/*

Excluded Regions: *

Build Configuration: Script Path: Project1/Jenkinsfile

What is happening is if I push a commit to master in sub-directory Project2, both Project1 and Project2 jobs get built. I only want Project2 to build. Can someone point out what I'm doing wrong?

Jenkinsfiles for both Projects are similar and look like:

```<code>#!groovy
node  {
    stage ('checkout') {
        checkout scm
    }

    stage ('build') {
        dir ('Project1') {
            bat 'powershell -Command gci'
            bat 'powershell -Command gci env:'
            bat 'powershell -File .\\Project1.ps1'
        }
    }
</code>```

答:
Default Jenkins behavior is that projects get rebuilt if their repo gets a commit, so your commit in repo generates event for both Jenkins projects and triggers both builds. Take a look on Jenkins docs: https://jenkins.io/doc/book/pipeline/

From Jenkins point of view it's hard to tell if change went into project 1 or 2 - what is immediately visible is "new commit to watched repo".

Simples solution would be to split repo into two separate repos one for each project. Since they are supposed to build separately it shouldn't be a problem.

Body:
I have a github repo called multibranch-test with two sub-directories Project1, Project2.

PS C:\Repos\multibranch-test> tree .
Folder PATH listing for volume Windows
Volume serial number is 2085-6D3D
C:\REPOS\MULTIBRANCH-TEST
├───Project1
└───Project2

Each sub-directory has a Jenkinsfile and the code for that project.

In Jenkins I have two multibranch pipeline jobs - one for Project1 and one for Project2. In the configuration for Project1 I don't want a push notification or polling to build Project1 if a commit was pushed in sub-directory for Project2.

So in Project1 I have configured Additional Behaviours:

Advanced clone behaviours: Shallow clone is checked

Sparse checkout path is set to Project1#

Polling ignores commits in certain paths

Included Regions: Project1/*

Excluded Regions: *

Build Configuration: Script Path: Project1/Jenkinsfile

What is happening is if I push a commit to master in sub-directory Project2, both Project1 and Project2 jobs get built. I only want Project2 to build. Can someone point out what I'm doing wrong?

Jenkinsfiles for both Projects are similar and look like:

#!groovy
node  {
    stage ('checkout') {
        checkout scm
    }

    stage ('build') {
        dir ('Project1') {
            bat 'powershell -Command gci'
            bat 'powershell -Command gci env:'
            bat 'powershell -File .\\Project1.ps1'
        }
    }


问:
Building expression trees combining two functions to a composite function
I got the following:

```<code> Expression<Func<double, double, double>> XTCylinderVolume =
                (r, h) => 3.14  * r * r * h;
 Expression<Func<double, double>> cubed =    (V) => V  * V * V ;
</code>```

I can combine them to building a composite function call it fgCompiled.

```<code> var cubedC = cubed.Compile();
 Func<double, double, double> fgComplied = (r, h) => cubedC(XTCylinderVolume.Compile()(r, h));

  fgCompiled(2,1)
 //answer = 1981.385..;
</code>```

How can I get an Expression fg  that is not compiled so that fg.ToString() would read like

```<code>=> (3.14 * r * r * h ) * ( 3.14 * r * r * h ) * (3.14 * r * r * h)
</code>```

or hopefully neater but that would be a start.

Is there a way to decompiled a compiled function back to an expression?

答:
Using Thomas Levesque's visitor implementation, single-parameter lambda composition can be generalized.</p>

```<code>public static Expression<Func<TSource, TFinal>>
  CompositeExpression<TSource, TInner, TFinal>
  (
    this Expression<Func<TInner, TFinal>> outerlambda,
    Expression<Func<TSource, TInner>> innerlambda)
{
  var visitor = new ParameterReplacementVisitor(outerlambda.Parameters[0], innerlambda.Body);
  var expandedOuter = visitor.Visit(outerlambda.Body);

  var composite =
    Expression.Lambda<Func<TSource, TFinal>>(
      expandedOuter,
      innerlambda.Parameters);
  return composite;
}
</code>```

Body:
I got the following:

 Expression<Func<double, double, double>> XTCylinderVolume =
                (r, h) => 3.14  * r * r * h;
 Expression<Func<double, double>> cubed =    (V) => V  * V * V ;

I can combine them to building a composite function call it fgCompiled.

 var cubedC = cubed.Compile();
 Func<double, double, double> fgComplied = (r, h) => cubedC(XTCylinderVolume.Compile()(r, h));

  fgCompiled(2,1)
 //answer = 1981.385..;

How can I get an Expression fg  that is not compiled so that fg.ToString() would read like

=> (3.14 * r * r * h ) * ( 3.14 * r * r * h ) * (3.14 * r * r * h)

or hopefully neater but that would be a start.

Is there a way to decompiled a compiled function back to an expression?

Body:
Using Thomas Levesque's visitor implementation, single-parameter lambda composition can be generalized.

public static Expression<Func<TSource, TFinal>>
  CompositeExpression<TSource, TInner, TFinal>
  (
    this Expression<Func<TInner, TFinal>> outerlambda,
    Expression<Func<TSource, TInner>> innerlambda)
{
  var visitor = new ParameterReplacementVisitor(outerlambda.Parameters[0], innerlambda.Body);
  var expandedOuter = visitor.Visit(outerlambda.Body);

  var composite =
    Expression.Lambda<Func<TSource, TFinal>>(
      expandedOuter,
      innerlambda.Parameters);
  return composite;
}


问:
Using mclapply in a function in custom R package
I used R Studio to create a package using these two sites as guides:

https://support.rstudio.com/hc/en-us/articles/200486488-Developing-Packages-with-RStudio
https://www.r-bloggers.com/building-a-package-in-rstudio-is-actually-very-easy/

The only modification is when I created the package using R Studio I used the option to create an R package with Rcpp.

One of the functions in the package is the following:

```<code>GenerateSims = function(num.sim, alpha0, alpha1, beta1, gamma1, delta, n.sim, covariates, burnin, type)
{
  print("In GenerateSims")

  sims = mclapply(1:num.sim, function(z) {
    GenerateData(alpha0, alpha1, beta1, gamma1, delta, n.sim, covariates, burnin, type)
  },
  mc.cores = 35)

  print("Leaving GenerateSims...")
  return(sims)
}
</code>```

When mc.cores =  1 it runs fine. When I set mc.cores to something other than 1 the console prints out "In GenerateSims" but stops there as if it's in an infinite loop.

The function GenerateData only uses one function from a non base package gamlss.dist::rDPO.

My DESCRIPTION file is as follows (not sure if this helps identify the issue or not):

```<code>Package: Summer2017Package
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Author: Who wrote it
Maintainer: The package maintainer <yourself@somewhere.net>
Description: More about what it does (maybe more than one line)
    Use four spaces when indenting paragraphs within the Description.
License: What license is it under?
Encoding: UTF-8
LazyData: true
Imports: Rcpp (>= 0.12.9), gamlss.dist, parallel, moments, stats
LinkingTo: Rcpp
</code>```

EDIT: I am running this on a machine running Debian.

答: So I figured out that within the GenerateData function there was a print statement. I got rid of this and it fixed my issue. I also came across this post, Printing from mclapply in R Studio, that mentioned this isn't an issue when running an R script from the command line. So that's an easier fix than getting rid of my print statements.</p>

Body:
I used R Studio to create a package using these two sites as guides:

https://support.rstudio.com/hc/en-us/articles/200486488-Developing-Packages-with-RStudio
https://www.r-bloggers.com/building-a-package-in-rstudio-is-actually-very-easy/

The only modification is when I created the package using R Studio I used the option to create an R package with Rcpp.

One of the functions in the package is the following:

GenerateSims = function(num.sim, alpha0, alpha1, beta1, gamma1, delta, n.sim, covariates, burnin, type)
{
  print("In GenerateSims")

  sims = mclapply(1:num.sim, function(z) {
    GenerateData(alpha0, alpha1, beta1, gamma1, delta, n.sim, covariates, burnin, type)
  },
  mc.cores = 35)

  print("Leaving GenerateSims...")
  return(sims)
}

When mc.cores =  1 it runs fine. When I set mc.cores to something other than 1 the console prints out "In GenerateSims" but stops there as if it's in an infinite loop.

The function GenerateData only uses one function from a non base package gamlss.dist::rDPO.

My DESCRIPTION file is as follows (not sure if this helps identify the issue or not):

Package: Summer2017Package
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Author: Who wrote it
Maintainer: The package maintainer <yourself@somewhere.net>
Description: More about what it does (maybe more than one line)
    Use four spaces when indenting paragraphs within the Description.
License: What license is it under?
Encoding: UTF-8
LazyData: true
Imports: Rcpp (>= 0.12.9), gamlss.dist, parallel, moments, stats
LinkingTo: Rcpp

EDIT: I am running this on a machine running Debian.


问:
Sending mail via SMTP in Perl
I am trying to send mail via SMTP in Perl.

I have written a script for this.

```<code>#!perl
use warnings;
use strict;
use Net::SMTP;

my $smtpserver = 'server';
my $smtpport = 25;
my $smtpuser   = 'username';
my $smtppassword = 'password';

my $smtp = Net::SMTP->new($smtpserver, Port=>$smtpport, Timeout => 10, Debug => 1);
die "Could not connect to server!\n" unless $smtp;

$smtp->auth($smtpuser, $smtppassword);
$smtp->to('mymail@gmail.com');
$smtp->data();
$smtp->datasend("To: mymail\@gmail.com\n");
$smtp->quit;
</code>```

When I run this script, my output is like following:

```<code>Net::SMTP>>> Net::SMTP(2.31)
Net::SMTP>>>   Net::Cmd(2.29)
Net::SMTP>>>     Exporter(5.65)
Net::SMTP>>>   IO::Socket::INET(1.31)
Net::SMTP>>>     IO::Socket(1.32)
Net::SMTP>>>       IO::Handle(1.31)
Net::SMTP=GLOB(0x273faf0)<<< 220 server GMX Mailservices E
Net::SMTP=GLOB(0x273faf0)>>> EHLO localhost.localdomain
Net::SMTP=GLOB(0x273faf0)<<< 250-server GMX Mailservices
Net::SMTP=GLOB(0x273faf0)<<< 250-8BITMIME
Net::SMTP=GLOB(0x273faf0)<<< 250-ENHANCEDSTATUSCODES
Net::SMTP=GLOB(0x273faf0)<<< 250-SIZE
Net::SMTP=GLOB(0x273faf0)<<< 250-AUTH=LOGIN PLAIN
Net::SMTP=GLOB(0x273faf0)<<< 250-AUTH LOGIN PLAIN
Net::SMTP=GLOB(0x273faf0)<<< 250 STARTTLS
Net::SMTP=GLOB(0x273faf0)>>> RCPT TO:<mymail@gmail.com>
Net::SMTP=GLOB(0x273faf0)<<< 503 5.5.1 MAIL first {mp-eu001}
Net::SMTP=GLOB(0x273faf0)>>> DATA
Net::SMTP=GLOB(0x273faf0)<<< 503 5.5.1 MAIL first {mp-eu001}
Net::SMTP=GLOB(0x273faf0)>>> To: mymail@gmail.com
Net::SMTP=GLOB(0x273faf0)>>> .
Net::SMTP=GLOB(0x273faf0)<<< 502 5.5.2 Unimplemented {mp-eu001}
Net::SMTP=GLOB(0x273faf0)>>> QUIT
Net::SMTP=GLOB(0x273faf0)<<< 502 5.5.2 Unimplemented {mp-eu001}
</code>```

I don't have enough information about Perl and SMTP, so I couldn't understand this error.

How can I solve this?

答:
For email services that use STARTTLS, it's best to use the newer NET::SMTPS module. Try the following code:</p>

```<code>my $msg = MIME::Lite ->new (
From => 'from@bellsouth.net',
To => 'to@gmail.com',
Subject => 'Test Message',
Data => 'This is a test',
Type => 'text/html'
);

my $USERNAME = 'from@bellsouth.net';
my $PASSWORD = 'abc123';

my $smtps = Net::SMTPS->new("smtp.mail.att.net", Port => 587,  doSSL => 'starttls', SSL_version=>'TLSv1');

$smtps->auth ( $USERNAME, $PASSWORD ) or die("Could not authenticate with bellsouth.\n");

$smtps ->mail('from@bellsouth.net');
$smtps->to('to@gmail.com');
$smtps->data();
$smtps->datasend( $msg->as_string() );
$smtps->dataend();
$smtps->quit;
</code>```

Title: Sending mail via SMTP in Perl

Body:
I am trying to send mail via SMTP in Perl.

I have written a script for this.

#!perl
use warnings;
use strict;
use Net::SMTP;

my $smtpserver = 'server';
my $smtpport = 25;
my $smtpuser   = 'username';
my $smtppassword = 'password';

my $smtp = Net::SMTP->new($smtpserver, Port=>$smtpport, Timeout => 10, Debug => 1);
die "Could not connect to server!\n" unless $smtp;

$smtp->auth($smtpuser, $smtppassword);
$smtp->to('mymail@gmail.com');
$smtp->data();
$smtp->datasend("To: mymail\@gmail.com\n");
$smtp->quit;

When I run this script, my output is like following:

Net::SMTP>>> Net::SMTP(2.31)
Net::SMTP>>>   Net::Cmd(2.29)
Net::SMTP>>>     Exporter(5.65)
Net::SMTP>>>   IO::Socket::INET(1.31)
Net::SMTP>>>     IO::Socket(1.32)
Net::SMTP>>>       IO::Handle(1.31)
Net::SMTP=GLOB(0x273faf0)<<< 220 server GMX Mailservices E
Net::SMTP=GLOB(0x273faf0)>>> EHLO localhost.localdomain
Net::SMTP=GLOB(0x273faf0)<<< 250-server GMX Mailservices
Net::SMTP=GLOB(0x273faf0)<<< 250-8BITMIME
Net::SMTP=GLOB(0x273faf0)<<< 250-ENHANCEDSTATUSCODES
Net::SMTP=GLOB(0x273faf0)<<< 250-SIZE
Net::SMTP=GLOB(0x273faf0)<<< 250-AUTH=LOGIN PLAIN
Net::SMTP=GLOB(0x273faf0)<<< 250-AUTH LOGIN PLAIN
Net::SMTP=GLOB(0x273faf0)<<< 250 STARTTLS
Net::SMTP=GLOB(0x273faf0)>>> RCPT TO:<mymail@gmail.com>
Net::SMTP=GLOB(0x273faf0)<<< 503 5.5.1 MAIL first {mp-eu001}
Net::SMTP=GLOB(0x273faf0)>>> DATA
Net::SMTP=GLOB(0x273faf0)<<< 503 5.5.1 MAIL first {mp-eu001}
Net::SMTP=GLOB(0x273faf0)>>> To: mymail@gmail.com
Net::SMTP=GLOB(0x273faf0)>>> .
Net::SMTP=GLOB(0x273faf0)<<< 502 5.5.2 Unimplemented {mp-eu001}
Net::SMTP=GLOB(0x273faf0)>>> QUIT
Net::SMTP=GLOB(0x273faf0)<<< 502 5.5.2 Unimplemented {mp-eu001}

I don't have enough information about Perl and SMTP, so I couldn't understand this error.

How can I solve this?

Body:
For email services that use STARTTLS, it's best to use the newer NET::SMTPS module. Try the following code:

my $msg = MIME::Lite ->new (
From => 'from@bellsouth.net',
To => 'to@gmail.com',
Subject => 'Test Message',
Data => 'This is a test',
Type => 'text/html'
);

my $USERNAME = 'from@bellsouth.net';
my $PASSWORD = 'abc123';

my $smtps = Net::SMTPS->new("smtp.mail.att.net", Port => 587,  doSSL => 'starttls', SSL_version=>'TLSv1');

$smtps->auth ( $USERNAME, $PASSWORD ) or die("Could not authenticate with bellsouth.\n");

$smtps ->mail('from@bellsouth.net');
$smtps->to('to@gmail.com');
$smtps->data();
$smtps->datasend( $msg->as_string() );
$smtps->dataend();
$smtps->quit;


问:
Selectively inheriting from any of multiple classes at runtime
I'm doing scientific computing and I'm beginner in c++. MyNLP is a class which contain all the problem data and methods. I'm using third party libraries for numerical optimization. Each third party is a specific algorithm to solve my problem. In order to use each library, my MyNLP class need to inherit corresponding class from third party library.

For example,

```<code>Class MyNLP :public IPOPT
{
};
</code>```

enable me to use IPOPT algorithm to solve my problem. Similarly,

```<code>class MyNLP: public SQP
{
};
</code>```

enable me to use SQP algorithm.

But in my case, only at the run-time, program decides which class it should inherit. I have to inherit either one of third party class.
Could any one give a  technique to achieve this in cpp?

答:
C++ class inheritance is a compile-time construct: it's fixed at runtime. The compiler has to have this information available to it at compile time to determine how to allocate objects and ensure type safety.

You should consider instead implementing a factory. In this design, a factory object or function decides which instance to generate based on input available at runtime. You should create a common base class that provides an interface to the required functionality. This should consist of one or more virtual functions that are used to dynamically call the correct implementation (this is called dynamic dispatch).

Here's a quick example based on your question:

```<code>class nlp_interface
{
public:
    virtual ~nlp_interface() = default;

    // This pure-virtual function has no implementation, forcing the
    // class to be abstract and for derived classes to implement the
    // member function.
    virtual void do_numeric_optimization(/* ... */) = 0;
};

class MyNLP_IPOPT:
    public nlp_interface,
    public IPOPT
{
public:
    // Provide a specific implementation.
    virtual void do_numeric_optimization(/* ... */);
};

class MyNLP_SQP:
    public nlp_interface,
    public SQP
{
public:
    // Provide a specific implementation.
    virtual void do_numeric_optimization(/* ... */);
};
</code>```

Here I use multiple inheritance to provide a well-known interface to the MyNLP_* classes. This is because I can't assume the third party base classes have a common virtual interface that can be used. If they do then just create instances of the third party classes directly. However you seemed to allude to the fact that you had to subclass them for one reason or another.

Here's the factory.

```<code>#include <memory>
#include <exception>

using nlp_pointer = std::unique_ptr<nlp_interface>;
nlp_pointer factory_function(const std::string& input)
{
    if (input == "IPOPT") {
        return nlp_pointer( new MyNLP_IPOPT );
    }
    if (input == "SQP") {
        return nlp_pointer( new MyNLP_SQP );
    }

    throw std::runtime_error("unrecognized algorithm kind");
}
</code>```

To use the factory, call factory_function() and invoke the do_numeric_optimization() member function on the returned nlp_interface instance (which is wrapped in a smart pointer). It will call the correct version via dynamic dispatch.

Body:
I'm doing scientific computing and I'm beginner in c++. MyNLP is a class which contain all the problem data and methods. I'm using third party libraries for numerical optimization. Each third party is a specific algorithm to solve my problem. In order to use each library, my MyNLP class need to inherit corresponding class from third party library.

For example,

Class MyNLP :public IPOPT
{
};

enable me to use IPOPT algorithm to solve my problem. Similarly,

class MyNLP: public SQP
{
};

enable me to use SQP algorithm.

But in my case, only at the run-time, program decides which class it should inherit. I have to inherit either one of third party class.
Could any one give a  technique to achieve this in cpp?

Body:
C++ class inheritance is a compile-time construct: it's fixed at runtime. The compiler has to have this information available to it at compile time to determine how to allocate objects and ensure type safety.

You should consider instead implementing a factory. In this design, a factory object or function decides which instance to generate based on input available at runtime. You should create a common base class that provides an interface to the required functionality. This should consist of one or more virtual functions that are used to dynamically call the correct implementation (this is called dynamic dispatch).

Here's a quick example based on your question:

class nlp_interface
{
public:
    virtual ~nlp_interface() = default;

    // This pure-virtual function has no implementation, forcing the
    // class to be abstract and for derived classes to implement the
    // member function.
    virtual void do_numeric_optimization(/* ... */) = 0;
};

class MyNLP_IPOPT:
    public nlp_interface,
    public IPOPT
{
public:
    // Provide a specific implementation.
    virtual void do_numeric_optimization(/* ... */);
};

class MyNLP_SQP:
    public nlp_interface,
    public SQP
{
public:
    // Provide a specific implementation.
    virtual void do_numeric_optimization(/* ... */);
};

Here I use multiple inheritance to provide a well-known interface to the MyNLP_* classes. This is because I can't assume the third party base classes have a common virtual interface that can be used. If they do then just create instances of the third party classes directly. However you seemed to allude to the fact that you had to subclass them for one reason or another.

Here's the factory.

#include <memory>
#include <exception>

using nlp_pointer = std::unique_ptr<nlp_interface>;
nlp_pointer factory_function(const std::string& input)
{
    if (input == "IPOPT") {
        return nlp_pointer( new MyNLP_IPOPT );
    }
    if (input == "SQP") {
        return nlp_pointer( new MyNLP_SQP );
    }

    throw std::runtime_error("unrecognized algorithm kind");
}

To use the factory, call factory_function() and invoke the do_numeric_optimization() member function on the returned nlp_interface instance (which is wrapped in a smart pointer). It will call the correct version via dynamic dispatch.


问:
Keep Getting a Segmentation Fault On This?
I keep getting the segmentation fault (core dumped) on the code below.  Any ideas on why this is happening.  The code is designed to read numbers from a text document, convert them to integers, perform radix sort, and print out the array.

```<code>#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <time.h>
#include <sstream>

using namespace std;

int getMax(int arr[], int n)
{
    int max = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] > max)
            max = arr[i];
    return max;
}

void countSort(int arr[], int n, int exp)
{
    int output[n];
    int i, count[10] = {0};
    for (i = 0; i < n; i++)
        count[(arr[i] / exp) % 10]++;
    for (i = 1; i < 10; i++)
        count[i] += count[i - 1];
    for (i = n - 1; i >= 0; i--)
    {
        output[count[(arr[i] / exp) % 10] - 1] = arr[i];
        count[(arr[i] / exp) % 10]--;
    }
    for (i = 0; i < n; i++)
        arr[i] = output[i];
}

void radixsort(int arr[], int n)
{
    clock_t clockStart;
    clockStart = clock();

    int m = getMax(arr, n);
    for (int exp = 1; m / exp > 0; exp *= 10)
        countSort(arr, n, exp);

    cout << "\nTime taken by radix sort: " << (double)(clock() - clockStart) / CLOCKS_PER_SEC << endl;
}

int StrToInt(string sti)
{
    int f;
    stringstream ss(sti); //turn the string into a stream
    ss >> f;
    return f;
}

int main()
{
    int arr[10000];
    int i = 0;
    int result;
    string line = "";

    ifstream myfile;
    myfile.open("integers2.txt");
    if(myfile.is_open())
    {
        while(!myfile.eof())
        {
            getline(myfile, line);
            result = StrToInt(line);
            arr[i] = result;
            //cout<< arr[i] <<"\n";
            i++;
        }
    }

    int n = sizeof(arr)/sizeof(arr[0]);
    radixsort(arr, n);

    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << "\n";
    }

    return 0;
}
</code>```

Contents of the text file I am using for input:
1244
3455
6565
55
765
8768
687
879

答:
Here's your working code:

```<code>#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <time.h>
#include <sstream>

using namespace std;

int getMax(int arr[], int n)
{
    int max = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] > max)
            max = arr[i];
    return max;
}

void countSort(int arr[], int n, int exp)
{
    int output[n];
    int i, count[10] = {0};
    for (i = 0; i < n; i++)
        count[(arr[i] / exp) % 10]++;
    for (i = 1; i < 10; i++)
        count[i] += count[i - 1];
    for (i = n - 1; i >= 0; i--)
    {
        output[count[(arr[i] / exp) % 10] - 1] = arr[i];
        count[(arr[i] / exp) % 10]--;
    }
    for (i = 0; i < n; i++)
        arr[i] = output[i];
}

void radixsort(int arr[], int n)
{
    clock_t clockStart;
    clockStart = clock();

    int m = getMax(arr, n);
    for (int exp = 1; m / exp > 0; exp *= 10)
        countSort(arr, n, exp);

    cout << "\nTime taken by radix sort: " << (double)(clock() - clockStart) / CLOCKS_PER_SEC << endl;
}

int StrToInt(string sti)
{
    int f;
    stringstream ss(sti); //turn the string into a stream
    ss >> f;
    return f;
}

int main()
{
    const int MAX_SIZE = 10;

    int arr[ MAX_SIZE ] = { 0 };

    //int i = 0;
    //int result = 0;
    string line = "";

    ifstream myfile;
    myfile.open("integers2.txt");
    if(!myfile.is_open())
    {
        cerr << "Could not open file!\n";
        return -1;
    }

    cout << "Reading integers...\n";

    int index = 0;
    //while ( index < SIZE && getline( myfile, line ) )
    while ( index < MAX_SIZE && myfile >> arr[ index ] )
    {
        //getline( myfile, line );
        //result = StrToInt( line );
        //arr[index] = std::stoi( line );
        cout << arr[index] <<"\n";
        index++;
    }

    cout << "Sorting integers...\n";

    //int n = sizeof(arr) / sizeof(arr[0]);

    radixsort( arr, index );

    for ( int i = 0; i < index; i++ )
    {
        cout << arr[i] << "\n";
    }

    return 0;
}
</code>```

Some points:

Check std::stoi for string to integer conversion; BTW, you don't need to do that. Just read it directly like this: while ( file >> integer ).

Need to check if the file is open; return ERROR otherwise; in your case, the rest of the code was executing anyway even if the file was not open i.e. code after if ( myfile.open() ) { ... }

while( !myfile.eof() ) is bad practice. See: Why is iostream::eof inside a loop condition considered wrong?

You don't need to calculate the size like int n = sizeof(arr) / sizeof(arr[0]); because you already know the size. Just use a const for this.

While reading from file, you also need to validate the maximum size of your array. You should read what the size allows you. Take care of out-of-bounds read / write errors.

Use <ctime> instead of <time.h>.

Body:
I keep getting the segmentation fault (core dumped) on the code below.  Any ideas on why this is happening.  The code is designed to read numbers from a text document, convert them to integers, perform radix sort, and print out the array.

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <time.h>
#include <sstream>

using namespace std;

int getMax(int arr[], int n)
{
    int max = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] > max)
            max = arr[i];
    return max;
}

void countSort(int arr[], int n, int exp)
{
    int output[n];
    int i, count[10] = {0};
    for (i = 0; i < n; i++)
        count[(arr[i] / exp) % 10]++;
    for (i = 1; i < 10; i++)
        count[i] += count[i - 1];
    for (i = n - 1; i >= 0; i--)
    {
        output[count[(arr[i] / exp) % 10] - 1] = arr[i];
        count[(arr[i] / exp) % 10]--;
    }
    for (i = 0; i < n; i++)
        arr[i] = output[i];
}

void radixsort(int arr[], int n)
{
    clock_t clockStart;
    clockStart = clock();

    int m = getMax(arr, n);
    for (int exp = 1; m / exp > 0; exp *= 10)
        countSort(arr, n, exp);

    cout << "\nTime taken by radix sort: " << (double)(clock() - clockStart) / CLOCKS_PER_SEC << endl;
}

int StrToInt(string sti)
{
    int f;
    stringstream ss(sti); //turn the string into a stream
    ss >> f;
    return f;
}

int main()
{
    int arr[10000];
    int i = 0;
    int result;
    string line = "";

    ifstream myfile;
    myfile.open("integers2.txt");
    if(myfile.is_open())
    {
        while(!myfile.eof())
        {
            getline(myfile, line);
            result = StrToInt(line);
            arr[i] = result;
            //cout<< arr[i] <<"\n";
            i++;
        }
    }

    int n = sizeof(arr)/sizeof(arr[0]);
    radixsort(arr, n);

    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << "\n";
    }

    return 0;
}

Contents of the text file I am using for input:
1244
3455
6565
55
765
8768
687
879

Body:
Here's your working code:

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <time.h>
#include <sstream>

using namespace std;

int getMax(int arr[], int n)
{
    int max = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] > max)
            max = arr[i];
    return max;
}

void countSort(int arr[], int n, int exp)
{
    int output[n];
    int i, count[10] = {0};
    for (i = 0; i < n; i++)
        count[(arr[i] / exp) % 10]++;
    for (i = 1; i < 10; i++)
        count[i] += count[i - 1];
    for (i = n - 1; i >= 0; i--)
    {
        output[count[(arr[i] / exp) % 10] - 1] = arr[i];
        count[(arr[i] / exp) % 10]--;
    }
    for (i = 0; i < n; i++)
        arr[i] = output[i];
}

void radixsort(int arr[], int n)
{
    clock_t clockStart;
    clockStart = clock();

    int m = getMax(arr, n);
    for (int exp = 1; m / exp > 0; exp *= 10)
        countSort(arr, n, exp);

    cout << "\nTime taken by radix sort: " << (double)(clock() - clockStart) / CLOCKS_PER_SEC << endl;
}

int StrToInt(string sti)
{
    int f;
    stringstream ss(sti); //turn the string into a stream
    ss >> f;
    return f;
}

int main()
{
    const int MAX_SIZE = 10;

    int arr[ MAX_SIZE ] = { 0 };

    //int i = 0;
    //int result = 0;
    string line = "";

    ifstream myfile;
    myfile.open("integers2.txt");
    if(!myfile.is_open())
    {
        cerr << "Could not open file!\n";
        return -1;
    }

    cout << "Reading integers...\n";

    int index = 0;
    //while ( index < SIZE && getline( myfile, line ) )
    while ( index < MAX_SIZE && myfile >> arr[ index ] )
    {
        //getline( myfile, line );
        //result = StrToInt( line );
        //arr[index] = std::stoi( line );
        cout << arr[index] <<"\n";
        index++;
    }

    cout << "Sorting integers...\n";

    //int n = sizeof(arr) / sizeof(arr[0]);

    radixsort( arr, index );

    for ( int i = 0; i < index; i++ )
    {
        cout << arr[i] << "\n";
    }

    return 0;
}

Some points:

Check std::stoi for string to integer conversion; BTW, you don't need to do that. Just read it directly like this: while ( file >> integer ).

Need to check if the file is open; return ERROR otherwise; in your case, the rest of the code was executing anyway even if the file was not open i.e. code after if ( myfile.open() ) { ... }

while( !myfile.eof() ) is bad practice. See: Why is iostream::eof inside a loop condition considered wrong?

You don't need to calculate the size like int n = sizeof(arr) / sizeof(arr[0]); because you already know the size. Just use a const for this.

While reading from file, you also need to validate the maximum size of your array. You should read what the size allows you. Take care of out-of-bounds read / write errors.

Use <ctime> instead of <time.h>.


问:
Issue casting to string in google sheets script
I have the following function for a google sheets document:

```<code>function names(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var str = String(nameCells[i]);
    var splitted = str.split(", ");
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}
</code>```

The function is supposed take a list of cells with names that are comma separated and return and single list of all the names.

For example:

```<code>James
Reese, Peter
Ryan, Monica
Reba

Nick
</code>```

Should produce

```<code>James
Reese
Peter
Ryan
Monica
Nick
</code>```

However I seem to be having an issue casting the cell values to string values and it says "Internal error executing the custom function" without giving me any more specifics than that. The following more basic program does work as expected:

```<code>function namesSimple(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
      roomieNames.push(nameCells[i]);
  }
  return roomieNames;
}
</code>```

However the following produces the error seen in the comments in line 4:

```<code>function namesBroken(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var splitted = nameCells[i].split(", ");  //TypeError: Cannot find function split in object James. (line 4).
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}
</code>```

Which leads to me to believe I need to cast the object to a string but as stated above that doesn't seem to be working either.

I tried googling casting techniques and feel that this should work. I have also tried .toString(); with no luck. Can someone help me out please. Thanks :)

答:
According to the api docs (https://developers.google.com/sheets/api/guides/values) the response for a request of a range of cells is returned as a 'ValueRange' object.

The data is represented:

```<code>{
  "range": string,
  "majorDimension": enum(Dimension),
  "values": [
    array
  ],
}
</code>```

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values#resource-valuerange

With values being an array of ListValue: https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.ListValue

The ListValues represent a Value object which will have one of the following values: (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Value)

```<code>null_value  NullValue   Represents a null value.
number_value    double  Represents a double value.
string_value    string  Represents a string value.
bool_value  bool    Represents a boolean value.
struct_value    Struct  Represents a structured value.
list_value  ListValue   Represents a repeated Value.
</code>```

The docs say:

Value represents a dynamically typed value which can be either null, a number, a string, a boolean, a recursive struct value, or a list of values. A producer of value is expected to set one of that variants, absence of any variant indicates an error.

Body:
I have the following function for a google sheets document:

function names(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var str = String(nameCells[i]);
    var splitted = str.split(", ");
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}

The function is supposed take a list of cells with names that are comma separated and return and single list of all the names.

For example:

James
Reese, Peter
Ryan, Monica
Reba

Nick

Should produce

James
Reese
Peter
Ryan
Monica
Nick

However I seem to be having an issue casting the cell values to string values and it says "Internal error executing the custom function" without giving me any more specifics than that. The following more basic program does work as expected:

function namesSimple(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
      roomieNames.push(nameCells[i]);
  }
  return roomieNames;
}

However the following produces the error seen in the comments in line 4:

function namesBroken(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var splitted = nameCells[i].split(", ");  //TypeError: Cannot find function split in object James. (line 4).
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}

Which leads to me to believe I need to cast the object to a string but as stated above that doesn't seem to be working either.

I tried googling casting techniques and feel that this should work. I have also tried .toString(); with no luck. Can someone help me out please. Thanks :)

Body:
According to the api docs (https://developers.google.com/sheets/api/guides/values) the response for a request of a range of cells is returned as a 'ValueRange' object.

The data is represented:

{
  "range": string,
  "majorDimension": enum(Dimension),
  "values": [
    array
  ],
}

https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values#resource-valuerange

With values being an array of ListValue: https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.ListValue

The ListValues represent a Value object which will have one of the following values: (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Value)

null_value  NullValue   Represents a null value.
number_value    double  Represents a double value.
string_value    string  Represents a string value.
bool_value  bool    Represents a boolean value.
struct_value    Struct  Represents a structured value.
list_value  ListValue   Represents a repeated Value.

The docs say:

Value represents a dynamically typed value which can be either null, a number, a string, a boolean, a recursive struct value, or a list of values. A producer of value is expected to set one of that variants, absence of any variant indicates an error.


问:
Show errors when uploading photo with dropzone
Hi I have problem with upload image in jquery. When i uplaod image ,show me errors. How do i solve this peroblem ?

I can't use the form to dropzone because it is in another form.
Errors:

POST http://localhost:3000/upload 400 (Bad Request)

Object {error: Object}

code html

```<code><div class="dropzone" action="/upload"  encType="multipart/form-data" method='post' id="id_dropzone" >
<div class="dz-message">
  ِDrop file here to upload
</div>
 </div>
</code>```

Code JQUERY

```<code>  $(document).ready(function(){

    Dropzone.autoDiscover = false;

$("#id_dropzone").dropzone({addRemoveLinks: true, autoQueue: true,paramName: "file", maxFilesize: 2, maxFiles: 1,

    success: function (file, response) {
            var imgName = response;
            file.previewElement.classList.add("dz-success");
            console.log("Successfully uploaded :" + imgName);
        },
        error: function (file, response) {
            file.previewElement.classList.add("dz-error");
              console.log(response);
        },
  maxThumbnailFilesize: 1,acceptedFiles: "image/*"  });
})
</code>```

Code app.js

```<code>    var express = require('express');
    var routes = require('./routes')();
    var fileUpload = require('express-fileupload');
    var path = require('path');
    var app = express();

    app.use(fileUpload());
    app.use('/files', express.static(__dirname + '/files'));
    .
    .
    .
    app.post('/upload', function(req, res) {
      var sampleFile;
      if (!req.files) {
        res.send('No files were uploaded.');
        return;
      }
      sampleFile = req.files;
      console.log(sampleFile);
      sampleFile.file.mv(__dirname + '/files/'+sampleFile.file.name,
      function(err) {
        if (err) {
          console.log(err);
          res.status(500).send(err);
        } else {
        res.send('File uploaded!');
      }
    });
  });
</code>```

package.json

```<code>{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "connect-mongo": "~0.3.3",
    "ejs": "^2.5.6",
    "express": "^3.21.2",
    "express-fileupload": "^0.1.4",
    "mongoose": "~3.6.19"
  },
  "devDependencies": {
    "mocha": "~1.12.1",
    "should": "~1.2.2",
    "supertest": "~0.7.1"
  }
}
</code>```

答:
I solved this problem with the following code.

app.js

```<code>var multiparty = require('multiparty');
const fs = require('fs');
var util = require('util');
.
.
.
    app.post('/file-upload', function(req,res){
      var form = new multiparty.Form({autoFiles:true });
      form.parse(req, function(err, fields, files) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        var oldpath = req.files.file.path;
        var newpath =  __dirname + '\\files\\' + req.files.file.name;
        var readStream = fs.createReadStream(oldpath);
        var writeStream = fs.createWriteStream(newpath);
        readStream.pipe(writeStream);
        res.end();
      });
      return;
   });
</code>```

Body:
Hi I have problem with upload image in jquery. When i uplaod image ,show me errors. How do i solve this peroblem ?

I can't use the form to dropzone because it is in another form.
Errors:

POST http://localhost:3000/upload 400 (Bad Request)

Object {error: Object}

code html

  ِDrop file here to upload

Code JQUERY

  $(document).ready(function(){

    Dropzone.autoDiscover = false;

$("#id_dropzone").dropzone({addRemoveLinks: true, autoQueue: true,paramName: "file", maxFilesize: 2, maxFiles: 1,

    success: function (file, response) {
            var imgName = response;
            file.previewElement.classList.add("dz-success");
            console.log("Successfully uploaded :" + imgName);
        },
        error: function (file, response) {
            file.previewElement.classList.add("dz-error");
              console.log(response);
        },
  maxThumbnailFilesize: 1,acceptedFiles: "image/*"  });
})

Code app.js

    var express = require('express');
    var routes = require('./routes')();
    var fileUpload = require('express-fileupload');
    var path = require('path');
    var app = express();

    app.use(fileUpload());
    app.use('/files', express.static(__dirname + '/files'));
    .
    .
    .
    app.post('/upload', function(req, res) {
      var sampleFile;
      if (!req.files) {
        res.send('No files were uploaded.');
        return;
      }
      sampleFile = req.files;
      console.log(sampleFile);
      sampleFile.file.mv(__dirname + '/files/'+sampleFile.file.name,
      function(err) {
        if (err) {
          console.log(err);
          res.status(500).send(err);
        } else {
        res.send('File uploaded!');
      }
    });
  });

package.json

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "connect-mongo": "~0.3.3",
    "ejs": "^2.5.6",
    "express": "^3.21.2",
    "express-fileupload": "^0.1.4",
    "mongoose": "~3.6.19"
  },
  "devDependencies": {
    "mocha": "~1.12.1",
    "should": "~1.2.2",
    "supertest": "~0.7.1"
  }
}

Body:
I solved this problem with the following code.

app.js

var multiparty = require('multiparty');
const fs = require('fs');
var util = require('util');
.
.
.
    app.post('/file-upload', function(req,res){
      var form = new multiparty.Form({autoFiles:true });
      form.parse(req, function(err, fields, files) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        var oldpath = req.files.file.path;
        var newpath =  __dirname + '\\files\\' + req.files.file.name;
        var readStream = fs.createReadStream(oldpath);
        var writeStream = fs.createWriteStream(newpath);
        readStream.pipe(writeStream);
        res.end();
      });
      return;
   });


问:
Excel: Different Cells with Duplicate Function
I have tried finding an answer to this question but I'm not sure how to even phrase it.

Say I have three cells A1, A2 and A3:

A1 has a data validation list contained within: X, Y, Z.

A3 is scripted to produce a VLOOKUP result depending on the letter selected.

I want A2 to mirror and provide an identical function to A1, but I also want both to be dependent on each other. For clarity, if I select 'X' on A1, A2 will also display 'X'. If I change 'X' to 'Y' on A2, A1 will then change to 'Y'. Either way, I want A3 to display the appropriate result whether or not the function is changed on A1 or A2.

Is this achievable? Or am I just messing with circular references?

答:
To have 2 cells always showing the same value regardless which one you input something, you need VBA. Something like:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
  If Not Intersect(Target.Parent.Range("A1"), Target) Is Nothing Then
    If Target.Parent.Range("A1").Value <> Target.Parent.Range("A2").Value Then
      Target.Parent.Range("A2").Value = Target.Parent.Range("A1").Value
    End If
  ElseIf Not Intersect(Target.Parent.Range("A2"), Target) Is Nothing Then
    If Target.Parent.Range("A1").Value <> Target.Parent.Range("A2").Value Then
      Target.Parent.Range("A1").Value = Target.Parent.Range("A2").Value
    End If
  End If
End Sub
</code>```

in your worksheet code part.

With just formulas, that is not possible. Also keep in mind, that you need the same data validation for both cells or you may get in trouble.

For A3 just pick one of the cells for your formula (as both show the same value it doesn't matter which one).

Body:
To have 2 cells always showing the same value regardless which one you input something, you need VBA. Something like:

Private Sub Worksheet_Change(ByVal Target As Range)
  If Not Intersect(Target.Parent.Range("A1"), Target) Is Nothing Then
    If Target.Parent.Range("A1").Value <> Target.Parent.Range("A2").Value Then
      Target.Parent.Range("A2").Value = Target.Parent.Range("A1").Value
    End If
  ElseIf Not Intersect(Target.Parent.Range("A2"), Target) Is Nothing Then
    If Target.Parent.Range("A1").Value <> Target.Parent.Range("A2").Value Then
      Target.Parent.Range("A1").Value = Target.Parent.Range("A2").Value
    End If
  End If
End Sub

in your worksheet code part.

With just formulas, that is not possible. Also keep in mind, that you need the same data validation for both cells or you may get in trouble.

For A3 just pick one of the cells for your formula (as both show the same value it doesn't matter which one).


问:
refreshing a page after deletion Javascript
I have a page filled with a list from a database, when clicking any element of this list, the details of this element will appear on another page to be edited. user also have the option of deletion here.
the problem is after deletion process completes the original page with the list doesnt refresh, so it still displays the deleted element in the list.
i tried different methods mentioned here in stackoverflow.com but none worked as i want.
for example this answer was mentioned here:

```<code>$sql = "delete from `lesson_plans` where `LP_ID` = '" . $_SESSION['LP_ID_S']."';";
if ($conn->query($sql) === TRUE)
    {
        echo "<script>var hWndB = window.open('myplans.php'),
                hWndA = window.self;
                hWndB.onunload = function(){ hWndA.location.reload(); }
              </script>";
    }
</code>```

the problem in this code that is opens a new page with new list successfully and keeps the old one open as well, so it doesnt refresh the old one, it only open a new link in a new tab.

答:
You can try like this using windows.redirect you can reload the page.</p>

```<code>$sql = "delete from `lesson_plans` where `LP_ID` = '" . $_SESSION['LP_ID_S']."';";
if ($conn->query($sql) === TRUE)
{
    echo "<script> window.location = "myplans.php"; </script>";
}
</code>```

Body:
I have a page filled with a list from a database, when clicking any element of this list, the details of this element will appear on another page to be edited. user also have the option of deletion here.
the problem is after deletion process completes the original page with the list doesnt refresh, so it still displays the deleted element in the list.
i tried different methods mentioned here in stackoverflow.com but none worked as i want.
for example this answer was mentioned here:

$sql = "delete from `lesson_plans` where `LP_ID` = '" . $_SESSION['LP_ID_S']."';";
if ($conn->query($sql) === TRUE)
    {
        echo "";
    }

the problem in this code that is opens a new page with new list successfully and keeps the old one open as well, so it doesnt refresh the old one, it only open a new link in a new tab.

Body:
You can try like this using windows.redirect you can reload the page.

$sql = "delete from `lesson_plans` where `LP_ID` = '" . $_SESSION['LP_ID_S']."';";
if ($conn->query($sql) === TRUE)
{
    echo "<script> window.location = "myplans.php"; </script>";
}


答:
You cannot select inheritance at runtime, because the resulting type is always determined by the compiler at compile time.

What you can do is to apply the Strategy Pattern:

The idea is to have an abstract class that represents the algorithm used in MyNLP:

```<code>class Data;

class NLPAlgo {
public:
    virtual ~NLPAlgo() = default;
    virtual void Apply(Data&) = 0;
};
</code>```

and provide concrete classes that use IPOPT and SQP:

```<code>class IPOPTAlgo : public NLPAlgo {
    IPOPT ipopt;
public:
    void Apply(Data& data) {
        // Use ipopt to realize the implementation
    }
};

class SQPAlgo : public NLPAlgo {
    SQP sqp;
public:
    void Apply(Data& data) {
        // Use sqp to realize the implementation
    }
};
</code>```

Further take that abstract class as parameter for MyNLP

```<code>class MyNLP {
    std::unique_ptr<NLPAlgo> algo_;
public:
    MyNLP(std::unique_ptr<NLPAlgo> algo) : algo_(algo) {}
    void Apply(Data& data) {
        algo->Apply(data);
    }
};
</code>```

Then you can configure at runtime which algorithm should be used with MyNLP:

```<code>// Note:
// That code could be factored out to an Abstract Factory:
// https://sourcemaking.com/design_patterns/abstract_factory
// That is figured out in more detail in this answer:
// https://stackoverflow.com/a/44985054/8242698
std::unique_ptr<NLPAlgo> algo;
if(condIPOPT) {
    algo = std::make_unique<IPOPTAlgo>();
}
else if(condSQP) {
    algo = std::make_unique<SQPAlgo>();
}

Data data;
MyNLP myNLP(algo);

myNLP.Apply(data);
</code>```

Title: Selectively inheriting from any of multiple classes at runtime

Body:
You cannot select inheritance at runtime, because the resulting type is always determined by the compiler at compile time.

What you can do is to apply the Strategy Pattern:

The idea is to have an abstract class that represents the algorithm used in MyNLP:

class Data;

class NLPAlgo {
public:
    virtual ~NLPAlgo() = default;
    virtual void Apply(Data&) = 0;
};

and provide concrete classes that use IPOPT and SQP:

class IPOPTAlgo : public NLPAlgo {
    IPOPT ipopt;
public:
    void Apply(Data& data) {
        // Use ipopt to realize the implementation
    }
};

class SQPAlgo : public NLPAlgo {
    SQP sqp;
public:
    void Apply(Data& data) {
        // Use sqp to realize the implementation
    }
};

Further take that abstract class as parameter for MyNLP

class MyNLP {
    std::unique_ptr<NLPAlgo> algo_;
public:
    MyNLP(std::unique_ptr<NLPAlgo> algo) : algo_(algo) {}
    void Apply(Data& data) {
        algo->Apply(data);
    }
};

Then you can configure at runtime which algorithm should be used with MyNLP:

// Note:
// That code could be factored out to an Abstract Factory:
// https://sourcemaking.com/design_patterns/abstract_factory
// That is figured out in more detail in this answer:
// https://stackoverflow.com/a/44985054/8242698
std::unique_ptr<NLPAlgo> algo;
if(condIPOPT) {
    algo = std::make_unique<IPOPTAlgo>();
}
else if(condSQP) {
    algo = std::make_unique<SQPAlgo>();
}

Data data;
MyNLP myNLP(algo);

myNLP.Apply(data);


问:
How to change icarousel radius according to the screen size?
Hello I want to make half circle rotating wheel. So I used iCarousel for this. My problem is how to change the radius of the wheel according to the screen size.

These are my constraints.

This red view is the iCarousel view

答:
There is an values iCarouselOptionRadius . This value definesradius of the Rotary, Cylinder and Wheel transforms .The radius of the Rotary, Cylinder and Wheel transforms in pixels/points. This is usually calculated so that the number of visible items exactly fits into the specified arc. You can manipulate this value to increase or reduce the item spacing (and the radius of the circle).

I hope you equipped with all demos of iCarousel. Check the Options Demo for an example of the effect that iCarouselOption values parameters have. You can download complete demo from here.

Hope it helps. Happy Coding!!


问:
asp.net mvc2: Why to minimize the code in controllers?
I heard a bit about we should keep the code in controllers as less as possible. So where do we put those code?</p>

答:
Do you know thin and skinny controller? So my answer is if you put many line of codes in controller, your code will be messy and hard to unit testing. Really the controller only executing the actions related with current HttpContext, so if you have business logic, data access, encryption,... you must separation of concern. The reason you don't put business logic at here is business belong to domain. So delegate to Domain for processing. Controller must be consider all actions related to HttpContext (Session, ViewData, TempData, User in current thread, Global and Local Resources,... ) and delegated all other actions to other component. Rule of thumb is fat model and thin controller for cook delicious cake(phpcake).
Some links you can reference for skinny and fat Controller at here and here.</p>