问:
React js Nested Loop array
Hi I need nelp for following json array loop.it likes that instagram or facebook post. I have a json nested array. I tried below code but it is not helped me. I need the view like that instagram post Below attached image.

I want get Profile,Likes,Comments,Post details separately through loop

Output:(for ex. If loop through Record1 means it get all nested item like (profile,Post..etc)).It print output like below image

Records1 :
     Profile
     Post
     likedetails
     commentdetails

Records2 :
     Profile
     Post
     likedetails
     commentdetails

Records3 :
     Profile
     Post
     likedetails
     commentdetails

Records4 :
     Profile
     Post
     likedetails
     commentdetails

Records5 :
     Profile
     Post
     likedetails
     commentdetails

```<code>render() {
  var Json={
     "AllPost":[
        {
           "User_Id":1,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"1",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"1",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"1"
                 }],
                 "likedetails":[{
                    "Post_Id":"1",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":2,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"2",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"2",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"2"
                 }],
                 "likedetails":[{
                    "Post_Id":"12",
                    "LikeCount":"3452"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":3,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"3",
                    "UserImage":"",
                    "Fullname":"Test3",
                    "Username":"te3"
                 }],
                 "Post":[{
                    "Post_Id":"3",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"3"
                 }],
                 "likedetails":[{
                    "Post_Id":"3",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":4,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"4",
                    "UserImage":"",
                    "Fullname":"Test4",
                    "Username":"te4"
                 }],
                 "Post":[{
                    "Post_Id":"4",
                    "UploadFile":"",
                    "Post_Caption":"Test4",
                    "User_Id":"4"
                 }],
                 "likedetails":[{
                    "Post_Id":"4",
                    "LikeCount":"3454"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":5,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"5",
                    "UserImage":"",
                    "Fullname":"Test5",
                    "Username":"te5"
                 }],
                 "Post":[{
                    "Post_Id":"5",
                    "UploadFile":"",
                    "Post_Caption":"Test5",
                    "User_Id":"5"
                 }],
                 "likedetails":[{
                    "Post_Id":"5",
                    "LikeCount":"3455"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        }
     ]
  }

let arr=[];
Object.keys(Json.AllPost).forEach((records, index) => {

        Json.AllPost[records].forEach((obj, idx) => {
           arr.push(obj);
           console.log(arr);
        })
    });
</code>```

ex:
codepen:https://codepen.io/dotnet345/pen/oNXBxBM

答:
As you have the nested array to loop through, you can try below method to get the values likes, comments and other details of each reocrd.

This might not be the best way to solve. But I'm sure it will help you. Thanks.

Json.AllPost.map( post =>
Object.values(post).map( record =>
record.map( item =>
console.log(item))))```

In the above snippet you can directly get the property values by accessing item.propertyName.

ex: item.Post

Title: React js Nested Loop array

Body:
Hi I need nelp for following json array loop.it likes that instagram or facebook post. I have a json nested array. I tried below code but it is not helped me. I need the view like that instagram post Below attached image.

I want get Profile,Likes,Comments,Post details separately through loop

Output:(for ex. If loop through Record1 means it get all nested item like (profile,Post..etc)).It print output like below image

Records1 :
     Profile
     Post
     likedetails
     commentdetails

Records2 :
     Profile
     Post
     likedetails
     commentdetails

Records3 :
     Profile
     Post
     likedetails
     commentdetails

Records4 :
     Profile
     Post
     likedetails
     commentdetails

Records5 :
     Profile
     Post
     likedetails
     commentdetails

render() {
  var Json={
     "AllPost":[
        {
           "User_Id":1,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"1",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"1",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"1"
                 }],
                 "likedetails":[{
                    "Post_Id":"1",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":2,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"2",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"2",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"2"
                 }],
                 "likedetails":[{
                    "Post_Id":"12",
                    "LikeCount":"3452"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":3,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"3",
                    "UserImage":"",
                    "Fullname":"Test3",
                    "Username":"te3"
                 }],
                 "Post":[{
                    "Post_Id":"3",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"3"
                 }],
                 "likedetails":[{
                    "Post_Id":"3",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":4,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"4",
                    "UserImage":"",
                    "Fullname":"Test4",
                    "Username":"te4"
                 }],
                 "Post":[{
                    "Post_Id":"4",
                    "UploadFile":"",
                    "Post_Caption":"Test4",
                    "User_Id":"4"
                 }],
                 "likedetails":[{
                    "Post_Id":"4",
                    "LikeCount":"3454"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":5,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"5",
                    "UserImage":"",
                    "Fullname":"Test5",
                    "Username":"te5"
                 }],
                 "Post":[{
                    "Post_Id":"5",
                    "UploadFile":"",
                    "Post_Caption":"Test5",
                    "User_Id":"5"
                 }],
                 "likedetails":[{
                    "Post_Id":"5",
                    "LikeCount":"3455"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        }
     ]
  }

let arr=[];
Object.keys(Json.AllPost).forEach((records, index) => {

        Json.AllPost[records].forEach((obj, idx) => {
           arr.push(obj);
           console.log(arr);
        })
    });

ex:
codepen:https://codepen.io/dotnet345/pen/oNXBxBM

Body:
As you have the nested array to loop through, you can try below method to get the values likes, comments and other details of each reocrd.

This might not be the best way to solve. But I'm sure it will help you. Thanks.

Json.AllPost.map( post =>
Object.values(post).map( record =>
record.map( item =>
console.log(item))))

In the above snippet you can directly get the property values by accessing item.propertyName.

ex: item.Post


来源: stackexchange

问:
Function calls are not supported in decorators in animation

ERROR in
  src/app/components/register/registration-form/registration-form.component.ts(27,18):
  Error during template compile of 'RegistrationFormComponent'

  Function calls are not supported in decorators but 'getanimationRule'
  was called.

RegistrationFormComponent

```<code>@Component({
  selector: 'app-registration-form',
  templateUrl: './registration-form.component.html',
  styleUrls: ['./registration-form.component.scss'],
  animations:[getanimationRule(registerChildrens)]
})
</code>```

getanimationRule

```<code>export function  getanimationRule(routeCollection: Routes)  {
    const routeArray = routeCollection.map(o => o.data && o.data.animation ? o.data.animation : null)
    .filter((el) => el != null);
    const animationRules = [];
    routeArray.forEach((element, value) => {
        if (element != null) {
            if (value === 0) {
                animationRules.push(transition(element + ' => *', animationDOWN));
            } else if (value === routeArray.length - 1) {
                animationRules.push(transition(element + '=> *', animationUP));
            } else {
                routeArray.forEach((subelement, subvalue) => {
                    if (subelement != null) {
                        if (subvalue < value) {
                            animationRules.push(transition(element + ' => ' + subelement, animationUP));
                        } else if (subvalue > value) {
                            animationRules.push(transition(element + ' => ' + subelement, animationDOWN));
                        }
                    }
                });
            }
        }
    });

    return trigger('routeAnimations',animationRules );
};
</code>```

答:
Unfortunately, You can't call a function inside component decorator, you can just pass it as a reference like

```<code>animations: [getanimationRule]
</code>```

follow this link for more info -> Medium

ContentLicense: CC BY-SA 4.0

Body:
ERROR in
  src/app/components/register/registration-form/registration-form.component.ts(27,18):
  Error during template compile of 'RegistrationFormComponent'

  Function calls are not supported in decorators but 'getanimationRule'
  was called.

RegistrationFormComponent

@Component({
  selector: 'app-registration-form',
  templateUrl: './registration-form.component.html',
  styleUrls: ['./registration-form.component.scss'],
  animations:[getanimationRule(registerChildrens)]
})

getanimationRule

export function  getanimationRule(routeCollection: Routes)  {
    const routeArray = routeCollection.map(o => o.data && o.data.animation ? o.data.animation : null)
    .filter((el) => el != null);
    const animationRules = [];
    routeArray.forEach((element, value) => {
        if (element != null) {
            if (value === 0) {
                animationRules.push(transition(element + ' => *', animationDOWN));
            } else if (value === routeArray.length - 1) {
                animationRules.push(transition(element + '=> *', animationUP));
            } else {
                routeArray.forEach((subelement, subvalue) => {
                    if (subelement != null) {
                        if (subvalue < value) {
                            animationRules.push(transition(element + ' => ' + subelement, animationUP));
                        } else if (subvalue > value) {
                            animationRules.push(transition(element + ' => ' + subelement, animationDOWN));
                        }
                    }
                });
            }
        }
    });

    return trigger('routeAnimations',animationRules );
};

Body:
Unfortunately, You can't call a function inside component decorator, you can just pass it as a reference like

animations: [getanimationRule]

follow this link for more info -> Medium


问:
C# - Constant value '4294901760' cannot be converted to a 'int'
Greetings,

I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).

In C# on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:

```<code>// error CS0266: Cannot implicitly convert type 'uint' to 'int'.
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;
</code>```

If I put an (int) cast around it like so, I get another error:

```<code>// error CS0221: Constant value '4294901760' cannot be converted to a 'int'
// (use 'unchecked' syntax to override)
public const int RED = (int)0xffff0000;
</code>```

But I know that my int is 32-bit, hence has a range of -2,147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80).aspx

So what gives?

Thanks in advance!

swine

答:
int is a signed integer ranging from -2,147,483,648 to 2,147,483,647.

What you want is an unsigned integer, i.e. uint, just like the first error message tells you.

ContentLicense: CC BY-SA 3.0

Body:
Greetings,

I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).

In C# on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:

// error CS0266: Cannot implicitly convert type 'uint' to 'int'.
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;

If I put an (int) cast around it like so, I get another error:

// error CS0221: Constant value '4294901760' cannot be converted to a 'int'
// (use 'unchecked' syntax to override)
public const int RED = (int)0xffff0000;

But I know that my int is 32-bit, hence has a range of -2,147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80).aspx

So what gives?

Thanks in advance!

swine


问:
receiving Acces Denied when get status of UWF_Filter using WMI in c#
I'm trying to get de status of the UWF Wilter in Windows 10 IoT as an User. I'm using the following code:

```<code>private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            ConnectionOptions Options = PrepareOptions();

            ManagementScope scope = new ManagementScope();
            scope.Path = new ManagementPath(@"\\localhost\root\StandardCimv2\embedded");
            scope.Options = Options;
            scope.Connect();

            using (ManagementClass mc = new ManagementClass(scope.Path.Path, "UWF_Filter", null))
            {
                //next line failes with Access Denied under normal user account
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    string UWFstate = (bool)mo.GetPropertyValue("CurrentEnabled");
                    if ( UWFstate )
                    {
                        // Do Something When Enabled
                    }
                    else
                    {
                        // Do Something Else When Disabled
                    }
                }
            }
        }
        catch (Exception ex)
        {
            trow;
        }
    }

