问:
Null field, but not null
So I've got the following lines of code:

```<code>else
            {
                //if not found, call Gateway Add()
                user.Id = await C3SDbContext.UserGateway.NextIdAsync(context);

                user.CreatedById = modifier.CreatedById;
                user.CreatedBy = modifier.CreatedBy;
                user.DateCreated = DateTime.Now;
                user.UserType = "G";
                System.Diagnostics.Debug.WriteLine(user.UserType);
                user.Status = UserStatus.NEW;
                System.Diagnostics.Debug.WriteLine(user.UserType);

                user.Uic = await C3SDbContext.UicGateway.GetUicByIdAsync(context, user.UicId);
                System.Diagnostics.Debug.WriteLine(user.UserType);
                user.Role = await C3SDbContext.RoleGateway.GetRoleByIdAsync(context, user.RoleId);
                System.Diagnostics.Debug.WriteLine(user.UserType);
                if (ModelState.IsValid)
                {
                    userCheck = await C3SDbContext.UserGateway.AddNewGovernmentUserAsync(context, user, modifier);
                }
                else
                {

                    System.Diagnostics.Debug.WriteLine(user.UserType);
                    ICollection<ModelState> ListValues = ModelState.Values;
                    List<object> Errors = new List<object>();
                    foreach (var item in ModelState.Values)
                    {
                        if (item.Errors.Count() > 0)
                        {
                            Errors.Add(item.Errors);
                        }
                    }
                }
            }
</code>```

user is an instance of GovernmentUser.cs, which inherits from User.cs.  UserType is a string property of User.  When I run this, all the instances of "System.Diagnostic.Debug.WriteLine(user.UserType);" return "G" in the Output window.  Heowever, the Errors list returns one item, telling me that UserType is null.

My questions are: what is going on here?  How can they both come to different results, when executed at the same type, and how can I get it so that ModelState.IsValid == true?

答: ModelState checks the data that was posted to you in MVC.  I don't know if this is in your controller or not, but if it is, then my guess is that the UserType wouldn't be on the original data that was posted.  I don't think you can use that check after setting it server-side.  It is a check on the data received from the client.  If UserType isn't required on the client side, just remove that rule from the Dto.  However, if you are uploading the actual Entity directly here and it is using the Required attribute that EF uses, then I would just save it like normal and let EF handle the valdiation instead of using ModelState.</p>

Title: Null field, but not null

Body:
So I've got the following lines of code:

else
            {
                //if not found, call Gateway Add()
                user.Id = await C3SDbContext.UserGateway.NextIdAsync(context);

                user.CreatedById = modifier.CreatedById;
                user.CreatedBy = modifier.CreatedBy;
                user.DateCreated = DateTime.Now;
                user.UserType = "G";
                System.Diagnostics.Debug.WriteLine(user.UserType);
                user.Status = UserStatus.NEW;
                System.Diagnostics.Debug.WriteLine(user.UserType);

                user.Uic = await C3SDbContext.UicGateway.GetUicByIdAsync(context, user.UicId);
                System.Diagnostics.Debug.WriteLine(user.UserType);
                user.Role = await C3SDbContext.RoleGateway.GetRoleByIdAsync(context, user.RoleId);
                System.Diagnostics.Debug.WriteLine(user.UserType);
                if (ModelState.IsValid)
                {
                    userCheck = await C3SDbContext.UserGateway.AddNewGovernmentUserAsync(context, user, modifier);
                }
                else
                {

                    System.Diagnostics.Debug.WriteLine(user.UserType);
                    ICollection<ModelState> ListValues = ModelState.Values;
                    List<object> Errors = new List<object>();
                    foreach (var item in ModelState.Values)
                    {
                        if (item.Errors.Count() > 0)
                        {
                            Errors.Add(item.Errors);
                        }
                    }
                }
            }

user is an instance of GovernmentUser.cs, which inherits from User.cs.  UserType is a string property of User.  When I run this, all the instances of "System.Diagnostic.Debug.WriteLine(user.UserType);" return "G" in the Output window.  Heowever, the Errors list returns one item, telling me that UserType is null.

My questions are: what is going on here?  How can they both come to different results, when executed at the same type, and how can I get it so that ModelState.IsValid == true?


来源: stackexchange

问:
Getting values from Object, putting them in one array separated by commas
Recently I asked a similar question but I will delete it because it was not clear enough, my bad.

I need to get year, month and date values from multiple dynamic objects

```<code>Object {year: 2017, month: 1, date: 26}
Object {year: 2017, month: 2, date: 5}
Object {year: 2017, month: 2, date: 12}
Object {year: 2017, month: 2, date: 19}
Object {year: 2017, month: 2, date: 26}
</code>```

and I need to make them in array like this:

```<code>[26/1/2017, 5/2/2017, 12/2/2017, 19/2/2017, 26/2/2017]
</code>```

and than, use that array to put these values in input hidden value like this:

```<code><input type="hidden" value="26/1/2017, 5/2/2017, 12/2/2017, 19/2/2017, 26/2/2017">
</code>```

I managed to get the values and push them in arrays but I can't get them to work as it should, here is my code:

```<code>           // Note: This code is in each function

            // This holds the objects
            var sundayData = $(this).data();

            // I get date, month and year values
            var dayAll = sundayData['date'];
            var monthAll = sundayData['month'];
            var yearAll = sundayData['year'];

            // Here, I putting them in the right format
            var sundayDatesAll = dayAll + '/' + (monthAll + 1) + '/' + yearAll;
            //
            var sundayDate = [];

            // Here, I push the dates in sundayDate
            sundayDate.push(sundayDatesAll);

            $('input').val(sundayDate.join());
</code>```

But, like this, it returns separated arrays like this:

```<code>["26/2/2017"]
["5/3/2017"]
["12/3/2017"]
["19/3/2017"]
["26/3/2017"]
</code>```

and there is only one value in the input, i think its the last value 26/3/2017

Any help is appreciated, thanks...

答:
You need to get the old value of the input, split it, then add the new date to it, rather than starting with an empty array each time.

```<code>var sundayDate = $('input').val().split(',');
// Here, I push the dates in sundayDate
sundayDate.push(sundayDatesAll);
$('input').val(sundayDate.join(','));
</code>```

You can combine this into:

```<code>$('input').val(function(i, oldDates) {
    var sundayDate = oldDates.split(',');
    sundayDate.push(sundayDatesAll);
    return sundayDate.join(',');
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Recently I asked a similar question but I will delete it because it was not clear enough, my bad.

I need to get year, month and date values from multiple dynamic objects

Object {year: 2017, month: 1, date: 26}
Object {year: 2017, month: 2, date: 5}
Object {year: 2017, month: 2, date: 12}
Object {year: 2017, month: 2, date: 19}
Object {year: 2017, month: 2, date: 26}

and I need to make them in array like this:

[26/1/2017, 5/2/2017, 12/2/2017, 19/2/2017, 26/2/2017]

and than, use that array to put these values in input hidden value like this:

<input type="hidden" value="26/1/2017, 5/2/2017, 12/2/2017, 19/2/2017, 26/2/2017">

I managed to get the values and push them in arrays but I can't get them to work as it should, here is my code:

           // Note: This code is in each function

            // This holds the objects
            var sundayData = $(this).data();

            // I get date, month and year values
            var dayAll = sundayData['date'];
            var monthAll = sundayData['month'];
            var yearAll = sundayData['year'];

            // Here, I putting them in the right format
            var sundayDatesAll = dayAll + '/' + (monthAll + 1) + '/' + yearAll;
            //
            var sundayDate = [];

            // Here, I push the dates in sundayDate
            sundayDate.push(sundayDatesAll);

            $('input').val(sundayDate.join());

But, like this, it returns separated arrays like this:

["26/2/2017"]
["5/3/2017"]
["12/3/2017"]
["19/3/2017"]
["26/3/2017"]

and there is only one value in the input, i think its the last value 26/3/2017

Any help is appreciated, thanks...

Body:
You need to get the old value of the input, split it, then add the new date to it, rather than starting with an empty array each time.

var sundayDate = $('input').val().split(',');
// Here, I push the dates in sundayDate
sundayDate.push(sundayDatesAll);
$('input').val(sundayDate.join(','));

You can combine this into:

$('input').val(function(i, oldDates) {
    var sundayDate = oldDates.split(',');
    sundayDate.push(sundayDatesAll);
    return sundayDate.join(',');
});


问:
C# Refactoring methods with same code except different function calls
The varying functions have different parameters and need to return values.

Example:

```<code>public T Foo(a, b, c, func_pointer)
{
   //common code
   if(no errors)
   {
      return func_pointer(a, b, c)
   }
   //common code
}

