问:
In my LinkedIn Oauth2.0.php access token's fetch function not responding any user content?
HI We are using LinkedIn API call at our website to get our website visitor details to logged in their profile through Linkedin.

The functionality was working fine but suddenly its stop working I checked in it.

We are getting Access Token Response in call but later on its fetching function is not working means not getting any values.I added some debug to check response and field value code and debug screenshot is attached

I tried to test made scope fields similar showing in app

```<code>define('SCOPE',        'r_basicprofile r_emailaddress'  --->
define('SCOPE',        'r_liteprofile r_emailaddress'
</code>```

and update call code to latest method

```<code>https://www.linkedin.com/uas/oauth2/authorization ->> https://www.linkedin.com/oauth/v2/authorization

https://www.linkedin.com/uas/oauth2/accessToken?  ->>
https://www.linkedin.com/oauth/v2/accessToken
</code>```

But still nothing change than I redo changs in code and this is the code

```<code><?php
$config = include(dirname(__FILE__).'/config.php');
// Change these
define('API_KEY',      'XXXXXXXXX');
define('API_SECRET',   'XXXXXXXXX');
//define('REDIRECT_URI', ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on")?'https':'http').'://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
define('REDIRECT_URI', ('https://example.com/linkedin/OAuth2.php'));
define('SCOPE',        'r_basicprofile r_emailaddress'                        );

// You'll probably use a database
    session_name('linkedin');
    session_start();

// OAuth 2 Control Flow
if (isset($_GET['error'])) {
    // LinkedIn returned an error
    print $_GET['error'] . ': ' . $_GET['error_description'];
    exit;
} elseif (isset($_GET['code'])) {
    // User authorized your application

        getAccessToken();

} else {
    if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
        // Token has expired, clear the state
    $_SESSION['access_token'] = '';

    }
    if (empty($_SESSION['access_token']) || $_SESSION['access_token'] == '') {
        // Start authorization process
        getAuthorizationCode();
    }
}

echo "Fetching" . "<br>";
// Congratulations! You have a valid token. Now fetch your profile
$user = fetch('GET', '/v1/people/~:(id,first-name,last-name,headline,email-address,picture-urls::(original),public-profile-url,picture-url,location,industry,site-standard-profile-request,interests,positions,summary,main-address,phone-numbers,skills:(skill))');

$userData = array('linkedin_id'=>'','first-name'=>'','last-name'=>'','picture-url'=>'','email-address'=>'','public_url'=>'','summary'=>'','twitter-account'=>'','headline'=>'','companyname'=>'','designation'=>'');

          foreach($user as $key=>$value)
          {

            if($key=='id')
                $userData['linkedin_id'] = $value;
            if($key=='firstName')
                $userData['first-name'] = $value;
            if($key=='lastName')
                $userData['last-name'] = $value;
            if($key=='pictureUrls')
            {
                $userData['picture-url'] = $value->values[0];
            }
            if($key=='pictureUrl' && $userData['picture-url']=='')
            {
                $userData['picture-url'] = $value;
            }

            if($key=='emailAddress')
                $userData['email-address'] = $value;
            if($key=='publicProfileUrl'){
                $userData['public_url'] = $value;

                          }
            if($key=='summary')
                $userData['summary'] = $value;

            if($key=='twitter-accounts')
            {
                foreach($value as $key=>$val)
                 {
                    if($key=='twitter-account')
                    {
                        $valueTwit = json_encode($val);
                        $valueTwit = json_decode($valueTwit,true);
                        $userData['twitter-account'] = $userData['twitter-account'].",".$valueTwit['provider-account-name'];
                    }
                 }
                 $userData['twitter-account'] = substr($userData['twitter-account'],1,strlen($userData['twitter-account']));
            }

            if($key=='headline')
                $userData['headline'] = $value;

                        if($key=='positions')
                               {

                                foreach($value as $key1=>$val)
                {

                     if($key1=='values')
                                {

                $company_array = $val[0];
                                 foreach($company_array as $key2=>$val1)
                 {
                                   if($key2=='company')
                                    {
                    foreach($val1 as $key3=>$val3)
                    {
                            if($key3=='name')
                                         {
                            $userData['companyname'] = $val3;
                            }
                    }
                                    }

                                 }
                                }
                                }
                               }

                        if($key=='positions')
                               {

                                foreach($value as $keys1=>$vals)
                {

                     if($keys1=='values')
                                {

                $company_array1 = $vals[0];
                                 foreach($company_array1 as $keys2=>$vals1)
                 {

                                   if($keys2=='title')
                                    {
                                        $userData['designation'] = $vals1;
                                    }

                                 }
                                }
                                }
                               }

          }

          $userRequiredDetails = "";
                   $random = rand();
          $userRequiredDetails.="?oid=".$userData['linkedin_id']."&email=".$userData['email-address']."&random=".$random;

          $linkedinMenter_array =array('oid'=> $userData['linkedin_id']."<br/>",'first_name'=>$userData['first-name']."<br/>",'last_name'=>$userData['last-name']."<br/>",'image'=>$userData['picture-url']."<br/>",'email'=>$userData['email-address']."<br/>",'public_url'=>$userData['public_url']."<br/>",'summary'=>$userData['summary']."<br/>",'twitter-account'=>$userData['twitter-account']."<br/>",'headline'=>$userData['headline']."<br/>", 'companyname'=>$userData['companyname']."<br/>", 'designation'=>$userData['designation']."<br/>",'questionId'=>$questionId, 'questionURL'=>$questionURL, 'projectId'=>$projectId, 'directoryConsultationId'=>$directoryConsultationId, 'feedbackId' => $feedbackId, 'mentorshipId' => $mentorshipId, 'plan_id' => $plan_id, 'planUserId' => $planUserId, 'sresult' => $sresult, 'projectUserId' => $projectUserId);
           echo "Request token retrieval failed:<br /><br />RESPONSE:<br /><br />```" . print_r($linkedinMenter_array, TRUE) . "```<br /><br />LINKEDIN OBJ:<br /><br />```" . print_r($OBJ_linkedin, TRUE) . "```";
           exit;
          /* for data write in file */
          $file = "../".$userData['linkedin_id'].".txt";
          file_put_contents($file, $linkedinMenter_array);
                 echo $file;
                 exit;
          //header("location:https://example.com/users/signuplinkedin".$userRequiredDetails);

function getAuthorizationCode() {
    $params = array('response_type' => 'code',
                    'client_id' => API_KEY,
                    'scope' => SCOPE,
                    'state' => uniqid('', true), // unique long string
                    'redirect_uri' => REDIRECT_URI,
              );

    // Authentication request
    $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);

    // Needed to identify request when it returns to us
    $_SESSION['state'] = $params['state'];

echo print_r($_SESSION, TRUE) . "\n<br>";
echo print_r($params, TRUE) . "\n<br>";

echo "Pankaj getAuthorizationCode";

    // Redirect user to authenticate
    header("Location: $url");
    exit;
}

function getAccessToken() {
    $params = array('grant_type' => 'authorization_code',
                    'client_id' => API_KEY,
                    'client_secret' => API_SECRET,
                    'code' => $_GET['code'],
                    'redirect_uri' => REDIRECT_URI,
              );

    // Access Token request
    $url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);

    // Tell streams to make a POST request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => 'POST',
                        )
                    )
                );

    // Retrieve access token information
    $response = file_get_contents($url, false, $context);

    // Native PHP object, please
    $token = json_decode($response);
 echo print_r($token, TRUE) . "\n<br>";
    // Store access token and expiration time
    $_SESSION['access_token'] = $token->access_token; // guard this!
    $_SESSION['expires_in']   = $token->expires_in; // relative time (in seconds)
    $_SESSION['expires_at']   = time() + $_SESSION['expires_in']; // absolute time

echo "Pankaj getAccessToken"  . "\n<br>";
    return true;
}

function fetch($method, $resource, $body = '') {
    $params = array('oauth2_access_token' => $_SESSION['access_token'],
                    'format' => 'json',
              );

    // Need to use HTTPS
    $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
    // Tell streams to make a (GET, POST, PUT, or DELETE) request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => $method,
                        )
                    )
                );

    // Hocus Pocus
    $response = file_get_contents($url, false, $context);
   //echo($response);
    // Native PHP object, please
    return json_decode($response);
}
</code>```

Getting this as a response in debug mode

```<code>stdClass Object ( [access_token] => AQX7maxbOfOpday8AEmpHyagkSKQcS26YYwMsocDx0FeIGPVwopJstJ27bqlSYrP754vT_DY6n1HoSr0kniJYY-RvhqvnX9ab4sczmzOYiqKo5p1ISVydiZJ_SiN-on9Hw12zD3tiktfvIPex6iHIi0dVhZ5-8CWWvdTX2Sj_d7YAusr9dJAmWQiNE3Aowe-i5cLlZSE-sOpzudCm3dns-ou2A4hg_NMLe5RAJcCQ2TlrGOiA29-1rZsN1_SJw5r4ZjLsx0HY8yUKmxmB1CnfOfg31y1RwlsDAaG679ILyGFvEqhdVJhcRrNzsHaI3JrDc1MJZTGAkBDCJt6WK9FexvqYHOLpw [expires_in] => 5184000 )
Pankaj getAccessToken
Fetching
Request token retrieval failed:

RESPONSE:

Array
(
    [oid] =>

    [first_name] =>

    [last_name] =>

    [image] =>

    [email] =>

    [public_url] =>

    [summary] =>

    [twitter-account] =>

    [headline] =>

    [companyname] =>

    [designation] =>

    [questionId] =>
    [questionURL] =>
    [projectId] =>
    [directoryConsultationId] =>
    [feedbackId] =>
    [mentorshipId] =>
    [plan_id] =>
    [planUserId] =>
    [sresult] =>
    [projectUserId] =>
)

LINKEDIN OBJ:
</code>```

答:
LinkedIn's v1 APIs have been deprecated, and you should be requesting the profile by sending a GET request to https://api.linkedin.com/v2/me.

Additionally, some users may have opted-out of sharing their data with 3rd party applications via LinkedIn APIs.

Body:
HI We are using LinkedIn API call at our website to get our website visitor details to logged in their profile through Linkedin.

The functionality was working fine but suddenly its stop working I checked in it.

We are getting Access Token Response in call but later on its fetching function is not working means not getting any values.I added some debug to check response and field value code and debug screenshot is attached

I tried to test made scope fields similar showing in app