public static ConnectionOptions PrepareOptions()
    {
        ConnectionOptions options = new ConnectionOptions();
        options.Impersonation = ImpersonationLevel.Impersonate;
        options.Authentication = AuthenticationLevel.Default;
        options.EnablePrivileges = true;
        return options;
    }
</code>```

When I try to run this code under a normal user account and with the write filter enabled the getinstances() method returns Access Denied. With the write filter disabled code runs fine. Also when run under an administrative user it works flawless.

When I try this using PowerShell I also receive an Access Denied message.

Documentation at MSDN of the UWF_Filter class states:

You must use an administrator account to make any changes to the configuration settings for UWF. Users with any kind of account can read the current configuration settings.

So I presume that a normal user must be able to read the UWF configuration. Or do I make a mistake somewhere?

Any idea?

Thanks Michel.

答:
I had the same problem. After so much of research finally found that WMI does not provide access even for admins to write exclusions  in UWF_Volume (tried via PowerShell ,C# , C++ from admin account) while UWF_Filter.Enable() , UWF_Filter.Disable() and few other methods worked properly.
   So, therefore to add exclusion, I used command tool from my program.</p>

Body:
I'm trying to get de status of the UWF Wilter in Windows 10 IoT as an User. I'm using the following code:

private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            ConnectionOptions Options = PrepareOptions();

            ManagementScope scope = new ManagementScope();
            scope.Path = new ManagementPath(@"\\localhost\root\StandardCimv2\embedded");
            scope.Options = Options;
            scope.Connect();

            using (ManagementClass mc = new ManagementClass(scope.Path.Path, "UWF_Filter", null))
            {
                //next line failes with Access Denied under normal user account
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    string UWFstate = (bool)mo.GetPropertyValue("CurrentEnabled");
                    if ( UWFstate )
                    {
                        // Do Something When Enabled
                    }
                    else
                    {
                        // Do Something Else When Disabled
                    }
                }
            }
        }
        catch (Exception ex)
        {
            trow;
        }
    }

public static ConnectionOptions PrepareOptions()
    {
        ConnectionOptions options = new ConnectionOptions();
        options.Impersonation = ImpersonationLevel.Impersonate;
        options.Authentication = AuthenticationLevel.Default;
        options.EnablePrivileges = true;
        return options;
    }

When I try to run this code under a normal user account and with the write filter enabled the getinstances() method returns Access Denied. With the write filter disabled code runs fine. Also when run under an administrative user it works flawless.

When I try this using PowerShell I also receive an Access Denied message.

Documentation at MSDN of the UWF_Filter class states:

You must use an administrator account to make any changes to the configuration settings for UWF. Users with any kind of account can read the current configuration settings.

So I presume that a normal user must be able to read the UWF configuration. Or do I make a mistake somewhere?

Any idea?

Thanks Michel.


问:
Why doesn't Tensorflow have if conditions?
Recently I was implementing a custom loss function in Tensorflow and I realized, Tensorflow doesn't have if conditions. I feel like if conditions are such an inherent programming feature why would Tensorflow developers not have such a fundamental feature in such a big project?</p>

答:
What you assume is not true, it does have if conditions and control flow, its just symbolic. For example tf.case:

```<code>f1 = lambda: tf.constant(17)
f2 = lambda: tf.constant(23)
r = tf.case([(tf.less(x, y), f1)], default=f2)
</code>```

Its equivalent to this code:

```<code>if x < y:
    return 17;
else:
    return 23;
