问:
Windows Identity always anonymous in ASP.NET request pipeline
I'm trying to create a simple action filter for my MVC site that checks the current Windows user against those allowed access to the site. For some reason, the filterContext.HttpContext.User.Identity object is always set to anonymous with no username. I've tried to grab it at different stages (OnAuthenticate and OnAuthorize), but it's always anonymous.

I currently have anonymous and Windows authentication enabled in IIS (actually followed this example to configure the Windows Auth feature), and I have the following block in the system.web node of my web.config:

```<code><authentication mode="Windows" />
<authorization>
  <allow users="*" />
  <deny users="?" />
</authorization>
</code>```

However for some reason, the Identity is always anonymous with no username. I have to be missing something here. With Windows Auth set in IIS, I'm always prompted for the username/password combo (which actually fails with HTTP401.1 error 0xc000006d, though I think this might be because I have a custom host header setup for development). I've also read a few articles that suggest this is because my site is determined to be in the internet zone and the answers always state to add the site to the intranet zone in Internet Explorer. This seems like a band-aid fix though, and not the actual solution.

Ideally, I would like to have the following:

User browses to my site

Behind the scenes, their Windows username is picked up, and authenticated against allowed users managed by the app

User authenticated successfully, page loads, user is none the wiser they were authenticated

What do I need to do to achieve this?

Thanks in advance for any help. Please let me know if I can provide more context.

Edit: Forgot to add I'm running this on Windows 7 SP1, IIS 7.5

答: You need to disable the anonymous authentication from iis and enable windows auth only.</p>

Body:
I'm trying to create a simple action filter for my MVC site that checks the current Windows user against those allowed access to the site. For some reason, the filterContext.HttpContext.User.Identity object is always set to anonymous with no username. I've tried to grab it at different stages (OnAuthenticate and OnAuthorize), but it's always anonymous.

I currently have anonymous and Windows authentication enabled in IIS (actually followed this example to configure the Windows Auth feature), and I have the following block in the system.web node of my web.config:

<authentication mode="Windows" />
<authorization>
  <allow users="*" />
  <deny users="?" />
</authorization>

However for some reason, the Identity is always anonymous with no username. I have to be missing something here. With Windows Auth set in IIS, I'm always prompted for the username/password combo (which actually fails with HTTP401.1 error 0xc000006d, though I think this might be because I have a custom host header setup for development). I've also read a few articles that suggest this is because my site is determined to be in the internet zone and the answers always state to add the site to the intranet zone in Internet Explorer. This seems like a band-aid fix though, and not the actual solution.

Ideally, I would like to have the following:

User browses to my site

Behind the scenes, their Windows username is picked up, and authenticated against allowed users managed by the app

User authenticated successfully, page loads, user is none the wiser they were authenticated

What do I need to do to achieve this?

Thanks in advance for any help. Please let me know if I can provide more context.

Edit: Forgot to add I'm running this on Windows 7 SP1, IIS 7.5


来源: stackexchange

问:
JUnit test — analysing expected Exceptions
In JUnit, I'm currently using annotation to expect an exception in my tests.

Is there a way to analyse this exception? For example, I expect a CriticalServerException, but I also want to verify the content of the getMessage method.

答:
I'm not sure if you should. Using a try-catch block to check the error message is so junit3ish. We have this cool feature now that you can write @Test(expected=CriticalServerException.class) and you want to go "back" and use try-catch again to fetch an exception you expect, just for checking the error message?

IMO you should stay for the @Test(expected=CriticalServerException.class) annotation and ignore the error message. Checking the error message, which can be changed a lot as it is a more "human readable" string and not a technical value, can also be tricky. You are forcing the exception to have a specific error message, but you might not know who generated the exception and what error message he chose.

In general you want to test if the method throws the exception or not, and not what the actual error message looks like. If the error message is really so important you should maybe consider using a subclass of the exception it throws and check it in @Test(expected=...).

ContentLicense: CC BY-SA 3.0


问:
Angular route is not working in my web application
Angular Router is not working in my application. I have a login form, Angular controller, and Welcome page. When I pass the login details and click on submit button, Angular is not routing to welcome.html page.
Below is the code snippet.

Login Form(AngularForm.html)

```<code> <html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.js"></script>
    <script src="LoginCtrl.js"></script>
</head>

<body ng-app="myAngular">
    <div ng-controller="LoginController">
        <form action="/" id="myForm">
            UserName:
            <input type="text" id="username" ng-model="username">
            <br> Password:
            <input type="password" id="passowrd" ng-model="password">
            <br>
            <button type="button" ng-click="submit()">Login</button>
        </form>
    </div>
</body>

</html>
</code>```

Login Controller(LoginCtrl.js)

```<code>        var App = angular.module('myAngular', ['ngRoute']);
    App.config(function($routeProvider){
        $routeProvider.when('/',{
            templateUrl: 'AngularForm.html'
        })
        .when('/welcome',{
              templateUrl: 'welcome.html'
              })
        .otherwise({
            redirectTo: '/'
        });
    });

    function UserLogin($scope,$location)
    {
        $scope.submit = function(){
           var uname=$scope.username
           var pwd=$scope.passowrd
            if($scope.username == 'admin' && $scope.password == 'admin')
               { $location.path('/welcome'); }

        }

    }

App.controller('LoginController',UserLogin);
</code>```

Welcome Page(welcome.html)

```<code><!DOCTYPE html>
<html>

<head></head>

<body>
    <h1>Login Successful!!</h1>
</body>

</html>
</code>```

答:
I think you need to separate the login content from the main AngularForm.html file

AngularForm.html

```<code><html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.js"></script>
        <script src="LoginCtrl.js"></script>
        </head>
        <body ng-app="myAngular">
            <div ng-view></div>
        </body>
</html>
</code>```

make sure to add the

 so that partial routes lay on top of this.

make the login HTML like this

login.html

```<code><div ng-controller="LoginController">
<form action="/" id="myForm">
    UserName:<input type="text" id="username" ng-model="username"><br>
    Password:<input type="password" id="passowrd" ng-model="password"><br>
    <button type="button" ng-click="submit()">Login</button>
</form>
</div>
</code>```

add a new state called login in the config

JS

```<code>var App = angular.module('myAngular', ['ngRoute']);
App.config(function($routeProvider){
    $routeProvider
    .when('/',{
        templateUrl: 'AngularForm.html'
    })
    .when('/login',{
        templateUrl: 'login.html'
    })
    .when('/welcome',{
          templateUrl: 'welcome.html'
          })
    .otherwise({
        redirectTo: '/login'
    });
});

function UserLogin($scope,$location)
{
    $scope.submit = function(){
       var uname=$scope.username
       var pwd=$scope.passowrd
        if($scope.username == 'admin' && $scope.password == 'admin')
           { $location.path('/welcome'); }

    }

}

App.controller('LoginController',UserLogin)
</code>```

Body:
Angular Router is not working in my application. I have a login form, Angular controller, and Welcome page. When I pass the login details and click on submit button, Angular is not routing to welcome.html page.
Below is the code snippet.

Login Form(AngularForm.html)

        <form action="/" id="myForm">
            UserName:
            <input type="text" id="username" ng-model="username">

 Password:
            <input type="password" id="passowrd" ng-model="password">

            <button type="button" ng-click="submit()">Login</button>
        </form>

Login Controller(LoginCtrl.js)

        var App = angular.module('myAngular', ['ngRoute']);
    App.config(function($routeProvider){
        $routeProvider.when('/',{
            templateUrl: 'AngularForm.html'
        })
        .when('/welcome',{
              templateUrl: 'welcome.html'
              })
        .otherwise({
            redirectTo: '/'
        });
    });

    function UserLogin($scope,$location)
    {
        $scope.submit = function(){
           var uname=$scope.username
           var pwd=$scope.passowrd
            if($scope.username == 'admin' && $scope.password == 'admin')
               { $location.path('/welcome'); }

        }

    }

App.controller('LoginController',UserLogin);

Welcome Page(welcome.html)

<!DOCTYPE html>

Login Successful!!

Body:
I think you need to separate the login content from the main AngularForm.html file

AngularForm.html

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.js"></script>
        <script src="LoginCtrl.js"></script>
        </head>
        <body ng-app="myAngular">
            <div ng-view></div>
        </body>
</html>

make sure to add the <div ng-view></div> so that partial routes lay on top of this.

make the login HTML like this

login.html

<div ng-controller="LoginController">
<form action="/" id="myForm">
    UserName:<input type="text" id="username" ng-model="username"><br>
    Password:<input type="password" id="passowrd" ng-model="password"><br>
    <button type="button" ng-click="submit()">Login</button>
</form>
</div>

add a new state called login in the config

JS

var App = angular.module('myAngular', ['ngRoute']);
App.config(function($routeProvider){
    $routeProvider
    .when('/',{
        templateUrl: 'AngularForm.html'
    })
    .when('/login',{
        templateUrl: 'login.html'
    })
    .when('/welcome',{
          templateUrl: 'welcome.html'
          })
    .otherwise({
        redirectTo: '/login'
    });
});

function UserLogin($scope,$location)
{
    $scope.submit = function(){
       var uname=$scope.username
       var pwd=$scope.passowrd
        if($scope.username == 'admin' && $scope.password == 'admin')
           { $location.path('/welcome'); }

    }

}

App.controller('LoginController',UserLogin)


问:
How to install the OpenCart 2.3 extension?
I'm trying to install an extension of the Bling platform in my OpenCart application, I know they have forum, but the material is scarce. So I came here. I downloaded the package and followed the steps of the installation, extracted the files and placed in the folder indicated by the documentation.

So I went to OpenCart to install the extension, but I did not find the file there, do I need to update something? Do I need to change the structuring of folders? If anyone can help me, I'll be happy.

Any suggestion?

答:
Log into your OpenCart Dashboard.
Go to Extensions > Product Feeds.
Click on “Install” next to the “Google Site Map” product feed name.
Click “Edit” and then change the status to “Enabled”
Copy the “Data Feed URL” and click “Save"</p>


问:
Android sdk Update contact with contact provider
I first do a request like that :