define('SCOPE',        'r_basicprofile r_emailaddress'  --->
define('SCOPE',        'r_liteprofile r_emailaddress'

and update call code to latest method

https://www.linkedin.com/uas/oauth2/authorization ->> https://www.linkedin.com/oauth/v2/authorization

https://www.linkedin.com/uas/oauth2/accessToken?  ->>
https://www.linkedin.com/oauth/v2/accessToken

But still nothing change than I redo changs in code and this is the code

<?php
$config = include(dirname(__FILE__).'/config.php');
// Change these
define('API_KEY',      'XXXXXXXXX');
define('API_SECRET',   'XXXXXXXXX');
//define('REDIRECT_URI', ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on")?'https':'http').'://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
define('REDIRECT_URI', ('https://example.com/linkedin/OAuth2.php'));
define('SCOPE',        'r_basicprofile r_emailaddress'                        );

// You'll probably use a database
    session_name('linkedin');
    session_start();

// OAuth 2 Control Flow
if (isset($_GET['error'])) {
    // LinkedIn returned an error
    print $_GET['error'] . ': ' . $_GET['error_description'];
    exit;
} elseif (isset($_GET['code'])) {
    // User authorized your application

        getAccessToken();

} else {
    if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
        // Token has expired, clear the state
    $_SESSION['access_token'] = '';

    }
    if (empty($_SESSION['access_token']) || $_SESSION['access_token'] == '') {
        // Start authorization process
        getAuthorizationCode();
    }
}

echo "Fetching" . "
";
// Congratulations! You have a valid token. Now fetch your profile
$user = fetch('GET', '/v1/people/~:(id,first-name,last-name,headline,email-address,picture-urls::(original),public-profile-url,picture-url,location,industry,site-standard-profile-request,interests,positions,summary,main-address,phone-numbers,skills:(skill))');

$userData = array('linkedin_id'=>'','first-name'=>'','last-name'=>'','picture-url'=>'','email-address'=>'','public_url'=>'','summary'=>'','twitter-account'=>'','headline'=>'','companyname'=>'','designation'=>'');

          foreach($user as $key=>$value)
          {

            if($key=='id')
                $userData['linkedin_id'] = $value;
            if($key=='firstName')
                $userData['first-name'] = $value;
            if($key=='lastName')
                $userData['last-name'] = $value;
            if($key=='pictureUrls')
            {
                $userData['picture-url'] = $value->values[0];
            }
            if($key=='pictureUrl' && $userData['picture-url']=='')
            {
                $userData['picture-url'] = $value;
            }

            if($key=='emailAddress')
                $userData['email-address'] = $value;
            if($key=='publicProfileUrl'){
                $userData['public_url'] = $value;

                          }
            if($key=='summary')
                $userData['summary'] = $value;

            if($key=='twitter-accounts')
            {
                foreach($value as $key=>$val)
                 {
                    if($key=='twitter-account')
                    {
                        $valueTwit = json_encode($val);
                        $valueTwit = json_decode($valueTwit,true);
                        $userData['twitter-account'] = $userData['twitter-account'].",".$valueTwit['provider-account-name'];
                    }
                 }
                 $userData['twitter-account'] = substr($userData['twitter-account'],1,strlen($userData['twitter-account']));
            }

            if($key=='headline')
                $userData['headline'] = $value;

                        if($key=='positions')
                               {

                                foreach($value as $key1=>$val)
                {

                     if($key1=='values')
                                {

                $company_array = $val[0];
                                 foreach($company_array as $key2=>$val1)
                 {
                                   if($key2=='company')
                                    {
                    foreach($val1 as $key3=>$val3)
                    {
                            if($key3=='name')
                                         {
                            $userData['companyname'] = $val3;
                            }
                    }
                                    }

                                 }
                                }
                                }
                               }

                        if($key=='positions')
                               {

                                foreach($value as $keys1=>$vals)
                {

                     if($keys1=='values')
                                {

                $company_array1 = $vals[0];
                                 foreach($company_array1 as $keys2=>$vals1)
                 {

                                   if($keys2=='title')
                                    {
                                        $userData['designation'] = $vals1;
                                    }

                                 }
                                }
                                }
                               }

          }

          $userRequiredDetails = "";
                   $random = rand();
          $userRequiredDetails.="?oid=".$userData['linkedin_id']."&email=".$userData['email-address']."&random=".$random;

          $linkedinMenter_array =array('oid'=> $userData['linkedin_id']."
",'first_name'=>$userData['first-name']."
",'last_name'=>$userData['last-name']."
",'image'=>$userData['picture-url']."
",'email'=>$userData['email-address']."
",'public_url'=>$userData['public_url']."
",'summary'=>$userData['summary']."
",'twitter-account'=>$userData['twitter-account']."
",'headline'=>$userData['headline']."
", 'companyname'=>$userData['companyname']."
", 'designation'=>$userData['designation']."
",'questionId'=>$questionId, 'questionURL'=>$questionURL, 'projectId'=>$projectId, 'directoryConsultationId'=>$directoryConsultationId, 'feedbackId' => $feedbackId, 'mentorshipId' => $mentorshipId, 'plan_id' => $plan_id, 'planUserId' => $planUserId, 'sresult' => $sresult, 'projectUserId' => $projectUserId);
           echo "Request token retrieval failed:

RESPONSE:

" . print_r($linkedinMenter_array, TRUE) . "

LINKEDIN OBJ:

" . print_r($OBJ_linkedin, TRUE) . "
";
           exit;
          /* for data write in file */
          $file = "../".$userData['linkedin_id'].".txt";
          file_put_contents($file, $linkedinMenter_array);
                 echo $file;
                 exit;
          //header("location:https://example.com/users/signuplinkedin".$userRequiredDetails);

function getAuthorizationCode() {
    $params = array('response_type' => 'code',
                    'client_id' => API_KEY,
                    'scope' => SCOPE,
                    'state' => uniqid('', true), // unique long string
                    'redirect_uri' => REDIRECT_URI,
              );

    // Authentication request
    $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);

    // Needed to identify request when it returns to us
    $_SESSION['state'] = $params['state'];

echo print_r($_SESSION, TRUE) . "\n
";
echo print_r($params, TRUE) . "\n
";

echo "Pankaj getAuthorizationCode";

    // Redirect user to authenticate
    header("Location: $url");
    exit;
}

function getAccessToken() {
    $params = array('grant_type' => 'authorization_code',
                    'client_id' => API_KEY,
                    'client_secret' => API_SECRET,
                    'code' => $_GET['code'],
                    'redirect_uri' => REDIRECT_URI,
              );

    // Access Token request
    $url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);

    // Tell streams to make a POST request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => 'POST',
                        )
                    )
                );

    // Retrieve access token information
    $response = file_get_contents($url, false, $context);

    // Native PHP object, please
    $token = json_decode($response);
 echo print_r($token, TRUE) . "\n
";
    // Store access token and expiration time
    $_SESSION['access_token'] = $token->access_token; // guard this!
    $_SESSION['expires_in']   = $token->expires_in; // relative time (in seconds)
    $_SESSION['expires_at']   = time() + $_SESSION['expires_in']; // absolute time

echo "Pankaj getAccessToken"  . "\n
";
    return true;
}

function fetch($method, $resource, $body = '') {
    $params = array('oauth2_access_token' => $_SESSION['access_token'],
                    'format' => 'json',
              );

    // Need to use HTTPS
    $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
    // Tell streams to make a (GET, POST, PUT, or DELETE) request
    $context = stream_context_create(
                    array('http' =>
                        array('method' => $method,
                        )
                    )
                );

    // Hocus Pocus
    $response = file_get_contents($url, false, $context);
   //echo($response);
    // Native PHP object, please
    return json_decode($response);
}

Getting this as a response in debug mode

stdClass Object ( [access_token] => AQX7maxbOfOpday8AEmpHyagkSKQcS26YYwMsocDx0FeIGPVwopJstJ27bqlSYrP754vT_DY6n1HoSr0kniJYY-RvhqvnX9ab4sczmzOYiqKo5p1ISVydiZJ_SiN-on9Hw12zD3tiktfvIPex6iHIi0dVhZ5-8CWWvdTX2Sj_d7YAusr9dJAmWQiNE3Aowe-i5cLlZSE-sOpzudCm3dns-ou2A4hg_NMLe5RAJcCQ2TlrGOiA29-1rZsN1_SJw5r4ZjLsx0HY8yUKmxmB1CnfOfg31y1RwlsDAaG679ILyGFvEqhdVJhcRrNzsHaI3JrDc1MJZTGAkBDCJt6WK9FexvqYHOLpw [expires_in] => 5184000 )
Pankaj getAccessToken
Fetching
Request token retrieval failed:

RESPONSE:

Array
(
    [oid] =>

    [first_name] =>

    [last_name] =>

    [image] =>

    [email] =>

    [public_url] =>

    [summary] =>

    [twitter-account] =>

    [headline] =>

    [companyname] =>

    [designation] =>

    [questionId] =>
    [questionURL] =>
    [projectId] =>
    [directoryConsultationId] =>
    [feedbackId] =>
    [mentorshipId] =>
    [plan_id] =>
    [planUserId] =>
    [sresult] =>
    [projectUserId] =>
)

LINKEDIN OBJ:


来源: stackexchange

问:
How do you create a custom Policy AuthorizeAttribute in ASP.NET Core?
I'm working on an intranet app(login by AD), which need authorize rights by users' department,title,or others information in AD.