</code>```

There is also tf.switch_case for switch statements.

Body:
What you assume is not true, it does have if conditions and control flow, its just symbolic. For example tf.case:

f1 = lambda: tf.constant(17)
f2 = lambda: tf.constant(23)
r = tf.case([(tf.less(x, y), f1)], default=f2)

Its equivalent to this code:

if x < y:
    return 17;
else:
    return 23;

There is also tf.switch_case for switch statements.


问:
how override spring framework beans?
I want to customize some of the codes of OAuth authorization server provided by spring security. the code responsible for generating /oauth/authorize is a bean named AuthorizationEndpoint. in AuthorizationServerEndpointsConfiguration class the following code creates a bean of AuthorizationEndpoint class:

```<code>@Bean
public AuthorizationEndpoint authorizationEndpoint() throws Exception {
    AuthorizationEndpoint authorizationEndpoint = new AuthorizationEndpoint();
    FrameworkEndpointHandlerMapping mapping = getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
    authorizationEndpoint.setUserApprovalPage(extractPath(mapping, "/oauth/confirm_access"));
    authorizationEndpoint.setProviderExceptionHandler(exceptionTranslator());
    authorizationEndpoint.setErrorPage(extractPath(mapping, "/oauth/error"));
    authorizationEndpoint.setTokenGranter(tokenGranter());
    authorizationEndpoint.setClientDetailsService(clientDetailsService);
    authorizationEndpoint.setAuthorizationCodeServices(authorizationCodeServices());
    authorizationEndpoint.setOAuth2RequestFactory(oauth2RequestFactory());
    authorizationEndpoint.setOAuth2RequestValidator(oauth2RequestValidator());
    authorizationEndpoint.setUserApprovalHandler(userApprovalHandler());
    return authorizationEndpoint;
}
</code>```

I want to override it by a new custom bean. I have created a class which extends AuthorizationEndpoint. for now I have pasted the same code inside this new class.

```<code>public class AuthorizationEndpointCustom extends AuthorizationEndpoint {
</code>```

creating the bean:

```<code>    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    AuthorizationServerEndpointsConfiguration asec;

    @Bean
//  @Order(value = Ordered.LOWEST_PRECEDENCE)
    @Primary
    public AuthorizationEndpoint authorizationEndpoint () {

        AuthorizationEndpointCustom authorizationEndpoint = new AuthorizationEndpointCustom();
        FrameworkEndpointHandlerMapping mapping = asec.getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
        authorizationEndpoint.setUserApprovalPage(extractPath(mapping, "/oauth/confirm_access"));
        authorizationEndpoint.setProviderExceptionHandler(asec.getEndpointsConfigurer().getExceptionTranslator());
        authorizationEndpoint.setErrorPage(extractPath(mapping, "/oauth/error"));
        authorizationEndpoint.setTokenGranter(asec.getEndpointsConfigurer().getTokenGranter());
        authorizationEndpoint.setClientDetailsService(clientDetailsService);
        authorizationEndpoint.setAuthorizationCodeServices(asec.getEndpointsConfigurer().getAuthorizationCodeServices());
        authorizationEndpoint.setOAuth2RequestFactory(asec.getEndpointsConfigurer().getOAuth2RequestFactory());
        authorizationEndpoint.setOAuth2RequestValidator(asec.getEndpointsConfigurer().getOAuth2RequestValidator());
        authorizationEndpoint.setUserApprovalHandler(asec.getEndpointsConfigurer().getUserApprovalHandler());

        return authorizationEndpoint;
    }

    private String extractPath(FrameworkEndpointHandlerMapping mapping, String page) {
        String path = mapping.getPath(page);
        if (path.contains(":")) {
            return path;
        }
        return "forward:" + path;
    }
</code>```

when I try to create a bean of this new class I encounter the following error:

APPLICATION FAILED TO START

Description:

The bean 'authorizationEndpoint', defined in
  org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration,
  could not be registered. A bean with that name has already been
  defined in class path resource
  [com/example/demo/AuthorizationServerConfig.class] and overriding is
  disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting
  spring.main.allow-bean-definition-overriding=true

the error goes away by adding the suggested config to application.properties. but the new bean does not replace the framework bean. in another part of my code I accessed the AuthorizationEndpoint from applicationContext. I called the .getClass() of this object and it is the same bean from the framework:

"org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint"

how can I force spring to use my bean?

答:
You need a Configuration class

```<code>import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public AuthorizationEndpoint authorizationEndpoint() {
        if(...) return new AuthorizationEndpoint();
        else return new AuthorizationEndpointCustom();
    }
}
</code>```

Title: how override spring framework beans?

Body:
I want to customize some of the codes of OAuth authorization server provided by spring security. the code responsible for generating /oauth/authorize is a bean named AuthorizationEndpoint. in AuthorizationServerEndpointsConfiguration class the following code creates a bean of AuthorizationEndpoint class:

@Bean
public AuthorizationEndpoint authorizationEndpoint() throws Exception {
    AuthorizationEndpoint authorizationEndpoint = new AuthorizationEndpoint();
    FrameworkEndpointHandlerMapping mapping = getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
    authorizationEndpoint.setUserApprovalPage(extractPath(mapping, "/oauth/confirm_access"));
    authorizationEndpoint.setProviderExceptionHandler(exceptionTranslator());
    authorizationEndpoint.setErrorPage(extractPath(mapping, "/oauth/error"));
    authorizationEndpoint.setTokenGranter(tokenGranter());
    authorizationEndpoint.setClientDetailsService(clientDetailsService);
    authorizationEndpoint.setAuthorizationCodeServices(authorizationCodeServices());
    authorizationEndpoint.setOAuth2RequestFactory(oauth2RequestFactory());
    authorizationEndpoint.setOAuth2RequestValidator(oauth2RequestValidator());
    authorizationEndpoint.setUserApprovalHandler(userApprovalHandler());
    return authorizationEndpoint;
}

I want to override it by a new custom bean. I have created a class which extends AuthorizationEndpoint. for now I have pasted the same code inside this new class.

public class AuthorizationEndpointCustom extends AuthorizationEndpoint {

creating the bean:

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    AuthorizationServerEndpointsConfiguration asec;

    @Bean
//  @Order(value = Ordered.LOWEST_PRECEDENCE)
    @Primary
    public AuthorizationEndpoint authorizationEndpoint () {

        AuthorizationEndpointCustom authorizationEndpoint = new AuthorizationEndpointCustom();
        FrameworkEndpointHandlerMapping mapping = asec.getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
        authorizationEndpoint.setUserApprovalPage(extractPath(mapping, "/oauth/confirm_access"));
        authorizationEndpoint.setProviderExceptionHandler(asec.getEndpointsConfigurer().getExceptionTranslator());
        authorizationEndpoint.setErrorPage(extractPath(mapping, "/oauth/error"));
        authorizationEndpoint.setTokenGranter(asec.getEndpointsConfigurer().getTokenGranter());
        authorizationEndpoint.setClientDetailsService(clientDetailsService);
        authorizationEndpoint.setAuthorizationCodeServices(asec.getEndpointsConfigurer().getAuthorizationCodeServices());
        authorizationEndpoint.setOAuth2RequestFactory(asec.getEndpointsConfigurer().getOAuth2RequestFactory());
        authorizationEndpoint.setOAuth2RequestValidator(asec.getEndpointsConfigurer().getOAuth2RequestValidator());
        authorizationEndpoint.setUserApprovalHandler(asec.getEndpointsConfigurer().getUserApprovalHandler());

        return authorizationEndpoint;
    }

    private String extractPath(FrameworkEndpointHandlerMapping mapping, String page) {
        String path = mapping.getPath(page);
        if (path.contains(":")) {
            return path;
        }
        return "forward:" + path;
    }

when I try to create a bean of this new class I encounter the following error:

APPLICATION FAILED TO START

Description:

The bean 'authorizationEndpoint', defined in
  org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration,
  could not be registered. A bean with that name has already been
  defined in class path resource
  [com/example/demo/AuthorizationServerConfig.class] and overriding is
  disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting
  spring.main.allow-bean-definition-overriding=true

the error goes away by adding the suggested config to application.properties. but the new bean does not replace the framework bean. in another part of my code I accessed the AuthorizationEndpoint from applicationContext. I called the .getClass() of this object and it is the same bean from the framework:

"org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint"

how can I force spring to use my bean?

Body:
You need a Configuration class

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public AuthorizationEndpoint authorizationEndpoint() {
        if(...) return new AuthorizationEndpoint();
        else return new AuthorizationEndpointCustom();
    }
}


问:
Library that can convert Word documents doc(x) to pdf
I'm working on a software that should be able to automatically convert Word documents to pdfs. Is there any library that supports Java preferably that can achieve this? It can be either free or commercial, it doesn't matter.

Thanks

答:
docx2pdf is a command line tool and python library that can achieve this on macOS and Windows. From Java, you should be able to call the tool using the command line. Internally, this python library calls an AppleScript from the command line in order to get it to work on macOS.

https://github.com/AlJohri/docx2pdf/

The benefit to this approach is that it uses Word's own APIs to create a pixel perfect conversion.

Disclaimer: I wrote this tool.


问:
How to get byte[] from float number
How to get byte[] from float number? I need to create message where for data I have four bytes, datum can be unsigned int( it is easy to get byte[] from int), binary and float ( but I don't know how to get four bytes from float ). Any solution ?</p>

答:
```<code> public static void main(String[] args)
            {
                float f = 23f;
                byte[] op = new byte[4];
                int fi = Float.floatToIntBits(f);
                for (int i = 0; i < 4; i++)
                    {
                        int offset = (op.length - 1 - i) * 8;
                        op[i] = (byte) ((fi >>> offset) & 0xff);
                    }
                for(byte b : op)
                    {
                        System.out.format("0x%02X ", b);
                    }
            }
</code>```

Title: How to get byte[] from float number


问:
IIS ARR reverse proxy only works for existing resource URLs
I have URL Rewrite & ARR installed in my IIS:
IIS machine dashboard

And ARR proxy enabled:
Server proxy setting

I have a .net app in my IIS.
a local .net app site

There are 2 files in it. WebForm1.aspx and WebForm2.aspx
.net project

And if I set up URL Rewrite from webform1.aspx to an external website, it works
URL Rewrite rule
browser log

But if I set it up with webform3.aspx, it shows 404. It's like the rule doesn't take effect for non-existing page.
error page

答:
If we enable failed request tracing then we will notice that the rewrite rule has succeeded.

Then problem is asp.net pipeline brake it.

If you try it on an empty website, it will work.

So you'd better be careful when you reverse proxy to an external website.


问:
How to write tables into Panoply using RPostgreSQL?
I am trying to write a table into my data warehouse using the RPostgreSQL package

```<code>library(DBI)
library(RPostgreSQL)

pano = dbConnect(dbDriver("PostgreSQL"),
                 host = 'db.panoply.io',
                 port = '5439',
                 user = panoply_user,
                 password = panoply_pw,
                 dbname = mydb)

RPostgreSQL::dbWriteTable(pano, "mtcars", mtcars[1:5, ])
</code>```

I am getting this error:

```<code>Error in postgresqlpqExec(new.con, sql4) :
  RS-DBI driver: (could not Retrieve the result : ERROR:  syntax error at or near "STDIN"
LINE 1: ..."hp","drat","wt","qsec","vs","am","gear","carb" ) FROM STDIN
                                                                  ^
)
</code>```

The above code writes into Panoply as a 0 row, 0 byte table. Columns seem to be properly entered into Panoply but nothing else appears.

答:
Fiest and most important redshift <> postgresql.

Redshift does not use the Postgres bulk loader. (so stdin is NOT allowed).

There are many options available which you should choose depending on your need, especially consider the volume of data.

For high volume of data you should write to s3 first and then use redshift copy command.
There are many options take a look at
https://github.com/sicarul/redshiftTools

for low volume see
inserting multiple records at once into Redshift with R

Body:
I am trying to write a table into my data warehouse using the RPostgreSQL package

library(DBI)
library(RPostgreSQL)

pano = dbConnect(dbDriver("PostgreSQL"),
                 host = 'db.panoply.io',
                 port = '5439',
                 user = panoply_user,
                 password = panoply_pw,
                 dbname = mydb)

RPostgreSQL::dbWriteTable(pano, "mtcars", mtcars[1:5, ])

I am getting this error:

Error in postgresqlpqExec(new.con, sql4) :
  RS-DBI driver: (could not Retrieve the result : ERROR:  syntax error at or near "STDIN"
LINE 1: ..."hp","drat","wt","qsec","vs","am","gear","carb" ) FROM STDIN
                                                                  ^
)

The above code writes into Panoply as a 0 row, 0 byte table. Columns seem to be properly entered into Panoply but nothing else appears.


问:
Make v-text-field required based on v-radio choice
I am new to front end specially vue
in my register page, I have this v-radio-group

```<code><v-radio-group
  v-model="row"
    row
  >
  <v-radio
    label="personal"
    value="false"
    data-cy="input-individual"
  />
  <v-radio
    label="company"
    value="true"
  />