public T Foo(a, b, c, **d**, func_pointer)
{
   //common code
   if(no errors)
   {
      return func_pointer(a, b, c, **d**)
   }
   //common code
}
</code>```

Is there anyway to avoid code duplication?

答: One way to handle this is to have the method with fewer arguments call the method with the next greater number of arguments, passing in default values for the missing args. Then the last method in the chain had the actual code, and does whatever is necessary with the default values. </p>

Body:
The varying functions have different parameters and need to return values.

Example:

public T Foo(a, b, c, func_pointer)
{
   //common code
   if(no errors)
   {
      return func_pointer(a, b, c)
   }
   //common code
}

public T Foo(a, b, c, **d**, func_pointer)
{
   //common code
   if(no errors)
   {
      return func_pointer(a, b, c, **d**)
   }
   //common code
}

Is there anyway to avoid code duplication?


问:
I can't get to work the IF statement
```<code>    </script>
    <script type="text/javascript">
    var p1 = 94.28
    var p2 = 86.43
    var p3 = 85.36
    var p4 = 82.26
    var p5 = 80.03
    var p6 = 77.60
    var p7 = 72.75

    function calculate11() {
    var USERINPUT11 = document.TESTING11.INPUT11.value,
                RESULT11 = (( p1 * USERINPUT11) / 1000 );

            document.TESTING11.OUTPUT11.value = RESULT11;
            }

                 if( USERINPUT11 => 3000 ); {
             {RESULT11 = (( p2 * USERINPUT11) / 1000 ); ;
        }
        //This IF statement is not working.

</script>
</code>```

<p>I can't get to work the if statement, the user will input a value, and depending of the value it will calculate differently.  any help would be appreciate and thank you. </p>

答:
Three things that I see..

Remove the semicolon after the condition.

Fix the comparator.

Put the if statement inside the function. (Clean up your curly braces)

Doing that you get..

```<code>function calculate11() {
    var USERINPUT11 = document.TESTING11.INPUT11.value,
        RESULT11 = (( p1 * USERINPUT11) / 1000 );

    document.TESTING11.OUTPUT11.value = RESULT11;

    if( USERINPUT11 >= 3000 ) {
        RESULT11 = ((p2 * USERINPUT11) / 1000 );
    }
}
</code>```

Now I'm going to assume you want to call the if statement before you use the object affected inside it. That will look something like this...

```<code>function calculate11() {
    var USERINPUT11 = document.TESTING11.INPUT11.value,
        RESULT11 = (( p1 * USERINPUT11) / 1000 );

    if( USERINPUT11 >= 3000 ) {
        RESULT11 = ((p2 * USERINPUT11) / 1000 );
    }

    document.TESTING11.OUTPUT11.value = RESULT11;
}
</code>```

Now since it is pretty clear you are just doing a conditional assignment, how about we use the ternary operator and refactor just a little to make it pretty.

```<code>function calculate11() {
    var USERINPUT11 = document.TESTING11.INPUT11.value;

    var pFactor = USERINPUT11 < 3000 ? p1 : p2;

    document.TESTING11.OUTPUT11.value = (pFactor * USERINPUT11) / 1000;
}
</code>```

Voila! Hope that helps and maybe try a javascript tutorial to learn more.

Title: I can't get to work the IF statement

Body:
    </script>

I can't get to work the if statement, the user will input a value, and depending of the value it will calculate differently.  any help would be appreciate and thank you.

Body:
Three things that I see..

Remove the semicolon after the condition.

Fix the comparator.

Put the if statement inside the function. (Clean up your curly braces)

Doing that you get..

function calculate11() {
    var USERINPUT11 = document.TESTING11.INPUT11.value,
        RESULT11 = (( p1 * USERINPUT11) / 1000 );

    document.TESTING11.OUTPUT11.value = RESULT11;

    if( USERINPUT11 >= 3000 ) {
        RESULT11 = ((p2 * USERINPUT11) / 1000 );
    }
}

Now I'm going to assume you want to call the if statement before you use the object affected inside it. That will look something like this...

function calculate11() {
    var USERINPUT11 = document.TESTING11.INPUT11.value,
        RESULT11 = (( p1 * USERINPUT11) / 1000 );

    if( USERINPUT11 >= 3000 ) {
        RESULT11 = ((p2 * USERINPUT11) / 1000 );
    }

    document.TESTING11.OUTPUT11.value = RESULT11;
}

Now since it is pretty clear you are just doing a conditional assignment, how about we use the ternary operator and refactor just a little to make it pretty.

function calculate11() {
    var USERINPUT11 = document.TESTING11.INPUT11.value;

    var pFactor = USERINPUT11 < 3000 ? p1 : p2;

    document.TESTING11.OUTPUT11.value = (pFactor * USERINPUT11) / 1000;
}

Voila! Hope that helps and maybe try a javascript tutorial to learn more.


问:
Is there a built-in (no for loop) way to put ranges of a vector into a cell array using a matrix for the indices?
Given:

```<code>data = 0:10;
indices = [1 2; 3 7; 2 5];
</code>```

Is there a one-line way to do this?:

```<code>for i = 1:length(indices)
    out{i} = data(indices(i,1):indices(i,2))
end
</code>```

答:
You can do this with arrayfun:

```<code>out = arrayfun(@(a,b) data(a:b), indices(:,1), indices(:,2), 'UniformOutput', false);
</code>```

However, internally arrayfun is still probably just using a for loop, so I wouldn't expect to see any improvement in speed. This syntax simply allows you to write it as a one-liner. A somewhat ugly one-liner.

Body:
Given:

data = 0:10;
indices = [1 2; 3 7; 2 5];

Is there a one-line way to do this?:

for i = 1:length(indices)
    out{i} = data(indices(i,1):indices(i,2))
end

Body:
You can do this with arrayfun:

out = arrayfun(@(a,b) data(a:b), indices(:,1), indices(:,2), 'UniformOutput', false);

However, internally arrayfun is still probably just using a for loop, so I wouldn't expect to see any improvement in speed. This syntax simply allows you to write it as a one-liner. A somewhat ugly one-liner.


问:
Date Range Based on Today
I am trying to write a stored procedure that will be called by an automated report on the 1st, 8th, 15th, and 22nd of each month.

Below I have the code I am currently trying to use however I keep getting the error Explicit conversion from data type int to date is not allowed. on the line for @StartDate if ran on the 1st. However I have tried commenting out that section and I just get the same error but then for the next @StartDate.

I need @StartDate and @EndDate to be able to change based on which day of the month the report is currently being ran.

On the 1st it would need to be ran from the 21st of the
previous month to the end of the previous month.

On the  8th it would need to be  1st of the current month to the  7th.

On the 15th it would need to be  8th of the current month to the 14th.

On the 22nd it would need to be 15th of the current month to the 21st.

```<code>Declare @RunDate    date
Declare @StartDate Date
Declare @EndDate    Date

Set  @RunDate = '3/1/2017'

If (Day(@RunDate) = 1)
Begin

Set @StartDate  = Convert(Date,(Month(DATEADD(d,-1,@Rundate)) + '/21/' + Case When Month(@Rundate) = '1' Then Year(@RunDate) Else Year(DATEADD(yy,-1,@Rundate)) End),101)
Set @EndDate    = Convert(date,DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,@Rundate),0))),101)

End
Else
IF (Day(@RunDate) = 8)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/1/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/7/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 15)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/8/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/14/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 22)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/15/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/21/' + Year(@RunDate)),101)

End
</code>```

I am using SQL Server 2012 back end with SSMS 2016 front end. If that helps.

答:
You can simplify all of that down to:

```<code>Declare @RunDate date, @StartDate date, @EndDate date;
Set  @RunDate = '20170301';
If (Day(@RunDate) = 1)
Begin;
Set @StartDate = dateadd(day,20,dateadd(month, datediff(month, 0, @RunDate)-1, 0))
Set @EndDate   = dateadd(day,-1,dateadd(month, datediff(month, 0, @RunDate), 0))
End;
Else
If (Day(@RunDate) in (8,15,22))
Begin;
Set @StartDate = dateadd(day,Day(@RunDate)-8,dateadd(month, datediff(month, 0, @RunDate), 0))
Set @EndDate   = dateadd(day,Day(@RunDate)-2,dateadd(month, datediff(month, 0, @RunDate), 0))
End;
</code>```

Alternative using case, but doesn't verify for the day() in 8,15,22:

```<code>Declare @RunDate date, @StartDate date, @EndDate date;
Set  @RunDate = '20170328';

set @StartDate = case day(@RunDate)
    when 1 then dateadd(day,20,dateadd(month, datediff(month, 0, @RunDate)-1, 0))
    else dateadd(day,Day(@RunDate)-8,dateadd(month, datediff(month, 0, @RunDate), 0))
    end;

set @EndDate = case day(@RunDate)
    when 1 then dateadd(day,-1,dateadd(month, datediff(month, 0, @RunDate), 0))
    else dateadd(day,Day(@RunDate)-2,dateadd(month, datediff(month, 0, @RunDate), 0))
    end;
</code>```

rextester demo of both: http://rextester.com/CCUFI85069

Title: Date Range Based on Today

Body:
I am trying to write a stored procedure that will be called by an automated report on the 1st, 8th, 15th, and 22nd of each month.

Below I have the code I am currently trying to use however I keep getting the error Explicit conversion from data type int to date is not allowed. on the line for @StartDate if ran on the 1st. However I have tried commenting out that section and I just get the same error but then for the next @StartDate.

I need @StartDate and @EndDate to be able to change based on which day of the month the report is currently being ran.

On the 1st it would need to be ran from the 21st of the
previous month to the end of the previous month.

On the  8th it would need to be  1st of the current month to the  7th.

On the 15th it would need to be  8th of the current month to the 14th.

On the 22nd it would need to be 15th of the current month to the 21st.

Declare @RunDate    date
Declare @StartDate Date
Declare @EndDate    Date

Set  @RunDate = '3/1/2017'

If (Day(@RunDate) = 1)
Begin

Set @StartDate  = Convert(Date,(Month(DATEADD(d,-1,@Rundate)) + '/21/' + Case When Month(@Rundate) = '1' Then Year(@RunDate) Else Year(DATEADD(yy,-1,@Rundate)) End),101)
Set @EndDate    = Convert(date,DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,@Rundate),0))),101)

End
Else
IF (Day(@RunDate) = 8)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/1/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/7/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 15)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/8/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/14/' + Year(@RunDate)),101)

End
Else
If (Day(@Rundate) = 22)
Begin

Set @StartDate  = Convert(Date,(Month(@Rundate) + '/15/' + Year(@RunDate)),101)
Set @EndDate    = Convert(Date,(Month(@Rundate) + '/21/' + Year(@RunDate)),101)

End

I am using SQL Server 2012 back end with SSMS 2016 front end. If that helps.

Body:
You can simplify all of that down to:

Declare @RunDate date, @StartDate date, @EndDate date;
Set  @RunDate = '20170301';
If (Day(@RunDate) = 1)
Begin;
Set @StartDate = dateadd(day,20,dateadd(month, datediff(month, 0, @RunDate)-1, 0))
Set @EndDate   = dateadd(day,-1,dateadd(month, datediff(month, 0, @RunDate), 0))
End;
Else
If (Day(@RunDate) in (8,15,22))
Begin;
Set @StartDate = dateadd(day,Day(@RunDate)-8,dateadd(month, datediff(month, 0, @RunDate), 0))
Set @EndDate   = dateadd(day,Day(@RunDate)-2,dateadd(month, datediff(month, 0, @RunDate), 0))
End;

Alternative using case, but doesn't verify for the day() in 8,15,22:

Declare @RunDate date, @StartDate date, @EndDate date;
Set  @RunDate = '20170328';

set @StartDate = case day(@RunDate)
    when 1 then dateadd(day,20,dateadd(month, datediff(month, 0, @RunDate)-1, 0))
    else dateadd(day,Day(@RunDate)-8,dateadd(month, datediff(month, 0, @RunDate), 0))
    end;

set @EndDate = case day(@RunDate)
    when 1 then dateadd(day,-1,dateadd(month, datediff(month, 0, @RunDate), 0))
    else dateadd(day,Day(@RunDate)-2,dateadd(month, datediff(month, 0, @RunDate), 0))
    end;

rextester demo of both: http://rextester.com/CCUFI85069


问:
FFmpeg php metadata wrapper
I have two questions about FFmpeg
1. Does FFmpeg Output change with versions (ffmpeg -i)
2. If the output don't change, anyone know a good PHP/Python class that parse FFmpeg Output and get all metadata (Duration, Codec, Audio Biterate, Video Biterate, Width, Height...)
3. if the FFmpeg output change, anyone know a linux tool (cmd line) that get those metadatas without dependence of FFmpeg.

I know that the php-ffmpeg module exist, but it's so old and buggy (wrong duration for example..., can't get $movie->getAudioBitRate() working )

Thanks

答: ffpmpeg-php seems to be your best bet, unless you want to grab/parse ffmpeg's output directly. If you plan on working with remote files (eg. urls vs. local files) then FFmpeg-php will not work with anything but absolute urls (eg. http://example.com/video.mp4 vs. http://example.com/?get_video=234). There might be a cURL option for accomplishing this but I've yet to come across anything stable.</p>

ContentLicense: CC BY-SA 2.5

Title: FFmpeg php metadata wrapper


问:
How can I filter OUT a <tagname> using adb logcat
This is related to Filter output in logcat by tagname. How can I filter out a tagname. Ex - If I don't want the tagname GNU.IO to be echoed to stdout, I would like something which would do the equivalent of -

```<code>adb logcat | grep -v <tagname>
</code>```

Unfortunately the above is not working for me.

答:
Just set specific tag's level to S(ilent):

```<code>adb logcat <TAG>:S
</code>```

as result, you'll see all messages excluding TAG

Body:
This is related to Filter output in logcat by tagname. How can I filter out a tagname. Ex - If I don't want the tagname GNU.IO to be echoed to stdout, I would like something which would do the equivalent of -

adb logcat | grep -v <tagname>

Unfortunately the above is not working for me.

Body:
Just set specific tag's level to S(ilent):

adb logcat <TAG>:S

as result, you'll see all messages excluding TAG


问:
Set not being called for array with getter/setter in C# .NET
I have a number of bytes stored as an array. When any of these bytes values are changed, I want to use the setter to call another method. In the below example, this is a messagebox:

```<code>private byte[] numberArps = new byte[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };   // EEPROM 21
public byte[] NumberArps
{
    get
    {
        MessageBox.Show("Get called");
        return this.numberArps;
    }
    set
    {
        MessageBox.Show("Set called");
    }
}
</code>```

This is called with the following code:

```<code>numberArps_textbox_1 = NumberArps[1].ToString();
NumberArps[1] = (byte)numberArps_textbox_1;
</code>```

The messagebox "Get called" shows. Strangely, the code within the set {} braces is never reached even when debugging, the value is in fact stored in the array.

Is this error due to using array getter/setter incorrectly, or an error in implementation?

答:
Because you are setting an individual value, not the property directly. Setter would only get called if you set it like this:

```<code>NumberArps = new byte[5];
</code>```

If you want to control changes in the collection, get notified when item is added/modified, try using ObservableCollection<T>.

Body:
I have a number of bytes stored as an array. When any of these bytes values are changed, I want to use the setter to call another method. In the below example, this is a messagebox:

private byte[] numberArps = new byte[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };   // EEPROM 21
public byte[] NumberArps
{
    get
    {
        MessageBox.Show("Get called");
        return this.numberArps;
    }
    set
    {
        MessageBox.Show("Set called");
    }
}

This is called with the following code:

numberArps_textbox_1 = NumberArps[1].ToString();
NumberArps[1] = (byte)numberArps_textbox_1;

The messagebox "Get called" shows. Strangely, the code within the set {} braces is never reached even when debugging, the value is in fact stored in the array.

Is this error due to using array getter/setter incorrectly, or an error in implementation?

Body:
Because you are setting an individual value, not the property directly. Setter would only get called if you set it like this:

NumberArps = new byte[5];

If you want to control changes in the collection, get notified when item is added/modified, try using ObservableCollection<T>.


问:
Calling a webservice in camel having the soap request as String
I want to call a Web Service using Apache Camel and I have the SOAP message in the form of String. Can anyone kindly let me know how to send SOAP request in form of String in Camel?</p>

答:
It depends of what type of endpoint you have for your outbound webservice.

If it is a CXF JAX-WS then it depends on what dataFormat property is set to: POJO or PAYLOAD.

For POJO you have take SOAP headers, SOAP Body elements, unmarshal them to JAXB Pojos, then set them to Camel Exchange Body properly pass Exchange to endpoint
For PAYLOAD - I'm not sure but maybe you can pass your string as is (or just SOAP body and SOAP headers elements) as strings. If not, check what CXF expects to get when dataFormat is PAYLOAD. (I just used it long time back).

For simple http endpoint just pass your string to it "as is" in the body with Http-method POST and Content-type header as application/xml


问:
Angular change detection on @Input object
I kind of understand how change detection works in Angular 2 but I'm really struggling to transfer/change my AngularJS methods over to NG2 regarding change detection.

Imagine I have a component that takes a single @Input() anObject and has a single function, logAllProperties() which, for arguments sake, logs all the properties to the console.
All I want to do is to call logAllProperties() every time anObject changes in anyway whatsoever.

I understand that treating the object as immutable (either with an external library like Immutable.js or by enforcing that the entire object changes even for a minor property change) will trigger ngOnChange but is there anyway to call a function whenever a change takes place aside from these or using DoCheck which I understand is potentially extremely inefficient.

As well as "is there a way", what is the correct way to do something like this? I'm new to Angular2 so I'm more than happy to learn the right way if Immutable and Observables are the way to go.

Thanks in advance

答:
I found out in our projects that using set works well in some cases, but others cases that need sync between components could be troubling, then we are using ngOnChange for those cases. Here's an example.

```<code>@Input() set myProperty(myProperty: MyPropertyType) {
        if (myProperty) {
            this.logService.log(myProperty);
        }

        this._myProperty = myProperty;
}
private _myProperty: MyPropertyType= new MyPropertyType();
</code>```

The thing about Angular2 new lifecycle still confuse, and the documentation samples doesn't fit most of the real world cases.

Body:
I found out in our projects that using set works well in some cases, but others cases that need sync between components could be troubling, then we are using ngOnChange for those cases. Here's an example.

@Input() set myProperty(myProperty: MyPropertyType) {
        if (myProperty) {
            this.logService.log(myProperty);
        }

        this._myProperty = myProperty;
}
private _myProperty: MyPropertyType= new MyPropertyType();

The thing about Angular2 new lifecycle still confuse, and the documentation samples doesn't fit most of the real world cases.


问:
Update statement with joins
I must create migration to update question image attribute but i need to check some attributes from other tables, my schema looks like this:

```<code>question {
id,
name,
groupId,
imageUrl -> i need to update this
}