In MS Docs, it seems that i should use Claims-based authorization(https://learn.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-2.2).

As you can image, some page should be authorized by different department, as the link said, what i can do is add several department Policies, but it's boring, because i have dozens of departments.

What can i do to implement like this or something else:

```<code>[Authorize(Policy = "Department" , Value = "Finance")]
[Authorize(Policy = "Title" , Value = "VP")]
</code>```

Thanks in advance.

答:
In addition to what Henk said, you can use an external policy-based framework such as xacml or alfa. The end result is similar to what Henk wrote but it's policy-based rather than code-based (using IAuthorizationRequirement).

A policy looks like plain old English.

policyset documents{
    target clause objectType == "document"
    apply firstApplicable
    policy employees{
        target clause user.role == "employee"
        apply firstApplicable
        /**
         * Employees can create documents in their own company
         */
         rule createDocument{
             target clause action.actionId=="create"
             condition user.company==resource.company
             permit
         }
         /**
          * Employees can delete documents they own
          */
        rule allowDelete{
            target clause action.actionId == "delete"
            condition user.userId == resource.owner
            permit
        }
    }
}
```

You then need to deploy the policy to your authorization engine / policy decision point and you invoke it from an interceptor within your app. Doing it this way keeps business logic (the app) separate from authorization logic (the policies). It also means that you can reuse the same policies / authorization across your apps no matter the language and across your stack (API, app, DB...)

ContentLicense: CC BY-SA 4.0

Body:
I'm working on an intranet app(login by AD), which need authorize rights by users' department,title,or others information in AD.

In MS Docs, it seems that i should use Claims-based authorization(https://learn.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-2.2).

As you can image, some page should be authorized by different department, as the link said, what i can do is add several department Policies, but it's boring, because i have dozens of departments.

What can i do to implement like this or something else:

[Authorize(Policy = "Department" , Value = "Finance")]
[Authorize(Policy = "Title" , Value = "VP")]

Thanks in advance.

Body:
In addition to what Henk said, you can use an external policy-based framework such as xacml or alfa. The end result is similar to what Henk wrote but it's policy-based rather than code-based (using IAuthorizationRequirement).

A policy looks like plain old English.

policyset documents{
    target clause objectType == "document"
    apply firstApplicable
    policy employees{
        target clause user.role == "employee"
        apply firstApplicable
        /**
         * Employees can create documents in their own company
         */
         rule createDocument{
             target clause action.actionId=="create"
             condition user.company==resource.company
             permit
         }
         /**
          * Employees can delete documents they own
          */
        rule allowDelete{
            target clause action.actionId == "delete"
            condition user.userId == resource.owner
            permit
        }
    }
}

You then need to deploy the policy to your authorization engine / policy decision point and you invoke it from an interceptor within your app. Doing it this way keeps business logic (the app) separate from authorization logic (the policies). It also means that you can reuse the same policies / authorization across your apps no matter the language and across your stack (API, app, DB...)


问:
Template specialization and inheritance template class from other template class
I have some questions about next code:

template<typename T>
class Base;

template<typename T, typename P>
class Base<T(P)> {

};

template<typename T>
class Derived;

template<typename T, typename P>
class Derived<T(P)> : public Base<T(P)> {

};
```

Class specialization Derived<T(P)> inherits from class template<typename T> class Base or  from class template<typename T, typename P> class Base<T(P)>?

What the name of when I'm binding template parameters T and P of class specialization Derived<T(P)> with template parameter T of class Base.

答:
A class instantiated from the template Derived<T(P)> inherits from the class instantiated from Base<T(P)>.  Since the type T(P) matches your Base partial specialization, that template will be used to instantiate the class to inherit from.

It's just called inheritance.  There's nothing special going on there.  You're just instantiating the template Base with the type T(P) and inheriting from the resulting class.

Base<T(P)> will get instantiated when Derived<T(P)> gets instantiated, so Derived<void(int)> inherits from Base<void(int)>.  Both of those instantiations will go through the same set of rules to figure out which template to use to instantiate that class.

You may be getting confused thinking that T(P) is some special template thing.  It is not.  It's just the type "function that returns T and takes a single argument of type P".  Granted, types like that don't come up much outside of templates, but they're perfectly legal other places.  i.e.

```<code>using FuncType = void(int);

// These two declarations are exactly the same
void doAThing(FuncType* callback);
void doAThing(void(*callback)(int));
</code>```

Body:
I have some questions about next code:

template<typename T>
class Base;

template<typename T, typename P>
class Base<T(P)> {

};

template<typename T>
class Derived;

template<typename T, typename P>
class Derived<T(P)> : public Base<T(P)> {

};

Class specialization Derived<T(P)> inherits from class template<typename T> class Base or  from class template<typename T, typename P> class Base<T(P)>?

What the name of when I'm binding template parameters T and P of class specialization Derived<T(P)> with template parameter T of class Base.

Body:
A class instantiated from the template Derived<T(P)> inherits from the class instantiated from Base<T(P)>.  Since the type T(P) matches your Base partial specialization, that template will be used to instantiate the class to inherit from.

It's just called inheritance.  There's nothing special going on there.  You're just instantiating the template Base with the type T(P) and inheriting from the resulting class.

Base<T(P)> will get instantiated when Derived<T(P)> gets instantiated, so Derived<void(int)> inherits from Base<void(int)>.  Both of those instantiations will go through the same set of rules to figure out which template to use to instantiate that class.

You may be getting confused thinking that T(P) is some special template thing.  It is not.  It's just the type "function that returns T and takes a single argument of type P".  Granted, types like that don't come up much outside of templates, but they're perfectly legal other places.  i.e.

using FuncType = void(int);

// These two declarations are exactly the same
void doAThing(FuncType* callback);
void doAThing(void(*callback)(int));


问:
Where is NSAlert.h in the iOS  SDK?
According to iOS's Using and Creating Error Objects, one can display a error object with the following code.

```<code>NSError *theError = nil;
BOOL success = [myDoc writeToURL:[self docURL] ofType:@"html" error:&theError];

if (success == NO) {
    // Maybe try to determine cause of error and recover first.
    NSAlert *theAlert = [NSAlert alertWithError:theError];
    [theAlert runModal]; // Ignore return value.
}
</code>```

Unfortunately, I am not smart enough to figure out how to include NSAlert.h.

Any help would be appreciated.

答:
NSAlert isn't availble in UIKit. the example it just an copy past of the OS X doc.

This code in Listing 2-1 uses the
  returned NSError to display an error
  alert to the user immediately.
  (UIAlertView, the UIKit class
  corresponding to NSAlert, has no
  equivalent method for
  alertWithError:.) Error objects in the
  Cocoa domain are always localized and
  ready to present to users, so they can
  often be presented without further
  evaluation.

ContentLicense: CC BY-SA 3.0

Title: Where is NSAlert.h in the iOS  SDK?

Body:
According to iOS's Using and Creating Error Objects, one can display a error object with the following code.

NSError *theError = nil;
BOOL success = [myDoc writeToURL:[self docURL] ofType:@"html" error:&theError];

if (success == NO) {
    // Maybe try to determine cause of error and recover first.
    NSAlert *theAlert = [NSAlert alertWithError:theError];
    [theAlert runModal]; // Ignore return value.
}

Unfortunately, I am not smart enough to figure out how to include NSAlert.h.

Any help would be appreciated.


问:
how to disable (uninstall) the old `mix phoenix`?
Coming back into phoenix after a while; I still have an install from the "previous 1.3" hanging around

Which lead to some "nice" issues trying to understand what was happening; because reading here and there, some tells you to use mix phoenix..., some other (more recent) tells you to run mix phx...

The problem is, those two commands does not end with the same result

mix phoenix.gen.json works, but you get the old web folder; while mix phx.gen.json puts you on the correct path

I could live off that by remembering to never type mix.phoenix; but still, I'd be looking to find a way to make my workstation unable to run those misleading mix phoenix...

I'm still new to this ecosystem; just don't have a clue where to search to clean this install

best;

答:
You can accomplish this by writing the following in your terminal:

```<code>mix archive uninstall phoenix_new
</code>```

You can confirm it has been removed by attempting to run:

```<code>mix phoenix.new hello
</code>```

You should get an error that says:

** (Mix) The task “phoenix.new” could not be found

Body:
You can accomplish this by writing the following in your terminal:

mix archive uninstall phoenix_new

You can confirm it has been removed by attempting to run:

mix phoenix.new hello

You should get an error that says:

** (Mix) The task “phoenix.new” could not be found


问:
jdbc. preparedStatement incrementing value in sql
I have 2 tables in database
    authors (author_id, first_name, last_name);
      books (book_id, book_title, book_author_id);
book_author_id is fk to author_id

and when im trying to fill database for tests

```<code>    private static BookDao dao = new BookDaoImpl(new DBConnection("liquibase/liquibase.properties"));
    private static Author author1 = new Author(1, "Joshua", "Bloch");
    private static Author author2 = new Author(2, "Robert", "Martin");
    private static Book book1 = new Book(1, "Effective Java", 1);
    private static Book book2 = new Book(2, "Java Puzzlers: Traps, Pitfalls, and Corner Cases", 1);
    private static Book book3 = new Book(3, "Clean code", 2);
    private static Book book4 = new Book(4, "Clean Architecture", 2);

    @BeforeClass
    public static void fillDataBases() throws DAOException {
        authorDao.save(author1);
        authorDao.save(author2);
        dao.save(book1);
        dao.save(book2);
        dao.save(book3);
        dao.save(book4);
    }
</code>```

receiving this log

```<code>2019-05-29 23:48:26 - starting to check if author exists in database
2019-05-29 23:48:26 - creating statement for finding author by name
2019-05-29 23:48:26 - sql : 'SELECT * from authors WHERE first_name = ? AND last_name = ?', parameters : ['Joshua','Bloch']
2019-05-29 23:48:26 - author doesn't exist in database. you can save new author
2019-05-29 23:48:26 - creating statement for saving new author
2019-05-29 23:48:26 - sql : 'insert into authors(first_name, last_name) values(?,?)', parameters : ['Joshua','Bloch']
2019-05-29 23:48:26 - new author saved
2019-05-29 23:48:26 - starting to check if author exists in database
2019-05-29 23:48:26 - creating statement for finding author by name
2019-05-29 23:48:26 - sql : 'SELECT * from authors WHERE first_name = ? AND last_name = ?', parameters : ['Robert','Martin']
2019-05-29 23:48:26 - author doesn't exist in database. you can save new author
2019-05-29 23:48:26 - creating statement for saving new author
2019-05-29 23:48:26 - sql : 'insert into authors(first_name, last_name) values(?,?)', parameters : ['Robert','Martin']
2019-05-29 23:48:26 - new author saved
2019-05-29 23:48:26 - creating statement for finding book by title and author
2019-05-29 23:48:26 - sql : 'SELECT * from books WHERE book_title = ? AND book_author_id = ?', parameters : ['Effective Java',1]
2019-05-29 23:48:26 - book doesn't exist in database. we can save new book
2019-05-29 23:48:26 - creating statement for saving new book
2019-05-29 23:48:26 - book title Effective Java book author's id 1
2019-05-29 23:48:26 - sql : 'insert into books(book_title, book_author_id) values(?,?)', parameters : ['Effective Java',1]
2019-05-29 23:48:26 - new book saved
2019-05-29 23:48:26 - creating statement for finding book by title and author
2019-05-29 23:48:26 - sql : 'SELECT * from books WHERE book_title = ? AND book_author_id = ?', parameters : ['Java Puzzlers: Traps, Pitfalls, and Corner Cases',1]
2019-05-29 23:48:26 - book doesn't exist in database. we can save new book
2019-05-29 23:48:26 - creating statement for saving new book
2019-05-29 23:48:26 - book title Java Puzzlers: Traps, Pitfalls, and Corner Cases book author's id 1
2019-05-29 23:48:26 - sql : 'insert into books(book_title, book_author_id) values(?,?)', parameters : ['Java Puzzlers: Traps, Pitfalls, and Corner Cases',2]
2019-05-29 23:48:26 - new book saved
2019-05-29 23:48:26 - creating statement for finding book by title and author
2019-05-29 23:48:26 - sql : 'SELECT * from books WHERE book_title = ? AND book_author_id = ?', parameters : ['Clean code',2]
2019-05-29 23:48:26 - book doesn't exist in database. we can save new book
2019-05-29 23:48:26 - creating statement for saving new book
2019-05-29 23:48:26 - book title Clean code book author's id 2
2019-05-29 23:48:26 - sql : 'insert into books(book_title, book_author_id) values(?,?)', parameters : ['Clean code',3]
2019-05-29 23:48:26 - (conn=1118) Cannot add or update a child row: a foreign key constraint fails (`myapp`.`books`, CONSTRAINT `fk_author_books` FOREIGN KEY (`book_author_id`) REFERENCES `authors` (`author_id`) ON DELETE CASCADE ON UPDATE CASCADE)
</code>```

as you can see preparedStatement increment book_author_id by 1 each time when im saving book into database, but it shouldn't do this. can you please explain why this happening and how to fix this. if i will use just database console sql queries it will work, but if using prepared statement got this problem.
Added book dao save method

```<code> public int save(Book book) throws DAOException {
        int i = 0;
        if (!isExists(book.getTitle(), book.getAuthorId())) {
            String sql = "insert into books(book_title, book_author_id) values(?,?)";
            try (Connection connection = dbConnection.getConnection()) {
                logger.trace("creating statement for saving new book");

                try(PreparedStatement statement = connection.prepareStatement(sql)) {
                    statement.setString(1, book.getTitle());
                    statement.setLong(2, book.getId());
                    logger.trace("book title " + book.getTitle() + " book author's id " + book.getAuthorId());
                    logger.trace(statement);
                    i = statement.executeUpdate();
                    logger.trace("new book saved");
                    logger.trace(connection.getMetaData());
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                throw new DAOException("cannot save new book to database", e);
            }
        } else {
            throw new DAOException("book " + book.getTitle() + " by author "
                    + book.getAuthorId() + " already exists in database");
        }
        return i;
    }

</code>```

isExists same method with select * from books where book_title = 'title' and book_author_id = id
return true if exists and false if doesnt

答:
when you look at your code sample: you're setting the second parameter of your prepared statement to the book id, instead of the book_author_id.

Your code:

```<code>                statement.setLong(2, book.getId());
</code>```

but it should be

```<code>                statement.setLong(2, book.getBookAuthorId()); // assuming the getter is called that way
</code>```

as a matter of fact- the ID of the books is incrementing by one for each

Body:
I have 2 tables in database
    authors (author_id, first_name, last_name);
      books (book_id, book_title, book_author_id);
book_author_id is fk to author_id

and when im trying to fill database for tests

    private static BookDao dao = new BookDaoImpl(new DBConnection("liquibase/liquibase.properties"));
    private static Author author1 = new Author(1, "Joshua", "Bloch");
    private static Author author2 = new Author(2, "Robert", "Martin");
    private static Book book1 = new Book(1, "Effective Java", 1);
    private static Book book2 = new Book(2, "Java Puzzlers: Traps, Pitfalls, and Corner Cases", 1);
    private static Book book3 = new Book(3, "Clean code", 2);
    private static Book book4 = new Book(4, "Clean Architecture", 2);

    @BeforeClass
    public static void fillDataBases() throws DAOException {
        authorDao.save(author1);
        authorDao.save(author2);
        dao.save(book1);
        dao.save(book2);
        dao.save(book3);
        dao.save(book4);
    }

receiving this log

2019-05-29 23:48:26 - starting to check if author exists in database
2019-05-29 23:48:26 - creating statement for finding author by name
2019-05-29 23:48:26 - sql : 'SELECT * from authors WHERE first_name = ? AND last_name = ?', parameters : ['Joshua','Bloch']
2019-05-29 23:48:26 - author doesn't exist in database. you can save new author
2019-05-29 23:48:26 - creating statement for saving new author
2019-05-29 23:48:26 - sql : 'insert into authors(first_name, last_name) values(?,?)', parameters : ['Joshua','Bloch']
2019-05-29 23:48:26 - new author saved
2019-05-29 23:48:26 - starting to check if author exists in database
2019-05-29 23:48:26 - creating statement for finding author by name
2019-05-29 23:48:26 - sql : 'SELECT * from authors WHERE first_name = ? AND last_name = ?', parameters : ['Robert','Martin']
2019-05-29 23:48:26 - author doesn't exist in database. you can save new author
2019-05-29 23:48:26 - creating statement for saving new author
2019-05-29 23:48:26 - sql : 'insert into authors(first_name, last_name) values(?,?)', parameters : ['Robert','Martin']
2019-05-29 23:48:26 - new author saved
2019-05-29 23:48:26 - creating statement for finding book by title and author
2019-05-29 23:48:26 - sql : 'SELECT * from books WHERE book_title = ? AND book_author_id = ?', parameters : ['Effective Java',1]
2019-05-29 23:48:26 - book doesn't exist in database. we can save new book
2019-05-29 23:48:26 - creating statement for saving new book
2019-05-29 23:48:26 - book title Effective Java book author's id 1
2019-05-29 23:48:26 - sql : 'insert into books(book_title, book_author_id) values(?,?)', parameters : ['Effective Java',1]
2019-05-29 23:48:26 - new book saved
2019-05-29 23:48:26 - creating statement for finding book by title and author
2019-05-29 23:48:26 - sql : 'SELECT * from books WHERE book_title = ? AND book_author_id = ?', parameters : ['Java Puzzlers: Traps, Pitfalls, and Corner Cases',1]
2019-05-29 23:48:26 - book doesn't exist in database. we can save new book
2019-05-29 23:48:26 - creating statement for saving new book
2019-05-29 23:48:26 - book title Java Puzzlers: Traps, Pitfalls, and Corner Cases book author's id 1
2019-05-29 23:48:26 - sql : 'insert into books(book_title, book_author_id) values(?,?)', parameters : ['Java Puzzlers: Traps, Pitfalls, and Corner Cases',2]
2019-05-29 23:48:26 - new book saved
2019-05-29 23:48:26 - creating statement for finding book by title and author
2019-05-29 23:48:26 - sql : 'SELECT * from books WHERE book_title = ? AND book_author_id = ?', parameters : ['Clean code',2]
2019-05-29 23:48:26 - book doesn't exist in database. we can save new book
2019-05-29 23:48:26 - creating statement for saving new book
2019-05-29 23:48:26 - book title Clean code book author's id 2
2019-05-29 23:48:26 - sql : 'insert into books(book_title, book_author_id) values(?,?)', parameters : ['Clean code',3]
2019-05-29 23:48:26 - (conn=1118) Cannot add or update a child row: a foreign key constraint fails (`myapp`.`books`, CONSTRAINT `fk_author_books` FOREIGN KEY (`book_author_id`) REFERENCES `authors` (`author_id`) ON DELETE CASCADE ON UPDATE CASCADE)

as you can see preparedStatement increment book_author_id by 1 each time when im saving book into database, but it shouldn't do this. can you please explain why this happening and how to fix this. if i will use just database console sql queries it will work, but if using prepared statement got this problem.
Added book dao save method

 public int save(Book book) throws DAOException {
        int i = 0;
        if (!isExists(book.getTitle(), book.getAuthorId())) {
            String sql = "insert into books(book_title, book_author_id) values(?,?)";
            try (Connection connection = dbConnection.getConnection()) {
                logger.trace("creating statement for saving new book");

                try(PreparedStatement statement = connection.prepareStatement(sql)) {
                    statement.setString(1, book.getTitle());
                    statement.setLong(2, book.getId());
                    logger.trace("book title " + book.getTitle() + " book author's id " + book.getAuthorId());
                    logger.trace(statement);
                    i = statement.executeUpdate();
                    logger.trace("new book saved");
                    logger.trace(connection.getMetaData());
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                throw new DAOException("cannot save new book to database", e);
            }
        } else {
            throw new DAOException("book " + book.getTitle() + " by author "
                    + book.getAuthorId() + " already exists in database");
        }
        return i;
    }

isExists same method with select * from books where book_title = 'title' and book_author_id = id
return true if exists and false if doesnt

Body:
when you look at your code sample: you're setting the second parameter of your prepared statement to the book id, instead of the book_author_id.

Your code:

                statement.setLong(2, book.getId());

but it should be

                statement.setLong(2, book.getBookAuthorId()); // assuming the getter is called that way

as a matter of fact- the ID of the books is incrementing by one for each


问:
How to query SQLite by integer?
I have a SQL table like the following:

```<code>ID(string)    Name(string)    Width(double)   Height(double)   Selected(int)

12345678      Book            210             297              1
12345679      Display         530             326              0
12345680      Phone           70              140              0
</code>```

I can query them by ID and Name by passing a String argument without issue, but all int and double queries return null. Why?

This is the code I tried:

```<code>Cursor cursor = mDatabase.query(  "Objects",null, "Selected" + " = ?", new String[]{String.valueOf(1)},null,null,null);
ObjectDataBase.ObjectCursor objectCursor = new
ObjectDataBase.ObjectCursor(cursor);
try {
    if (objectCursor.getCount() == 0) {  return null;  }
    objectCursor.moveToFirst();
    return objectCursor.getObject();
} finally { cursor.close();}
</code>```

ObjectDataBase is the Database class, and ObjectCursor is the cursor wrapper and inner class of ObjectDataBase.

When I peek through the database using DB browser, the data is correct, so what else can be wrong?

答:
When I peek through the database using DB browser, the data is
  correct, so what else can be wrong?

a) The data in DB Browser may not be the data on the device.

This is a frequent cause of issues.

To rule this out I'd suggest running the query without the select clause so that all rows are returned along with some basic debugging

such as

```<code>Cursor cursor = mDatabase.query("Objects",null, "Selected" + " = ?", new String[]{String.valueOf(1)},null,null,null);
Log.d("CURSORINFO","The Cursor has " + String.valueOf(cursor.getCount()) + " rows."); //<<<<<<<<<< 4 DEBUG
DatabaseUtils.dumpCursor(cursor); //<<<<<<<<<< 4 DEBUG

ObjectDataBase.ObjectCursor objectCursor = new
ObjectDataBase.ObjectCursor(cursor);
try {
    if (objectCursor.getCount() == 0) {  return null;  }
    objectCursor.moveToFirst();
    return objectCursor.getObject();
} finally { cursor.close();}
</code>```

If the first message in the log reports that there are 0 rows, then you have no data in the table.

If you do have data in the table then the output from the dumpCursor method will output all of the data. You need to check that it matches what you expect the table to hold.

If the data matches the expectations then re-introduce the select clause and rerun. A row count of 0 and the issue is then with the select clause.

b) Wrapping code in a try clause