</v-radio-group>
</code>```

and I want to make the v-text-field phone number and company name required if the user choose company

```<code><v-text-field
  v-model="name"
  label="* fullname"
  :rules="requirerule"
  required
  data-cy="input-name"
/>

<v-text-field
  v-model="telephone"
    label="phone number"
    data-cy="input-telephone"
/>
<v-text-field
  v-model="companyname"
  label="company name"
  data-cy="input-companyname"
/>
</code>```

Does anyone has a solution what should I do, thank you very much

答:
It should work fine as long as you use,

<v-text-field
  v-model="telephone"
    label="phone number"
    data-cy="input-telephone"
    :required="row"
/>
```

<p>Also your radio buttons are passing value as string in props, it will work as Boolean as long as you change the radio value props as follow,</p>

<pre class="lang-js prettyprint-override"><code><v-radio
    label="company"
    :value="true"
  />
</code>```

I have just made your value to :value so instead of reading it as string it execute the value which will be considered as Boolean.

Body:
I am new to front end specially vue
in my register page, I have this v-radio-group

<v-radio-group
  v-model="row"
    row
  >
  <v-radio
    label="personal"
    value="false"
    data-cy="input-individual"
  />
  <v-radio
    label="company"
    value="true"
  />
</v-radio-group>

and I want to make the v-text-field phone number and company name required if the user choose company

<v-text-field
  v-model="name"
  label="* fullname"
  :rules="requirerule"
  required
  data-cy="input-name"
/>

<v-text-field
  v-model="telephone"
    label="phone number"
    data-cy="input-telephone"
/>
<v-text-field
  v-model="companyname"
  label="company name"
  data-cy="input-companyname"
/>

Does anyone has a solution what should I do, thank you very much

Body:
It should work fine as long as you use,

<v-text-field
  v-model="telephone"
    label="phone number"
    data-cy="input-telephone"
    :required="row"
/>

Also your radio buttons are passing value as string in props, it will work as Boolean as long as you change the radio value props as follow,

<v-radio
    label="company"
    :value="true"
  />

I have just made your value to :value so instead of reading it as string it execute the value which will be considered as Boolean.


问:
passing unknown class as parameter and trying to run function on it
Using C#, lets say I have these classes:

```<code>classZero
classOne
classTwo
</code>```

class classZero and classOne have a public function named "Hello()".

how can i creat a new function (in any class) that takes a unknown class as a paramenter and then run the function "Hello" on this unknown class, if it exists?

in sebdo code this would look something like this:

```<code>function runHelloIfPossible(anyclass aclass):
   if aclass contains function Hello:
      aclass.Hello()
</code>```

if in my case the anyclass argument where any of classZero or classOne the function Hello would run.

答:
the key word dynamic can be used, please see below codes.

```<code>class Program
{
    static void Main(string[] args)
    {
        var class0 = new ClassZero();
        var class1 = new ClassOne();
        var class2 = new ClassTwo();
        var class3 = new ClassWithoutHello();

        class2.DynamicCall(class0);
        class2.DynamicCall(class3);

        Console.ReadLine();
    }
}

public class ClassZero
{
    public void Hello()
    {
        Console.WriteLine("say hello from Class Zero");
    }
}

public class ClassOne
{
    public void Hello()
    {
        Console.WriteLine("say hello from Class One");
    }
}

public class ClassWithoutHello
{

}

public class ClassTwo
{
    public void DynamicCall(dynamic input)
    {
        Console.WriteLine("calling input from Class Two");

        if ((input is ClassZero) || (input is ClassOne))
        {
            input.Hello();
        }
        else
        {
            Console.WriteLine("this type does NOT support hello method");
        }
    }
}
</code>```

Body:
Using C#, lets say I have these classes:

classZero
classOne
classTwo

class classZero and classOne have a public function named "Hello()".

how can i creat a new function (in any class) that takes a unknown class as a paramenter and then run the function "Hello" on this unknown class, if it exists?

in sebdo code this would look something like this:

function runHelloIfPossible(anyclass aclass):
   if aclass contains function Hello:
      aclass.Hello()

if in my case the anyclass argument where any of classZero or classOne the function Hello would run.

Body:
the key word dynamic can be used, please see below codes.

class Program
{
    static void Main(string[] args)
    {
        var class0 = new ClassZero();
        var class1 = new ClassOne();
        var class2 = new ClassTwo();
        var class3 = new ClassWithoutHello();

        class2.DynamicCall(class0);
        class2.DynamicCall(class3);

        Console.ReadLine();
    }
}

public class ClassZero
{
    public void Hello()
    {
        Console.WriteLine("say hello from Class Zero");
    }
}

public class ClassOne
{
    public void Hello()
    {
        Console.WriteLine("say hello from Class One");
    }
}

public class ClassWithoutHello
{

}

public class ClassTwo
{
    public void DynamicCall(dynamic input)
    {
        Console.WriteLine("calling input from Class Two");

        if ((input is ClassZero) || (input is ClassOne))
        {
            input.Hello();
        }
        else
        {
            Console.WriteLine("this type does NOT support hello method");
        }
    }
}


问:
How to update column in a database with a function in a view using Laravel
I am currently working on a project where if a date is in the past. The user should get an email notifying them there current 'Contract' finished. Now I already build the function where if the date is in the past the users gets the email but the problem is each time the users reloads the page it sends the email again. Now I added a column in my table named email_send what a default value of 0 but it doesn't seem to update from 0 to 1 when the function sends the email?

This is my sslController.php:

```<code>
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class sslController extends Controller
{
    function SSL(){
        $data = DB::table('SSL')->where('userID', Auth::id())
        ->join('users', 'users.id', '=', 'SSL.userID')->get();
        return view('SSL',['data'=>$data]);
    }
}
</code>```

Note that the join is so that the loged in user only sees his own data in the table

This is the sslModel.php:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class sslModel extends Model
{
    protected $table='SSL';
    protected $fillable = [
         'email_send',
    ];
}
</code>```

and this is part of my ssl.blade.php:

```<code></tr>
    @foreach ($data as $i )
       <tr>
         <td>
           {{$i->AanvraagID}}
         </td>
         <td>
           {{$i->Status}}
         </td>
         <td>
           {{$i->StartDatum}}
         </td>
         <td>
           {{$i->EindDatum}}
         </td>
         <td>
           {{$i->Leverancier}}
         </td>
         <td>
           {{$i->Product}}
         </td>
         <td>
           {{$i->Validatie}}
         </td>
         <td>
           {{$i->TypeCertificaat}}
         </td>
         <td class="wrong">
             @php
                $date = new DateTime($i->EindDatum);
                $now = new DateTime();

                if($date < $now)  echo  'Certificaat verlopen';

                if ($date < $now && $i->email_send == 0) {
                $user = App\User::find(1)->first();
                $user->notify(new App\Notifications\TaksComplete);
                $user->update(['email_send' => 1]);
                }
              @endphp
           </td>
     </tr>
</code>```

I also tried this:

```<code>if ($date < $now && $i->email_send == 0) {

$user=App\User::find(1);
$user->notify(new App\Notifications\TaksComplete);                                                            $SSL=App\sslModel::find(1);
$SSL->email_send=1;
$SSL->update();
}
</code>```

答:
if you are using find() function then don't use first()

```<code>$user=App\User::find(1);
$user->email_send=1;
$user->update();
</code>```

if App\User is not working
then
use App\Models\User;

```<code>$user=User::find(1);
$user->email_send=1;
$user->update();
</code>```

For update sslModel

```<code>$sslModel=App\sslModel::where('userID', Auth::id())->first();
$sslModel->email_send=1;
$sslModel->update();
</code>```

Body:
I am currently working on a project where if a date is in the past. The user should get an email notifying them there current 'Contract' finished. Now I already build the function where if the date is in the past the users gets the email but the problem is each time the users reloads the page it sends the email again. Now I added a column in my table named email_send what a default value of 0 but it doesn't seem to update from 0 to 1 when the function sends the email?

This is my sslController.php:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class sslController extends Controller
{
    function SSL(){
        $data = DB::table('SSL')->where('userID', Auth::id())
        ->join('users', 'users.id', '=', 'SSL.userID')->get();
        return view('SSL',['data'=>$data]);
    }
}

Note that the join is so that the loged in user only sees his own data in the table

This is the sslModel.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class sslModel extends Model
{
    protected $table='SSL';
    protected $fillable = [
         'email_send',
    ];
}