group {
id,
name,
quizId
}

quiz {
id,
name,
type -> where type is 'History'
}
</code>```

And i need to update attribute imageUrl from table question WHERE quiz type is for example 'History', i'm not sure how i can join this tables when using UPDATE. I tried something like this but it's not working like i want.

```<code>UPDATE question SET image_url = 'pathToImage' FROM quiz q WHERE q.type = 'History'
</code>```

答:
JOIN three tables on this way:</p>

```<code>UPDATE question q
SET    image_url = 'pathToImage'
FROM   (select g.Id
        from group g
        JOIN   quiz z
        ON     g.quizID = z.Id
        WHERE  z.type = 'History') p
ON     q.groupId = p.Id;
</code>```

Title: Update statement with joins

Body:
I must create migration to update question image attribute but i need to check some attributes from other tables, my schema looks like this:

question {
id,
name,
groupId,
imageUrl -> i need to update this
}

group {
id,
name,
quizId
}

quiz {
id,
name,
type -> where type is 'History'
}

And i need to update attribute imageUrl from table question WHERE quiz type is for example 'History', i'm not sure how i can join this tables when using UPDATE. I tried something like this but it's not working like i want.

UPDATE question SET image_url = 'pathToImage' FROM quiz q WHERE q.type = 'History'

Body:
JOIN three tables on this way:

UPDATE question q
SET    image_url = 'pathToImage'
FROM   (select g.Id
        from group g
        JOIN   quiz z
        ON     g.quizID = z.Id
        WHERE  z.type = 'History') p
ON     q.groupId = p.Id;


问:
C++ effective calculation
which is the most effective way to calculate does double is equal to another double, does it less with 1 or greater with one of it.

EDIT:
Example 18 > 18, 17 and 19 - true; 5,5 > 5,5, 4,5, and 6,5 - true.

If 18 is is in range between 17 and 19 - return true. Else return false.

If 5,5 is equal to 5,5 or it is in range of 4,5 to 6,5 - return true. Else return false.
Code started:

```<code>bool inRange(double one, double two)
{
    return  (one== one);
}
</code>```

答:
```<code>#include <cmath>

bool inRange(double dNumber, double dMiddle)
{
    return std::fabs(dNumber - dMiddle) <= 1;
}
</code>```

Title: C++ effective calculation

Body:
which is the most effective way to calculate does double is equal to another double, does it less with 1 or greater with one of it.

EDIT:
Example 18 > 18, 17 and 19 - true; 5,5 > 5,5, 4,5, and 6,5 - true.

If 18 is is in range between 17 and 19 - return true. Else return false.

If 5,5 is equal to 5,5 or it is in range of 4,5 to 6,5 - return true. Else return false.
Code started:

bool inRange(double one, double two)
{
    return  (one== one);
}


问:
languageext Either.Map/Bind with a Task in the Right position
I am using the toolkit languageext package for C# and am running into a problem with the Either class when the Right value is some kind of Task.  For some reason this is causing a hang:

```<code>        var res = repo.GetAccountWithID(accountID)
            .Map(c => filesServiceCustomer.Initialize(c))
            .Bind(t => t.Result);
</code>```

Here, GetAccountWithID returns an Either<Exception, Account> and the Initialize method take an Account and returns a Task<Either<Exception, bool>>.  However, it would appear that either the Map or Bind calls are hanging.

Does anyone have any idea what might be causing this or what to do about it?

答:
(I'm the author of the language-ext project).  There's no fundamental reason for your expression to hang, other than if the Task itself is blocking - Map and Bind are trivial functions that don't do anything particularly clever, and definitely don't do any synchronisation or anything like that.  I just added this code to the unit tests in lang-ext, and it returns fine:

```<code>    public class Account : NewType<Account, Unit>
    {
        public Account(Unit _) : base(unit) { }
    }

    Either<Exception, Account> GetAccountWithID(int accountId) =>
        Account.New(unit);

    Task<Either<Exception, bool>> Initialize(Account c) =>
        Task.FromResult(Right<Exception, bool>(true));

    [Fact]
    public void StackOverflowQuestion()
    {
        int accountID = 0;

        var res = GetAccountWithID(accountID)
            .Map(c => Initialize(c))
            .Bind(t => t.Result);
    }
</code>```

One thing it's worth mentioning is that it's not great practice to call .Result on a task.  You can definitely leverage other features in language-ext to make this work better for you:

For example:

```<code>    var task = from c in GetAccountWithID(accountID).AsTask()
               from r in Initialize(c)
               select r;