This can hide useful information if there is an underlying exception.

Your code would be better as :-

```<code>ObjectType rv = null;
if (objectCursor.moveToFirst()) {
    rv = objectCursor.getObject();
}
cursor.close();
return rv;
</code>```

If an exception happens then you will know about it.

c) The Cursor wrapper code is incorrectly assigning values.

As the code is not included in the question then it's impossible to say anything other than check the code.

Title: How to query SQLite by integer?

Body:
I have a SQL table like the following:

ID(string)    Name(string)    Width(double)   Height(double)   Selected(int)

12345678      Book            210             297              1
12345679      Display         530             326              0
12345680      Phone           70              140              0

I can query them by ID and Name by passing a String argument without issue, but all int and double queries return null. Why?

This is the code I tried:

Cursor cursor = mDatabase.query(  "Objects",null, "Selected" + " = ?", new String[]{String.valueOf(1)},null,null,null);
ObjectDataBase.ObjectCursor objectCursor = new
ObjectDataBase.ObjectCursor(cursor);
try {
    if (objectCursor.getCount() == 0) {  return null;  }
    objectCursor.moveToFirst();
    return objectCursor.getObject();
} finally { cursor.close();}

ObjectDataBase is the Database class, and ObjectCursor is the cursor wrapper and inner class of ObjectDataBase.