```<code>Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

    String[] projection = new String[]{
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.Contacts.PHOTO_ID,
            ContactsContract.Contacts.HAS_PHONE_NUMBER,
            ContactsContract.CommonDataKinds.Phone.NUMBER
    };

    Cursor cursor = resolver.query(uri, projection, null, null, null);

    ArrayList<Contact> contactList = new ArrayList<> ();

    if (cursor != null && cursor.moveToFirst ()) {
        do {
            Contact contact = new Contact();
            contact.Id = cursor.getLong (cursor.getColumnIndex (projection [0]));
            contact.DisplayName = cursor.getString (cursor.getColumnIndex (projection [1]));
            contact.PhotoId = cursor.getString (cursor.getColumnIndex (projection [2]));
            contact.PhoneNumber = cursor.getString (cursor.getColumnIndex (projection [4]));

            contactList.add (contact);
        } while (cursor.moveToNext());

        cursor.close();
    }

    return contactList;
</code>```

Then I use the ID returned by this first request to update a contact like so :

```<code>ArrayList<ContentProviderOperation> ops = new ArrayList<>();

    // Name
    ops.add(ContentProviderOperation
            .newUpdate(ContactsContract.Data.CONTENT_URI)
            .withSelection(
                    ContactsContract.Contacts._ID
                            + "=? AND "
                            + ContactsContract.Data.MIMETYPE
                            + "=?",
                    new String[] {
                            String.valueOf(contact.Id),
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
            .withValue(ContactsContract.Contacts.DISPLAY_NAME, contact.DisplayName)
            .build());

    try {
        resolver.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        e.printStackTrace();
    }
</code>```

But unfortunately the update part is not working.
Any idea of how to use result from the first request with the update request ?

答:
You can't update a field from the Contacts table by updating the Data table.
All the fields in your projection that come from Contacts.X are added via an implicit join, but actually belong to a different table.

If I understand correctly, you're trying to update a contact's display-name, here's how to do it (make sure you import all classes from ContactsContract):

```<code>ops.add(ContentProviderOperation
        .newUpdate(Data.CONTENT_URI)
        .withSelection(Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?", new String[] { String.valueOf(contact.Id), StructuredName.CONTENT_ITEM_TYPE })
        .withValue(StructuredName.DISPLAY_NAME, contact.DisplayName)
        .build());
</code>```

Also, FYI, you don't need to use cursor.getColumnIndex in your first query, just do:

```<code>contact.Id = cursor.getLong(0);
contact.DisplayName = cursor.getString(1);
contact.PhotoId = cursor.getString(2);
contact.PhoneNumber = cursor.getString(4);
</code>```

Docs

Some columns from the associated raw contact are also available
  through an implicit join. The other columns are excluded as
  uninteresting in this context.

...

The ID column for the associated aggregated contact table
  ContactsContract.Contacts is available via the implicit join to the
  ContactsContract.RawContacts table, see above. The remaining columns
  from this table are also available, through an implicit join. This
  facilitates lookup by the value of a single data element, such as the
  email address.

Body:
I first do a request like that :

Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

    String[] projection = new String[]{
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.Contacts.PHOTO_ID,
            ContactsContract.Contacts.HAS_PHONE_NUMBER,
            ContactsContract.CommonDataKinds.Phone.NUMBER
    };

    Cursor cursor = resolver.query(uri, projection, null, null, null);

    ArrayList<Contact> contactList = new ArrayList<> ();

    if (cursor != null && cursor.moveToFirst ()) {
        do {
            Contact contact = new Contact();
            contact.Id = cursor.getLong (cursor.getColumnIndex (projection [0]));
            contact.DisplayName = cursor.getString (cursor.getColumnIndex (projection [1]));
            contact.PhotoId = cursor.getString (cursor.getColumnIndex (projection [2]));
            contact.PhoneNumber = cursor.getString (cursor.getColumnIndex (projection [4]));

            contactList.add (contact);
        } while (cursor.moveToNext());

        cursor.close();
    }

    return contactList;

Then I use the ID returned by this first request to update a contact like so :