and this is part of my ssl.blade.php:

    @foreach ($data as $i )

           {{$i->AanvraagID}}

           {{$i->Status}}

           {{$i->StartDatum}}

           {{$i->EindDatum}}

           {{$i->Leverancier}}

           {{$i->Product}}

           {{$i->Validatie}}

           {{$i->TypeCertificaat}}

             @php
                $date = new DateTime($i->EindDatum);
                $now = new DateTime();

                if($date < $now)  echo  'Certificaat verlopen';

                if ($date < $now && $i->email_send == 0) {
                $user = App\User::find(1)->first();
                $user->notify(new App\Notifications\TaksComplete);
                $user->update(['email_send' => 1]);
                }
              @endphp

I also tried this:

if ($date < $now && $i->email_send == 0) {

$user=App\User::find(1);
$user->notify(new App\Notifications\TaksComplete);                                                            $SSL=App\sslModel::find(1);
$SSL->email_send=1;
$SSL->update();
}

Body:
if you are using find() function then don't use first()

$user=App\User::find(1);
$user->email_send=1;
$user->update();

if App\User is not working
then
use App\Models\User;

$user=User::find(1);
$user->email_send=1;
$user->update();

For update sslModel

$sslModel=App\sslModel::where('userID', Auth::id())->first();
$sslModel->email_send=1;
$sslModel->update();


问:
How to know the connected WiFi is Walled Gardened (Captive Portal)?
I know there is way to find out whether a WiFi network is a captive portal by checking the response of something like "http://clients3.google.com/generate_204".

But my question is somewhat different. We all know that on Android when we connect to a WiFi network the connection cycle goes through a number of state mentioned in the class NetworkInfo.DetailedState, like AUTHENTICATING, OBTAINING_IPADDR, VERIFYING_POOR_LINK etc. Also, one of the states is CAPTIVE_PORTAL_CHECK and android system check whether the network which is being connected is captive or not. For this Android uses the CaptivePortalTracker#isCaptivePortal(InetAddress server) which results in a boolean. So we are certain that Android knows whether the connection is restricted (captive) or not

So, my question is does Android system gives some callback or some state by which we can get to know the Network is captive portal without checking it manually? Since Android system have already checked the network for captive portal, do we need to do the same thing again?

P.S. I'm only targeting API 19 (KitKat 4.4.2).

答:
Might be late to the party. But If the documentations hold correct then there is a way to detect captive portal from connectivityManager. https://developer.android.com/reference/android/net/NetworkInfo.DetailedState.html#CAPTIVE_PORTAL_CHECK

```<code>ConnectivityManager connectivityManager
                = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
NetworkInfo.DetailedState detailedState = activeNetworkInfo.getDetailedState();
return detailedState == NetworkInfo.DetailedState.CAPTIVE_PORTAL_CHECK;
</code>```

PS: This is deprecated in API 29

Body:
Might be late to the party. But If the documentations hold correct then there is a way to detect captive portal from connectivityManager. https://developer.android.com/reference/android/net/NetworkInfo.DetailedState.html#CAPTIVE_PORTAL_CHECK

ConnectivityManager connectivityManager
                = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
NetworkInfo.DetailedState detailedState = activeNetworkInfo.getDetailedState();
return detailedState == NetworkInfo.DetailedState.CAPTIVE_PORTAL_CHECK;

PS: This is deprecated in API 29


问:
Height transition with CSS instead of Javascript?
I have made these cards with HTML and CSS. For height transition, I have used javascript but depends on the page sometimes it works really slow. Is there a way to write this animate function in CSS without my javascript code?
2. Question
I set from 110px to 160px height raisement in JS, is it possible to raise the box's height depends on the text's height so if there is more text hidden the box will raise more?

$('#dynamic-cards .card-box').hover(function(){
   $(this).find('.description').animate({
        'height': '160px'
    }, 500);
},function(){
  $(this).find('.description').animate({
        'height': '110px'
    }, 300);
}).trigger('mouseleave');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dynamic-cards {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  max-width: 1000px;
}
#dynamic-cards .card-box {
  position: relative;
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
  z-index: 1;
  display: block;
  background: #ffffff;
  height: 450px;
  -webkit-transition: all 0.3s linear 0s;
  -moz-transition: all 0.3s linear 0s;
  -ms-transition: all 0.3s linear 0s;
  -o-transition: all 0.3s linear 0s;
  transition: all 0.3s linear 0s;
}

#dynamic-cards .card-box:hover .card-pic img,
#dynamic-cards .hover .card-pic img {
  -webkit-transform: scale(1.1);
  -moz-transform: scale(1.1);
  transform: scale(1.1);
  opacity: 0.6;
}

#dynamic-cards .card-box .card-pic {
  background: #000000;
  overflow: hidden;
}

#dynamic-cards .card-box .card-pic img {
  display: block;
  max-width: 300px;
  -webkit-transition: all 0.3s linear 0s;
  -moz-transition: all 0.3s linear 0s;
  -ms-transition: all 0.3s linear 0s;
  -o-transition: all 0.3s linear 0s;
  transition: all 0.3s linear 0s;
}

#dynamic-cards .card-box .card-box-content {
  position: absolute;
  bottom: 0;
  background-color: #EFEFEF;
  width: 100%;
  padding: 15px 15px 0px 15px;
  -webkti-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -moz-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -ms-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -o-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
}

#dynamic-cards .card-box .card-box-content .category {
  position: absolute;
  top: -34px;
  left: 0;
  background: #002776;
  padding: 10px 15px;
  color: #ffffff;
  font-size: 14px;
  font-weight: 600;
  text-transform: uppercase;
}

#dynamic-cards .card-box .card-box-content .title {
  margin: 0;
  padding: 0 0 10px;
  margin-top: 10px;
  color: #002776;
  font-size: 26px;
  font-weight: 700;
}

#dynamic-cards .card-box .card-box-content .sub_title {
  margin: 0;
  padding: 0 0 20px;
  color: #002776;
  font-size: 20px;
  font-weight: 400;
}

#dynamic-cards .card-box .card-box-content .description {
  height: 105px;
  color: black;
  font-size: 15px;
  line-height: 1.4em;
  padding-bottom: 0px !important;
}

#dynamic-cards .card-box .card-box-content .card-box-footer {
  font-size: 14px;
  height: 20%;
  position: relative;
  background-color: #EFEFEF;
  padding-bottom: 27px;
  margin: 0px;
}

#dynamic-cards .card-box .card-box-content .card-box-footer a {
  color: white;
  background-color: #002776;
  padding: 10px;
  font-weight: bold;
}

#dynamic-cards .card-box .card-box-content .card-box-footer a:hover {
  background-color: #009fda;
}

#dynamic-cards .hover .card-box-content .description {
  display: block !important;
  height: auto !important;
  opacity: 1 !important;
}</code>```

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum.

                Button

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est
                Lorem ipsum dolor sit amet.

                Button

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata.

```

https://codepen.io/rahman23/pen/MWweeoN

答:
You can do that by adding transition to your .description class and adding this css code:

```<code>#dynamic-cards .card-box:hover .card-box-content .description {
    height: 160px;
}
</code>```

For your second question, I myself have searched for it a lot not long ago and found no good answer. If you give height auto to your box it will snap to the 100% height. if you know the max-height of your box you can use max-height other than height itself. Check this article https://css-tricks.com/using-css-transitions-auto-dimensions/

#dynamic-cards {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        max-width: 1000px;
    }
    #dynamic-cards .card-box {
        position: relative;
        font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
        z-index: 1;
        display: block;
        background: #ffffff;
        height: 450px;
        -webkit-transition: all 0.3s linear 0s;
        -moz-transition: all 0.3s linear 0s;
        -ms-transition: all 0.3s linear 0s;
        -o-transition: all 0.3s linear 0s;
        transition: all 0.3s linear 0s;
    }

    #dynamic-cards .card-box:hover .card-pic img,
    #dynamic-cards .hover .card-pic img {
        -webkit-transform: scale(1.1);
        -moz-transform: scale(1.1);
        transform: scale(1.1);
        opacity: 0.6;
    }

    #dynamic-cards .card-box .card-pic {
        background: #000000;
        overflow: hidden;
    }

    #dynamic-cards .card-box .card-pic img {
        display: block;
        max-width: 300px;
        -webkit-transition: all 0.3s linear 0s;
        -moz-transition: all 0.3s linear 0s;
        -ms-transition: all 0.3s linear 0s;
        -o-transition: all 0.3s linear 0s;
        transition: all 0.3s linear 0s;
    }

    #dynamic-cards .card-box .card-box-content {
        position: absolute;
        bottom: 0;
        background-color: #EFEFEF;
        width: 100%;
        padding: 15px 15px 0px 15px;
        -webkti-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        -webkit-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
        -moz-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
        -ms-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
        -o-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
        transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
    }

    #dynamic-cards .card-box .card-box-content .category {
        position: absolute;
        top: -34px;
        left: 0;
        background: #002776;
        padding: 10px 15px;
        color: #ffffff;
        font-size: 14px;
        font-weight: 600;
        text-transform: uppercase;
    }

    #dynamic-cards .card-box .card-box-content .title {
        margin: 0;
        padding: 0 0 10px;
        margin-top: 10px;
        color: #002776;
        font-size: 26px;
        font-weight: 700;
    }

    #dynamic-cards .card-box .card-box-content .sub_title {
        margin: 0;
        padding: 0 0 20px;
        color: #002776;
        font-size: 20px;
        font-weight: 400;
    }

    #dynamic-cards .card-box .card-box-content .description {
        height: 105px;
        color: black;
        font-size: 15px;
        line-height: 1.4em;
        padding-bottom: 0px !important;
        transition: all 0.3s linear;
    }

    #dynamic-cards .card-box .card-box-content .card-box-footer {
        font-size: 14px;
        height: 20%;
        position: relative;
        background-color: #EFEFEF;
        padding-bottom: 27px;
        margin: 0px;
    }

    #dynamic-cards .card-box .card-box-content .card-box-footer a {
        color: white;
        background-color: #002776;
        padding: 10px;
        font-weight: bold;
    }

    #dynamic-cards .card-box .card-box-content .card-box-footer a:hover {
        background-color: #009fda;
    }

    #dynamic-cards .hover .card-box-content .description {
        display: block !important;
        height: auto !important;
        opacity: 1 !important;
        transition: all 0.5s linear;
        height: 110px;
    }

    #dynamic-cards .card-box:hover .card-box-content .description {
        height: 160px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div  id="dynamic-cards">
  <!-- Card-->
  <div class="card-box mb-3">
    <!-- Bild-->
    <div class="card-pic">
         <img src="https://upload.wikimedia.org/wikipedia/commons/c/cc/Grey_squirrel_400px.jpg">
    </div>
    <!--  Content-->
    <div class="card-box-content">

      <h2 class="title">Headline</h2>

      <p class="description">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</p>

       <div class="card-box-footer">
            <br>
            Button</div>
       </div>

     </div>