</code>```

AsTask lifts the Either<Exception, Account> into a Task<Either<Exception, Account>>, which then means it's usable in a LINQ expression with Initialize (which also returns a Task).

If you're fundamentally opposed to the LINQ syntax, then you can do:

```<code>    var task = GetAccountWithID(accountID).AsTask().BindT(Initialize);
</code>```

task is then a Task<Either<Exception, bool>> which you can await:

```<code>    var res = (await task).IfLeft(false);
</code>```

Another trick (if you're using version 2.0.*) is to use Sequence which flips the inner and outer monads:

```<code>    var res = task.Sequence();
</code>```

That will turn the Task<Either<Exception, bool>> into a Either<Exception, Task<bool>> which you can match on.  Obviously it depends on your use-case as to what's most appropriate.

Body:
I am using the toolkit languageext package for C# and am running into a problem with the Either class when the Right value is some kind of Task.  For some reason this is causing a hang:

        var res = repo.GetAccountWithID(accountID)
            .Map(c => filesServiceCustomer.Initialize(c))
            .Bind(t => t.Result);

Here, GetAccountWithID returns an Either<Exception, Account> and the Initialize method take an Account and returns a Task<Either<Exception, bool>>.  However, it would appear that either the Map or Bind calls are hanging.

Does anyone have any idea what might be causing this or what to do about it?

Body:
(I'm the author of the language-ext project).  There's no fundamental reason for your expression to hang, other than if the Task itself is blocking - Map and Bind are trivial functions that don't do anything particularly clever, and definitely don't do any synchronisation or anything like that.  I just added this code to the unit tests in lang-ext, and it returns fine:

    public class Account : NewType<Account, Unit>
    {
        public Account(Unit _) : base(unit) { }
    }

    Either<Exception, Account> GetAccountWithID(int accountId) =>
        Account.New(unit);

    Task<Either<Exception, bool>> Initialize(Account c) =>
        Task.FromResult(Right<Exception, bool>(true));

    [Fact]
    public void StackOverflowQuestion()
    {
        int accountID = 0;

        var res = GetAccountWithID(accountID)
            .Map(c => Initialize(c))
            .Bind(t => t.Result);
    }

One thing it's worth mentioning is that it's not great practice to call .Result on a task.  You can definitely leverage other features in language-ext to make this work better for you:

For example:

    var task = from c in GetAccountWithID(accountID).AsTask()
               from r in Initialize(c)
               select r;

AsTask lifts the Either<Exception, Account> into a Task<Either<Exception, Account>>, which then means it's usable in a LINQ expression with Initialize (which also returns a Task).

If you're fundamentally opposed to the LINQ syntax, then you can do:

    var task = GetAccountWithID(accountID).AsTask().BindT(Initialize);

task is then a Task<Either<Exception, bool>> which you can await:

    var res = (await task).IfLeft(false);

Another trick (if you're using version 2.0.*) is to use Sequence which flips the inner and outer monads:

    var res = task.Sequence();

That will turn the Task<Either<Exception, bool>> into a Either<Exception, Task<bool>> which you can match on.  Obviously it depends on your use-case as to what's most appropriate.


问:
Printing the second half of a linked list in reverse order
I want to print the elements of a linked list, first in their order and then, once I reach the middle, in reverse order (from the last one backwards). For example:

If the elements are: 1 2 3 4 5 6

It should print: 1 2 3 6 5 4

But it's printing: 1 2 3 5 4

Why isn't it printing the last element? How can this be solved?

```<code>void reverse()
{
    int c=1;
    node *current,*prev,*temp;
    current=head;
    prev=NULL;
    std::stack<int>s;
    while(current->next!=NULL)
    {
        c++;
        s.push(current->data);
        current=current->next;
    }

    int mid=0;
    if((c%2)==0)
    {
        mid=c/2;
    }
    else
    {
        mid=(c+1)/2;
    }
    current=head;
    for(int i=0;i<mid;i++)
    {
        cout<<current->data<<"\t";
        current=current->next;
    }

    for(int i=mid;i>1;i--)
    {
       std::cout<<s.top()<<"\t";
       s.pop();
    }
    std::cout << '\n';
}
</code>```

答:
In your while loop you are checking if current->next is null you need to check if current is null.

```<code>while(current)
{
    c++;
    s.push(current->data);
    current=current->next;
}
</code>```

You weren't adding the last number into the stack

Body:
I want to print the elements of a linked list, first in their order and then, once I reach the middle, in reverse order (from the last one backwards). For example:

If the elements are: 1 2 3 4 5 6

It should print: 1 2 3 6 5 4

But it's printing: 1 2 3 5 4

Why isn't it printing the last element? How can this be solved?

void reverse()
{
    int c=1;
    node *current,*prev,*temp;
    current=head;
    prev=NULL;
    std::stack<int>s;
    while(current->next!=NULL)
    {
        c++;
        s.push(current->data);
        current=current->next;
    }

    int mid=0;
    if((c%2)==0)
    {
        mid=c/2;
    }
    else
    {
        mid=(c+1)/2;
    }
    current=head;
    for(int i=0;i<mid;i++)
    {
        cout<<current->data<<"\t";
        current=current->next;
    }

    for(int i=mid;i>1;i--)
    {
       std::cout<<s.top()<<"\t";
       s.pop();
    }
    std::cout << '\n';
}

Body:
In your while loop you are checking if current->next is null you need to check if current is null.

while(current)
{
    c++;
    s.push(current->data);
    current=current->next;
}

You weren't adding the last number into the stack


答:
@input decorator is denoted your component is expecting to get some data from its parent which will be caught at that property

same way @output is the decorator in angular2 wherein parent component you can catch something from child.

Internally it uses observable and I don't think it's immutable.

ngrx provides a redux type immutable mechanism where every state is remembered and you can go back to them as well.

Observable and ngrx are running in parallel now.

Title: Angular change detection on @Input object

Body:
I kind of understand how change detection works in Angular 2 but I'm really struggling to transfer/change my AngularJS methods over to NG2 regarding change detection.

Imagine I have a component that takes a single @Input() anObject and has a single function, logAllProperties() which, for arguments sake, logs all the properties to the console.
All I want to do is to call logAllProperties() every time anObject changes in anyway whatsoever.

I understand that treating the object as immutable (either with an external library like Immutable.js or by enforcing that the entire object changes even for a minor property change) will trigger ngOnChange but is there anyway to call a function whenever a change takes place aside from these or using DoCheck which I understand is potentially extremely inefficient.

As well as "is there a way", what is the correct way to do something like this? I'm new to Angular2 so I'm more than happy to learn the right way if Immutable and Observables are the way to go.

Thanks in advance


问:
Adding a Random Page Button to Weebly
I have been trying for quite a while to add a random page button to my Weebly website so that my users can click on it and it will bring them to a random game page. I have researched this topic and found a couple of guides but they do not seem to work. Here's my code. It never works.

<form>
<input type="button" value="Click here for a random game!" onClick="randomlinks()">
</form>```

Just for reference here is a link to a test page where the code is applied.

答:
try using the following code ...

<form>
<input type="button" value="Click here for a random game!" onclick="randomlinks()">
</form>```

Title: Adding a Random Page Button to Weebly

Body:
I have been trying for quite a while to add a random page button to my Weebly website so that my users can click on it and it will bring them to a random game page. I have researched this topic and found a couple of guides but they do not seem to work. Here's my code. It never works.

<form>
<input type="button" value="Click here for a random game!" onClick="randomlinks()">
</form>

Just for reference here is a link to a test page where the code is applied.

Body:
try using the following code ...

<script type="text/javascript">
function randomlinks() {
    var links = [
      "http://www.awesomeinternetgames.weebly.com/age-of-war",
      "http://www.awesomeinternetgames.weebly.com/age-of-war-2",
      "http://www.awesomeinternetgames.weebly.com/apple-shooter",
      "http://www.awesomeinternetgames.weebly.com/avalanche",
      "http://www.awesomeinternetgames.weebly.com/band-rpg",
      "http://www.awesomeinternetgames.weebly.com/bloons-td-5",
      "http://www.awesomeinternetgames.weebly.com/bloons-td-4",
      "http://awesomeinternetgames.weebly.com/canyon-defense",
      "http://awesomeinternetgames.weebly.com/cyclomaniacs",
      "http://awesomeinternetgames.weebly.com/cock-shooter",
      "http://awesomeinternetgames.weebly.com/corporate-soccer-2",
      "http://awesomeinternetgames.weebly.com/counter-terror",
      "http://awesomeinternetgames.weebly.com/commando",
      "http://awesomeinternetgames.weebly.com/commando-2",
      "http://awesomeinternetgames.weebly.com/copter",
      "http://awesomeinternetgames.weebly.com/corporation-inc",
      "http://awesomeinternetgames.weebly.com/cubefield",
      "http://awesomeinternetgames.weebly.com/curve-fever",
      "http://awesomeinternetgames.weebly.com/demolition-city-2",
      "http://awesomeinternetgames.weebly.com/dead-zed-2",
      "http://awesomeinternetgames.weebly.com/dino-run",
      "http://awesomeinternetgames.weebly.com/drag-racer",
      "http://awesomeinternetgames.weebly.com/duck-life-4",
      "http://awesomeinternetgames.weebly.com/dune-buggy",
      "http://awesomeinternetgames.weebly.com/earn-to-die-2-exodus",
      "http://awesomeinternetgames.weebly.com/earn-to-die",
      "http://awesomeinternetgames.weebly.com/earn-to-die-2012",
      "http://awesomeinternetgames.weebly.com/earn-to-die-2012-part-2",
      "http://awesomeinternetgames.weebly.com/effing-worms",
      "http://awesomeinternetgames.weebly.com/effing-worms-2",
      "http://awesomeinternetgames.weebly.com/enough-plumbers",
      "http://awesomeinternetgames.weebly.com/fireboy-and-watergirl",
      "http://awesomeinternetgames.weebly.com/flappy-bird-flash",
      "http://awesomeinternetgames.weebly.com/flight",
      "http://awesomeinternetgames.weebly.com/game-corp",
      "http://awesomeinternetgames.weebly.com/gravity-guy",
      "http://awesomeinternetgames.weebly.com/happy-wheels",
      "http://awesomeinternetgames.weebly.com/helic",
      "http://awesomeinternetgames.weebly.com/infected",
      "http://awesomeinternetgames.weebly.com/infectonator-2",
      "http://awesomeinternetgames.weebly.com/innkeeper",
      "http://awesomeinternetgames.weebly.com/into-space",
      "http://awesomeinternetgames.weebly.com/into-space-2",
      "http://awesomeinternetgames.weebly.com/kingdom-rush",
      "http://awesomeinternetgames.weebly.com/the-last-stand",
      "http://awesomeinternetgames.weebly.com/learn-to-fly",
      "http://awesomeinternetgames.weebly.com/learn-to-fly-2",
      "http://awesomeinternetgames.weebly.com/learn-to-fly-3",
      "http://awesomeinternetgames.weebly.com/moby-dick-2",
      "http://awesomeinternetgames.weebly.com/monster-trucks-nitro",
      "http://awesomeinternetgames.weebly.com/papa-louie",
      "http://awesomeinternetgames.weebly.com/planet-racer",
      "http://awesomeinternetgames.weebly.com/pointer",
      "http://awesomeinternetgames.weebly.com/potty-racers",
      "http://awesomeinternetgames.weebly.com/porry-racers-2",
      "http://awesomeinternetgames.weebly.com/portal-flash",
      "http://awesomeinternetgames.weebly.com/escaping-the-prison",
      "http://awesomeinternetgames.weebly.com/breaking-the-bank",
      "http://awesomeinternetgames.weebly.com/stealing-the-diamond",
      "http://awesomeinternetgames.weebly.com/renegade-racing",
      "http://awesomeinternetgames.weebly.com/rollercoaster-creator",
      "http://awesomeinternetgames.weebly.com/rogue-soul",
      "http://awesomeinternetgames.weebly.com/rubble-trouble-moscow",
      "http://awesomeinternetgames.weebly.com/rubble-trouble-new-york",
      "http://awesomeinternetgames.weebly.com/run",
      "http://awesomeinternetgames.weebly.com/rural-racer",
      "http://awesomeinternetgames.weebly.com/shop-empire",
      "http://awesomeinternetgames.weebly.com/shop-empire-2",
      "http://awesomeinternetgames.weebly.com/shopping-city",
      "http://awesomeinternetgames.weebly.com/shopping-street",
      "http://awesomeinternetgames.weebly.com/snake",
      "http://awesomeinternetgames.weebly.com/sniper-assassin",
      "http://awesomeinternetgames.weebly.com/sugarsugar2",
      "http://awesomeinternetgames.weebly.com/super-mario-flash",
      "http://awesomeinternetgames.weebly.com/stick-war",
      "http://awesomeinternetgames.weebly.com/strike-force-heroes",
      "http://awesomeinternetgames.weebly.com/strike-force-heroes-2",
      "http://awesomeinternetgames.weebly.com/stunt-pilot",
      "http://awesomeinternetgames.weebly.com/tank-trouble",
      "http://awesomeinternetgames.weebly.com/territory-war",
      "http://awesomeinternetgames.weebly.com/theme-hotel",
      "http://awesomeinternetgames.weebly.com/trials-2",
      "http://awesomeinternetgames.weebly.com/tu-46",
      "http://awesomeinternetgames.weebly.com/tu-95",
      "http://awesomeinternetgames.weebly.com/the-unfair-platformer",
      "http://awesomeinternetgames.weebly.com/valet-parking-3d",
      "http://awesomeinternetgames.weebly.com/zombie-trailer-park"
    ];
    var myrandom = Math.floor(Math.random() * links.length);
    window.location = links[myrandom];
}
</script>
<form>
<input type="button" value="Click here for a random game!" onclick="randomlinks()">
</form>


问:
Django paging with slicing
I'm new to Django and Python and I'm trying to understand how to accomplish paging without getting all the records from a QuerySet first.  All the examples I've seen with QuerySets will get all the records first like below.

```<code>tickets = Ticket.objects.filter(site=site.id)
paginator = Paginator(tickets, settings.PAGE_SIZE)
</code>```

This seems to make sense so that the Paginator will have a reference to how many pages it needs.  However, this seems inefficient to get all the records for each page request.  I know that QuerySets can be sliced to return a range of records.

How do I design my paging in order to only get the records pertinent for that page (slicing?), yet still have paging features?

Edit: Added template code that iterates.

```<code>  {% for ticket in tickets.object_list %}
        {{ ticket }}<br/>
   {% endfor %}