ArrayList<ContentProviderOperation> ops = new ArrayList<>();

    // Name
    ops.add(ContentProviderOperation
            .newUpdate(ContactsContract.Data.CONTENT_URI)
            .withSelection(
                    ContactsContract.Contacts._ID
                            + "=? AND "
                            + ContactsContract.Data.MIMETYPE
                            + "=?",
                    new String[] {
                            String.valueOf(contact.Id),
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
            .withValue(ContactsContract.Contacts.DISPLAY_NAME, contact.DisplayName)
            .build());

    try {
        resolver.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        e.printStackTrace();
    }

But unfortunately the update part is not working.
Any idea of how to use result from the first request with the update request ?

Body:
You can't update a field from the Contacts table by updating the Data table.
All the fields in your projection that come from Contacts.X are added via an implicit join, but actually belong to a different table.

If I understand correctly, you're trying to update a contact's display-name, here's how to do it (make sure you import all classes from ContactsContract):

ops.add(ContentProviderOperation
        .newUpdate(Data.CONTENT_URI)
        .withSelection(Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?", new String[] { String.valueOf(contact.Id), StructuredName.CONTENT_ITEM_TYPE })
        .withValue(StructuredName.DISPLAY_NAME, contact.DisplayName)
        .build());

Also, FYI, you don't need to use cursor.getColumnIndex in your first query, just do:

contact.Id = cursor.getLong(0);
contact.DisplayName = cursor.getString(1);
contact.PhotoId = cursor.getString(2);
contact.PhoneNumber = cursor.getString(4);

Docs

Some columns from the associated raw contact are also available
  through an implicit join. The other columns are excluded as
  uninteresting in this context.

...

The ID column for the associated aggregated contact table
  ContactsContract.Contacts is available via the implicit join to the
  ContactsContract.RawContacts table, see above. The remaining columns
  from this table are also available, through an implicit join. This
  facilitates lookup by the value of a single data element, such as the
  email address.


问:
asset_path rails helper using only the dns of assethost given
Hi following is the how the asset-host is defined.

```<code>config.action_controller.asset_host = 'cdn.com/site1'
</code>```

Scss file example:

```<code>.home-ntf-headline.ntf-img {
  background-image: url(asset_path('ntf-logo.png'));
}
</code>```

The actual url frame for above Scss is cdn.com/assets/ntf-logo-b1a1fa585e8393a621c8ac16d515d96560d469afd8b9aadb36dc290acc4e9c42.png.

But what i actually expects
cdn.com/site1/assets/ntf-logo-b1a1fa585e8393a621c8ac16d515d96560d469afd8b9aadb36dc290acc4e9c42.png.

The static assets in request life cycle(i.e css, js, images) are framed correctly.

答:
The "host" here is limited to the top level host, rather than a prefix to the full asset path. If you specify anything after cdn.com then it will be stripped before being applied as the asset_host in Actionview Helpers.

If you're looking to have multiple sites on the same CDN then you're going to have to look at subdomains rather than paths, or some kind of per-site unique naming convention for your assets (I'd advise against that).

Body:
Hi following is the how the asset-host is defined.

config.action_controller.asset_host = 'cdn.com/site1'

Scss file example:

.home-ntf-headline.ntf-img {
  background-image: url(asset_path('ntf-logo.png'));
}

The actual url frame for above Scss is cdn.com/assets/ntf-logo-b1a1fa585e8393a621c8ac16d515d96560d469afd8b9aadb36dc290acc4e9c42.png.

But what i actually expects
cdn.com/site1/assets/ntf-logo-b1a1fa585e8393a621c8ac16d515d96560d469afd8b9aadb36dc290acc4e9c42.png.

The static assets in request life cycle(i.e css, js, images) are framed correctly.


问:
Group by and select lowest
I am trying to select the non repeated records of my database, and if there is one repeated, choose the one with the soonest date. To do so, I have tried the following query:

```<code>SELECT name, MIN(date) FROM `table` GROUP BY number_offer ORDER BY `date` ASC
</code>```

and then, showing them like this:

```<code>echo $row['fecha'];
echo $row['name'];
</code>```

The query selects correctly all the non repeated records but fails at selecting the sooner date (it says 'undefined index "date"'). Do you have any idea of how to do that?

答: You can set MIN(date) as datee or MIN(date) datee

ContentLicense: CC BY-SA 4.0

Title: Group by and select lowest

Body:
I am trying to select the non repeated records of my database, and if there is one repeated, choose the one with the soonest date. To do so, I have tried the following query:

SELECT name, MIN(date) FROM `table` GROUP BY number_offer ORDER BY `date` ASC

and then, showing them like this:

echo $row['fecha'];
echo $row['name'];

The query selects correctly all the non repeated records but fails at selecting the sooner date (it says 'undefined index "date"'). Do you have any idea of how to do that?


问:
jQuery ancestors
Is there an easier way to say

```<code>$('element').parent('parentElement').parent('grandParentElement');
</code>```

Answer: Try parents() or closest()

Title: jQuery ancestors

Body:
Is there an easier way to say

$('element').parent('parentElement').parent('grandParentElement');

Answer: Try parents() or closest()

Body: $('element').parent().parent();

ContentLicense: CC BY-SA 2.5


问:
FTP Directory name with spaces not accessible in iOS programmatically
I have to access the folder name with spaces, but I am getting 550 error which means file does not exist.

ftp://192.xxx.xx.x/C/xxx/xxxx/xxx xxx xxx/5mb.jpg

I can access directories upto this path
ftp://192.xxx.xx.x/C/xxx/xxxx/

But after that, as there is space in directory name (in bold), it is not accessible.

答:
Replace the spaces with below and try again</p>

```<code>%20
</code>```

Body:
Replace the spaces with below and try again

%20


问:
Committing to git without knowning the whole history
We have a fairly large git repository to which we do automatic commits.

Is it possible to commit to a git repository without downloading the hole history first?

In my opinion it should be, since the current commit just references the last one, but I don't know how.

答:
Yep you can do it.

```<code># clone specific branch and only latest commit
# This will only download a single branch and you will not be able to
# see other branches

git clone <url> --branch=<branch> --depth=1
</code>```

Git clone options:

-b / --branch

Download only a specific branch

--branch can also take tags and detaches the HEAD at that commit
in the resulting repository.

--depth

How many commits (latest) to download.

Create a shallow clone with a history truncated to the specified number of commits.

--shallow-since=<date>

Create a shallow clone with a history after the specified time.

You can also checkout any past commit form history and not only the latest

Body:
Yep you can do it.

# clone specific branch and only latest commit
# This will only download a single branch and you will not be able to
# see other branches

git clone <url> --branch=<branch> --depth=1

Git clone options:

-b / --branch

Download only a specific branch

--branch can also take tags and detaches the HEAD at that commit
in the resulting repository.

--depth

How many commits (latest) to download.

Create a shallow clone with a history truncated to the specified number of commits.

--shallow-since=<date>

Create a shallow clone with a history after the specified time.

You can also checkout any past commit form history and not only the latest


问:
Reading pg_buffercache output
I am using postgres-9.3 (in CenOS 6.9) and trying to understand the pg_buffercache table output.

I ran this:

```<code>SELECT c.relname,count(*) AS buffers FROM pg_class c INNER JOIN
pg_buffercache b ON b.relfilenode=c.relfilenode INNER JOIN
pg_database d ON (b.reldatabase=d.oid AND
d.datname=current_database()) GROUP BY c.relname
ORDER BY 2 DESC LIMIT 5;
</code>```

and the output below showed one of the tables using 6594 buffers. This was during when I had tons of INSERT followed by SELECT and UPDATE in the data_main table).

```<code>       relname      | buffers
  ------------------+---------
  data_main         |    6594
  objt_main         |    1897
  objt_access       |     788
  idx_data_mai      |     736
</code>```

I also ran "select * from pg_buffercache where is dirty" which showed around 50 entries.

How should I interpret these numbers? Does the buffer count correspond to all the transactions since I created the extension or the recent ones. How can I find out if my specific operation using the proper amount of buffers?

Here's my setting:

```<code> # show shared_buffers;
    shared_buffers
  ----------------
     1GB

 # show work_mem;
  work_mem
 ----------
   128kB
 # show maintenance_work_mem;
   maintenance_work_mem
  ----------------------
   64GB
</code>```

And the current free mem (I have 64GM memory in this machine). And I have a mixed workload machine with period bursts of INSERTS and lots of SELECTS. Currently the database and tables are small but will grow to at least 2 million rows.

```<code>  $ free -m
         total       used      free     shared    buffers     cached
 Mem:   64375      33483      30891        954         15      15731
 /+ buffers/cache: 18097      46278
Swap:   32767         38      32729
</code>```

Basically, I am trying to understand how to properly use this pg_buffercache table. Should I ran this query periodically? And do I need to change my shared_buffers accordingly.

答:
I did some reading and testing and this is what I have found. Found a userful query here: How large is a "buffer" in PostgreSQL

Here are a few notes for others that have similar questions.

You will need to create the extension for each database. So "\c db_name" then "create extension pg_buffercache".

Same for running the queries.

Restarting the database clears the queries.

Title: Reading pg_buffercache output

Body:
I am using postgres-9.3 (in CenOS 6.9) and trying to understand the pg_buffercache table output.

I ran this:

SELECT c.relname,count(*) AS buffers FROM pg_class c INNER JOIN
pg_buffercache b ON b.relfilenode=c.relfilenode INNER JOIN
pg_database d ON (b.reldatabase=d.oid AND
d.datname=current_database()) GROUP BY c.relname
ORDER BY 2 DESC LIMIT 5;

and the output below showed one of the tables using 6594 buffers. This was during when I had tons of INSERT followed by SELECT and UPDATE in the data_main table).

       relname      | buffers
  ------------------+---------
  data_main         |    6594
  objt_main         |    1897
  objt_access       |     788
  idx_data_mai      |     736

I also ran "select * from pg_buffercache where is dirty" which showed around 50 entries.

How should I interpret these numbers? Does the buffer count correspond to all the transactions since I created the extension or the recent ones. How can I find out if my specific operation using the proper amount of buffers?

Here's my setting:

 # show shared_buffers;
    shared_buffers
  ----------------
     1GB

 # show work_mem;
  work_mem
 ----------
   128kB
 # show maintenance_work_mem;
   maintenance_work_mem
  ----------------------
   64GB

And the current free mem (I have 64GM memory in this machine). And I have a mixed workload machine with period bursts of INSERTS and lots of SELECTS. Currently the database and tables are small but will grow to at least 2 million rows.

  $ free -m
         total       used      free     shared    buffers     cached
 Mem:   64375      33483      30891        954         15      15731
 /+ buffers/cache: 18097      46278
Swap:   32767         38      32729

Basically, I am trying to understand how to properly use this pg_buffercache table. Should I ran this query periodically? And do I need to change my shared_buffers accordingly.


问:
Inheritance for Algebraic Data Types in Rascal?
Right, I have this data type in Rascal:

```<code>data Type = Any() | Void() | Int() | Not(Type l) | And(set[Type] es) | Or(set[Type] es);
</code>```

What I want to do is define another type like this:

```<code>data Primitive = Any() | Void() | Int();
</code>```

And then be able to do things like this:

```<code>Primitive p = Any();
Type d = p;
</code>```

Or, for example, match against Primitive when simplifying Type.  Something like this:

```<code>public Type reduce(Not(Primitive p)) = p;
</code>```

Currently, the only solution I can see is to expand the above rule for each case like so:

```<code>public Type reduce(Not(Any)) = Any();
public Type reduce(Not(Void)) = Void();
public Type reduce(Not(Int)) = Int();
</code>```

I'm guessing there is a way to do this, but I didn't figure it out yet ... thoughts?

答:
The short answer: although Abstract Data Types can be extended (i.e., their definition can be extended across modules) there is no direct inheritance.

Work arounds:

Solution A

```<code>data Type = Any() | Void() | Int() | Not(Type l) | And(set[Type] es) | Or(set[Type] es);

bool isPrim(Any()) = true;
bool isPrim(Void()) = true;
bool isPrim(Int()) = true;
default bool isPrim(Type t) = false;

Type reduce(Not(Type t)) = t when isPrim(t);
default Type reduce(Type t ) = t;
</code>```

Here all constructors for Type are in a single ADT and the predicate isPrim selects the primitives. For example, reduce(Not(Void())) will reduce to Void().

Solution B

```<code>data Primitive = Any() | Void() | Int();

data Type = prim(Primitive p) | Not(Type l) | And(set[Type] es) | Or(set[Type] es);

Type reduce(Not(prim(Primitive p))) = prim(p);
default Type reduce(Type t ) = t;
</code>```

Here the primitives are collected in a separate ADT Primitive and they are included in Type via the constructor prim. Now reduce(Not(prim(Void()))) will reduce to prim(Void()).

Final Notes

We would also prefer to have inheritance (without the extra constructor prim as in Solution B) but for various technical reasons we did not include it. Although desirable, I am not sure that we will ever do.

Note the functions preceded by default, they are the catch all case when the other declarations of a function do not match.

All functions are public, unless preceded by the key word private.

Body:
Right, I have this data type in Rascal:

data Type = Any() | Void() | Int() | Not(Type l) | And(set[Type] es) | Or(set[Type] es);

What I want to do is define another type like this:

data Primitive = Any() | Void() | Int();

And then be able to do things like this:

Primitive p = Any();
Type d = p;

Or, for example, match against Primitive when simplifying Type.  Something like this:

public Type reduce(Not(Primitive p)) = p;

Currently, the only solution I can see is to expand the above rule for each case like so:

public Type reduce(Not(Any)) = Any();
public Type reduce(Not(Void)) = Void();
public Type reduce(Not(Int)) = Int();

I'm guessing there is a way to do this, but I didn't figure it out yet ... thoughts?

Body:
The short answer: although Abstract Data Types can be extended (i.e., their definition can be extended across modules) there is no direct inheritance.

Work arounds:

Solution A

data Type = Any() | Void() | Int() | Not(Type l) | And(set[Type] es) | Or(set[Type] es);

bool isPrim(Any()) = true;
bool isPrim(Void()) = true;
bool isPrim(Int()) = true;
default bool isPrim(Type t) = false;

Type reduce(Not(Type t)) = t when isPrim(t);
default Type reduce(Type t ) = t;

Here all constructors for Type are in a single ADT and the predicate isPrim selects the primitives. For example, reduce(Not(Void())) will reduce to Void().

Solution B

data Primitive = Any() | Void() | Int();

data Type = prim(Primitive p) | Not(Type l) | And(set[Type] es) | Or(set[Type] es);

Type reduce(Not(prim(Primitive p))) = prim(p);
default Type reduce(Type t ) = t;

Here the primitives are collected in a separate ADT Primitive and they are included in Type via the constructor prim. Now reduce(Not(prim(Void()))) will reduce to prim(Void()).

Final Notes

We would also prefer to have inheritance (without the extra constructor prim as in Solution B) but for various technical reasons we did not include it. Although desirable, I am not sure that we will ever do.

Note the functions preceded by default, they are the catch all case when the other declarations of a function do not match.

All functions are public, unless preceded by the key word private.


问:
iOS: How to get a proper Month name from a number?
I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.

Somewhere in my code, there is an int representing a month. So: 1 would be January, 2 February, etc.

In my user interface, I would like to display this integer as proper month name. Moreover, it should adhere to the locale of the device.

Thank you for your insights

In the mean time, I have done the following:

```<code>int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[formatter release];
</code>```

is this the way to do it? It seems a bit wordy.

答: You should be able to get rid of the release and re-allocation of the dateFormatter, cutting out a couple of lines, but that's all I see.</p>

Body:
I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.

Somewhere in my code, there is an int representing a month. So: 1 would be January, 2 February, etc.

In my user interface, I would like to display this integer as proper month name. Moreover, it should adhere to the locale of the device.

Thank you for your insights

In the mean time, I have done the following:

int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[formatter release];

is this the way to do it? It seems a bit wordy.


问:
How I can resize the text of the pages using mupdf in android
I port my own app to read pdf files in android using mupdf, all is working fine here, but the text on the pages appear very small, so how I can resize the font or scale the view to be more readable for a myopic User?

Someone can help-me

答:
mupdf has two versions, one is mini and the other is old.

the "old" has reflow function, which can enlarge font by zooming in with two fingers.

but i do not think it is perfect because the text is not justified, so the right margin is huge and ugly.


问:
Template file path
I'm trying to open and read this html file with in my django project, however i'm getting this
[Errno 2] No such file or directory: 'test.html'.

```<code>html = 'test.html'
open_html = open(html, 'r')
soup =  BeautifulSoup(open_html, "html5lib")
open_html.close()
</code>```

But the template path seems to work fine when rendered

```<code>template = 'test.html'
context = {
}
return render(request, template, context)

TEMPLATES = [
        'DIRS': [os.path.join(BASE_DIR, "templates")],
]
</code>```

I know my templates are suppose to go into my apps folders, however i like to keep them in one folder when developing and debugging.

答:
Because you are trying to access file from templates so you need to add full path

Try following solution

```<code>from your_project_name.settings import BASE_DIR
path = os.path.join(BASE_DIR, 'templates', 'test.html')
with open(path, 'r') as open_html:
    soup =  BeautifulSoup(open_html, "html5lib")
</code>```

Hope this is help you

Title: Template file path

Body:
I'm trying to open and read this html file with in my django project, however i'm getting this
[Errno 2] No such file or directory: 'test.html'.

html = 'test.html'
open_html = open(html, 'r')
soup =  BeautifulSoup(open_html, "html5lib")
open_html.close()

But the template path seems to work fine when rendered

template = 'test.html'
context = {
}
return render(request, template, context)

TEMPLATES = [
        'DIRS': [os.path.join(BASE_DIR, "templates")],
]

I know my templates are suppose to go into my apps folders, however i like to keep them in one folder when developing and debugging.

Body:
Because you are trying to access file from templates so you need to add full path

Try following solution

from your_project_name.settings import BASE_DIR
path = os.path.join(BASE_DIR, 'templates', 'test.html')
with open(path, 'r') as open_html:
    soup =  BeautifulSoup(open_html, "html5lib")

Hope this is help you


问:
How do I make Sphinx stop ignoring spaces?
I'm using Sphynx and ThinkingSphynx in my Rails project. Is there any way I can make Sphynx stop ignoring spaces so that "Foo " key would find me "Foo Bar" and wouldn't find me, for example,  "foo@bar.com"  ?</p>

答:
I've added blend_chars option to indice and everything started working as needed:

```<code>set_property :blend_chars => 'U+20, @, .'
</code>```

U+20 is actually a space.

Body:
I've added blend_chars option to indice and everything started working as needed:

set_property :blend_chars => 'U+20, @, .'

U+20 is actually a space.


问:
The requested resource does not support http method 'GET" while making a POST call in WebAPI
I am trying to call an API written by me. However when I am trying to call a POST method via $.ajax it returns an error:

The requested resource does not support http method 'GET"

When I try to call via Postman, I get the desired results. On top of this, the $.ajax for the same method works for all calls. Here is my API method

```<code>[HttpPost]
[Route("api/Ticket/GetTicketsAssignedToTechnician/")]
public List<Ticket> GetTicketsAssignedToTechnician([FromBody]string technicianEmail)
{
    return dbManager.GetTicketsByAssignedTechnician(technicianEmail);
}
</code>```

```<code>postData: function (serviceURL, parameterValue, success, failure, error) {
    $.ajax({
        url: serviceURL,
        method: "POST",
        data: JSON.stringify(parameterValue),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: success,
        failure: failure,
        error: error
    });
}
</code>```

Here is call to $.ajax:

```<code>Utility.postData(Dashboard.hostURL + "Ticket/GetTicketsAssignedToTechnician/", email, function(data) {
  console.log(data);
}, function(data) {
  console.log("failure." + data.responseText);
}, function(data) {
  console.log("Error." + data.responseText);
});
</code>```

答:
The issue is because you're using the wrong property name in the $.ajax options. it's type, not method. Therefore jQuery uses the default, which is GET.

```<code>$.ajax({
    url: serviceURL,
    type: "POST", // < change here
    data: parameterValue, // no need to JSON.stringify here, jQuery will do it for you
    // other options...
});
</code>```

Body:
I am trying to call an API written by me. However when I am trying to call a POST method via $.ajax it returns an error:

The requested resource does not support http method 'GET"

When I try to call via Postman, I get the desired results. On top of this, the $.ajax for the same method works for all calls. Here is my API method

[HttpPost]
[Route("api/Ticket/GetTicketsAssignedToTechnician/")]
public List<Ticket> GetTicketsAssignedToTechnician([FromBody]string technicianEmail)
{
    return dbManager.GetTicketsByAssignedTechnician(technicianEmail);
}

postData: function (serviceURL, parameterValue, success, failure, error) {
    $.ajax({
        url: serviceURL,
        method: "POST",
        data: JSON.stringify(parameterValue),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: success,
        failure: failure,
        error: error
    });
}

Here is call to $.ajax:

Utility.postData(Dashboard.hostURL + "Ticket/GetTicketsAssignedToTechnician/", email, function(data) {
  console.log(data);
}, function(data) {
  console.log("failure." + data.responseText);
}, function(data) {
  console.log("Error." + data.responseText);
});

Body:
The issue is because you're using the wrong property name in the $.ajax options. it's type, not method. Therefore jQuery uses the default, which is GET.

$.ajax({
    url: serviceURL,
    type: "POST", // < change here
    data: parameterValue, // no need to JSON.stringify here, jQuery will do it for you
    // other options...
});


问:
Python is throwing AttributeError: 'Ship' object has no attribute 'bullet_width'
Can someone please help me fix this error:

```<code>AttributeError: 'Ship' object has no attribute 'bullet_width'.
</code>```

I am still learning. I am just trying to create a game named by "Alien Invasion " from book , but every time I am trying to keydown the SPACE it will throw

```<code>AttributeError: 'Ship' object has no attribute 'bullet_width'.
</code>```

I am not even what the error means other than that I am missing a request somewhere.

Any help and explanation of what I am doing wrong will be greatly appreciated. Thank you in advance. And sorry for there may be some Chinese in it, if it makes you uncomfortable , cause I'm from China.

Here are my models:

alien_invasion.py

```<code>import sys
import pygame
from pygame.sprite import Group

from settings import Settings
from ship import  Ship
import game_functions as gf

def run_game():
    #初始化pygame、设置和屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_hight))
    pygame.display.set_caption("Alien Invavsion")

    #设置背景色
    bg_color=(230,230,230)

    #创建一艘飞船
    ship = Ship(ai_settings, screen)
    #创建一个用于存储子弹的编组
    bullets = Group()

    #开始游戏的主循环
    while True:
        #监视键盘和鼠标事件
        gf.check_events(ai_settings, screen, ship, bullets)
        ship.update()
        bullets.update()
        gf.updata_screen(ai_settings, screen, ship, bullets)

run_game()
</code>```

settings.py

```<code>class Settings():
    """存储《外星人入侵》的所有设置的类"""

    def __init__(self):
        """初始化游戏的设置"""
        #屏幕设置
        self.screen_width = 1200
        self.screen_hight = 700
        self.bg_color = (250,250,250)

        #飞船的位置
        self.ship_speed_factor = 1.5

        #子弹设置
        self.bullet_speed_factor = 1
        self.bullet_width = 3
        self.bullet_height = 15
        self.bullet_color = 60, 60, 60
</code>```

game_functions.py

```<code>import sys
from bullet import Bullet
import pygame

def check_keydown_events(event, ai_settings, screen, ship, bullets):
    """响应按键"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        #创建一颗子弹，并将其加入到编组bullets中
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)

def check_keyup_events(event, ship):
    """响应松开 """
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False

def check_events(ai_settings, screen, ship, bullets):
    """响应按键和鼠标事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ship, screen, bullets, ai_settings)
        elif event.type == pygame.KEYUP:
                check_keyup_events(event,ship)

def updata_screen(ai_settings, screen, ship, bullets):
    """更新屏幕上的图像，并切换到新屏幕"""
    # 每次循环时都重绘屏幕
    screen.fill(ai_settings.bg_color)
    #在飞船和外星人后面重绘所有子弹
    for bullet in bullets.sprites():
        bullet.draw_bullet()

    ship.blitme()

    # 让最近绘制的屏幕可见
    pygame.display.flip()
</code>```

ship.py

```<code>import pygame

class Ship():
    def __init__(self, ai_settings, screen):
        """初始化飞船并设置其初始位置"""
        self.screen=screen
        self.ai_settings = ai_settings

        #加载飞船图像并获取其外接矩形
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        #将每艘新飞船放在屏幕底部中央
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        #在飞船的属性center中存储小数值
        self.center = float(self.rect.centerx)

        #移动标志
        self.moving_right = False
        self.moving_left = False

    def update(self):
        """根据移动标志调整飞船的位置"""
        #更新飞船的center值，而不是rect
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left > 0:
            self.center -= self.ai_settings.ship_speed_factor

        #根据self.centerx跟新的rect对象
        self.rect.centerx = self.center

    def blitme(self):
        """在指定位置绘制飞船"""
        self.screen.blit(self.image, self.rect)
</code>```

bullet.py

```<code>import pygame
from pygame.sprite import Sprite

class Bullet(Sprite):
    """一个对飞船发射子弹的进行管理的类"""

    def __init__(self, ai_settings, screen, ship):
        """在飞船所处位置创建一个子弹对象"""
        super(Bullet, self).__init__()
        self.screen = screen

        #在（0，0）处创建一个表示子弹移动的矩形，再设置正确的位置
        self.rect = pygame.Rect(0, 0, ai_settings.bullet_width,
                                ai_settings.bullet_height)
        self.rect.conterx = ship.rect.centerx
        self.rect.top = ship = ship.rect.top

        #存储用小数表示的子弹位置
        self.y =float(self.rect.y)

        self.color = ai_settings.bullet_color
        self.speed_factor = ai_settings.bullet_speed_factor

    def update(self):
        """向上移动子弹"""
        #更新表示子弹位置的小数值
        self.y -= self.speed_factor
        #更新表示子弹的rect的位置
        self.rect.y = self.y

    def draw_bullet(self):
        """在屏幕上绘制子弹"""
        pygame.draw.rect(self.screen, self.color, self.rect)
</code>```

答:
I am also learning  python, there are 2 problems I find for you reference:
1. game_functions.py:
   a. updata is wrong, it should be update
   b. the order in check_keydown_events is wrong*(check_keydown_events(event, ship, screen, bullets, ai_settings)*,the right order is as follows:
   check_keydown_events(event,ai_setting,screen,ship,bullets)
2. alien_invasion.py
bg_color is repeated contrast to ship.py
(in other words,you have set the attribute"bg_color" in ship.py, there is no need to repeat it in alien_invasion.py)

Hope to help you~

Body:
Can someone please help me fix this error:

AttributeError: 'Ship' object has no attribute 'bullet_width'.

I am still learning. I am just trying to create a game named by "Alien Invasion " from book , but every time I am trying to keydown the SPACE it will throw

AttributeError: 'Ship' object has no attribute 'bullet_width'.

I am not even what the error means other than that I am missing a request somewhere.

Any help and explanation of what I am doing wrong will be greatly appreciated. Thank you in advance. And sorry for there may be some Chinese in it, if it makes you uncomfortable , cause I'm from China.

Here are my models:

alien_invasion.py

import sys
import pygame
from pygame.sprite import Group

from settings import Settings
from ship import  Ship
import game_functions as gf

def run_game():
    #初始化pygame、设置和屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_hight))
    pygame.display.set_caption("Alien Invavsion")

    #设置背景色
    bg_color=(230,230,230)

    #创建一艘飞船
    ship = Ship(ai_settings, screen)
    #创建一个用于存储子弹的编组
    bullets = Group()

    #开始游戏的主循环
    while True:
        #监视键盘和鼠标事件
        gf.check_events(ai_settings, screen, ship, bullets)
        ship.update()
        bullets.update()
        gf.updata_screen(ai_settings, screen, ship, bullets)

run_game()

settings.py

class Settings():
    """存储《外星人入侵》的所有设置的类"""

    def __init__(self):
        """初始化游戏的设置"""
        #屏幕设置
        self.screen_width = 1200
        self.screen_hight = 700
        self.bg_color = (250,250,250)

        #飞船的位置
        self.ship_speed_factor = 1.5

        #子弹设置
        self.bullet_speed_factor = 1
        self.bullet_width = 3
        self.bullet_height = 15
        self.bullet_color = 60, 60, 60

game_functions.py

import sys
from bullet import Bullet
import pygame

def check_keydown_events(event, ai_settings, screen, ship, bullets):
    """响应按键"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        #创建一颗子弹，并将其加入到编组bullets中
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)

def check_keyup_events(event, ship):
    """响应松开 """
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False

def check_events(ai_settings, screen, ship, bullets):
    """响应按键和鼠标事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ship, screen, bullets, ai_settings)
        elif event.type == pygame.KEYUP:
                check_keyup_events(event,ship)

def updata_screen(ai_settings, screen, ship, bullets):
    """更新屏幕上的图像，并切换到新屏幕"""
    # 每次循环时都重绘屏幕
    screen.fill(ai_settings.bg_color)
    #在飞船和外星人后面重绘所有子弹
    for bullet in bullets.sprites():
        bullet.draw_bullet()

    ship.blitme()

    # 让最近绘制的屏幕可见
    pygame.display.flip()

ship.py

import pygame

class Ship():
    def __init__(self, ai_settings, screen):
        """初始化飞船并设置其初始位置"""
        self.screen=screen
        self.ai_settings = ai_settings

        #加载飞船图像并获取其外接矩形
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        #将每艘新飞船放在屏幕底部中央
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        #在飞船的属性center中存储小数值
        self.center = float(self.rect.centerx)

        #移动标志
        self.moving_right = False
        self.moving_left = False

    def update(self):
        """根据移动标志调整飞船的位置"""
        #更新飞船的center值，而不是rect
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left > 0:
            self.center -= self.ai_settings.ship_speed_factor

        #根据self.centerx跟新的rect对象
        self.rect.centerx = self.center

    def blitme(self):
        """在指定位置绘制飞船"""
        self.screen.blit(self.image, self.rect)

bullet.py

import pygame
from pygame.sprite import Sprite

class Bullet(Sprite):
    """一个对飞船发射子弹的进行管理的类"""

    def __init__(self, ai_settings, screen, ship):
        """在飞船所处位置创建一个子弹对象"""
        super(Bullet, self).__init__()
        self.screen = screen

        #在（0，0）处创建一个表示子弹移动的矩形，再设置正确的位置
        self.rect = pygame.Rect(0, 0, ai_settings.bullet_width,
                                ai_settings.bullet_height)
        self.rect.conterx = ship.rect.centerx
        self.rect.top = ship = ship.rect.top

        #存储用小数表示的子弹位置
        self.y =float(self.rect.y)

        self.color = ai_settings.bullet_color
        self.speed_factor = ai_settings.bullet_speed_factor

    def update(self):
        """向上移动子弹"""
        #更新表示子弹位置的小数值
        self.y -= self.speed_factor
        #更新表示子弹的rect的位置
        self.rect.y = self.y

    def draw_bullet(self):
        """在屏幕上绘制子弹"""
        pygame.draw.rect(self.screen, self.color, self.rect)


问:
Private constructor and inheritance (Java)
I have first class for which constructor takes a parameter.

```<code>public class First {
    First(Object o){
        o.toString();
    }
}
</code>```

I have a second class which extends this first one.

```<code>public class Second extends First {
    Second(Object o) {
        super(o);
    }
}
</code>```

What I want is to keep the constructor of Second class private in order to have a possibility to instantiate the only one instance of this class (using Singleton pattern, for instance), but compiler doesn't allow me to do that.

If I can't set the constructor as private here, what can I do to allow the only one instance of the class to be created?

答:
You can make the constructor of Second private with no problems. What you can't do is make the constructor of First private, unless you use nested classes.

As an example, this works fine:

```<code>class First {
    First(Object o) {
        o.toString();
    }
}

class Second extends First {
    private final static Second instance = new Second(new Object());

    private Second(Object o) {
        super(o);
    }

    public static Second getInstance() {
        return instance;
    }
}
</code>```

Body:
I have first class for which constructor takes a parameter.

public class First {
    First(Object o){
        o.toString();
    }
}

I have a second class which extends this first one.

public class Second extends First {
    Second(Object o) {
        super(o);
    }
}

What I want is to keep the constructor of Second class private in order to have a possibility to instantiate the only one instance of this class (using Singleton pattern, for instance), but compiler doesn't allow me to do that.

If I can't set the constructor as private here, what can I do to allow the only one instance of the class to be created?

Body:
You can make the constructor of Second private with no problems. What you can't do is make the constructor of First private, unless you use nested classes.

As an example, this works fine:

class First {
    First(Object o) {
        o.toString();
    }
}

class Second extends First {
    private final static Second instance = new Second(new Object());

    private Second(Object o) {
        super(o);
    }

    public static Second getInstance() {
        return instance;
    }
}


问:
How to replace string with fallback option?
I would like to replace string with fallback option. for example

```<code>var x = " Hello {{first_name | fallback : 'User' }} "
var f_name = "ME";
</code>```

in above case i want if f_name is defined then result will like this

```<code>Hello ME
</code>```

other wise result will be

```<code>Hello User
</code>```

so how can i do this?

答:
This should work.</p>

```<code>x = x + (f_name === null ? "User" : f_name);
</code>```

Body:
I would like to replace string with fallback option. for example

var x = " Hello {{first_name | fallback : 'User' }} "
var f_name = "ME";

in above case i want if f_name is defined then result will like this

Hello ME

other wise result will be

Hello User

so how can i do this?

Body:
This should work.

x = x + (f_name === null ? "User" : f_name);


问:
Handle multiple parameters in array_map call back
I have the following code:

```<code>$a=array(15,12,13,25,27,36,18);
$b=array(1,1,1,1,1,1,1);//is it possible to pass only one value=1, instead of array containing seven 1's
// expectation: $b = array(1); or $b= 1;
//instead of $b=array(1,1,1,1,1,1,1);

function array_add($p,$q){
   return($p+$q);
}
$c=array_map("array_add",$a,$b);
</code>```

I want something like:

```<code>$a=array(15,12,13,25,27,36,18);
$b=array(1);

function array_add($p,$q){
   return($p+$q);
}
$c=array_map("array_add",$a,$b);
</code>```

Any better solution thanks.

答:
You can use array_map as this, and pass the $param2 with use()

```<code>array_map(function($v) use($param2){
    //do something
}, $input);
</code>```

Body:
I have the following code:

$a=array(15,12,13,25,27,36,18);
$b=array(1,1,1,1,1,1,1);//is it possible to pass only one value=1, instead of array containing seven 1's
// expectation: $b = array(1); or $b= 1;
//instead of $b=array(1,1,1,1,1,1,1);

function array_add($p,$q){
   return($p+$q);
}
$c=array_map("array_add",$a,$b);

I want something like:

$a=array(15,12,13,25,27,36,18);
$b=array(1);

function array_add($p,$q){
   return($p+$q);
}
$c=array_map("array_add",$a,$b);

Any better solution thanks.

Body:
You can use array_map as this, and pass the $param2 with use()

array_map(function($v) use($param2){
    //do something
}, $input);


问:
Table
 space not change
I try to put small space in table
 but I can't do it, I try to do that, but not change it, how can I fix it? To  understand about my question look at this image:

.panel-booking .panel-body {
    padding: 0px;
    height: 100px;
}
.panel-booking  {
top:-60px; position:relative;
}
.tab-tb2 .nav-tabs li a {border-left: 1px solid #bfc1c3;height: 25px;}
#line-booking hr{margin-top: -45px; margin-left: 1px; width: 408px;color: #f00;
background-color: #ececec;
height: 1px;}

.booking-left-btn tr {line-height:30px;}
.booking-left-btn table, th, td {
}
.booking-left-btn th, td {
    padding: 5px;
    text-align: left;
}

.booking-left-btn .btn {
    display: inline-block;
    padding: 12px 7px;
    margin-bottom: 21px;
    font-size: 14px;
    margin-left: -15px;
    font-weight: normal;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    background-color: none;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border: 1px solid #bdc4cb;
    border-radius: 10px;
}

.booking-left-btn .room-detials {
    text-align: center;
    margin-left: -2px; color: #53585f;
}
.booking-left-btn .room-number {
    text-align: center;
    font-size: 15px;
    color: #444444;
}
.booking-left-btn  .panel-default {
  border-color: #ddd;
    height: 67px;
    -moz-border-radius: 12px;
    -webkit-border-radius: 12px;
    -ie-border-radius: 12px;
    -opera-border-radius: 12px;
    -chrome-border-radius: 12px;
    border-radius: 11px;
    overflow: hidden;
    width: 329px;
    margin-left: -5px;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
                          <div class="panel-booking">

<div class="booking-left-btn" style="margin-left:25px;">

  <table style="width:100%">

    <tr>
      <td><button type="button" class="btn btn-default">    <div class="room-detials">Room</div>
          <div class="room-number">1</div></button></td>
      <td>    <div class="panel panel-default">
      <div class="panel-heading">Mahesh H</div>
      <div class="panel-body">Panel Content</div>
    </div></td>
    </tr>
    <tr>
      <td >     <button type="button" class="btn btn-default">    <div class="room-detials">Room</div>
          <div class="room-number">1</div></button></td>
      <td> <div class="panel panel-default">
      <div class="panel-heading">Panel with panel-default class</div>
      <div class="panel-body">Panel Content</div>
    </div></td>
    </tr>
    <tr>
      <td >     <button type="button" class="btn btn-default">    <div class="room-detials">Room</div>
          <div class="room-number">1</div></button></td>
      <td> <div class="panel panel-default">
      <div class="panel-heading">Panel with panel-default class</div>
      <div class="panel-body">Panel Content</div>
    </div></td>
    </tr>
    <tr>
      <td >     <button type="button" class="btn btn-default">    <div class="room-detials">Room</div>
          <div class="room-number">1</div></button></td>
      <td> <div class="panel panel-default">
      <div class="panel-heading">Panel with panel-default class</div>
      <div class="panel-body">Panel Content</div>
    </div></td>
    </tr>
    <tr>
      <td >     <button type="button" class="btn btn-default">    <div class="room-detials">Room</div>
          <div class="room-number">1</div></button></td>
      <td> <div class="panel panel-default">
      <div class="panel-heading">Panel with panel-default class</div>
      <div class="panel-body">Panel Content</div>
    </div></td>
    </tr>
    <tr>
      <td >     <button type="button" class="btn btn-default">    <div class="room-detials">Room</div>
          <div class="room-number">1</div></button></td>
      <td> <div class="panel panel-default">
      <div class="panel-heading">Panel with panel-default class</div>
      <div class="panel-body">Panel Content</div>
    </div></td>
    </tr>
  </table>

</div>

                            </div></code>```

答:
Use

```<code><div class="panel-body"> Panel Content</div>
</code>```

If in between table then use cellspacing="20" in your table tag

Title: Table <tr> space not change

Body:
I try to put small space in table
 but I can't do it, I try to do that, but not change it, how can I fix it? To  understand about my question look at this image:

.panel-booking .panel-body {
    padding: 0px;
    height: 100px;
}
.panel-booking  {
top:-60px; position:relative;
}
.tab-tb2 .nav-tabs li a {border-left: 1px solid #bfc1c3;height: 25px;}
#line-booking hr{margin-top: -45px; margin-left: 1px; width: 408px;color: #f00;
background-color: #ececec;
height: 1px;}

.booking-left-btn tr {line-height:30px;}
.booking-left-btn table, th, td {
}
.booking-left-btn th, td {
    padding: 5px;
    text-align: left;
}

.booking-left-btn .btn {
    display: inline-block;
    padding: 12px 7px;
    margin-bottom: 21px;
    font-size: 14px;
    margin-left: -15px;
    font-weight: normal;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    background-color: none;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border: 1px solid #bdc4cb;
    border-radius: 10px;
}

.booking-left-btn .room-detials {
    text-align: center;
    margin-left: -2px; color: #53585f;
}
.booking-left-btn .room-number {
    text-align: center;
    font-size: 15px;
    color: #444444;
}
.booking-left-btn  .panel-default {
  border-color: #ddd;
    height: 67px;
    -moz-border-radius: 12px;
    -webkit-border-radius: 12px;
    -ie-border-radius: 12px;
    -opera-border-radius: 12px;
    -chrome-border-radius: 12px;
    border-radius: 11px;
    overflow: hidden;
    width: 329px;
    margin-left: -5px;

}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="btn btn-default">
Room

1
</button>

Mahesh H

Panel Content

           <button type="button" class="btn btn-default">
Room

1
</button>

Panel with panel-default class

Panel Content

           <button type="button" class="btn btn-default">
Room

1
</button>

Panel with panel-default class

Panel Content

           <button type="button" class="btn btn-default">
Room

1
</button>

Panel with panel-default class

Panel Content

           <button type="button" class="btn btn-default">
Room

1
</button>

Panel with panel-default class

Panel Content

           <button type="button" class="btn btn-default">
Room

1
</button>

Panel with panel-default class

Panel Content

Body:
Use &nbsp;

<div class="panel-body">&nbsp;Panel Content</div>

If in between table then use cellspacing="20" in your table tag


问:
Best way to execute js only on specific page
I was wondering what would be the best way to execute a java-script code only on specific pages.

Let's imagine we have a template-based web-site, rewrite rule for the content ist set, jquery available and it basically looks like this:

```<code>  <!DOCTYPE html>
  <html>
   <head>
    <script src="script.js"></script>
   </head>
   <body>
    ...
    include $content;
    ..
   </body>
</html>
</code>```

content 'info' contains a button, we want something to happen on click, content 'alert' should give us a message when you hover a text field.

What is the best way to trigger these actions, without running into an error, because the object is not found?

Option one: using     window.location.pathname

```<code> $(document).ready(function() {
      if (window.location.pathname == '/info.php') {
          $("#button1").click(function(){
            //do something
          })
      }else if(window.location.pathname == '/alert.php'){
           $("#mytextfield").hover(){
             alert('message');
           }
    }
</code>```

Option two: checking if elements exist

```<code>$(document).ready(function() {
  if ($("#button1").length > 0) {
      $("#button1").click(function(){
        //do something
      })
  }else if ($("#mytextfield").length > 0){
       $("#mytextfield").hover(){
         alert('message');
       }
}
</code>```

Option three: include the script in the loaded template

```<code>//stands for itself
</code>```

Is there a better solution? Or do I have to get along with one of these solutions?

Your experience, usage, or any links related to this topic are appreciated.

//EDIT:

I might have choosen a bad example, the actual code would be somethin like:

```<code>    mCanvas = $("#jsonCanvas");
    mMyPicture = new myPicture (mCanvas);
</code>```

where the myPicture constructor get's the context of the canvas element, and throws an error, if mCanvas is undefined.

答: You can use Require js (RequireJS is a JavaScript file and module loader) and load script if they only needed. Link is http://requirejs.org/, I know using require js not so much easy.</p>

Body:
I was wondering what would be the best way to execute a java-script code only on specific pages.

Let's imagine we have a template-based web-site, rewrite rule for the content ist set, jquery available and it basically looks like this:

  <!DOCTYPE html>

    ...
    include $content;
    ..

content 'info' contains a button, we want something to happen on click, content 'alert' should give us a message when you hover a text field.

What is the best way to trigger these actions, without running into an error, because the object is not found?

Option one: using     window.location.pathname

 $(document).ready(function() {
      if (window.location.pathname == '/info.php') {
          $("#button1").click(function(){
            //do something
          })
      }else if(window.location.pathname == '/alert.php'){
           $("#mytextfield").hover(){
             alert('message');
           }
    }

Option two: checking if elements exist

$(document).ready(function() {
  if ($("#button1").length > 0) {
      $("#button1").click(function(){
        //do something
      })
  }else if ($("#mytextfield").length > 0){
       $("#mytextfield").hover(){
         alert('message');
       }
}

Option three: include the script in the loaded template

//stands for itself

Is there a better solution? Or do I have to get along with one of these solutions?

Your experience, usage, or any links related to this topic are appreciated.

//EDIT:

I might have choosen a bad example, the actual code would be somethin like:

    mCanvas = $("#jsonCanvas");
    mMyPicture = new myPicture (mCanvas);

where the myPicture constructor get's the context of the canvas element, and throws an error, if mCanvas is undefined.


问:
Generate number combinations in Javascript
I have been asked to help with writing a simple number generation script. The script should take an array of numbers from 1 to 9 as input. It should then calculate and output all the possible 3-number combinations in a output array.

Here's a link to a site that generates and outputs the numbers exactly as we want our script to do.

Thanks.

答:
Working now with the following code:</p>

```<code>for(var a = 0; a < 10; a++) {
    for(var b = 0; b < 10; b++) {
        for(var c = 0; c < 10; c++) {
            var combination = a + '' + b + '' + c;
            if(checkCode(parseInt(combination))) {
                console.log("Password is: + combination)
            }
        }
    }
}
</code>```

Body:
Working now with the following code:

for(var a = 0; a < 10; a++) {
    for(var b = 0; b < 10; b++) {
        for(var c = 0; c < 10; c++) {
            var combination = a + '' + b + '' + c;
            if(checkCode(parseInt(combination))) {
                console.log("Password is: + combination)
            }
        }
    }
}


问:
extract and display contents of zip file in Adobe AIR
I have a requirement where my Air application loads ZIP files instead of swf.
The zip contains all swf ,images and other files.
My requirement is when user browses for file in a browse dialog, user selects a zip file and the contents of this zip file should be displayed to the user.

i found examples to extract zip files, but i want  to know how to read te contents and display them?  i am not good at programming so can someone reply me Urgently
here is the exaple to extract files
http://pradeek.blogspot.com/2009/05/extracting-zip-files-in-adobe-air-with.html

答:
In example you posted there is a loop which writes to disk each packaged file. Modify this loop to create list of files and display this list to user. Below is modified onDirSelect method that adds filenames to Vector.

```<code>private var files:Vector.<String>;
private function onDirSelect(e:Event):void {
    files = new Vector.<String>();
    for(var i:uint = 0; i < zipFile.entries.length; i++)
    {
     var zipEntry:ZipEntry = zipFile.entries[i] as ZipEntry;
     files.push( zipEntry.name );
    }
   }
</code>```

You can find more detailed example at AS3 Zip Library homepage - http://nochump.com/blog/archives/15

Body:
In example you posted there is a loop which writes to disk each packaged file. Modify this loop to create list of files and display this list to user. Below is modified onDirSelect method that adds filenames to Vector.

private var files:Vector.<String>;
private function onDirSelect(e:Event):void {
    files = new Vector.<String>();
    for(var i:uint = 0; i < zipFile.entries.length; i++)
    {
     var zipEntry:ZipEntry = zipFile.entries[i] as ZipEntry;
     files.push( zipEntry.name );
    }
   }

You can find more detailed example at AS3 Zip Library homepage - http://nochump.com/blog/archives/15


答: can you try using <strong>&nbsp</strong>; This can be used as trick  </p>

Title: Table <tr> space not change

Body: can you try using &nbsp; This can be used as trick


问:
Looking at a list of numbers and getting that number from another file>
I don't really know how to word the question, but I have this file with a number and a decimal next to it, like so(the file name is num.txt):

```<code>33    0.239
78    0.298
85    1.993
96    0.985
107    1.323
108    1.000
</code>```

I have this string of numbers that I want to find the certain numbers from the file, take the decimal numbers, and append it to a list:

```<code>['78','85','108']
</code>```

Here is my code so far:

```<code>chosen_number = ['78','85','108']
memory_list = []
for line in open(path/to/num.txt):
    checker = line[0:2]
    if not checker in chosen_number: continue
    dec = line.split()[-1]
    memory_list.append(float(dec))
</code>```

The error they give to me is that it is not in a list and they only account for the 3 digit numbers. I don't really understand why this is happening and would like some tips to know how to fix it. Thanks.

As for the error, there is no actual error. The only problem is that they ignore the two digit numbers and only get the three digit numbers. I want them to get both the 2 and 3 digit numbers. For example, the script would pass 78 and 85, going to the line with '108'.

答:
The following would should work:

```<code>chosen_number = ['78','85','108']
memory_list = []

with open('num.txt') as f_input:
    for line in f_input:
        v1, v2 = line.split()

        if v1 in chosen_number:
            memory_list.append(float(v2))

print memory_list
</code>```

Giving you:

```<code>[0.298, 1.993, 1.0]
</code>```

Also, it is better to use a with statement when dealing with files so that the file is automatically closed afterwards.

Body:
I don't really know how to word the question, but I have this file with a number and a decimal next to it, like so(the file name is num.txt):

33    0.239
78    0.298
85    1.993
96    0.985
107    1.323
108    1.000

I have this string of numbers that I want to find the certain numbers from the file, take the decimal numbers, and append it to a list:

['78','85','108']

Here is my code so far:

chosen_number = ['78','85','108']
memory_list = []
for line in open(path/to/num.txt):
    checker = line[0:2]
    if not checker in chosen_number: continue
    dec = line.split()[-1]
    memory_list.append(float(dec))

The error they give to me is that it is not in a list and they only account for the 3 digit numbers. I don't really understand why this is happening and would like some tips to know how to fix it. Thanks.

As for the error, there is no actual error. The only problem is that they ignore the two digit numbers and only get the three digit numbers. I want them to get both the 2 and 3 digit numbers. For example, the script would pass 78 and 85, going to the line with '108'.

Body:
The following would should work:

chosen_number = ['78','85','108']
memory_list = []

with open('num.txt') as f_input:
    for line in f_input:
        v1, v2 = line.split()

        if v1 in chosen_number:
            memory_list.append(float(v2))

print memory_list

Giving you:

[0.298, 1.993, 1.0]

Also, it is better to use a with statement when dealing with files so that the file is automatically closed afterwards.


问:
Android marshmallow request permission?
I am currently working on an application that requires several "dangerous" permissions. So I tried adding "ask for permission" as required in Android Marshmallow(API Level 23), but couldn't find how to do it.

How can I ask for permission using new permission model in my app?

答:
```<code>  if (CommonMethod.isNetworkAvailable(MainActivity.this)) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
                                android.Manifest.permission.CAMERA);
                        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                            //showing dialog to select image
                            callFacebook();
                            Log.e("permission", "granted MarshMallow");
                        } else {
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE,
                                            android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, 1);
                        }
                    } else {
                        Log.e("permission", "Not Required Less than MarshMallow Version");
                        callFacebook();
                    }
                } else {
                    CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
                }
</code>```

Title: Android marshmallow request permission?


问:
Using an abstract class in C++
I'm trying to use an abstract class when passing an extended object as an parameter to a function, but my attempts so far have led to some compiler errors.

I have a few clues as to what the problem is, I'm obviously not allowed to instantiate an abstract class, and I believe some of the code in MyClass is trying to do this, even though this is not my intention. Some researching has suggested that I should reference the object as a pointer to achieve what I want, but my attempts so far have failed and I'm not even sure that this is the answer (hence my asking here).

I'll submit now that I'm more familiar with Java than C++, and I'm sure part of my problem is due to this.

Here is an example of what I'm trying to do in my program:

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

class B : public A {
    public:
        B() {}

        void action() {
            // Do stuff
        }
};

class MyClass {

    public:

        void setInstance(A newInstance) {
            instance = newInstance;
        }

        void doSomething() {
            instance.action();
        }

    private:

        A instance;
};

int main(int argc, char** argv) {
    MyClass c;
    B myInstance;
    c.setInstance(myInstance);
    c.doSomething();
    return 0;
}
</code>```

This example produces the same compiler error that I am getting in my program:

```<code>sean@SEAN-PC:~/Desktop$ gcc -o test test.cpp
test.cpp:20: error: cannot declare parameter ‘newInstance’ to be of abstract type ‘A’
test.cpp:2: note:   because the following virtual functions are pure within ‘A’:
test.cpp:4: note:   virtual void A::action()
test.cpp:30: error: cannot declare field ‘MyClass::instance’ to be of abstract type ‘A’
test.cpp:2: note:   since type ‘A’ has pure virtual functions
test.cpp: In function ‘int main(int, char**)’:
test.cpp:36: error: cannot allocate an object of abstract type ‘A’
test.cpp:2: note:   since type ‘A’ has pure virtual functions
</code>```

Update

Thanks for the feedback everyone.

I've since changed "MyClass::instance to contain a pointer of type A, but I now get some bizarre errors related to the vtable:

```<code>sean@SEAN-PC:~/Desktop$ gcc -o test test.cpp
/tmp/ccoEdRxq.o:(.rodata._ZTI1B[typeinfo for B]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
/tmp/ccoEdRxq.o:(.rodata._ZTI1A[typeinfo for A]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
/tmp/ccoEdRxq.o:(.rodata._ZTV1A[vtable for A]+0x8): undefined reference to `__cxa_pure_virtual'
collect2: ld returned 1 exit status
</code>```

My modified code is as follows (A and B have not been modified):

```<code>class MyClass {

    public:

        void setInstance(A* newInstance) {
            instance = newInstance;
        }

        void doSomething() {
            instance->action();
        }

    private:

        A* instance;
};

int main(int argc, char** argv) {
    MyClass c;
    B myInstance;
    c.setInstance(&myInstance);
    c.doSomething();
    return 0;
}
</code>```

答:
I had this problem by including parent.h before iostream:

wrong:

```<code>include "parent.h"
include <iostream>
</code>```

right:

```<code>include <iostream>
include "parent.h"
</code>```

OwnerDisplayName: seanhodges

Title: Using an abstract class in C++

Body:
I'm trying to use an abstract class when passing an extended object as an parameter to a function, but my attempts so far have led to some compiler errors.

I have a few clues as to what the problem is, I'm obviously not allowed to instantiate an abstract class, and I believe some of the code in MyClass is trying to do this, even though this is not my intention. Some researching has suggested that I should reference the object as a pointer to achieve what I want, but my attempts so far have failed and I'm not even sure that this is the answer (hence my asking here).

I'll submit now that I'm more familiar with Java than C++, and I'm sure part of my problem is due to this.

Here is an example of what I'm trying to do in my program:

class A {
    public:
        virtual void action() = 0;
};

class B : public A {
    public:
        B() {}

        void action() {
            // Do stuff
        }
};

class MyClass {

    public:

        void setInstance(A newInstance) {
            instance = newInstance;
        }

        void doSomething() {
            instance.action();
        }

    private:

        A instance;
};

int main(int argc, char** argv) {
    MyClass c;
    B myInstance;
    c.setInstance(myInstance);
    c.doSomething();
    return 0;
}

This example produces the same compiler error that I am getting in my program:

sean@SEAN-PC:~/Desktop$ gcc -o test test.cpp
test.cpp:20: error: cannot declare parameter ‘newInstance’ to be of abstract type ‘A’
test.cpp:2: note:   because the following virtual functions are pure within ‘A’:
test.cpp:4: note:   virtual void A::action()
test.cpp:30: error: cannot declare field ‘MyClass::instance’ to be of abstract type ‘A’
test.cpp:2: note:   since type ‘A’ has pure virtual functions
test.cpp: In function ‘int main(int, char**)’:
test.cpp:36: error: cannot allocate an object of abstract type ‘A’
test.cpp:2: note:   since type ‘A’ has pure virtual functions

Update

Thanks for the feedback everyone.

I've since changed "MyClass::instance to contain a pointer of type A, but I now get some bizarre errors related to the vtable:

sean@SEAN-PC:~/Desktop$ gcc -o test test.cpp
/tmp/ccoEdRxq.o:(.rodata._ZTI1B[typeinfo for B]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
/tmp/ccoEdRxq.o:(.rodata._ZTI1A[typeinfo for A]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
/tmp/ccoEdRxq.o:(.rodata._ZTV1A[vtable for A]+0x8): undefined reference to `__cxa_pure_virtual'
collect2: ld returned 1 exit status

My modified code is as follows (A and B have not been modified):

class MyClass {

    public:

        void setInstance(A* newInstance) {
            instance = newInstance;
        }

        void doSomething() {
            instance->action();
        }

    private:

        A* instance;
};

int main(int argc, char** argv) {
    MyClass c;
    B myInstance;
    c.setInstance(&myInstance);
    c.doSomething();
    return 0;
}

LastEditorDisplayName: seanhodges

Body:
I had this problem by including parent.h before iostream:

wrong:

include "parent.h"
include <iostream>

right:

include <iostream>
include "parent.h"


问:
[Retrofit][Android] Parse Object for each model with standard Json reponse
I'm working with retrofit2
In standard json response : {url}/login

```<code>{
  "message": "succesfully",
  "status_code": "100",
  "data":{
    "token":"jiur02Pje9",
    "username":"usertest",
    "id":"jlow81"
  }
}
</code>```

and another api:

```<code>{
  "message": "get information succesfully",
  "status_code": 100,
  "data": {
    "username": "usertest02",
    "phone": "1111111",
    "image": "http://test/1.jpg",
    "online_status": 1
  }
}
</code>```

I create file model

BaseData.java

```<code>String message;
int statusCode;
Object data;
</code>```

UserInformation.java (field : username, image ...)

Authentication.java (field : token, id, username ...)

How to parse [data] to UserInformation and Authentication object

Thank for reading.

答:
There are many ways of doing it.

You can go ahead with third party libraries like Gson

Your pojo class, will look somewhat like this, use Android plugin or online json to pojo convertor.

```<code>public class Response {

    @SerializedName("data")
    private Data mData;
    @SerializedName("message")
    private String mMessage;
    @SerializedName("status_code")
    private String mStatusCode;

    public Data getData() {
        return mData;
    }

    public void setData(Data data) {
        mData = data;
    }

    public String getMessage() {
        return mMessage;
    }

    public void setMessage(String message) {
        mMessage = message;
    }

    public String getStatusCode() {
        return mStatusCode;
    }

    public void setStatusCode(String statusCode) {
        mStatusCode = statusCode;
    }

    public class Data {

        @SerializedName("image")
        private String mImage;
        @SerializedName("online_status")
        private Long mOnlineStatus;
        @SerializedName("phone")
        private String mPhone;
        @SerializedName("username")
        private String mUsername;
        @SerializedName("token")
        private String mToken;
        @SerializedName("id")
        private String mId;
        public String getImage() {
            return mImage;
        }

        public void setImage(String image) {
            mImage = image;
        }

        public Long getOnlineStatus() {
            return mOnlineStatus;
        }

        public void setOnlineStatus(Long onlineStatus) {
            mOnlineStatus = onlineStatus;
        }

        public String getPhone() {
            return mPhone;
        }

        public void setPhone(String phone) {
            mPhone = phone;
        }

        public String getUsername() {
            return mUsername;
        }

        public void setUsername(String username) {
            mUsername = username;
        }

        public String getmToken() {
            return mToken;
        }

        public void setmToken(String mToken) {
            this.mToken = mToken;
        }

        public String getmId() {
            return mId;
        }

        public void setmId(String mId) {
            this.mId = mId;
        }
    }

}
</code>```

Now to convert json string to pojo, use Gson as -

```<code>Gson gson = new Gson();
Response response = gson.fromJson(yourresponseStr.toString(), Response.class);
</code>```

You can use the same response class, or you can have mapper class which will take Response as param and returns different pojo's by mapping the state with UserInformation.java or Authentication.java

This way code is more readable and cleaner and you are using only the data you need.
Also, if you need to serialize and pass to other components, you will be passing only the required fields.

Body:
I'm working with retrofit2
In standard json response : {url}/login

{
  "message": "succesfully",
  "status_code": "100",
  "data":{
    "token":"jiur02Pje9",
    "username":"usertest",
    "id":"jlow81"
  }
}

and another api:

{
  "message": "get information succesfully",
  "status_code": 100,
  "data": {
    "username": "usertest02",
    "phone": "1111111",
    "image": "http://test/1.jpg",
    "online_status": 1
  }
}

I create file model

BaseData.java

String message;
int statusCode;
Object data;

UserInformation.java (field : username, image ...)

Authentication.java (field : token, id, username ...)

How to parse [data] to UserInformation and Authentication object

Thank for reading.

Body:
There are many ways of doing it.

You can go ahead with third party libraries like Gson

Your pojo class, will look somewhat like this, use Android plugin or online json to pojo convertor.

public class Response {

    @SerializedName("data")
    private Data mData;
    @SerializedName("message")
    private String mMessage;
    @SerializedName("status_code")
    private String mStatusCode;

    public Data getData() {
        return mData;
    }

    public void setData(Data data) {
        mData = data;
    }

    public String getMessage() {
        return mMessage;
    }

    public void setMessage(String message) {
        mMessage = message;
    }

    public String getStatusCode() {
        return mStatusCode;
    }

    public void setStatusCode(String statusCode) {
        mStatusCode = statusCode;
    }

    public class Data {

        @SerializedName("image")
        private String mImage;
        @SerializedName("online_status")
        private Long mOnlineStatus;
        @SerializedName("phone")
        private String mPhone;
        @SerializedName("username")
        private String mUsername;
        @SerializedName("token")
        private String mToken;
        @SerializedName("id")
        private String mId;
        public String getImage() {
            return mImage;
        }

        public void setImage(String image) {
            mImage = image;
        }

        public Long getOnlineStatus() {
            return mOnlineStatus;
        }

        public void setOnlineStatus(Long onlineStatus) {
            mOnlineStatus = onlineStatus;
        }

        public String getPhone() {
            return mPhone;
        }

        public void setPhone(String phone) {
            mPhone = phone;
        }

        public String getUsername() {
            return mUsername;
        }

        public void setUsername(String username) {
            mUsername = username;
        }

        public String getmToken() {
            return mToken;
        }

        public void setmToken(String mToken) {
            this.mToken = mToken;
        }

        public String getmId() {
            return mId;
        }

        public void setmId(String mId) {
            this.mId = mId;
        }
    }

}

Now to convert json string to pojo, use Gson as -

Gson gson = new Gson();
Response response = gson.fromJson(yourresponseStr.toString(), Response.class);

You can use the same response class, or you can have mapper class which will take Response as param and returns different pojo's by mapping the state with UserInformation.java or Authentication.java

This way code is more readable and cleaner and you are using only the data you need.
Also, if you need to serialize and pass to other components, you will be passing only the required fields.


问:
Why can't I log into the Discord.js client?
This code isn't working, it never logs Ready! to the console. It's also not logging out any errors, so I believe it may have logged in correctly but just isn't working. Does anyone have any pointers?

```<code>var Discord = require("discord.js");
var client = new Discord.Client();

client.login('myEmail', 'myPassword', output);

client.on('ready', () => {
  console.log("Ready!");
});

function output(error, token) {
        console.log("errorz!");
        if (error) {
            console.log("There was an error logging in: ${error}");
            return;
        } else {
            console.log("`Logged in. Token: ${token}`");
        }
}
</code>```

Just to make sure I am doing this right, I have put this in a file called discord-fisher.js and I am running it using node discord-fisher.js from the terminal.

答:
Per the documentation for Discord.js for Client#login:

.login( token )

Logs the client in, establishing a websocket connection to Discord.

So when you use login, you don't provide your email or password details, you provide your API token associated with your account.

Body:
This code isn't working, it never logs Ready! to the console. It's also not logging out any errors, so I believe it may have logged in correctly but just isn't working. Does anyone have any pointers?

var Discord = require("discord.js");
var client = new Discord.Client();

client.login('myEmail', 'myPassword', output);

client.on('ready', () => {
  console.log("Ready!");
});

function output(error, token) {
        console.log("errorz!");
        if (error) {
            console.log("There was an error logging in: ${error}");
            return;
        } else {
            console.log("`Logged in. Token: ${token}`");
        }
}

Just to make sure I am doing this right, I have put this in a file called discord-fisher.js and I am running it using node discord-fisher.js from the terminal.


问:
Adding StructFields to an existing schema
I created a class "Attribute". Each class object has a name, a datatype and a boolean value (nullable or not). All objects are saved to a ListBuffer.

I try to create a schema from the list and pass each value to the StructField(). Initiating works but unfortunately no further items are getting added to the schema.

```<code>def create_schema_from_attr_list(attr_list: ListBuffer[Attribute]): StructType = {
  // Get first list item and initiate schema
  var schema = StructType(StructField(attr_list(0).name, attr_list(0).data_type, attr_list(0).nullable) :: Nil)

  // Add remaining items
  for (i <- 1 until attr_list.length) {
    schema.add(attr_list(i).name, attr_list(i).data_type, attr_list(i).nullable)
    println("Test " + attr_list(i).name.toString())
  }
  return schema
}
</code>```

答:
You initiated the schema but you never assigned the added structfield back to schema inside the loop. That's why your added structFields are not reflected in the initiated schema.

You should use DataTypes api for flexible creation of schema. Following is my suggestion. Hope it helps

```<code>def create_schema_from_attr_list(attr_list: ListBuffer[Attribute]): StructType = {
  // create bufferedlist of structfield
  val bufferFields : util.ArrayList[StructField] = new util.ArrayList[StructField]
  // Add structfields
  for (i <- 0 until attr_list.length) {
    bufferFields.add(DataTypes.createStructField(attr_list(i).name, attr_list(i).data_type, attr_list(i).nullable))
  }
  DataTypes.createStructType(bufferFields)
}
</code>```

Body:
I created a class "Attribute". Each class object has a name, a datatype and a boolean value (nullable or not). All objects are saved to a ListBuffer.

I try to create a schema from the list and pass each value to the StructField(). Initiating works but unfortunately no further items are getting added to the schema.

def create_schema_from_attr_list(attr_list: ListBuffer[Attribute]): StructType = {
  // Get first list item and initiate schema
  var schema = StructType(StructField(attr_list(0).name, attr_list(0).data_type, attr_list(0).nullable) :: Nil)

  // Add remaining items
  for (i <- 1 until attr_list.length) {
    schema.add(attr_list(i).name, attr_list(i).data_type, attr_list(i).nullable)
    println("Test " + attr_list(i).name.toString())
  }
  return schema
}

Body:
You initiated the schema but you never assigned the added structfield back to schema inside the loop. That's why your added structFields are not reflected in the initiated schema.

You should use DataTypes api for flexible creation of schema. Following is my suggestion. Hope it helps

def create_schema_from_attr_list(attr_list: ListBuffer[Attribute]): StructType = {
  // create bufferedlist of structfield
  val bufferFields : util.ArrayList[StructField] = new util.ArrayList[StructField]
  // Add structfields
  for (i <- 0 until attr_list.length) {
    bufferFields.add(DataTypes.createStructField(attr_list(i).name, attr_list(i).data_type, attr_list(i).nullable))
  }
  DataTypes.createStructType(bufferFields)
}


问:
Disable Swipe left and right on CarouselView when swiping down Xamarin
First of all I am working on a Xamarin PCL project using Refractored.XamForms.PullToRefresh to refresh the content on my pages that happen to be in a CarouselView, but I have found that it is nearly impossible to pull down and not swipe left or right to the next page. Is there a way I could disable or block the left to right swiping when the page begins to pull down? I am struggling even trying to come up with a method to do this. </p>

答:
You could create a carouselviewpage renderer perhaps and than on the ViewDidLoad you could do

```<code>foreach (var g in this.View.GestureRecognizers)
            g.ShouldBegin = recognizer => false;
</code>```

--> this removes all gesture recognizers on your carouspage

Body:
You could create a carouselviewpage renderer perhaps and than on the ViewDidLoad you could do

foreach (var g in this.View.GestureRecognizers)
            g.ShouldBegin = recognizer => false;

--> this removes all gesture recognizers on your carouspage