</div></code>```

Body:
I have made these cards with HTML and CSS. For height transition, I have used javascript but depends on the page sometimes it works really slow. Is there a way to write this animate function in CSS without my javascript code?
2. Question
I set from 110px to 160px height raisement in JS, is it possible to raise the box's height depends on the text's height so if there is more text hidden the box will raise more?

$('#dynamic-cards .card-box').hover(function(){
   $(this).find('.description').animate({
        'height': '160px'
    }, 500);
},function(){
  $(this).find('.description').animate({
        'height': '110px'
    }, 300);
}).trigger('mouseleave');

#dynamic-cards {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  max-width: 1000px;
}
#dynamic-cards .card-box {
  position: relative;
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
  z-index: 1;
  display: block;
  background: #ffffff;
  height: 450px;
  -webkit-transition: all 0.3s linear 0s;
  -moz-transition: all 0.3s linear 0s;
  -ms-transition: all 0.3s linear 0s;
  -o-transition: all 0.3s linear 0s;
  transition: all 0.3s linear 0s;
}

#dynamic-cards .card-box:hover .card-pic img,
#dynamic-cards .hover .card-pic img {
  -webkit-transform: scale(1.1);
  -moz-transform: scale(1.1);
  transform: scale(1.1);
  opacity: 0.6;
}

#dynamic-cards .card-box .card-pic {
  background: #000000;
  overflow: hidden;
}

#dynamic-cards .card-box .card-pic img {
  display: block;
  max-width: 300px;
  -webkit-transition: all 0.3s linear 0s;
  -moz-transition: all 0.3s linear 0s;
  -ms-transition: all 0.3s linear 0s;
  -o-transition: all 0.3s linear 0s;
  transition: all 0.3s linear 0s;
}

#dynamic-cards .card-box .card-box-content {
  position: absolute;
  bottom: 0;
  background-color: #EFEFEF;
  width: 100%;
  padding: 15px 15px 0px 15px;
  -webkti-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -moz-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -ms-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -o-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
}

#dynamic-cards .card-box .card-box-content .category {
  position: absolute;
  top: -34px;
  left: 0;
  background: #002776;
  padding: 10px 15px;
  color: #ffffff;
  font-size: 14px;
  font-weight: 600;
  text-transform: uppercase;
}

#dynamic-cards .card-box .card-box-content .title {
  margin: 0;
  padding: 0 0 10px;
  margin-top: 10px;
  color: #002776;
  font-size: 26px;
  font-weight: 700;
}

#dynamic-cards .card-box .card-box-content .sub_title {
  margin: 0;
  padding: 0 0 20px;
  color: #002776;
  font-size: 20px;
  font-weight: 400;
}

#dynamic-cards .card-box .card-box-content .description {
  height: 105px;
  color: black;
  font-size: 15px;
  line-height: 1.4em;
  padding-bottom: 0px !important;
}

#dynamic-cards .card-box .card-box-content .card-box-footer {
  font-size: 14px;
  height: 20%;
  position: relative;
  background-color: #EFEFEF;
  padding-bottom: 27px;
  margin: 0px;
}

#dynamic-cards .card-box .card-box-content .card-box-footer a {
  color: white;
  background-color: #002776;
  padding: 10px;
  font-weight: bold;
}

#dynamic-cards .card-box .card-box-content .card-box-footer a:hover {
  background-color: #009fda;
}

#dynamic-cards .hover .card-box-content .description {
  display: block !important;
  height: auto !important;
  opacity: 1 !important;
}

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum.

                Button

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est
                Lorem ipsum dolor sit amet.

                Button

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata.

https://codepen.io/rahman23/pen/MWweeoN

Body:
You can do that by adding transition to your .description class and adding this css code:

#dynamic-cards .card-box:hover .card-box-content .description {
    height: 160px;
}

For your second question, I myself have searched for it a lot not long ago and found no good answer. If you give height auto to your box it will snap to the 100% height. if you know the max-height of your box you can use max-height other than height itself. Check this article https://css-tricks.com/using-css-transitions-auto-dimensions/

#dynamic-cards {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        max-width: 1000px;
    }
    #dynamic-cards .card-box {
        position: relative;
        font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
        z-index: 1;
        display: block;
        background: #ffffff;
        height: 450px;
        -webkit-transition: all 0.3s linear 0s;
        -moz-transition: all 0.3s linear 0s;
        -ms-transition: all 0.3s linear 0s;
        -o-transition: all 0.3s linear 0s;
        transition: all 0.3s linear 0s;
    }

    #dynamic-cards .card-box:hover .card-pic img,
    #dynamic-cards .hover .card-pic img {
        -webkit-transform: scale(1.1);
        -moz-transform: scale(1.1);
        transform: scale(1.1);
        opacity: 0.6;
    }

    #dynamic-cards .card-box .card-pic {
        background: #000000;
        overflow: hidden;
    }

    #dynamic-cards .card-box .card-pic img {
        display: block;
        max-width: 300px;
        -webkit-transition: all 0.3s linear 0s;
        -moz-transition: all 0.3s linear 0s;
        -ms-transition: all 0.3s linear 0s;
        -o-transition: all 0.3s linear 0s;
        transition: all 0.3s linear 0s;
    }

    #dynamic-cards .card-box .card-box-content {
        position: absolute;
        bottom: 0;
        background-color: #EFEFEF;
        width: 100%;
        padding: 15px 15px 0px 15px;
        -webkti-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        -webkit-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
        -moz-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
        -ms-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
        -o-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
        transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
    }

    #dynamic-cards .card-box .card-box-content .category {
        position: absolute;
        top: -34px;
        left: 0;
        background: #002776;
        padding: 10px 15px;
        color: #ffffff;
        font-size: 14px;
        font-weight: 600;
        text-transform: uppercase;
    }

    #dynamic-cards .card-box .card-box-content .title {
        margin: 0;
        padding: 0 0 10px;
        margin-top: 10px;
        color: #002776;
        font-size: 26px;
        font-weight: 700;
    }

    #dynamic-cards .card-box .card-box-content .sub_title {
        margin: 0;
        padding: 0 0 20px;
        color: #002776;
        font-size: 20px;
        font-weight: 400;
    }

    #dynamic-cards .card-box .card-box-content .description {
        height: 105px;
        color: black;
        font-size: 15px;
        line-height: 1.4em;
        padding-bottom: 0px !important;
        transition: all 0.3s linear;
    }

    #dynamic-cards .card-box .card-box-content .card-box-footer {
        font-size: 14px;
        height: 20%;
        position: relative;
        background-color: #EFEFEF;
        padding-bottom: 27px;
        margin: 0px;
    }

    #dynamic-cards .card-box .card-box-content .card-box-footer a {
        color: white;
        background-color: #002776;
        padding: 10px;
        font-weight: bold;
    }

    #dynamic-cards .card-box .card-box-content .card-box-footer a:hover {
        background-color: #009fda;
    }

    #dynamic-cards .hover .card-box-content .description {
        display: block !important;
        height: auto !important;
        opacity: 1 !important;
        transition: all 0.5s linear;
        height: 110px;
    }

    #dynamic-cards .card-box:hover .card-box-content .description {
        height: 160px;
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div  id="dynamic-cards">
  <!-- Card-->
  <div class="card-box mb-3">
    <!-- Bild-->
    <div class="card-pic">
         <img src="https://upload.wikimedia.org/wikipedia/commons/c/cc/Grey_squirrel_400px.jpg">
    </div>
    <!--  Content-->
    <div class="card-box-content">

      <h2 class="title">Headline</h2>

      <p class="description">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</p>

       <div class="card-box-footer">
            <br>
            <a href="htttps://www.hays.de" target="_blank">Button</a></div>
       </div>

     </div>

</div>


问:
Template or abstract base class?
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

```<code>class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};
</code>```

Version 2a: Template

```<code>template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};
</code>```

Version 2b: Template and private inheritance

```<code>template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};
</code>```

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

答:
This depends on your goals. You can use version 1 if you

Intend to replace brakes of a car (at runtime)

Intend to pass Car around to non-template functions

I would generally prefer version 1 using the runtime polymorphism, because it is still flexible and allows you to have the Car still have the same type: Car<Opel> is another type than Car<Nissan>. If your goals are great performance while using the brakes frequently, i recommend you to use the templated approach. By the way, this is called policy based design. You provide a brake policy. Example because you said you programmed in Java, possibly you are not yet too experienced with C++. One way of doing it:

```<code>template<typename Accelerator, typename Brakes>
class Car {
    Accelerator accelerator;
    Brakes brakes;

public:
    void brake() {
        brakes.brake();
    }
}
</code>```

If you have lots of policies you can group them together into their own struct, and pass that one, for example as a SpeedConfiguration collecting Accelerator, Brakes and some more. In my projects i try to keep a good deal of code template-free, allowing them to be compiled once into their own object files, without needing their code in headers, but still allowing polymorphism (via virtual functions). For example, you might want to keep common data and functions that non-template code will probably call on many occasions in a base-class:

```<code>class VehicleBase {
protected:
    std::string model;
    std::string manufacturer;
    // ...

public:
    ~VehicleBase() { }
    virtual bool checkHealth() = 0;
};