</code>```

答:
Underlying queries for the QuerySet objects are not executed until you explicitly evaluate them. Explicit evaluation occurs whenever you iterate through them, which includes calling str() or unicode().

Thus, the above code snippet is indeed efficient. The line tickets = Ticket.objects.filter(site=site.id) creates a new QuerySet, but the query isn't evaluated yet.

For the same reason, stuff like Model.objects.filter(foo).filter(bar).order_by(baz)... doesn't execute a single SQL query.

Title: Django paging with slicing

Body:
I'm new to Django and Python and I'm trying to understand how to accomplish paging without getting all the records from a QuerySet first.  All the examples I've seen with QuerySets will get all the records first like below.

tickets = Ticket.objects.filter(site=site.id)
paginator = Paginator(tickets, settings.PAGE_SIZE)

This seems to make sense so that the Paginator will have a reference to how many pages it needs.  However, this seems inefficient to get all the records for each page request.  I know that QuerySets can be sliced to return a range of records.

How do I design my paging in order to only get the records pertinent for that page (slicing?), yet still have paging features?

Edit: Added template code that iterates.

  {% for ticket in tickets.object_list %}
        {{ ticket }}

   {% endfor %}


问:
How to modify wagtail CMS so that any user can post blog posts under their own blog
I have an existing website that is a Django App.
I have installed Wagtail, and the Wagtail CMS is now accessible at www.example.com/cms. Wagtail is working correctly with my database, and all the existing users are visible when I go to settings and then users, in the wagtail CMS admin page.

I want to use Wagtail to add blog functionality to my website.

Requirements

I want any user to be able to create a new blog and add posts to their blog.

I want the blog created by a user to be visible at www.example.com/blogs/username/

How can I set Wagtail up to accomplish this?

I have checked the documentation at http://docs.wagtail.io/en/v1.9/ but could not figure out where to start with my modifications. I have also installed the example blog project (https://github.com/wagtail/wagtaildemo) but I was also unable to figure out how to accomplish 1 and 2 above from this.

Any complete answers, or general pointers, very welcome.

答:
The permission model built into Wagtail supports this kind of setup: http://docs.wagtail.io/en/stable/topics/permissions.html

After creating the index page for a blog, you'd create a group (Settings -> Groups in the Wagtail admin) for that blog - possibly just containing a single user - and under the 'Page permissions' section, assign it 'add' and 'publish' permission on that index page. Permissions propagate down the tree from that point, and 'add' permission encompasses the ability to edit pages that you've created yourself, so this would have the effect of giving the user control over the subpages of their blog.

This doesn't quite match the setup you've described, since it involves an existing Wagtail admin user having to do the initial setup, rather than users creating their own blog. However, since all of this configuration is done internally by creating / updating standard Django models such as Group and PagePermission, it would be possible in principle to script this process - for example, you could implement a Django view for "Set up my blog" on your site front-end, which runs the following steps:

Create a BlogIndexPage under /blogs with a title/slug matching request.user.username (see https://stackoverflow.com/a/43041179/1853523 for how to create pages programmatically)

Create a user group (django.contrib.auth.models.Group) for the current user, and assign them wagtailadmin.access_admin permission (so that they can log in to Wagtail admin)

Create a wagtailcore.PagePermission object corresponding to the newly-created group and blog index page, and 'add' permission; and likewise for 'publish' permission

ContentLicense: CC BY-SA 4.0


问:
How to use 'expect', 'toBe', 'toEqual' in Angular 2?
I'm trying to use something I've seen around that looks like:

```<code>let test1 = {value:5};
let test2 = {value:5};

// Returns true.
expect(test1).toEqual(test2);
</code>```

However, it's just giving me an error:

```<code>EXCEPTION: Error in :0:0 caused by: expect is not defined
</code>```

I understand these functions come from Jasmine, and I read somewhere that as of Angular RC5 that they don't need to be imported, as they are global. Is that true? If not, how should I import them?

答:
As far I can understand you tried to write some unit tests, yes?

"I'm trying to use something I've seen around that looks like" - this sentence sounds like:
"They are doing like this so I should too".

In comments I saw that @cXoltero provide you some useful informations but some of them aren't correct. Mocha is test runner and a Chai is framework for BDD(units).

How install chai package - http://chaijs.com/guide/installation/

Guide for using assertions - http://chaijs.com/guide/styles/

Body:
I'm trying to use something I've seen around that looks like:

let test1 = {value:5};
let test2 = {value:5};

// Returns true.
expect(test1).toEqual(test2);

However, it's just giving me an error:

EXCEPTION: Error in :0:0 caused by: expect is not defined

I understand these functions come from Jasmine, and I read somewhere that as of Angular RC5 that they don't need to be imported, as they are global. Is that true? If not, how should I import them?


问:
Emulator in Android Studio doesn't start
I think it's a problem with the SDK reference in Project Structure, but when I click run and I choose Launch Emulator nothing appears.</p>

答: I spent several hours on this problem. What worked for me was opening the Tools->Android->SDK Manager, choosing Android SDK under System Settings on the left of the screen and going to the SDK tools tab. I then unchecked the settings for Android emulator and the Intel x86 Emulator Accelerator. I applied these changes, restarted Android Studio and then re-checked these option and applied the changes. The program reinstalled the emulator components and things seem to work. Hope this helps someone.</p>


问:
Best Way to load Static Data in Apache Spark
I have a spark project that makes use of some static metadata about states/regions.  Currently the data is hardcoded like so:

```<code>object RegionUtil {
   val regionNames = Map("US-AL" -> "ALABAMA",
                  "US-AK" -> "ALASKA",
                  "US-AZ" -> "ARIZONA",
                  "US-AR" -> "ARKANSAS",
                  "US-CA" -> "CALIFORNIA",
                  "US-CO" -> "COLORADO",
                  // ... etc
                  "US-WY" -> "WYOMING")
 }
</code>```

And then region mappings are simply looked up from the map in RegionUtil.  This is just an example as there are a number of similar static mappings the application relies on.

But some of this metadata is occasionally (rarely) updated, and is already maintained in a MySQL database.  What I would like to do is initially load that data when spark starts up, and then look up a cached copy of that data from that point forward (ideally with each slave node maintaining its own copy) whenever metadata needs to be accessed.

Does anyone know how that can be accomplished?

答:
You want to look into broadcasting for this purpose:

Broadcast variables allow the programmer to keep a read-only variable cached on each machine rather than shipping a copy of it with tasks. They can be used, for example, to give every node a copy of a large input dataset in an efficient manner. Spark also attempts to distribute broadcast variables using efficient broadcast algorithms to reduce communication cost.

And their code example:

```<code>val broadcastVar = sc.broadcast(Array(1, 2, 3))
</code>```

Body:
I have a spark project that makes use of some static metadata about states/regions.  Currently the data is hardcoded like so:

object RegionUtil {
   val regionNames = Map("US-AL" -> "ALABAMA",
                  "US-AK" -> "ALASKA",
                  "US-AZ" -> "ARIZONA",
                  "US-AR" -> "ARKANSAS",
                  "US-CA" -> "CALIFORNIA",
                  "US-CO" -> "COLORADO",
                  // ... etc
                  "US-WY" -> "WYOMING")
 }

And then region mappings are simply looked up from the map in RegionUtil.  This is just an example as there are a number of similar static mappings the application relies on.

But some of this metadata is occasionally (rarely) updated, and is already maintained in a MySQL database.  What I would like to do is initially load that data when spark starts up, and then look up a cached copy of that data from that point forward (ideally with each slave node maintaining its own copy) whenever metadata needs to be accessed.

Does anyone know how that can be accomplished?

Body:
You want to look into broadcasting for this purpose:

Broadcast variables allow the programmer to keep a read-only variable cached on each machine rather than shipping a copy of it with tasks. They can be used, for example, to give every node a copy of a large input dataset in an efficient manner. Spark also attempts to distribute broadcast variables using efficient broadcast algorithms to reduce communication cost.

And their code example:

val broadcastVar = sc.broadcast(Array(1, 2, 3))


问:
Sorting all worksheets in the workbook
I have this code that actually do exactly what I want to:

goes to the specific range, copy the table in a new range and reorder the table.

Here is the code:

```<code> Sub copy_paste_sort()

Dim oneRange As Range
Dim aCell As Range
Dim WS_Count As Integer
Dim I As Integer

         ' Set WS_Count equal to the number of worksheets in the active
         ' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count

         ' Begin the loop.
    For I = 1 To WS_Count

Set oneRange = Range("CZ269:DA294")
Set aCell = Range("DA269")

Range("CW269:CX294").Select
Selection.Copy

Range("CZ269:DA294").Select
ActiveSheet.Paste

oneRange.Sort Key1:=aCell, Order1:=xlDescending, Header:=xlNo

    Next I

End Sub
</code>```

The problem is: the code is not working in all worksheets, it is repeating n times in the first worksheet.

答:
Try it as,

```<code>Sub copy_paste_sort()

    Dim I As Long

    ' Begin the loop.
    For I = 1 To ActiveWorkbook.Worksheets.Count
        With Worksheets(I)

            With .Range("CW269:CX294")
                .Copy destination:=.Range("CZ269")
                .Offset(0, 3).Cells.Sort Key1:=aCell, Order1:=xlDescending, Header:=xlNo
            End With
        End With
    Next I