When I peek through the database using DB browser, the data is correct, so what else can be wrong?

Body:
When I peek through the database using DB browser, the data is
  correct, so what else can be wrong?

a) The data in DB Browser may not be the data on the device.

This is a frequent cause of issues.

To rule this out I'd suggest running the query without the select clause so that all rows are returned along with some basic debugging

such as

Cursor cursor = mDatabase.query("Objects",null, "Selected" + " = ?", new String[]{String.valueOf(1)},null,null,null);
Log.d("CURSORINFO","The Cursor has " + String.valueOf(cursor.getCount()) + " rows."); //<<<<<<<<<< 4 DEBUG
DatabaseUtils.dumpCursor(cursor); //<<<<<<<<<< 4 DEBUG

ObjectDataBase.ObjectCursor objectCursor = new
ObjectDataBase.ObjectCursor(cursor);
try {
    if (objectCursor.getCount() == 0) {  return null;  }
    objectCursor.moveToFirst();
    return objectCursor.getObject();
} finally { cursor.close();}

If the first message in the log reports that there are 0 rows, then you have no data in the table.

If you do have data in the table then the output from the dumpCursor method will output all of the data. You need to check that it matches what you expect the table to hold.

If the data matches the expectations then re-introduce the select clause and rerun. A row count of 0 and the issue is then with the select clause.

b) Wrapping code in a try clause

This can hide useful information if there is an underlying exception.

Your code would be better as :-

ObjectType rv = null;
if (objectCursor.moveToFirst()) {
    rv = objectCursor.getObject();
}
cursor.close();
return rv;

If an exception happens then you will know about it.

c) The Cursor wrapper code is incorrectly assigning values.

As the code is not included in the question then it's impossible to say anything other than check the code.


问:
Abstract parent class calls derived class method
So I was wondering about how classes instances are built.

```<code>public abstract class test {

    int count;

    public test(){
        count();
        count();
        System.out.println("test" + this.count);
    }
    abstract void count();
}

public class derive extends test{

    int count;

    public derive(){
        System.out.println("derive");
    }
    @Override
    public void count(){
        count++;
    }
}
    public static void main(String[] args) {
    derived o = new derived();
}
</code>```

The output is:

test0

derive

How come count = 0? and not 2?

答:
The superclass constructor is called first.  It calls count() twice.  With polymorphism, count() in derive is called, incrementing count to 2.  What is incremented is the  count variable in derive, because that what the simple name count means in the subclass.  The count variable in test is hidden by the count in derive.

However, the print statement refers to the count in scope in the superclass, which is still 0.

Note that when the superclass constructor finishes, then the subclass constructor body can finally execute.  This includes giving all instance variables initial values.  Here, even though count is already 2, it is "initialized" to 0 anyway.  So even if you add a print statement in the subclass constructor, you'll still get 0 for count there too.

To get a count of 2, remove the count in derive and change the count in test to be protected or package-private (no access modifier).  This will make count() increment the variable count in test.

Body:
So I was wondering about how classes instances are built.

public abstract class test {

    int count;

    public test(){
        count();
        count();
        System.out.println("test" + this.count);
    }
    abstract void count();
}

public class derive extends test{

    int count;

    public derive(){
        System.out.println("derive");
    }
    @Override
    public void count(){
        count++;
    }
}
    public static void main(String[] args) {
    derived o = new derived();
}

The output is:

test0

derive

How come count = 0? and not 2?


问:
Can I run a VBA macro to run SQL queries I have saved in a MS Access database?
I spent alot of time to create 24 different separate MS Access queries that I have saved in the MS Access database.  They have to be run in a specific order.

I want to run a macro that will just execute them one after another.

I know I can do this using VBA but I have copy all the SQL into VBA one at a time.

is there a way I can just have VBA run the saved queries in the MS Access database without copying them into VBA?

I am very good with SQL. 15+ years doing Oracle work,  Code writing, DB Tuning, Data DBA work.

I am new to using SQL and VBA to run against MS Access DB.

答:
You can do something like this to run saved queries:

```<code>Dim db As DAO.Database, qry As DAO.QueryDef

Set db = CurrentDb

Debug.Print "-- Start --"
For Each qry In db.QueryDefs
    If qry.Name Like pattern Then
        Debug.Print qry.Name,
        qry.Execute
        Debug.Print "(" & qry.RecordsAffected & ")"
    End If
Next
Debug.Print "-- End --"

db.Close()
</code>```

Name the queries so that the alphabetical order matches the the expected execution order, e.g., 01_deleteCustomers, 02_appendCustomers, 03_etc.

Specify a pattern string or remove the If alltogether if you want to run all the queries.

Note that in the Visual Basic editor under menu Tools > References... I have selected Microsoft DAO 3.6 Object Library. (You might have another version)

Body:
You can do something like this to run saved queries:

Dim db As DAO.Database, qry As DAO.QueryDef

Set db = CurrentDb

Debug.Print "-- Start --"
For Each qry In db.QueryDefs
    If qry.Name Like pattern Then
        Debug.Print qry.Name,
        qry.Execute
        Debug.Print "(" & qry.RecordsAffected & ")"
    End If
Next
Debug.Print "-- End --"

db.Close()

Name the queries so that the alphabetical order matches the the expected execution order, e.g., 01_deleteCustomers, 02_appendCustomers, 03_etc.

Specify a pattern string or remove the If alltogether if you want to run all the queries.

Note that in the Visual Basic editor under menu Tools > References... I have selected Microsoft DAO 3.6 Object Library. (You might have another version)


问:
R function to identify cases where condition is met x number of times in any of n number of columns?
I have a dataframe where I would like to identify cases (rows) where a given condition is met at least a certain number of times in a set of columns. In the toy example below, I would like to identify cases where "A" is the choice for two of three columns (Choice_1 to Choice_3). I do not care in which two of the three columns "A" is found. In my example, ID = 1 and ID = 4 would be identified.

This should work with any number of "A"s desired in any number of columns (e.g if I wanted to identify cases where "A" is the choice in three of the four Choice columns, only ID = 1 would be identified).

```<code>ID <- 1:4
Choice_1 <- c("A", "B", "C", "D")
Choice_2 <- c("A", "D", "C", "A")
Choice_3 <- c("A", "C", "A", "A")
Choice_4 <- c("B", "B", "A", "B")

df <- data.frame(ID, Choice_1, Choice_2, Choice_3, Choice_4)

> df
ID Choice_1 Choice_2 Choice_3 Choice_4
 1        A        A        A        B
 2        B        D        C        B
 3        C        C        A        A
 4        D        A        A        B
</code>```

One kind of roundabout way to do this would be to convert "A"s to 1 and all else to 0, sum the Choice columns I am interested in and check the sum is equal or higher than my threshold, but I feel like there must be a better way.

The way I imagine it, it would be some form of if_else statement included in a mutate so rows that match the condition would be identified with 1 and those that don't with 0:

```<code>df %>% mutate(cond_matched = if_else( two of (Choice_1, Choice_2, Choice_3) == "A", 1, 0))

ID Choice_1 Choice_2 Choice_3 Choice_4 cond_matched
 1        A        A        A        B            1
 2        B        D        C        B            0
 3        C        C        A        A            0
 4        D        A        A        B            1
</code>```

I'm hoping I've just been searching with the wrong keywords. Thank you for any help!

答:
One dplyr and tidyr possibility could be:

```<code>df %>%
 gather(var, val, -c(ID, Choice_4)) %>%
 group_by(ID) %>%
 summarise(cond_matched = as.integer(sum(val == "A") >= 2)) %>%
 ungroup() %>%
 left_join(df, by = c("ID" = "ID"))

     ID cond_matched Choice_1 Choice_2 Choice_3 Choice_4
  <int>        <int> <chr>    <chr>    <chr>    <chr>
1     1            1 A        A        A        B
2     2            0 B        D        C        B
3     3            0 C        C        A        A
4     4            1 D        A        A        B
</code>```

Or with just dplyr (using basically the same logic as @akrun):

```<code>df %>%
 mutate(cond_matched = as.integer(rowSums(.[-ncol(.)] == "A") >= 2))
</code>```

To name the columns explicitly:

```<code>df %>%
 mutate(cond_matched = as.integer(rowSums(.[grepl("Choice_1|Choice_2|Choice_3", colnames(.))] == "A") >= 2))
</code>```

Body:
I have a dataframe where I would like to identify cases (rows) where a given condition is met at least a certain number of times in a set of columns. In the toy example below, I would like to identify cases where "A" is the choice for two of three columns (Choice_1 to Choice_3). I do not care in which two of the three columns "A" is found. In my example, ID = 1 and ID = 4 would be identified.

This should work with any number of "A"s desired in any number of columns (e.g if I wanted to identify cases where "A" is the choice in three of the four Choice columns, only ID = 1 would be identified).