template<typename Accelerator, typename Breaks>
class Car : public VehicleBase {
    Accelerator accelerator;
    Breaks breaks;
    // ...

    virtual bool checkHealth() { ... }
};
</code>```

Incidentally, that is also the approach that C++ streams use: std::ios_base contains flags and stuff that do not depend on the char type or traits like openmode, format flags and stuff, while std::basic_ios then is a class template that inherits it. This also reduces code bloat by sharing the code that is common to all instantiations of a class template.

Private Inheritance?

Private inheritance should be avoided in general. It is only very rarely useful and containment is a better idea in most cases. Common case where the opposite is true when size is really crucial (policy based string class, for example): Empty Base Class Optimization can apply when deriving from an empty policy class (just containing functions).

Read Uses and abuses of Inheritance by Herb Sutter.

ContentLicense: CC BY-SA 2.5

Title: Template or abstract base class?

Body:
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};

Version 2a: Template

template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};

Version 2b: Template and private inheritance

template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

Body:
This depends on your goals. You can use version 1 if you

Intend to replace brakes of a car (at runtime)

Intend to pass Car around to non-template functions

I would generally prefer version 1 using the runtime polymorphism, because it is still flexible and allows you to have the Car still have the same type: Car<Opel> is another type than Car<Nissan>. If your goals are great performance while using the brakes frequently, i recommend you to use the templated approach. By the way, this is called policy based design. You provide a brake policy. Example because you said you programmed in Java, possibly you are not yet too experienced with C++. One way of doing it:

template<typename Accelerator, typename Brakes>
class Car {
    Accelerator accelerator;
    Brakes brakes;

public:
    void brake() {
        brakes.brake();
    }
}

If you have lots of policies you can group them together into their own struct, and pass that one, for example as a SpeedConfiguration collecting Accelerator, Brakes and some more. In my projects i try to keep a good deal of code template-free, allowing them to be compiled once into their own object files, without needing their code in headers, but still allowing polymorphism (via virtual functions). For example, you might want to keep common data and functions that non-template code will probably call on many occasions in a base-class:

class VehicleBase {
protected:
    std::string model;
    std::string manufacturer;
    // ...

public:
    ~VehicleBase() { }
    virtual bool checkHealth() = 0;
};

template<typename Accelerator, typename Breaks>
class Car : public VehicleBase {
    Accelerator accelerator;
    Breaks breaks;
    // ...

    virtual bool checkHealth() { ... }
};

Incidentally, that is also the approach that C++ streams use: std::ios_base contains flags and stuff that do not depend on the char type or traits like openmode, format flags and stuff, while std::basic_ios then is a class template that inherits it. This also reduces code bloat by sharing the code that is common to all instantiations of a class template.

Private Inheritance?

Private inheritance should be avoided in general. It is only very rarely useful and containment is a better idea in most cases. Common case where the opposite is true when size is really crucial (policy based string class, for example): Empty Base Class Optimization can apply when deriving from an empty policy class (just containing functions).

Read Uses and abuses of Inheritance by Herb Sutter.

OwnerDisplayName: litb

LastEditorDisplayName: litb


答:
Try using unchecked as suggested by the compiler message:

```<code>public const int RED = unchecked((int)0xffff0000);
</code>```

This defines RED as -65536, which is 0xffff0000 interpreted as signed int.

Title: C# - Constant value '4294901760' cannot be converted to a 'int'

Body:
Greetings,

I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).

In C# on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:

// error CS0266: Cannot implicitly convert type 'uint' to 'int'.
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;

If I put an (int) cast around it like so, I get another error:

// error CS0221: Constant value '4294901760' cannot be converted to a 'int'
// (use 'unchecked' syntax to override)
public const int RED = (int)0xffff0000;

But I know that my int is 32-bit, hence has a range of -2,147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80).aspx

So what gives?

Thanks in advance!

swine

Body:
Try using unchecked as suggested by the compiler message:

public const int RED = unchecked((int)0xffff0000);

This defines RED as -65536, which is 0xffff0000 interpreted as signed int.


问:
Magento2 - How to place order using graphql?
I am following this tutorial to process cart / checkout for placing orders using graphql. Magento GraphQl Tutorial. And we have installed stripe on magento(backend).

So we are facing issue while placing order, we have done few steps upto point 5.

Customer logs in get a authentication token

Create empty cart

Add product to cart

Set billing and shipping address for cart

Set payment method to stripe_payments (without card details)

How to set payment information and where to set ?

Placing order receiving error here

How can I set payment method and debit card details to cart using graphql and place an successful test order?

答:
Make sure all steps ( 1 to 5 ) have been done without any issue. Please check the below steps for the mutation by which you can set the payment method and place the order.

Example: Use the setPaymentMethodOnCart mutation to set the payment method for your order. The value checkmo ("Check / Money order" payment method code) was returned in the query.

```<code>mutation {
      setPaymentMethodOnCart(input: {
          cart_id: "{ CART_ID }"
          payment_method: {
              code: "checkmo"
          }
      }) {
        cart {
          selected_payment_method {
            code
          }
        }
      }
    }
</code>```

Response:

If the operation is successful, the response contains the code of the selected payment method.

```<code>{
  "data": {
    "setPaymentMethodOnCart": {
      "cart": {
        "selected_payment_method": {
          "code": "checkmo"
        }
      }
    }
  }
}
</code>```

Set payment method and place order
Use the setPaymentMethodAndPlaceOrder mutation to set the payment method and place the order.

Request:

```<code>mutation {
  setPaymentMethodAndPlaceOrder(input: {
      cart_id: "{ CART_ID }"
      payment_method: {
          code: "checkmo"
      }
  }) {
    order {
      order_id
    }
  }
}
</code>```

Response:

If the operation is successful, the response contains the order ID.

```<code>{
  "data": {
    "setPaymentMethodAndPlaceOrder": {
      "order": {
        "order_id": "000000001"
      }
    }
  }
}
</code>```

Note: Make sure "setPaymentMethodAndPlaceOrder mutation" is not deprecated in the current version of Magento 2.

Body:
Make sure all steps ( 1 to 5 ) have been done without any issue. Please check the below steps for the mutation by which you can set the payment method and place the order.

Example: Use the setPaymentMethodOnCart mutation to set the payment method for your order. The value checkmo ("Check / Money order" payment method code) was returned in the query.

mutation {
      setPaymentMethodOnCart(input: {
          cart_id: "{ CART_ID }"
          payment_method: {
              code: "checkmo"
          }
      }) {
        cart {
          selected_payment_method {
            code
          }
        }
      }
    }

Response:

If the operation is successful, the response contains the code of the selected payment method.

{
  "data": {
    "setPaymentMethodOnCart": {
      "cart": {
        "selected_payment_method": {
          "code": "checkmo"
        }
      }
    }
  }
}

Set payment method and place order
Use the setPaymentMethodAndPlaceOrder mutation to set the payment method and place the order.

Request:

mutation {
  setPaymentMethodAndPlaceOrder(input: {
      cart_id: "{ CART_ID }"
      payment_method: {
          code: "checkmo"
      }
  }) {
    order {
      order_id
    }
  }
}

Response:

If the operation is successful, the response contains the order ID.

{
  "data": {
    "setPaymentMethodAndPlaceOrder": {
      "order": {
        "order_id": "000000001"
      }
    }
  }
}

Note: Make sure "setPaymentMethodAndPlaceOrder mutation" is not deprecated in the current version of Magento 2.


问:
Getting filepath and showing it on entry of toplevel widget is not working
Funtion of the toplevel is get configuration information for my program.
In toplevel, there is a button to get filepath and entry to show the filepath.
But the filepath is not shown in the entry.
And there is configure button, if i click it and then filled information is properly entered then the Toplevel should be destroyed but it is not working well.</p>

```<code>global MDR_DIR