End Sub
</code>```

You were looping through I as the index number of the workshjeets but not doing anything with it. The With Worksheets(I) ... End With references eac h worksheet in turn. Note that Range(...) becomes .Range(...) so that it knows what worksheet is its parent.

Title: Sorting all worksheets in the workbook

Body:
I have this code that actually do exactly what I want to:

goes to the specific range, copy the table in a new range and reorder the table.

Here is the code:

 Sub copy_paste_sort()

Dim oneRange As Range
Dim aCell As Range
Dim WS_Count As Integer
Dim I As Integer

         ' Set WS_Count equal to the number of worksheets in the active
         ' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count

         ' Begin the loop.
    For I = 1 To WS_Count

Set oneRange = Range("CZ269:DA294")
Set aCell = Range("DA269")

Range("CW269:CX294").Select
Selection.Copy

Range("CZ269:DA294").Select
ActiveSheet.Paste

oneRange.Sort Key1:=aCell, Order1:=xlDescending, Header:=xlNo

    Next I

End Sub

The problem is: the code is not working in all worksheets, it is repeating n times in the first worksheet.

Body:
Try it as,

Sub copy_paste_sort()

    Dim I As Long

    ' Begin the loop.
    For I = 1 To ActiveWorkbook.Worksheets.Count
        With Worksheets(I)

            With .Range("CW269:CX294")
                .Copy destination:=.Range("CZ269")
                .Offset(0, 3).Cells.Sort Key1:=aCell, Order1:=xlDescending, Header:=xlNo
            End With
        End With
    Next I

End Sub

You were looping through I as the index number of the workshjeets but not doing anything with it. The With Worksheets(I) ... End With references eac h worksheet in turn. Note that Range(...) becomes .Range(...) so that it knows what worksheet is its parent.


问:
Unicode to ANSI
How can I convert a unicode to ANSI?

Example I have the following unicode username:

```<code>очередной
</code>```

and I call this import method:

```<code>[DllImport("kernel32.dll", EntryPoint = "GetTempPathA")]
public static extern uint GetTempPath(uint nBufferLength, [Out()]
System.Text.StringBuilder lpBuffer);
</code>```

I receive the following result:

```<code>C:\Users\A690~1\AppData\Local\Temp\
</code>```

Now I've tried multiple encoding things like:

```<code>Encoding.ASCII.GetString(Encoding.Unicode.GetBytes(Environment.UserName));
Encoding.GetEncoding(1250).GetString(Encoding.Unicode.GetBytes(Environment.UserName));
Encoding.GetEncoding(1251).GetString(Encoding.Unicode.GetBytes(Environment.UserName));
</code>```

but none of them gave me the same result as the import method. How can I properly convert a unicode string to ANSI so that it gives me the same result as the import method?

答:
You should use the GetTempPathW method instead of the GetTempPathA method. The W makes it Unicode, which is what you need for your Unicode characters.

Trying to convert your Unicode to ASCII (which is impossible when you want to use characters from the non-ASCII range) will not solve the issue.

Title: Unicode to ANSI

Body:
How can I convert a unicode to ANSI?

Example I have the following unicode username:

очередной

and I call this import method:

[DllImport("kernel32.dll", EntryPoint = "GetTempPathA")]
public static extern uint GetTempPath(uint nBufferLength, [Out()]
System.Text.StringBuilder lpBuffer);

I receive the following result:

C:\Users\A690~1\AppData\Local\Temp\

Now I've tried multiple encoding things like:

Encoding.ASCII.GetString(Encoding.Unicode.GetBytes(Environment.UserName));
Encoding.GetEncoding(1250).GetString(Encoding.Unicode.GetBytes(Environment.UserName));
Encoding.GetEncoding(1251).GetString(Encoding.Unicode.GetBytes(Environment.UserName));

but none of them gave me the same result as the import method. How can I properly convert a unicode string to ANSI so that it gives me the same result as the import method?


问:
Python 2.7 finding if some anagram of one string is a substring of another
EDIT: Posting my final solution because this was a very helpful thread and I want to add some finality to it. Using the advice from both answers below I was able to craft a solution. I added a helper function in which I defined an anagram. Here is my final solution:

```<code>def anagram(s1, s2):
    s1 = list(s1)
    s2 = list(s2)
    s1.sort()
    s2.sort()
    return s1 == s2

def Question1(t, s):
    t_len = len(t)
    s_len = len(s)
    t_sort = sorted(t)
    for start in range(s_len - t_len + 1):
        if anagram(s[start: start+t_len], t):
            return True
    return False

print Question1("app", "paple")
</code>```

I am working on some practice technical interview questions and I'm stuck on the following question:

Find whether an anagram of string t is a substring of s

I have worked out the following two variants of my code, and a solution to this I believe lies in a cross between the two. The problem I am having is that the first code always prints False., regardless of input. The second variation works to some degree.  However, it cannot sort individual letters. For example t=jks s=jksd will print True! however t=kjs s=jksd will print False.

```<code>def Question1():
    # Define strings as raw user input.
    t = raw_input("Enter phrase t:")
    s = raw_input("Enter phrase s:")
    # Use the sorted function to find if t in s
    if sorted(t.lower()) in sorted(s.lower()):
        print("True!")
    else:
        print("False.")

Question1()
</code>```

Working variant:

```<code>def Question1():
    # Define strings as raw user input.
    t = raw_input("Enter phrase t:")
    s = raw_input("Enter phrase s:")
    # use a loop to find if t is in s.
    if t.lower() in s.lower():
        print("True!")
    else:
        print("False.")

Question1()
</code>```

I believe there is a solution that lies between these two, but I'm having trouble figuring out how to use sorted in this situation.

答:
I think your problem lies in the "substring" requirement. If you sort, you destroy order. Which means that while you can determine that an anagram of string1 is an anagram of a substring of string2, until you actually deal with string2 in order, you won't have a correct answer.

I'd suggest iterating over all the substrings of length len(s1) in s2. This is a straightforward for loop. Once you have the substrings, you can compare them (sorted vs sorted) with s1 to decide if there is any rearrangement of s1 that yields a contiguous substring of s2.

Viz:

```<code>s1 = "jks"
s2 = "aksjd"

print('s1=',s1, ' s2=', s2)
for offset in range(len(s2) - len(s1) + 1):
    ss2 = s2[offset:offset+len(s1)]
    if sorted(ss2) == sorted(s1):
        print('{} is an anagram of {} at offset {} in {}'.format(ss2, s1, offset, s2))
</code>```

Body:
EDIT: Posting my final solution because this was a very helpful thread and I want to add some finality to it. Using the advice from both answers below I was able to craft a solution. I added a helper function in which I defined an anagram. Here is my final solution:

def anagram(s1, s2):
    s1 = list(s1)
    s2 = list(s2)
    s1.sort()
    s2.sort()
    return s1 == s2

def Question1(t, s):
    t_len = len(t)
    s_len = len(s)
    t_sort = sorted(t)
    for start in range(s_len - t_len + 1):
        if anagram(s[start: start+t_len], t):
            return True
    return False

print Question1("app", "paple")

I am working on some practice technical interview questions and I'm stuck on the following question:

Find whether an anagram of string t is a substring of s

I have worked out the following two variants of my code, and a solution to this I believe lies in a cross between the two. The problem I am having is that the first code always prints False., regardless of input. The second variation works to some degree.  However, it cannot sort individual letters. For example t=jks s=jksd will print True! however t=kjs s=jksd will print False.

def Question1():
    # Define strings as raw user input.
    t = raw_input("Enter phrase t:")
    s = raw_input("Enter phrase s:")
    # Use the sorted function to find if t in s
    if sorted(t.lower()) in sorted(s.lower()):
        print("True!")
    else:
        print("False.")

Question1()

Working variant:

def Question1():
    # Define strings as raw user input.
    t = raw_input("Enter phrase t:")
    s = raw_input("Enter phrase s:")
    # use a loop to find if t is in s.
    if t.lower() in s.lower():
        print("True!")
    else:
        print("False.")

Question1()

I believe there is a solution that lies between these two, but I'm having trouble figuring out how to use sorted in this situation.

Body:
I think your problem lies in the "substring" requirement. If you sort, you destroy order. Which means that while you can determine that an anagram of string1 is an anagram of a substring of string2, until you actually deal with string2 in order, you won't have a correct answer.

I'd suggest iterating over all the substrings of length len(s1) in s2. This is a straightforward for loop. Once you have the substrings, you can compare them (sorted vs sorted) with s1 to decide if there is any rearrangement of s1 that yields a contiguous substring of s2.

Viz:

s1 = "jks"
s2 = "aksjd"

print('s1=',s1, ' s2=', s2)
for offset in range(len(s2) - len(s1) + 1):
    ss2 = s2[offset:offset+len(s1)]
    if sorted(ss2) == sorted(s1):
        print('{} is an anagram of {} at offset {} in {}'.format(ss2, s1, offset, s2))


问:
Removing spacing between input fields
There is some small spacing between the input fields that I have. How can I remove this? Additionaly the confirm button seems to have a different vertical position than the other elements, why is this? Screenshot below:

.stockWrapper {
    position: absolute;
    display: block;
    top: 10px;
    margin: 0 auto;
    width: 250px;
    left: calc(50% - 75px);
    padding: 0px;
}

.stock {
    box-sizing: border-box;
    width: 75px;
    font-size: 2em;
    margin: 0px;
    width: 100px;
    height: 50px;
}

.confirmBtn, .clearBtn {
    box-sizing: border-box;
    color: white;
    font-weight: bold;
    border: 1px solid black;
    font-size: 2em;
    margin: 0px;
    width: 50px;
    height: 50px;
    padding: 0px;
}

.clearBtn {
    background-color: red;
}

.confirmBtn {
    background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="stockWrapper">
    <input type="button" class="clearBtn" value="X">
    <input type="number" class="stock">
    <input type="button" class="confirmBtn" value="✓">
</div></code>```

答:
You have some non printable characters (hidden) between tags. Please use this:</p>

```<code><div class="stockWrapper"><input type="button" class="clearBtn" value="X"><input type="number" class="stock"><input type="button" class="confirmBtn" value="✓"></div>
</code>```

Title: Removing spacing between input fields

Body:
There is some small spacing between the input fields that I have. How can I remove this? Additionaly the confirm button seems to have a different vertical position than the other elements, why is this? Screenshot below:

.stockWrapper {
    position: absolute;
    display: block;
    top: 10px;
    margin: 0 auto;
    width: 250px;
    left: calc(50% - 75px);
    padding: 0px;
}

.stock {
    box-sizing: border-box;
    width: 75px;
    font-size: 2em;
    margin: 0px;
    width: 100px;
    height: 50px;
}

.confirmBtn, .clearBtn {
    box-sizing: border-box;
    color: white;
    font-weight: bold;
    border: 1px solid black;
    font-size: 2em;
    margin: 0px;
    width: 50px;
    height: 50px;
    padding: 0px;
}

.clearBtn {
    background-color: red;
}

.confirmBtn {
    background-color: green;
}

    <input type="button" class="clearBtn" value="X">
    <input type="number" class="stock">
    <input type="button" class="confirmBtn" value="✓">

Body:
You have some non printable characters (hidden) between tags. Please use this:

<div class="stockWrapper"><input type="button" class="clearBtn" value="X"><input type="number" class="stock"><input type="button" class="confirmBtn" value="✓"></div>


答:
This method can work ... declare a function to get the size of the linkList

```<code>public int size()
{
    int counter = 0;
    node *nodePtr = head;

    while (nodePtr)
    {
        if (nodePtr->next != null)
        {
            counter++;
        }
    }

    return counter;
}
</code>```

then if size returned is an even number ...

```<code>int c = size()/2;
</code>```

else ...

```<code>int c = (size()+1)/2;
</code>```

then initialize and array and print them in reverse .... try it out might work :)

Title: Printing the second half of a linked list in reverse order

Body:
This method can work ... declare a function to get the size of the linkList

public int size()
{
    int counter = 0;
    node *nodePtr = head;

    while (nodePtr)
    {
        if (nodePtr->next != null)
        {
            counter++;
        }
    }

    return counter;
}

then if size returned is an even number ...