ID <- 1:4
Choice_1 <- c("A", "B", "C", "D")
Choice_2 <- c("A", "D", "C", "A")
Choice_3 <- c("A", "C", "A", "A")
Choice_4 <- c("B", "B", "A", "B")

df <- data.frame(ID, Choice_1, Choice_2, Choice_3, Choice_4)

> df
ID Choice_1 Choice_2 Choice_3 Choice_4
 1        A        A        A        B
 2        B        D        C        B
 3        C        C        A        A
 4        D        A        A        B

One kind of roundabout way to do this would be to convert "A"s to 1 and all else to 0, sum the Choice columns I am interested in and check the sum is equal or higher than my threshold, but I feel like there must be a better way.

The way I imagine it, it would be some form of if_else statement included in a mutate so rows that match the condition would be identified with 1 and those that don't with 0:

df %>% mutate(cond_matched = if_else( two of (Choice_1, Choice_2, Choice_3) == "A", 1, 0))

ID Choice_1 Choice_2 Choice_3 Choice_4 cond_matched
 1        A        A        A        B            1
 2        B        D        C        B            0
 3        C        C        A        A            0
 4        D        A        A        B            1

I'm hoping I've just been searching with the wrong keywords. Thank you for any help!

Body:
One dplyr and tidyr possibility could be:

df %>%
 gather(var, val, -c(ID, Choice_4)) %>%
 group_by(ID) %>%
 summarise(cond_matched = as.integer(sum(val == "A") >= 2)) %>%
 ungroup() %>%
 left_join(df, by = c("ID" = "ID"))

     ID cond_matched Choice_1 Choice_2 Choice_3 Choice_4
  <int>        <int> <chr>    <chr>    <chr>    <chr>
1     1            1 A        A        A        B
2     2            0 B        D        C        B
3     3            0 C        C        A        A
4     4            1 D        A        A        B

Or with just dplyr (using basically the same logic as @akrun):

df %>%
 mutate(cond_matched = as.integer(rowSums(.[-ncol(.)] == "A") >= 2))

To name the columns explicitly:

df %>%
 mutate(cond_matched = as.integer(rowSums(.[grepl("Choice_1|Choice_2|Choice_3", colnames(.))] == "A") >= 2))


答: derived count is 2 while test's count always is 0 as what you called count() is the derived method instead of test's one.

Title: Abstract parent class calls derived class method


问:
write python script to run the shell script?
I run the svn status got the modified files :

```<code>  svn status
  ?       .settings
  ?       .buildpath
  ?       .directory
  A       A.php
  M       B.php
  D       html/C.html
  M       html/D.fr
  M       api/E.api
  M       F.php
  ..
</code>```

After I want to keep all of these files

zcvf MY.tar.gz all files that svn stat display
(not include ? just M,A,D)

My idea is to create the python script can run the shell,because right now to do this I just copy the file name one by one.

zcvf MY.tar.gz all the files that we run svn stat

Anybody could guide how to do this or some related tutorial? But if you think it difficult than copy && paste I will ignore my trying?

thanks

答:
Once you figure out your command as a string you can just call it with subprocess

subprocess

This module spawns called processes and allows you to control them. From there its up to you.

Body:
I run the svn status got the modified files :

  svn status
  ?       .settings
  ?       .buildpath
  ?       .directory
  A       A.php
  M       B.php
  D       html/C.html
  M       html/D.fr
  M       api/E.api
  M       F.php
  ..

After I want to keep all of these files

zcvf MY.tar.gz all files that svn stat display
(not include ? just M,A,D)

My idea is to create the python script can run the shell,because right now to do this I just copy the file name one by one.

zcvf MY.tar.gz all the files that we run svn stat

Anybody could guide how to do this or some related tutorial? But if you think it difficult than copy && paste I will ignore my trying?

thanks


问:
It is possible use tinymce to upload pdf?
I´m develloping a website that needs to have an upload pdf function.

I´m already using tinymce to insert posts in the website, because its more easy to format, add images, etc.

But I also need to upload pdf, and I dont see any option for that in my tinymce4.

So I came here to ask if somebody there knows if its possible use tinymce for this purpose, or I really need to devellop the pdf uploder step by step?

Thanks!

答:
Yes, using a hidden form.

The HTML:

```<code><form id="PDFform"
      class="hideMe"
      method="post"
      enctype="multipart/form-data"
      <input id="pdfToken" type="hidden" name="dzToken">
      <input id="fileInput" name="pdf" type="file">
</form>
</code>```

The script:

```<code>tinyMCE.init({
        selector: "#tinyEditor",
        themr: "modern",
        plugins: [
              "advlist autolink lists link charmap print preview",
              "searchreplace visualblocks code fullscreen",
              "insertdatetime media table paste image paste"
        ],
        height: 450,
        force_br_newlines: false,
        force_p_newlines: false,
        images_upload_url: 'cgi/editorUpload.exe',
        file_picker_types: 'file, image',
        file_picker_callback: function(callback, value, meta) {

                $("#fileInput").click();  // open the chooser

                var tkn=getToken();       // set any other fields to upload with your file
                $("#pdfToken").val(tkn);

                $("#fileInput").on("change",function(){

                    var dataString=new FormData($("#PDFform")[0]);

                      $.ajax({
                            type: "POST",
                            url: "cgi/serverScriptToProcessFile.exe",
                            enctype: "multipart/form-data",
                            data: dataString,
                            processData: false,
                            contentType: false,
                            dataType: "json",
                            error: yourErrorHandlerFunction,
                            success: function(json) {

                                // reset the form or it won't work a 2nd time
                                $("#PDFuform").trigger("reset");

                                // if your script returns JSON you can process it here
                                // mine looks like {"location":"data/editorUploads/test.pdf","alt":"test.pdf"}
                                callback(json.location, {alt: json.alt, text: json.alt });

                            }
                      });

                });

        },
        automatic_uploads: true
});
</code>```

Body:
Yes, using a hidden form.

The HTML:

<form id="PDFform"
      class="hideMe"
      method="post"
      enctype="multipart/form-data"
      <input id="pdfToken" type="hidden" name="dzToken">
      <input id="fileInput" name="pdf" type="file">
</form>

The script:

tinyMCE.init({
        selector: "#tinyEditor",
        themr: "modern",
        plugins: [
              "advlist autolink lists link charmap print preview",
              "searchreplace visualblocks code fullscreen",
              "insertdatetime media table paste image paste"
        ],
        height: 450,
        force_br_newlines: false,
        force_p_newlines: false,
        images_upload_url: 'cgi/editorUpload.exe',
        file_picker_types: 'file, image',
        file_picker_callback: function(callback, value, meta) {

                $("#fileInput").click();  // open the chooser

                var tkn=getToken();       // set any other fields to upload with your file
                $("#pdfToken").val(tkn);

                $("#fileInput").on("change",function(){

                    var dataString=new FormData($("#PDFform")[0]);

                      $.ajax({
                            type: "POST",
                            url: "cgi/serverScriptToProcessFile.exe",
                            enctype: "multipart/form-data",
                            data: dataString,
                            processData: false,
                            contentType: false,
                            dataType: "json",
                            error: yourErrorHandlerFunction,
                            success: function(json) {

                                // reset the form or it won't work a 2nd time
                                $("#PDFuform").trigger("reset");

                                // if your script returns JSON you can process it here
                                // mine looks like {"location":"data/editorUploads/test.pdf","alt":"test.pdf"}
                                callback(json.location, {alt: json.alt, text: json.alt });

                            }
                      });

                });

        },
        automatic_uploads: true
});


问:
Call Kotlin function with Lambda parameters in Java
How do I call Kotlin functions with lambdas in the parameter from a Java class.

Example

```<code>fun getToken(
        tokenUrl: String,
        onSuccess: (String) -> Unit,
        onError: (Error) -> Unit
    ): Provider {
        //Implementation
    }
</code>```

答:
You can do this</p>
```<code>    value.getToken("url",
    new Function1<String, Unit>() {
        @Override
        public Unit invoke(String s) {
            /* TODO */
            return Unit.INSTANCE;
        }
    }, new Function1<Throwable, Unit>() {
        @Override
        public Unit invoke(Throwable throwable) {
            /* TODO */
            return Unit.INSTANCE;
        }
    });
</code>```

Body:
How do I call Kotlin functions with lambdas in the parameter from a Java class.

Example

fun getToken(
        tokenUrl: String,
        onSuccess: (String) -> Unit,
        onError: (Error) -> Unit
    ): Provider {
        //Implementation
    }

Body:
You can do this

    value.getToken("url",
    new Function1<String, Unit>() {
        @Override
        public Unit invoke(String s) {
            /* TODO */
            return Unit.INSTANCE;
        }
    }, new Function1<Throwable, Unit>() {
        @Override
        public Unit invoke(Throwable throwable) {
            /* TODO */
            return Unit.INSTANCE;
        }
    });


问:
MATLAB: How to automatically abort failed unit test
I am wondering how I can make a unit test to automatically stop, once an error in the system under test (sut) occurs?

Let's assume, the unit test runs some 1,000 different input combinations, and is supposed to verify that the results are equal to the expectations. Now, let's further assume there is a simple syntax error in sut, which causes an error. In this case I would like the unit test to automatically stop and invoke the tear down method.

Is that possible?

Edit:

I am borrowing a MATLAB example from their help site (https://de.mathworks.com/help/matlab/matlab_prog/create-basic-parameterized-test.html) in order to show more clearly what I mean:

Here you can see the test class:

```<code>classdef TestCarpet < matlab.unittest.TestCase

    properties (TestParameter)
        type = {'single','double','uint16'};
        level = struct('small', 2,'medium', 4, 'large', 6);
        side = struct('small', 9, 'medium', 81,'large', 729);
    end

    methods (Test)
        function testRemainPixels(testCase, level)
            % expected number pixels equal to 1
            expPixelCount = 8^level;
            % actual number pixels equal to 1
            actPixels = find(sierpinski(level));
            testCase.verifyNumElements(actPixels,expPixelCount)
        end

        function testClass(testCase, type, level)
            testCase.verifyClass(...
                sierpinski(level,type), type)
        end

        function testDefaultL1Output(testCase)
            exp = single([1 1 1; 1 0 1; 1 1 1]);
            testCase.verifyEqual(sierpinski(1), exp)
        end
    end

    methods (Test, ParameterCombination='sequential')
        function testNumel(testCase, level, side)
            import matlab.unittest.constraints.HasElementCount
            testCase.verifyThat(sierpinski(level),...
                HasElementCount(side^2))
        end
    end
end
</code>```

Here's the system under test:

```<code>function carpet = sierpinski(nLevels,classname)
if nargin == 1
    classname = 'single';
end

% original line: mSize = 3^nLevels;
mSize = "That's clearly wrong here";
carpet = ones(mSize,classname);

cutCarpet(1,1,mSize,nLevels) % begin recursion

    function cutCarpet(x,y,s,cL)
        if cL
            ss = s/3; % define subsize
            for lx = 0:2
                for ly = 0:2
                    if lx == 1 && ly == 1
                        % remove center square
                        carpet(x+ss:x+2*ss-1,y+ss:y+2*ss-1) = 0;
                    else
                        % recurse
                        cutCarpet(x + lx*ss, y + ly*ss, ss, cL-1)
                    end
                end
            end
        end
    end
end
</code>```

I changed the definition of mSize to a string to produce an error. Now, if I run the tests, all tests will result in an error. I am wondering if it is possible to stop the tests as soon as possible, i.e. after the occurence of the first error?

The problem that I see is that the test code won't even reach the last line of testRemainPixels (testCase.verifyNumElements(actPixels,expPixelCount)). A fatalAssert does not help at this point, right?

答:
Assuming you are using the test framework built into MATLAB, take a look at the types of qualifications, in particular the bulleted list at the top of this page:

https://www.mathworks.com/help/matlab/matlab_prog/types-of-qualifications.html

If you want to stop the entire testing session you can use fatal assertions. If you want other tests to continue you can use assertions. If you want to skip all the test methods (and parameterizations) in a single file you can use an assertion in TestClassSetup or just add a basic "smoke" level exercise step of the code in TestClassSetup and if it errors it will behave like an assertion.

Hope that helps.

Body:
I am wondering how I can make a unit test to automatically stop, once an error in the system under test (sut) occurs?

Let's assume, the unit test runs some 1,000 different input combinations, and is supposed to verify that the results are equal to the expectations. Now, let's further assume there is a simple syntax error in sut, which causes an error. In this case I would like the unit test to automatically stop and invoke the tear down method.

Is that possible?

Edit:

I am borrowing a MATLAB example from their help site (https://de.mathworks.com/help/matlab/matlab_prog/create-basic-parameterized-test.html) in order to show more clearly what I mean:

Here you can see the test class:

classdef TestCarpet < matlab.unittest.TestCase

    properties (TestParameter)
        type = {'single','double','uint16'};
        level = struct('small', 2,'medium', 4, 'large', 6);
        side = struct('small', 9, 'medium', 81,'large', 729);
    end

    methods (Test)
        function testRemainPixels(testCase, level)
            % expected number pixels equal to 1
            expPixelCount = 8^level;
            % actual number pixels equal to 1
            actPixels = find(sierpinski(level));
            testCase.verifyNumElements(actPixels,expPixelCount)
        end

        function testClass(testCase, type, level)
            testCase.verifyClass(...
                sierpinski(level,type), type)
        end

        function testDefaultL1Output(testCase)
            exp = single([1 1 1; 1 0 1; 1 1 1]);
            testCase.verifyEqual(sierpinski(1), exp)
        end
    end

    methods (Test, ParameterCombination='sequential')
        function testNumel(testCase, level, side)
            import matlab.unittest.constraints.HasElementCount
            testCase.verifyThat(sierpinski(level),...
                HasElementCount(side^2))
        end
    end
end

Here's the system under test:

function carpet = sierpinski(nLevels,classname)
if nargin == 1
    classname = 'single';
end

% original line: mSize = 3^nLevels;
mSize = "That's clearly wrong here";
carpet = ones(mSize,classname);

cutCarpet(1,1,mSize,nLevels) % begin recursion

    function cutCarpet(x,y,s,cL)
        if cL
            ss = s/3; % define subsize
            for lx = 0:2
                for ly = 0:2
                    if lx == 1 && ly == 1
                        % remove center square
                        carpet(x+ss:x+2*ss-1,y+ss:y+2*ss-1) = 0;
                    else
                        % recurse
                        cutCarpet(x + lx*ss, y + ly*ss, ss, cL-1)
                    end
                end
            end
        end
    end
end

I changed the definition of mSize to a string to produce an error. Now, if I run the tests, all tests will result in an error. I am wondering if it is possible to stop the tests as soon as possible, i.e. after the occurence of the first error?

The problem that I see is that the test code won't even reach the last line of testRemainPixels (testCase.verifyNumElements(actPixels,expPixelCount)). A fatalAssert does not help at this point, right?


问:
Node.js: Map function doesn't work on query from PostgreSQL

I'm creating my first app using Node.js and PostgreSQL.

This app connect's to db and return record to browser in JSON format, its work perfectly till i try to use map function to formating properties.

When i use map it return an error:

TypeError: rows.map is not a function

This is my code.

```<code> app.get('/car/:id', (req, res) => {

    const car_id = req.params.id;
    const queryString = `SELECT * FROM cars WHERE car_id= ${car_id}`;

    client.query(queryString, (err, rows, fields) => {
        if (err) {
            console.log(err.stack);
            res.sendStatus(500);
            res.end();
        } else {
                const car = rows.map((row) => {
                return {"Car_ID": row.car_id}
            });

            res.json(car);
            console.log(rows.rows);
        }
    });
</code>```

答:
It should be result.rows not just rows

According to this - https://node-postgres.com/api/result

```<code>app.get('/car/:id', (req, res) => {

    const car_id = req.params.id;
    const queryString = `SELECT * FROM cars WHERE car_id= ${car_id}`;

    client.query(queryString, (err, result, fields) => {
        if (err) {
            console.log(err.stack);
            res.sendStatus(500);
            res.end();
        } else {
                const car = result.rows.map((row) => {
                return {"Car_ID": row.car_id}
            });

            res.json(car);
            console.log(result.rows);
        }
    });
</code>```

Body:
I'm creating my first app using Node.js and PostgreSQL.

This app connect's to db and return record to browser in JSON format, its work perfectly till i try to use map function to formating properties.

When i use map it return an error:

TypeError: rows.map is not a function

This is my code.

 app.get('/car/:id', (req, res) => {

    const car_id = req.params.id;
    const queryString = `SELECT * FROM cars WHERE car_id= ${car_id}`;

    client.query(queryString, (err, rows, fields) => {
        if (err) {
            console.log(err.stack);
            res.sendStatus(500);
            res.end();
        } else {
                const car = rows.map((row) => {
                return {"Car_ID": row.car_id}
            });

            res.json(car);
            console.log(rows.rows);
        }
    });

Body:
It should be result.rows not just rows

According to this - https://node-postgres.com/api/result

app.get('/car/:id', (req, res) => {

    const car_id = req.params.id;
    const queryString = `SELECT * FROM cars WHERE car_id= ${car_id}`;

    client.query(queryString, (err, result, fields) => {
        if (err) {
            console.log(err.stack);
            res.sendStatus(500);
            res.end();
        } else {
                const car = result.rows.map((row) => {
                return {"Car_ID": row.car_id}
            });

            res.json(car);
            console.log(result.rows);
        }
    });


问:
Trying to understand why there are extra brackets at the end of a call
Possibly a silly question, I am trying to work through an example for OAuth and want to understand exactly what is happening before I add to my own code.

Sample is node, express using passport-azure-ad

The route is being defined and a call to passport.authenticate is made.

```<code>app.get('/login',
  (req, res, next) => {
      passport.authenticate('azuread-openidconnect',
      {
        response: res,
        resourceURL: config.resourceURL,
        failureRedirect: '/'
      })(req, res, next); // <-- Here is what I am stuck on.
   },
   (req, res) => {
       log.info('Login was called in the Sample');
       res.redirect('/');
});
</code>```

I am trying to understand the (req, res, next); that follows directly after the authenticate.

Appreciate any help, or a link to the theory/documentation on this syntax.

答:
I think this is just a question of understanding the Javascript syntax for what is called a "lambda" function. Consider the following expression:

```<code>(a) => { console.log(a) }
</code>```

That's a way of writing a function that takes one argument and prints it out.  You can put that expression in anyplace you need to specify a function that prints out one argument.  This is useful because in Javascript functions can be passed around just like data, and this syntax allows you to define a function right when you need it, without bothering to give it a name.

In your example you are calling app.get with three arguments.  The first is the string '/login'.  The second is a function that takes 3 arguments, and the function is defined right there in line, to call passport.authenticate, which returns a function, which is called with those 3 arguments. The third is a function that takes 2 arguments, also defined right there in line.

Body:
Possibly a silly question, I am trying to work through an example for OAuth and want to understand exactly what is happening before I add to my own code.

Sample is node, express using passport-azure-ad

The route is being defined and a call to passport.authenticate is made.

app.get('/login',
  (req, res, next) => {
      passport.authenticate('azuread-openidconnect',
      {
        response: res,
        resourceURL: config.resourceURL,
        failureRedirect: '/'
      })(req, res, next); // <-- Here is what I am stuck on.
   },
   (req, res) => {
       log.info('Login was called in the Sample');
       res.redirect('/');
});

I am trying to understand the (req, res, next); that follows directly after the authenticate.

Appreciate any help, or a link to the theory/documentation on this syntax.

Body:
I think this is just a question of understanding the Javascript syntax for what is called a "lambda" function. Consider the following expression:

(a) => { console.log(a) }

That's a way of writing a function that takes one argument and prints it out.  You can put that expression in anyplace you need to specify a function that prints out one argument.  This is useful because in Javascript functions can be passed around just like data, and this syntax allows you to define a function right when you need it, without bothering to give it a name.

In your example you are calling app.get with three arguments.  The first is the string '/login'.  The second is a function that takes 3 arguments, and the function is defined right there in line, to call passport.authenticate, which returns a function, which is called with those 3 arguments. The third is a function that takes 2 arguments, also defined right there in line.


问:
compare an element of a list with the following in a recursively way
Hi,
Update: Thanks for all your suggestion

assuming that, this exercise it's like a rebus,
I have a list of numbers made with the concept of Cons and Nil,

```<code>List l = new Cons(**3**, new Cons(**2**,new Cons(**1**, new
Cons(**4**, new Cons(**1**, new Nil())))));
</code>```

and I want to count how many of them are immediately followed by a lower number, recursively.

For example

```<code>[5,0,5,3].count() == 2, [5,5,0].count() == 1
</code>```

The count() method is made by me (it cannot have any parameters), the rest is default, and I can't make and other method or use already defined one's like add(),size()...
The "NEXT" must have the next value after the current elem but I can't get a solution.

Any solutions are welcome.

```<code>abstract class List {

    public abstract boolean empty();

    public abstract int first();

    public abstract int count();

}

class Cons extends List {

    private int elem;

    private List next;

  public Cons(int elem, List next) {

   this.elem = elem;

   this.next = next;

}

public boolean empty(){
 return false;
}

public int first(){
 return elem;
}

@Override
public int count() {
  if(elem>NEXT) {
      return 1 + next.count();
  }else {
      return next.count();
 }

}

```![enter image description here](https://i.stack.imgur.com/kWo0v.jpg)
```

答:
The following code will create a recursive list with N elements with N value being defined by the size of the amount of elements found in the int array called elements in RecursiveList class. Call the startRecursion() method to create a recursive list with the defined elements and call count() to get the amount of elements in the array that are immediately followed by a lower number.

Main Class

This your application entry point:

```<code>public static void main(String[] args) {

    int count = RecursiveList.startRecursion().count();
    System.out.printf("List has %d recursive elements", count);
}
</code>```

RecursiveList Class

```<code>abstract class RecursiveList {

    protected static int index = -1;
    protected static int[] elements = new int[]{ 5,2,1,4,3,2,6 };

    public static RecursiveList startRecursion() {
        return new Cons();
    }

    public abstract boolean empty();

    public abstract int count();

    public abstract Integer getElement();

    public static int incIndex() {
        return index += 1;
    }
}
</code>```

Cons Class

```<code>public class Cons extends RecursiveList {

    private static int result;

    private final Integer elem;
    private final RecursiveList prev;
    private final RecursiveList next;

    private Cons(Cons parent) {

        prev = parent;
        elem = incIndex() < elements.length ? elements[index] : null;
        System.out.printf("Creating new Cons with element %d(%d)%n", elem, index);
        next = elem != null ? new Cons(this) : null;
    }

    Cons() {
        this(null);
    }

    public boolean empty() {
        return false;
    }

    @Override
    public /*@Nullable*/ Integer getElement() {
        return elem;
    }

    @Override
    public int count() {

        if (elem != null)
        {
            if (prev != null && elem < prev.getElement())
                result += 1;

            if (next != null) {
                return next.count();
            }
        }
        return result;
    }
}
</code>```

EDIT

Alright here is the answer you were actually looking for. This completely conforms to the limitations imposed on this exercise that you provided. The solution uses pure Java, neither the class nor any of it's method or field declarations were modified in any way and no such new elements were added. I've only added the implementation where the exercise said you should.

Main Class

```<code>public static void main(String[] args) {

    List l = new Cons(3, new Cons(2,new Cons(1, new
            Cons(4, new Cons(1, new Nil())))));

    assert l.count() == 3;

    l = new Cons(5, new Nil());
    assert l.count() == 0;

    l = new Cons(5, new Cons(5, new Cons(0, new Nil())));
    assert l.count() == 1;

    l = new Cons(5, new Cons(0, new Cons(5, new Cons(3, new Nil()))));
    assert l.count() == 2;

    System.out.println("All tests completed successfully!");
}
</code>```

Cons Class

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

public class Cons extends List {
    private int elem;
    private List next;

    public Cons(int elem, List next) {
        this.elem = elem;
        this.next = next;
    }

    public boolean empty()
    { return false; }

    public int first()
    { return elem; }

    public int count()
    {
        try {
            if (first() > next.first()) {
                return 1 + next.count();
            }
            else return next.count();
        }
        catch (NoSuchElementException e) {
            return 0;
        }
    }
}
</code>```

Nil Class

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

public class Nil extends List {
    public boolean empty()
    { return true; }

    public int first()
    { throw new NoSuchElementException(); }

    public int count()
    {
        throw new IllegalAccessError();
    }
}
</code>```

Body:
Hi,
Update: Thanks for all your suggestion

assuming that, this exercise it's like a rebus,
I have a list of numbers made with the concept of Cons and Nil,

List l = new Cons(**3**, new Cons(**2**,new Cons(**1**, new
Cons(**4**, new Cons(**1**, new Nil())))));

and I want to count how many of them are immediately followed by a lower number, recursively.

For example

[5,0,5,3].count() == 2, [5,5,0].count() == 1

The count() method is made by me (it cannot have any parameters), the rest is default, and I can't make and other method or use already defined one's like add(),size()...
The "NEXT" must have the next value after the current elem but I can't get a solution.

Any solutions are welcome.

abstract class List {

    public abstract boolean empty();

    public abstract int first();

    public abstract int count();

}

class Cons extends List {

    private int elem;

    private List next;

  public Cons(int elem, List next) {

   this.elem = elem;

   this.next = next;

}

public boolean empty(){
 return false;
}

public int first(){
 return elem;
}

@Override
public int count() {
  if(elem>NEXT) {
      return 1 + next.count();
  }else {
      return next.count();
 }

}

```![enter image description here](https://i.stack.imgur.com/kWo0v.jpg)

Body:
The following code will create a recursive list with N elements with N value being defined by the size of the amount of elements found in the int array called elements in RecursiveList class. Call the startRecursion() method to create a recursive list with the defined elements and call count() to get the amount of elements in the array that are immediately followed by a lower number.

Main Class

This your application entry point:

public static void main(String[] args) {

    int count = RecursiveList.startRecursion().count();
    System.out.printf("List has %d recursive elements", count);
}

RecursiveList Class

abstract class RecursiveList {

    protected static int index = -1;
    protected static int[] elements = new int[]{ 5,2,1,4,3,2,6 };

    public static RecursiveList startRecursion() {
        return new Cons();
    }

    public abstract boolean empty();

    public abstract int count();

    public abstract Integer getElement();

    public static int incIndex() {
        return index += 1;
    }
}

Cons Class

public class Cons extends RecursiveList {

    private static int result;

    private final Integer elem;
    private final RecursiveList prev;
    private final RecursiveList next;

    private Cons(Cons parent) {

        prev = parent;
        elem = incIndex() < elements.length ? elements[index] : null;
        System.out.printf("Creating new Cons with element %d(%d)%n", elem, index);
        next = elem != null ? new Cons(this) : null;
    }

    Cons() {
        this(null);
    }

    public boolean empty() {
        return false;
    }

    @Override
    public /*@Nullable*/ Integer getElement() {
        return elem;
    }

    @Override
    public int count() {

        if (elem != null)
        {
            if (prev != null && elem < prev.getElement())
                result += 1;

            if (next != null) {
                return next.count();
            }
        }
        return result;
    }
}

EDIT

Alright here is the answer you were actually looking for. This completely conforms to the limitations imposed on this exercise that you provided. The solution uses pure Java, neither the class nor any of it's method or field declarations were modified in any way and no such new elements were added. I've only added the implementation where the exercise said you should.

Main Class

public static void main(String[] args) {

    List l = new Cons(3, new Cons(2,new Cons(1, new
            Cons(4, new Cons(1, new Nil())))));

    assert l.count() == 3;

    l = new Cons(5, new Nil());
    assert l.count() == 0;

    l = new Cons(5, new Cons(5, new Cons(0, new Nil())));
    assert l.count() == 1;

    l = new Cons(5, new Cons(0, new Cons(5, new Cons(3, new Nil()))));
    assert l.count() == 2;

    System.out.println("All tests completed successfully!");
}

Cons Class

import java.util.NoSuchElementException;

public class Cons extends List {
    private int elem;
    private List next;

    public Cons(int elem, List next) {
        this.elem = elem;
        this.next = next;
    }

    public boolean empty()
    { return false; }

    public int first()
    { return elem; }

    public int count()
    {
        try {
            if (first() > next.first()) {
                return 1 + next.count();
            }
            else return next.count();
        }
        catch (NoSuchElementException e) {
            return 0;
        }
    }
}

Nil Class

import java.util.NoSuchElementException;

public class Nil extends List {
    public boolean empty()
    { return true; }

    public int first()
    { throw new NoSuchElementException(); }

    public int count()
    {
        throw new IllegalAccessError();
    }
}


问:
Navigation Controller strategy with an Address Book picker
So I'd like to have a user select a contact using the People Picker and THEN enter some custom data once a contact has been successfully selected. Simple enough.

My question is where is the best place for my <ABPeoplePickerNavigationControllerDelegate>?  Should I put it in the RootViewController which is the delegate to the view with the button that will initiate this process? Then once an address book contact has been picked THEN pass that ABRecordID into my next view controller (AddPersonViewController) that knows more about the extra goodies in my Person class and will handle the addition of the custom data I want to associate with said address book contact...

OR, is it considered better to fire up the AddPersonViewController but before it displays immediately throw up the modal ABPeoplePickerNavigationController onto the stack as well

Wondering if anyone has any sage advice either pro or con with this?

Thanks!

答:
The former.

Create views and controllers in the order you will use them. When finished with one transition to the next.

OwnerDisplayName: Zorba

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: Andrew Grant


问:
How to fabricate ASPX POST request
I'm battling with this for days, I have an ASPX page that has a file upload control and an upload button, and no matter what I do, I can't get the page to accept the automated POST request.

The request body is as follows (all newlines CRLF), all UTF8 == ANSII (no spec chars right now)

```<code>-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="btnUpload"

Upload
-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="ctrFileUpload"; filename="myfile.txt"
Content-Type: text/plain

This is a test!

-----------------------------8cdc74445fc88d0--
</code>```

The form has multiple buttons, so I need to kinda fill the file upload, and press the upload button. But this doesn't seem to work.

The same page works just fine from a web browser, although, in that scenario there is a viewstate garbage as one of the parts. I tried EnableViewState="false", ValidateRequest="false", EnableSessionState="ReadOnly", but the garbage part is still there when I use the browser.

Am I missing something? Tried studying the RFC and everything, but nothing seems to work.

答: Why not use fiddler to compare your post with the post that works..</p>

Title: How to fabricate ASPX POST request

Body:
I'm battling with this for days, I have an ASPX page that has a file upload control and an upload button, and no matter what I do, I can't get the page to accept the automated POST request.

The request body is as follows (all newlines CRLF), all UTF8 == ANSII (no spec chars right now)

-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="btnUpload"

Upload
-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="ctrFileUpload"; filename="myfile.txt"
Content-Type: text/plain

This is a test!

-----------------------------8cdc74445fc88d0--

The form has multiple buttons, so I need to kinda fill the file upload, and press the upload button. But this doesn't seem to work.

The same page works just fine from a web browser, although, in that scenario there is a viewstate garbage as one of the parts. I tried EnableViewState="false", ValidateRequest="false", EnableSessionState="ReadOnly", but the garbage part is still there when I use the browser.

Am I missing something? Tried studying the RFC and everything, but nothing seems to work.