def configureBtn(initWin):
    EMAIL_REGEX = re.compile(r"^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$")
    USERNAME = username.get()
    USERCODE = usercode.get()
    USERMAIL = useremail.get()
    UF_PATH = MDR_DIR.get()
    if not USERNAME:
        messagebox.showwarning("Warning", "Username should not be empty")
    elif not USERNAME:
        messagebox.showwarning("Warning", "Usercode should not be empty")
    elif not USERMAIL:
        messagebox.showwarning("Warning", "User email should not be empty")
    elif not EMAIL_REGEX.match(USERMAIL):
        messagebox.showwarning("Warning", "User email address is not valid")
    elif not validate_email(USERMAIL):
        messagebox.showwarning("Warning", "User email address does not exist")
    elif not UF_PATH:
        messagebox.showwarning("Warning", "User directory should not be empty")
    else :
        makeCfgFile(USERNAME, USERCODE, USERMAIL, UF_PATH)
        initWin.destroy()
def browseButton():
    filename = filedialog.askdirectory(
    title="Select working directory")
    MDR_DIR.set(filename)
    print(filename)

def configMain():
    if not os.path.exists('./lpConverter'):
        os.mkdir('./lpConverter')
    initWin = tkinter.Toplevel()
    initWin.title('LPCoverter_v.1.0.0 Configuration')
    lb_Username = tkinter.Label(initWin, text = "Username")
    username = tkinter.StringVar()
    lb_Usercode = tkinter.Label(initWin, text = "Usercode")
    usercode = tkinter.StringVar()

    lb_UserEmail = tkinter.Label(initWin, text = "Email")
    useremail = tkinter.StringVar()

    lb_UserDir = tkinter.Label(initWin, text= "MedDRA_DIR")
    MDR_DIR = tkinter.StringVar()
    lb_UserDirShow = tkinter.Entry(initWin, text="./", textvariable=MDR_DIR)
    lb_UserDirShow.insert(0, './')

    entry_Username = tkinter.Entry(initWin, textvariable=username)
    entry_Username.insert(0, 'Username')
    entry_Usercode = tkinter.Entry(initWin, textvariable=usercode)
    entry_Usercode.insert(0, 'Usercode')
    entry_UserEmail = tkinter.Entry(initWin, textvariable=useremail)
    btn_UserMDir = tkinter.Button(initWin, text="..." , command=browseButton)
    lb_Username.grid(row=0, sticky='E')
    lb_Usercode.grid(row=1, sticky='E')
    lb_UserEmail.grid(row=2, sticky='E')
    lb_UserDir.grid(row=3, sticky='E')
    lb_UserDirShow.grid(row=3, column=1)

    entry_Username.grid(row=0, column=1)
    entry_Usercode.grid(row=1, column=1)
    entry_UserEmail.grid(row=2, column=1)
    btn_UserMDir.grid(row=3, column=2)
    cfgButton = tkinter.Button(initWin, text="Configure", command=configureBtn)
    cfgButton.grid(row=5, column=1)

def lltptMain():
    print("Enter")
    if os.path.isfile(FNAME):
        line3 = readCfgFile()
    if lines is not None :
        mdrFilepath = lines[3]
        today = date.today()
        if line3 is not None:
            root.filename = filedialog.askopenfilename(initialdir=mdrFilepath, title="Select MDR Code", filetypes=(("EXCEL files", "*.xlsx"), ("CSV files", "*.csv"), ("ASCII files", "*.asc")))
        mdrFileLoc = root.filename
        if root.filename is not None:
            lltptConverter()

root = tkinter.Tk()
root.title('LPCoverter_v.1.0.0')
setCfgBtn = tkinter.Button(root, text="Select Configure", command=configMain)
doConvBtn = tkinter.Button(root, text="Converter", command=lltptMain)
setCfgBtn.pack()
doConvBtn.pack()
root.mainloop()
</code>```

答:
Use the following code to create configure button in order to delete the window created

```<code>cfgButton = tkinter.Button(initWin, text="Configure", command=lambda: configureBtn(initWin))
cfgButton.grid(row=5, column=1)
</code>```

Using lambda here allows the function to get parameter of the main window.

Body:
Funtion of the toplevel is get configuration information for my program.
In toplevel, there is a button to get filepath and entry to show the filepath.
But the filepath is not shown in the entry.
And there is configure button, if i click it and then filled information is properly entered then the Toplevel should be destroyed but it is not working well.

global MDR_DIR

def configureBtn(initWin):
    EMAIL_REGEX = re.compile(r"^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$")
    USERNAME = username.get()
    USERCODE = usercode.get()
    USERMAIL = useremail.get()
    UF_PATH = MDR_DIR.get()
    if not USERNAME:
        messagebox.showwarning("Warning", "Username should not be empty")
    elif not USERNAME:
        messagebox.showwarning("Warning", "Usercode should not be empty")
    elif not USERMAIL:
        messagebox.showwarning("Warning", "User email should not be empty")
    elif not EMAIL_REGEX.match(USERMAIL):
        messagebox.showwarning("Warning", "User email address is not valid")
    elif not validate_email(USERMAIL):
        messagebox.showwarning("Warning", "User email address does not exist")
    elif not UF_PATH:
        messagebox.showwarning("Warning", "User directory should not be empty")
    else :
        makeCfgFile(USERNAME, USERCODE, USERMAIL, UF_PATH)
        initWin.destroy()
def browseButton():
    filename = filedialog.askdirectory(
    title="Select working directory")
    MDR_DIR.set(filename)
    print(filename)

def configMain():
    if not os.path.exists('./lpConverter'):
        os.mkdir('./lpConverter')
    initWin = tkinter.Toplevel()
    initWin.title('LPCoverter_v.1.0.0 Configuration')
    lb_Username = tkinter.Label(initWin, text = "Username")
    username = tkinter.StringVar()
    lb_Usercode = tkinter.Label(initWin, text = "Usercode")
    usercode = tkinter.StringVar()

    lb_UserEmail = tkinter.Label(initWin, text = "Email")
    useremail = tkinter.StringVar()

    lb_UserDir = tkinter.Label(initWin, text= "MedDRA_DIR")
    MDR_DIR = tkinter.StringVar()
    lb_UserDirShow = tkinter.Entry(initWin, text="./", textvariable=MDR_DIR)
    lb_UserDirShow.insert(0, './')

    entry_Username = tkinter.Entry(initWin, textvariable=username)
    entry_Username.insert(0, 'Username')
    entry_Usercode = tkinter.Entry(initWin, textvariable=usercode)
    entry_Usercode.insert(0, 'Usercode')
    entry_UserEmail = tkinter.Entry(initWin, textvariable=useremail)
    btn_UserMDir = tkinter.Button(initWin, text="..." , command=browseButton)
    lb_Username.grid(row=0, sticky='E')
    lb_Usercode.grid(row=1, sticky='E')
    lb_UserEmail.grid(row=2, sticky='E')
    lb_UserDir.grid(row=3, sticky='E')
    lb_UserDirShow.grid(row=3, column=1)

    entry_Username.grid(row=0, column=1)
    entry_Usercode.grid(row=1, column=1)
    entry_UserEmail.grid(row=2, column=1)
    btn_UserMDir.grid(row=3, column=2)
    cfgButton = tkinter.Button(initWin, text="Configure", command=configureBtn)
    cfgButton.grid(row=5, column=1)

def lltptMain():
    print("Enter")
    if os.path.isfile(FNAME):
        line3 = readCfgFile()
    if lines is not None :
        mdrFilepath = lines[3]
        today = date.today()
        if line3 is not None:
            root.filename = filedialog.askopenfilename(initialdir=mdrFilepath, title="Select MDR Code", filetypes=(("EXCEL files", "*.xlsx"), ("CSV files", "*.csv"), ("ASCII files", "*.asc")))
        mdrFileLoc = root.filename
        if root.filename is not None:
            lltptConverter()

root = tkinter.Tk()
root.title('LPCoverter_v.1.0.0')
setCfgBtn = tkinter.Button(root, text="Select Configure", command=configMain)
doConvBtn = tkinter.Button(root, text="Converter", command=lltptMain)
setCfgBtn.pack()
doConvBtn.pack()
root.mainloop()

Body:
Use the following code to create configure button in order to delete the window created

cfgButton = tkinter.Button(initWin, text="Configure", command=lambda: configureBtn(initWin))
cfgButton.grid(row=5, column=1)

Using lambda here allows the function to get parameter of the main window.