int c = size()/2;

else ...

int c = (size()+1)/2;

then initialize and array and print them in reverse .... try it out might work :)


答:
You're very much on the right track.  First, please note that there is no loop in your second attempt.

The problem is that you can't simply sort all of s and then look for sorted(t) in that.  Rather, you have to consider each len(t) sized substring of s, and check that against the sorted t.  Consider the trivial example:

```<code>t = "abd"
s = "abdc"
</code>```

s trivially contains t.  However, when you sort them, you get the strings abd and abcd, and the in comparison fails.  The sorting gets other letters in the way.

Instead, you need to step through s in chunks the size of t.

```<code>t_len = len(t)
s_len = len(s)
t_sort = sorted(t)
for start in range(s_len - t_len + 1):
   chunk = s[start:start+t_len]
   if t_sort == sorted(chunk):
       # SUCCESS!!
</code>```

Title: Python 2.7 finding if some anagram of one string is a substring of another

Body:
You're very much on the right track.  First, please note that there is no loop in your second attempt.

The problem is that you can't simply sort all of s and then look for sorted(t) in that.  Rather, you have to consider each len(t) sized substring of s, and check that against the sorted t.  Consider the trivial example:

t = "abd"
s = "abdc"

s trivially contains t.  However, when you sort them, you get the strings abd and abcd, and the in comparison fails.  The sorting gets other letters in the way.

Instead, you need to step through s in chunks the size of t.

t_len = len(t)
s_len = len(s)
t_sort = sorted(t)
for start in range(s_len - t_len + 1):
   chunk = s[start:start+t_len]
   if t_sort == sorted(chunk):
       # SUCCESS!!


问:
Opening Files for Edit
I am having some trouble with a basic file opening. I can't successfully initiate the filestream. It keeps coming back NULL... Can anyone tell me what I'm missing? I created a "test.dat" file in the same directory that the source code lives.</p>

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

int main (void)
{
    if((cfPtr = fopen("test.dat", "rb+")) == NULL) {
        printf("File could not be opened.\n");
    }
    return 0;
}
</code>```

答: Try moving the test.dat file to the directory where the compiled .exe lives, or if the current directory for the application is somewhere else, place the file in that directory.

Title: Opening Files for Edit

Body:
I am having some trouble with a basic file opening. I can't successfully initiate the filestream. It keeps coming back NULL... Can anyone tell me what I'm missing? I created a "test.dat" file in the same directory that the source code lives.

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    if((cfPtr = fopen("test.dat", "rb+")) == NULL) {
        printf("File could not be opened.\n");
    }
    return 0;
}


问:
Why seems to have padding on this p background?
I have the follow html code:

```<code><div class="row">
<div class="col">
 <a href="id">
  <img src="file">
   <p class="titulo-noticia">The title</p>
 </a>
</div>
<div class="col">
 <a href="id">
  <img src="file">
   <p class="titulo-noticia">Another title</p>
 </a>
</div>
</div>
</code>```

This must show a row with two images with a footer that it is the title.

The css is the following:

```<code>.col{
    display: table-cell;
}

.row{
    display: row;
}

.titulo-noticia{
    display: block;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    text-align: center;
    background: #000;
    background: rgba(0,0,0, .8);
    color: #fff;
    font-size: 18px;
}
</code>```

My problem is that the
 have a size of 1196*51, but the background color not fullfill this size. I attach an image:

The black color is not the full size of
 tag.

How can achieve to fullfill the p with the color?

答:
This rule

```<code>.titulo-noticia{
    display: block;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    text-align: center;
    background: #000;
    background: rgba(0,0,0, .8);
    color: #fff;
    font-size: 18px;
}
</code>```

can be reduced to

```<code>.titulo-noticia{
    padding: 15px;
    text-align: center;
    background: #000;
    background: rgba(0,0,0, .8);
    color: #fff;
    font-size: 18px;
}
</code>```

Everything else has no relevance in this situation. But if there is a gap as you describe, you should add margin: 0 to that rule - this will reset any margin which is inherited from another rule.

BTW: There is no display: row - that DIV will simply remain a block element. (there is display: table-row , though - maybe you want that...)

Body:
I have the follow html code:

The title

Another title

This must show a row with two images with a footer that it is the title.

The css is the following:

.col{
    display: table-cell;
}

.row{
    display: row;
}

.titulo-noticia{
    display: block;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    text-align: center;
    background: #000;
    background: rgba(0,0,0, .8);
    color: #fff;
    font-size: 18px;
}

My problem is that the
 have a size of 1196*51, but the background color not fullfill this size. I attach an image:

The black color is not the full size of
 tag.

How can achieve to fullfill the p with the color?

Body:
This rule

.titulo-noticia{
    display: block;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    text-align: center;
    background: #000;
    background: rgba(0,0,0, .8);
    color: #fff;
    font-size: 18px;
}

can be reduced to

.titulo-noticia{
    padding: 15px;
    text-align: center;
    background: #000;
    background: rgba(0,0,0, .8);
    color: #fff;
    font-size: 18px;
}

Everything else has no relevance in this situation. But if there is a gap as you describe, you should add margin: 0 to that rule - this will reset any margin which is inherited from another rule.

BTW: There is no display: row - that DIV will simply remain a block element. (there is display: table-row , though - maybe you want that...)


问:
Maintaining static files
In my django framework I collect user input from a form and create a matplotlib image. This image is displayed after a button push in a tagged field in an html file.

After each button push this image is updated, changes and is newly displayed. This works well. Now I intend to introduce a second image at a second tag, that shows up and changes after pressing a different button.

The problem that I have, is that after pushing the second button, the first image disappears and after pushing the first button, the second image disappears. Here is part of the html code:

```<code><form method=post action="">
    {% csrf_token %}
    <table>
        {% for field in form %}
        <tr>
            <td>{{ field.label }}</td>
            <td>{{ field }}</td>
        </tr>
        {% endfor %}
    </table>
    <br>
    <p><input type=submit name='button1' value='Create' class="btn btn-default"></form></p>
</form>

<p>
    {% if result != None %}
    {% load static %}
    <img src="{% get_static_prefix %}{{ result }}" width=1000>
    {% endif %}
</p>

<form method="post" class="topright">
    {{form3}}
    {% csrf_token %}
    <p><input type=submit name='button2' value='Update' class="btn btn-default" default=1></p>
</form>

<form method=post action="">
    {% csrf_token %}
    <table>
        {% for field in form4 %}
        <tr>
            <td>{{ field.label }}</td>
            <td>{{ field }}</td>
        </tr>
        {% endfor %}
    </table>
    <p><input type=submit name='button3' value='Predict' class="btn btn-default" default=1></p>
</form>

<p>
    {% if predictresult != None %}
    {% load static %}
    <img src="{% get_static_prefix %}{{ predictresult }}" width=1000>
    {% endif %}
</p>
</code>```

The image files are saved via: plt.savefig(plotfile) into the static folder. Most of the views code is the following:

```<code>def bayes_create_and_update(request):
    #os.chdir(os.path.dirname(__file__))
    global bandit
    global invgammaresult
    global predictresult
    invgammaresult = None
    predictresult = None
    if request.method == 'POST' and 'button1' in request.POST:
        form = InputForm(request.POST)
        if form.is_valid():
            form2 = form.save(commit=False)
            bandit = gauss_bandit(form2.m, form2.s)
            invgammaresult=pull_and_update(bandit,1)
            invgammaresult=invgammaresult[7:]
            form3= Sample_InputForm()
            form4=Predict_InputForm()

    elif request.method == 'POST' and 'button2' in request.POST:
        form3 = Sample_InputForm(request.POST)
        if form3.is_valid():
            form2 = form3.save(commit=False)
            invgammaresult=pull_and_update(bandit,form2.n)
            invgammaresult=invgammaresult[7:]
            form = InputForm(request.POST)
            form4=Predict_InputForm()

    elif request.method == 'POST' and 'button3' in request.POST:
        form4 = Predict_InputForm(request.POST)
        if form4.is_valid():
            form2 = form4.save(commit=False)
            predictresult=bandit.predict(form2.p1,form2.p2)
            predictresult=predictresult[7:]
            form = InputForm(request.POST)
            form3= Sample_InputForm()
    else:
        form = InputForm()
        form3= Sample_InputForm()
        form4=Predict_InputForm

    return render ( request, 'C:/Users/Jan/PycharmProjects/Newversion/newattempt/online_comp/templates/bayes/bayes.html',
            {'form': form,
             'result': invgammaresult,
             'form3':form3,
             'form4':form4,
             'predictresult':predictresult
             })
</code>```

and my models that give rise to the form is this code:

```<code>from django.db import models
from django.forms import ModelForm

class Input(models.Model):
    m = models.FloatField(
        verbose_name=' Mean of the Normal Distribution:', default=0.0)
    s = models.FloatField(
        verbose_name=' Standard Deviation of the Normal Distribution:', default=1.0)

class InputForm(ModelForm):
    class Meta:
        model = Input
        fields='__all__'

class Sample_Input(models.Model):
    n = models.FloatField(
        verbose_name=' Number of samples you wish to draw:', default=1)

class Sample_InputForm(ModelForm):
    class Meta:
        model=Sample_Input
        fields='__all__'

class Predict_Input(models.Model):
    p1 = models.FloatField(
        verbose_name=' Lower bound', default=-1.0)
    p2 = models.FloatField(
        verbose_name=' Upper bound', default=1.0)

class Predict_InputForm(ModelForm):
    class Meta:
        model=Predict_Input
        fields='__all__'
</code>```

Thx

答: I have solved the problem by creating two sub directories in the static folder and changing the path of saving the file in the compute file (not shown above). So the image output of both functions wouldn't interfere with each other.</p>

Title: Maintaining static files

Body:
In my django framework I collect user input from a form and create a matplotlib image. This image is displayed after a button push in a tagged field in an html file.

After each button push this image is updated, changes and is newly displayed. This works well. Now I intend to introduce a second image at a second tag, that shows up and changes after pressing a different button.

The problem that I have, is that after pushing the second button, the first image disappears and after pushing the first button, the second image disappears. Here is part of the html code:

<form method=post action="">
    {% csrf_token %}

        {% for field in form %}

            {{ field.label }}
            {{ field }}

        {% endfor %}

<input type=submit name='button1' value='Create' class="btn btn-default"></form>

</form>

    {% if result != None %}
    {% load static %}

    {% endif %}

<form method="post" class="topright">
    {{form3}}
    {% csrf_token %}

<input type=submit name='button2' value='Update' class="btn btn-default" default=1>

</form>

<form method=post action="">
    {% csrf_token %}

        {% for field in form4 %}

            {{ field.label }}
            {{ field }}

        {% endfor %}

<input type=submit name='button3' value='Predict' class="btn btn-default" default=1>

</form>

    {% if predictresult != None %}
    {% load static %}

    {% endif %}

The image files are saved via: plt.savefig(plotfile) into the static folder. Most of the views code is the following:

def bayes_create_and_update(request):
    #os.chdir(os.path.dirname(__file__))
    global bandit
    global invgammaresult
    global predictresult
    invgammaresult = None
    predictresult = None
    if request.method == 'POST' and 'button1' in request.POST:
        form = InputForm(request.POST)
        if form.is_valid():
            form2 = form.save(commit=False)
            bandit = gauss_bandit(form2.m, form2.s)
            invgammaresult=pull_and_update(bandit,1)
            invgammaresult=invgammaresult[7:]
            form3= Sample_InputForm()
            form4=Predict_InputForm()

    elif request.method == 'POST' and 'button2' in request.POST:
        form3 = Sample_InputForm(request.POST)
        if form3.is_valid():
            form2 = form3.save(commit=False)
            invgammaresult=pull_and_update(bandit,form2.n)
            invgammaresult=invgammaresult[7:]
            form = InputForm(request.POST)
            form4=Predict_InputForm()

    elif request.method == 'POST' and 'button3' in request.POST:
        form4 = Predict_InputForm(request.POST)
        if form4.is_valid():
            form2 = form4.save(commit=False)
            predictresult=bandit.predict(form2.p1,form2.p2)
            predictresult=predictresult[7:]
            form = InputForm(request.POST)
            form3= Sample_InputForm()
    else:
        form = InputForm()
        form3= Sample_InputForm()
        form4=Predict_InputForm

    return render ( request, 'C:/Users/Jan/PycharmProjects/Newversion/newattempt/online_comp/templates/bayes/bayes.html',
            {'form': form,
             'result': invgammaresult,
             'form3':form3,
             'form4':form4,
             'predictresult':predictresult
             })

and my models that give rise to the form is this code:

from django.db import models
from django.forms import ModelForm

class Input(models.Model):
    m = models.FloatField(
        verbose_name=' Mean of the Normal Distribution:', default=0.0)
    s = models.FloatField(
        verbose_name=' Standard Deviation of the Normal Distribution:', default=1.0)

class InputForm(ModelForm):
    class Meta:
        model = Input
        fields='__all__'

class Sample_Input(models.Model):
    n = models.FloatField(
        verbose_name=' Number of samples you wish to draw:', default=1)

class Sample_InputForm(ModelForm):
    class Meta:
        model=Sample_Input
        fields='__all__'

class Predict_Input(models.Model):
    p1 = models.FloatField(
        verbose_name=' Lower bound', default=-1.0)
    p2 = models.FloatField(
        verbose_name=' Upper bound', default=1.0)

class Predict_InputForm(ModelForm):
    class Meta:
        model=Predict_Input
        fields='__all__'

Thx


问:
Python - Pandas Dataframe with Multiple Names per Column
Is there a way in pandas to give the same column of a pandas dataframe two names, so that I can index the column by only one of the two names? Here is a quick example illustrating my problem:</p>

```<code>import pandas as pd

index=['a','b','c','d']
# The list of tuples here is really just to
# somehow visualize my problem below:
columns = [('A','B'), ('C','D'),('E','F')]
df = pd.DataFrame(index=index, columns=columns)

# I can index like that:
df[('A','B')]
# But I would like to be able to index like this:
df[('A',*)] #error
df[(*,'B')] #error
</code>```

答:
You can create a multi-index column:

```<code>df.columns = pd.MultiIndex.from_tuples(df.columns)
</code>```

Then you can do:

```<code>df.loc[:, ("A", slice(None))]
</code>```

Or: df.loc[:, (slice(None), "B")]

Here slice(None) is equivalent to selecting all indices at the level, so (slice(None), "B") selects columns whose second level is B regardless of the first level names. This is semantically the same as :. Or write in pandas index slice way. df.loc[:, pd.IndexSlice[:, "B"]] for the second case.

Body:
Is there a way in pandas to give the same column of a pandas dataframe two names, so that I can index the column by only one of the two names? Here is a quick example illustrating my problem:

import pandas as pd

index=['a','b','c','d']
# The list of tuples here is really just to
# somehow visualize my problem below:
columns = [('A','B'), ('C','D'),('E','F')]
df = pd.DataFrame(index=index, columns=columns)

# I can index like that:
df[('A','B')]
# But I would like to be able to index like this:
df[('A',*)] #error
df[(*,'B')] #error

Body:
You can create a multi-index column:

df.columns = pd.MultiIndex.from_tuples(df.columns)

Then you can do:

df.loc[:, ("A", slice(None))]

Or: df.loc[:, (slice(None), "B")]

Here slice(None) is equivalent to selecting all indices at the level, so (slice(None), "B") selects columns whose second level is B regardless of the first level names. This is semantically the same as :. Or write in pandas index slice way. df.loc[:, pd.IndexSlice[:, "B"]] for the second case.


问:
Refreshing a setInterval in React
This is based on the answer given
here:

I'm having trouble resetting a setInterval.

As of now the following works. I have a prop called mediaList which contains an object array of images. When changeActiveMedia is called, the object position is moved to the next one in the list.

```<code>class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { activeMediaIndex: 0 };
  }

  componentDidMount() {
    setInterval(this.changeActiveMedia.bind(this), 5000);
  }

  changeActiveMedia() {
    const mediaListLength = this.props.mediaList.length;
    let nextMediaIndex = this.state.activeMediaIndex + 1;

    if(nextMediaIndex >= mediaListLength) {
      nextMediaIndex = 0;
    }

    this.setState({ activeMediaIndex:nextMediaIndex });
  }

  renderSlideshow(){
    const singlePhoto = this.props.mediaList[this.state.activeMediaIndex];
      return(
        <div>
          <img src={singlePhoto.url} />
        </div>
      );
    }

  render(){
    return(
      <div>
          {this.renderSlideshow()}
      </div>
    )
  }
}
</code>```

My problem arises here.

I have logic that can change the number of objects in the list, mediaList.

This becomes a problem because since the interval only updates once every 5000 seconds, if the nextMediaIndex within that time is 2, and then I all of a sudden update the mediaList to have only 1 item, I run into an error since mediaList[2] would not exist.

So my question is, is there a way to RESET and CLEAR the setInterval whenever this.props.mediaList is updated?

答:
window.setInterval returns an id which identifies an Interval timer. You can use it in conjunction with clearInterval to cancel the interval.

```<code>this.interval = setInterval(...);
...
clearInterval(this.interval);
</code>```

you can use componentWillReceiveProps as kind of a generic method of checking to see if mediaList has changed. for example:

```<code>componentWillReceiveProps(nextProps) {
    if (nextProps.mediaList !== this.props.mediaList) {
        clearInterval(this.interval);
    }
}
</code>```

Title: Refreshing a setInterval in React

Body:
This is based on the answer given
here:

I'm having trouble resetting a setInterval.

As of now the following works. I have a prop called mediaList which contains an object array of images. When changeActiveMedia is called, the object position is moved to the next one in the list.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { activeMediaIndex: 0 };
  }

  componentDidMount() {
    setInterval(this.changeActiveMedia.bind(this), 5000);
  }

  changeActiveMedia() {
    const mediaListLength = this.props.mediaList.length;
    let nextMediaIndex = this.state.activeMediaIndex + 1;

    if(nextMediaIndex >= mediaListLength) {
      nextMediaIndex = 0;
    }

    this.setState({ activeMediaIndex:nextMediaIndex });
  }

  renderSlideshow(){
    const singlePhoto = this.props.mediaList[this.state.activeMediaIndex];
      return(

      );
    }

  render(){
    return(

          {this.renderSlideshow()}

    )
  }
}

My problem arises here.

I have logic that can change the number of objects in the list, mediaList.

This becomes a problem because since the interval only updates once every 5000 seconds, if the nextMediaIndex within that time is 2, and then I all of a sudden update the mediaList to have only 1 item, I run into an error since mediaList[2] would not exist.

So my question is, is there a way to RESET and CLEAR the setInterval whenever this.props.mediaList is updated?

Body:
window.setInterval returns an id which identifies an Interval timer. You can use it in conjunction with clearInterval to cancel the interval.

this.interval = setInterval(...);
...
clearInterval(this.interval);

you can use componentWillReceiveProps as kind of a generic method of checking to see if mediaList has changed. for example:

componentWillReceiveProps(nextProps) {
    if (nextProps.mediaList !== this.props.mediaList) {
        clearInterval(this.interval);
    }
}


问:
How to make rows on bootstrap with unknown number of columns?
I have dynamic generated columns that have variable width according to the user screen size:

How can I split these divs in rows?

答:
You don't need to split them into rows. Many responsive layouts require column units to exceed 12 in a row. This is known as column wrapping in Bootstrap.

If the content of the columns varies in height, you will need to use responsive resets to prevent the height problem. This will force a "wrap" every X number of columns, based on the tier.

Clearfix Demo (responsive tiers)

There is also a CSS-only variation of the 'clearfix'.


问:
Update DATE in tables stored as VARCHAR after conversion
I imported data from Excel and brought dates over in VARCHAR format as 03/24/2017 because the dates were not saving. So I used VARCHAR for expediency. Now I am paying the price.

I am trying to use the STR_TO_DATE function to convert so that I can UPDATE a new column (defined as DATE) in the row.

When I use the following it looks promising, but only the month/day convert properly, the year becomes 2020 as shown below:

date_order   $conv_date_order

3/24/2017    2020-03-24

```<code>    SELECT  date_order, STR_TO_DATE(date_order, '%m/%d/%y')     AS $conv_date_order,
            date_shipped, STR_TO_DATE(date_shipped, '%m/%d/%y') AS $conv_date_shipped,
            date_need, STR_TO_DATE(date_need, '%m/%d/%y')       AS $conv_date_need
    FROM    Orders
    WHERE   Orders.id = $id;
</code>```

答: You need to use a capital Y in your '%m/%d/%Y' format string to indicate a four digit year. The lowercase y indicates a two digit year.

Body:
I imported data from Excel and brought dates over in VARCHAR format as 03/24/2017 because the dates were not saving. So I used VARCHAR for expediency. Now I am paying the price.

I am trying to use the STR_TO_DATE function to convert so that I can UPDATE a new column (defined as DATE) in the row.

When I use the following it looks promising, but only the month/day convert properly, the year becomes 2020 as shown below:

date_order   $conv_date_order

3/24/2017    2020-03-24

    SELECT  date_order, STR_TO_DATE(date_order, '%m/%d/%y')     AS $conv_date_order,
            date_shipped, STR_TO_DATE(date_shipped, '%m/%d/%y') AS $conv_date_shipped,
            date_need, STR_TO_DATE(date_need, '%m/%d/%y')       AS $conv_date_need
    FROM    Orders
    WHERE   Orders.id = $id;


问:
moveToNext() is false
```<code>//row --> 2
int row = mCursor.getCount();
for (int i = 0; i < row; i++) {
 if (mCursor.moveToPosition(i)){
  int val = mCursor.getInt(mCursor.getColumnIndexOrThrow(UTILI_COLLOC_ID_UTILI))
 }
}
</code>```

I don't understand because I have 2 rows in my query. But when I want to read the seconde row with "mCursor.moveToPosition(i)", so it's false...Why ?

答:
I think you can just safely use

```<code>while(mCursor.moveToNext()) {
// code
}
</code>```

instead of for looping

Title: moveToNext() is false

Body:
//row --> 2
int row = mCursor.getCount();
for (int i = 0; i < row; i++) {
 if (mCursor.moveToPosition(i)){
  int val = mCursor.getInt(mCursor.getColumnIndexOrThrow(UTILI_COLLOC_ID_UTILI))
 }
}

I don't understand because I have 2 rows in my query. But when I want to read the seconde row with "mCursor.moveToPosition(i)", so it's false...Why ?

Body:
I think you can just safely use

while(mCursor.moveToNext()) {
// code
}

instead of for looping