问:
Install xp_msver in Azure
An application calls xp_msver to determine if the SQL server is an appropriate version. The application will then determine whether or not to install or execute.
I want to use Azure SQL, but this procedure xp_msver is not found in Azure. Is there a way to create it or export it from an existing SQL instance and import it to Azure? Azure is available as Basic, Standard & Premium, perhaps the Premium has this procedure?</p>

答:
So long as you don't need to run this from Master, you can create your own stored procedure called xp_msver that does whatever you want.  In particular you can clone the results from a SQL Server of your choice.

Something like this:

```<code>set nocount on

declare @t table ([Index] int, Name nvarchar(200), Internal_Value varchar(200) null, Character_Value nvarchar(200))

insert into @t
exec xp_msver

set statistics time off
select 'create or alter procedure xp_msver
as
begin

declare @t table ([Index] int primary key, Name nvarchar(200), Internal_Value bigint null, Character_Value nvarchar(200))
'

select concat('insert into @t([Index],Name,Internal_Value,Character_value) values (',[Index],',''',Name,''',',coalesce(Internal_Value,'null'),',''',Character_Value,''')')
from @t

select '

select * from @t
order by [Index]

end'
</code>```

Which outputs a stored procedure DDL statement like this:

```<code>create or alter procedure xp_msver
as
begin

declare @t table ([Index] int primary key, Name nvarchar(200), Internal_Value bigint null, Character_Value nvarchar(200))

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
insert into @t([Index],Name,Internal_Value,Character_value) values (1,'ProductName',null,'Microsoft SQL Server')
insert into @t([Index],Name,Internal_Value,Character_value) values (2,'ProductVersion',917504,'14.0.1000.169')
insert into @t([Index],Name,Internal_Value,Character_value) values (3,'Language',1033,'English (United States)')
insert into @t([Index],Name,Internal_Value,Character_value) values (4,'Platform',null,'NT x64')
insert into @t([Index],Name,Internal_Value,Character_value) values (5,'Comments',null,'SQL')
insert into @t([Index],Name,Internal_Value,Character_value) values (6,'CompanyName',null,'Microsoft Corporation')
insert into @t([Index],Name,Internal_Value,Character_value) values (7,'FileDescription',null,'SQL Server Windows NT - 64 Bit')
insert into @t([Index],Name,Internal_Value,Character_value) values (8,'FileVersion',null,'2017.0140.1000.169 ((SQLServer).170822-2340)')
insert into @t([Index],Name,Internal_Value,Character_value) values (9,'InternalName',null,'SQLSERVR')
insert into @t([Index],Name,Internal_Value,Character_value) values (10,'LegalCopyright',null,'Microsoft. All rights reserved.')
insert into @t([Index],Name,Internal_Value,Character_value) values (11,'LegalTrademarks',null,'Microsoft SQL Server is a registered trademark of Microsoft Corporation.')
insert into @t([Index],Name,Internal_Value,Character_value) values (12,'OriginalFilename',null,'SQLSERVR.EXE')
insert into @t([Index],Name,Internal_Value,Character_value) values (13,'PrivateBuild',null,'')
insert into @t([Index],Name,Internal_Value,Character_value) values (14,'SpecialBuild',65536169,'')
insert into @t([Index],Name,Internal_Value,Character_value) values (15,'WindowsVersion',65536169,'6.3 (16299)')
insert into @t([Index],Name,Internal_Value,Character_value) values (16,'ProcessorCount',4,'4')
insert into @t([Index],Name,Internal_Value,Character_value) values (17,'ProcessorActiveMask',null,'               f')
insert into @t([Index],Name,Internal_Value,Character_value) values (18,'ProcessorType',8664,'')
insert into @t([Index],Name,Internal_Value,Character_value) values (19,'PhysicalMemory',16310,'16310 (17102405632)')
insert into @t([Index],Name,Internal_Value,Character_value) values (20,'Product ID',null,'')

---------------------------

select * from @t
order by [Index]

end
</code>```

Title: Install xp_msver in Azure

Body:
So long as you don't need to run this from Master, you can create your own stored procedure called xp_msver that does whatever you want.  In particular you can clone the results from a SQL Server of your choice.

Something like this:

set nocount on

declare @t table ([Index] int, Name nvarchar(200), Internal_Value varchar(200) null, Character_Value nvarchar(200))

insert into @t
exec xp_msver

set statistics time off
select 'create or alter procedure xp_msver
as
begin

declare @t table ([Index] int primary key, Name nvarchar(200), Internal_Value bigint null, Character_Value nvarchar(200))
'

select concat('insert into @t([Index],Name,Internal_Value,Character_value) values (',[Index],',''',Name,''',',coalesce(Internal_Value,'null'),',''',Character_Value,''')')
from @t

select '

select * from @t
order by [Index]

end'

Which outputs a stored procedure DDL statement like this:

create or alter procedure xp_msver
as
begin

declare @t table ([Index] int primary key, Name nvarchar(200), Internal_Value bigint null, Character_Value nvarchar(200))

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
insert into @t([Index],Name,Internal_Value,Character_value) values (1,'ProductName',null,'Microsoft SQL Server')
insert into @t([Index],Name,Internal_Value,Character_value) values (2,'ProductVersion',917504,'14.0.1000.169')
insert into @t([Index],Name,Internal_Value,Character_value) values (3,'Language',1033,'English (United States)')
insert into @t([Index],Name,Internal_Value,Character_value) values (4,'Platform',null,'NT x64')
insert into @t([Index],Name,Internal_Value,Character_value) values (5,'Comments',null,'SQL')
insert into @t([Index],Name,Internal_Value,Character_value) values (6,'CompanyName',null,'Microsoft Corporation')
insert into @t([Index],Name,Internal_Value,Character_value) values (7,'FileDescription',null,'SQL Server Windows NT - 64 Bit')
insert into @t([Index],Name,Internal_Value,Character_value) values (8,'FileVersion',null,'2017.0140.1000.169 ((SQLServer).170822-2340)')
insert into @t([Index],Name,Internal_Value,Character_value) values (9,'InternalName',null,'SQLSERVR')
insert into @t([Index],Name,Internal_Value,Character_value) values (10,'LegalCopyright',null,'Microsoft. All rights reserved.')
insert into @t([Index],Name,Internal_Value,Character_value) values (11,'LegalTrademarks',null,'Microsoft SQL Server is a registered trademark of Microsoft Corporation.')
insert into @t([Index],Name,Internal_Value,Character_value) values (12,'OriginalFilename',null,'SQLSERVR.EXE')
insert into @t([Index],Name,Internal_Value,Character_value) values (13,'PrivateBuild',null,'')
insert into @t([Index],Name,Internal_Value,Character_value) values (14,'SpecialBuild',65536169,'')
insert into @t([Index],Name,Internal_Value,Character_value) values (15,'WindowsVersion',65536169,'6.3 (16299)')
insert into @t([Index],Name,Internal_Value,Character_value) values (16,'ProcessorCount',4,'4')
insert into @t([Index],Name,Internal_Value,Character_value) values (17,'ProcessorActiveMask',null,'               f')
insert into @t([Index],Name,Internal_Value,Character_value) values (18,'ProcessorType',8664,'')
insert into @t([Index],Name,Internal_Value,Character_value) values (19,'PhysicalMemory',16310,'16310 (17102405632)')
insert into @t([Index],Name,Internal_Value,Character_value) values (20,'Product ID',null,'')

---------------------------

select * from @t
order by [Index]

end


来源: stackexchange

问:
Kleopatra No secret key
I support an application who call a CMD line to decrypt a file.
The application is a .exe file that is called by the Windows Task Scheduler and is execute as the same user who have all right.

The application run every week day in the evening at 6h30pm and sometimes the CMD line return the message: no secret key.
The application failed because the file was not decrypted. But it doesn't failed every evening, just random evening. It looks totally random.

And if I run the application myself after it failed with the same user, it worked.

The secret key is imported in Kleopatra and it work fine with other application that run in the morning. And it work fine when I used it.

What can cause this?

Thank you

答:
Some ideas to help you run down the problem:

Check the private keys available to the machine on which the application fails

gpg --list-secret-keys

(IIRC Kleopatra runs on top of GnuPG, so I assume your application does as well. I've been wrong before.) You might notice something out of place with your private (decryption) keys. For example, if the key is listed as either

```<code>sec#
ssb>
</code>```

Then it's a (primary or sub respectively) key located on a smart card for storage. If the card, for whatever reason, isn't in the machine when the app runs it'll fail to decrypt.

Check the disk containing the private keyring is attached/inserted/mounted at the time the application ran and failed to decrypt. If the keys are stored on removable (or unreliable) media then that could also result in a failure to decrypt.

Check that the item failing to decrypt was encrypted properly. If there is some secondary recipient necessary for the app to run there may be a required key that you don't know about (I gather from your post you didn't create this app, just maintain it.) It may even be that the app is trying to decrypt a different file erroneously, but that kind of thing can only be found out by stepping through your source code and resident files.

Failing those, pray for @Jens Erat to notice your question.

ContentLicense: CC BY-SA 3.0

Title: Kleopatra No secret key

Body:
Some ideas to help you run down the problem:

Check the private keys available to the machine on which the application fails

gpg --list-secret-keys

(IIRC Kleopatra runs on top of GnuPG, so I assume your application does as well. I've been wrong before.) You might notice something out of place with your private (decryption) keys. For example, if the key is listed as either

sec#
ssb>

Then it's a (primary or sub respectively) key located on a smart card for storage. If the card, for whatever reason, isn't in the machine when the app runs it'll fail to decrypt.

Check the disk containing the private keyring is attached/inserted/mounted at the time the application ran and failed to decrypt. If the keys are stored on removable (or unreliable) media then that could also result in a failure to decrypt.

Check that the item failing to decrypt was encrypted properly. If there is some secondary recipient necessary for the app to run there may be a required key that you don't know about (I gather from your post you didn't create this app, just maintain it.) It may even be that the app is trying to decrypt a different file erroneously, but that kind of thing can only be found out by stepping through your source code and resident files.

Failing those, pray for @Jens Erat to notice your question.


问:
Access Query - Invalid Operation when using Order By clause
The following query works fine but as soon as I add the Order By clause, I get an

error - "invalid operation"

Can any one help me please?

```<code>SELECT dbo_jobs.jobid,
       dbo_jobs.jobrefno,
       dbo_jobs.createdon,
       dbo_jobs.archived,
       dbo_jobs.published,
       dbo_jobs.jobtitle,
       dbo_jobs.statusid,
       dbo_jobs.clientid,
       dbo_clients.company,
       dbo_clientcontacts.clientcontactid,
       dbo_employmenttypes.employmenttypeid,
       dbo_employmenttypes.description,
       dbo_locations.description,
       dbo_jobsectordefinedcolumns.clientname,
       dbo_jobsectordefinedcolumns.natureofcase,
       dbo_jobsectordefinedcolumns.timescaletodeadline,
       dbo_jobs.notes,
       dbo_jobsectordefinedcolumns.status,
       dbo_clientcontacts.contactpersonid,
       dbo_jobsectordefinedcolumns.vat,
       dbo_jobsectordefinedcolumns.postcode,
       dbo_jobsectordefinedcolumns.additionalinfo,
       dbo_jobsectordefinedcolumns.solicitorref,
       dbo_jobconsultants.userid,
       dbo_users.loginname,
       dbo_jobs.positionattributeid,
       dbo_jobsectordefinedcolumns.consultancyservice,
       [dbo_person].[PersonName] & ' ' & [dbo_person].[Surname] AS ClientCon,
       dbo_person.personname,
       dbo_person.surname,
       dbo_jobstatus.description,
       dbo_jobsectordefinedcolumns.priority,
       RevListCount.countofrevids,
       CVCount.cvsentcount
FROM   (((SELECT dbo_jobs.jobid,
                dbo_jobs.jobrefno,
                dbo_jobs.createdon,
                dbo_jobs.archived,
                dbo_jobs.published,
                dbo_jobs.jobtitle,
                dbo_jobs.statusid,
                dbo_jobs.clientid,
                dbo_clients.company,
                dbo_clientcontacts.clientcontactid,
                dbo_employmenttypes.employmenttypeid,
                dbo_employmenttypes.description,
                dbo_locations.description,
                dbo_jobsectordefinedcolumns.clientname,
                dbo_jobsectordefinedcolumns.natureofcase,
                dbo_jobsectordefinedcolumns.timescaletodeadline,
                dbo_jobs.notes,
                dbo_jobsectordefinedcolumns.status,
                dbo_clientcontacts.contactpersonid,
                dbo_jobsectordefinedcolumns.vat,
                dbo_jobsectordefinedcolumns.postcode,
                dbo_jobsectordefinedcolumns.additionalinfo,
                dbo_jobsectordefinedcolumns.solicitorref,
                dbo_jobconsultants.userid,
                dbo_users.loginname,
                dbo_jobs.positionattributeid,
                dbo_jobsectordefinedcolumns.consultancyservice,
                [dbo_person].[personname] & ' ' & [dbo_person].[surname] AS
                 ClientCon,
                dbo_person.personname,
                dbo_person.surname,
                dbo_jobstatus.description,
                dbo_jobsectordefinedcolumns.priority
         FROM   ((((((((dbo_employmenttypes
                        INNER JOIN dbo_jobs
                                ON dbo_employmenttypes.employmenttypeid =
                                  dbo_jobs.employmenttypeid)
                       INNER JOIN dbo_clients
                               ON dbo_jobs.clientid = dbo_clients.clientid)
                      INNER JOIN dbo_clientcontacts
                              ON dbo_jobs.clientcontactid =
                                 dbo_clientcontacts.clientcontactid)
                     LEFT JOIN dbo_jobsectordefinedcolumns
                            ON dbo_jobs.jobid =
dbo_jobsectordefinedcolumns.jobid)
                    INNER JOIN dbo_person
                            ON dbo_clientcontacts.contactpersonid =
                   dbo_person.personid)
                   LEFT JOIN dbo_jobconsultants
                          ON dbo_jobs.jobid = dbo_jobconsultants.jobid)
                  LEFT JOIN dbo_users
                         ON dbo_jobconsultants.userid = dbo_users.userid)
                 LEFT JOIN dbo_jobstatus
                        ON dbo_jobs.statusid = dbo_jobstatus.jobstatusid)
                LEFT JOIN dbo_locations
                       ON dbo_jobs.locationid = dbo_locations.locationid
         WHERE  ( ( ( dbo_jobs.archived ) = 'N' )
                  AND ( ( dbo_employmenttypes.employmenttypeid ) <> 12 )
                  AND ( ( dbo_jobconsultants.userrelationshipid ) = 9 )
                  AND
         ( ( dbo_jobstatus.description ) <> 'Filled'
           AND ( dbo_jobstatus.description ) <> 'Filled - Ongoing' ) )) AS
        AllJobs
         LEFT JOIN (SELECT dbo_reviewlists.jobid,
                           Count(dbo_reviewlistapplicants.reviewlistid) AS
                           CountOfRevIDs
                    FROM   dbo_reviewlists
                           LEFT JOIN dbo_reviewlistapplicants
                                  ON dbo_reviewlists.reviewlistid =
                                     dbo_reviewlistapplicants.reviewlistid
                    GROUP  BY dbo_reviewlists.jobid) AS RevListCount
                ON AllJobs.jobid = RevListCount.jobid)
        LEFT JOIN (SELECT dbo_applicantactions.jobid,
                          Count(dbo_applicantactions.statusid) AS CVSentCount
                   FROM   dbo_applicantactions
                   WHERE  (( ( dbo_applicantactions.statusid ) = 29 ))
                   GROUP  BY dbo_applicantactions.jobid) AS CVCount
               ON AllJobs.jobid = CVCount.jobid)
ORDER  BY dbo_jobs.jobid DESC
</code>```

答:
You haven't given an alias name to your outermost query block, and you are trying to order by dbo_Jobs.JobId instead of alias_name.JobId

(Either that, or your bracket between the group by and order by clauses is not needed - I lost count of the brackets!)

Body:
The following query works fine but as soon as I add the Order By clause, I get an

error - "invalid operation"

Can any one help me please?

SELECT dbo_jobs.jobid,
       dbo_jobs.jobrefno,
       dbo_jobs.createdon,
       dbo_jobs.archived,
       dbo_jobs.published,
       dbo_jobs.jobtitle,
       dbo_jobs.statusid,
       dbo_jobs.clientid,
       dbo_clients.company,
       dbo_clientcontacts.clientcontactid,
       dbo_employmenttypes.employmenttypeid,
       dbo_employmenttypes.description,
       dbo_locations.description,
       dbo_jobsectordefinedcolumns.clientname,
       dbo_jobsectordefinedcolumns.natureofcase,
       dbo_jobsectordefinedcolumns.timescaletodeadline,
       dbo_jobs.notes,
       dbo_jobsectordefinedcolumns.status,
       dbo_clientcontacts.contactpersonid,
       dbo_jobsectordefinedcolumns.vat,
       dbo_jobsectordefinedcolumns.postcode,
       dbo_jobsectordefinedcolumns.additionalinfo,
       dbo_jobsectordefinedcolumns.solicitorref,
       dbo_jobconsultants.userid,
       dbo_users.loginname,
       dbo_jobs.positionattributeid,
       dbo_jobsectordefinedcolumns.consultancyservice,
       [dbo_person].[PersonName] & ' ' & [dbo_person].[Surname] AS ClientCon,
       dbo_person.personname,
       dbo_person.surname,
       dbo_jobstatus.description,
       dbo_jobsectordefinedcolumns.priority,
       RevListCount.countofrevids,
       CVCount.cvsentcount
FROM   (((SELECT dbo_jobs.jobid,
                dbo_jobs.jobrefno,
                dbo_jobs.createdon,
                dbo_jobs.archived,
                dbo_jobs.published,
                dbo_jobs.jobtitle,
                dbo_jobs.statusid,
                dbo_jobs.clientid,
                dbo_clients.company,
                dbo_clientcontacts.clientcontactid,
                dbo_employmenttypes.employmenttypeid,
                dbo_employmenttypes.description,
                dbo_locations.description,
                dbo_jobsectordefinedcolumns.clientname,
                dbo_jobsectordefinedcolumns.natureofcase,
                dbo_jobsectordefinedcolumns.timescaletodeadline,
                dbo_jobs.notes,
                dbo_jobsectordefinedcolumns.status,
                dbo_clientcontacts.contactpersonid,
                dbo_jobsectordefinedcolumns.vat,
                dbo_jobsectordefinedcolumns.postcode,
                dbo_jobsectordefinedcolumns.additionalinfo,
                dbo_jobsectordefinedcolumns.solicitorref,
                dbo_jobconsultants.userid,
                dbo_users.loginname,
                dbo_jobs.positionattributeid,
                dbo_jobsectordefinedcolumns.consultancyservice,
                [dbo_person].[personname] & ' ' & [dbo_person].[surname] AS
                 ClientCon,
                dbo_person.personname,
                dbo_person.surname,
                dbo_jobstatus.description,
                dbo_jobsectordefinedcolumns.priority
         FROM   ((((((((dbo_employmenttypes
                        INNER JOIN dbo_jobs
                                ON dbo_employmenttypes.employmenttypeid =
                                  dbo_jobs.employmenttypeid)
                       INNER JOIN dbo_clients
                               ON dbo_jobs.clientid = dbo_clients.clientid)
                      INNER JOIN dbo_clientcontacts
                              ON dbo_jobs.clientcontactid =
                                 dbo_clientcontacts.clientcontactid)
                     LEFT JOIN dbo_jobsectordefinedcolumns
                            ON dbo_jobs.jobid =
dbo_jobsectordefinedcolumns.jobid)
                    INNER JOIN dbo_person
                            ON dbo_clientcontacts.contactpersonid =
                   dbo_person.personid)
                   LEFT JOIN dbo_jobconsultants
                          ON dbo_jobs.jobid = dbo_jobconsultants.jobid)
                  LEFT JOIN dbo_users
                         ON dbo_jobconsultants.userid = dbo_users.userid)
                 LEFT JOIN dbo_jobstatus
                        ON dbo_jobs.statusid = dbo_jobstatus.jobstatusid)
                LEFT JOIN dbo_locations
                       ON dbo_jobs.locationid = dbo_locations.locationid
         WHERE  ( ( ( dbo_jobs.archived ) = 'N' )
                  AND ( ( dbo_employmenttypes.employmenttypeid ) <> 12 )
                  AND ( ( dbo_jobconsultants.userrelationshipid ) = 9 )
                  AND
         ( ( dbo_jobstatus.description ) <> 'Filled'
           AND ( dbo_jobstatus.description ) <> 'Filled - Ongoing' ) )) AS
        AllJobs
         LEFT JOIN (SELECT dbo_reviewlists.jobid,
                           Count(dbo_reviewlistapplicants.reviewlistid) AS
                           CountOfRevIDs
                    FROM   dbo_reviewlists
                           LEFT JOIN dbo_reviewlistapplicants
                                  ON dbo_reviewlists.reviewlistid =
                                     dbo_reviewlistapplicants.reviewlistid
                    GROUP  BY dbo_reviewlists.jobid) AS RevListCount
                ON AllJobs.jobid = RevListCount.jobid)
        LEFT JOIN (SELECT dbo_applicantactions.jobid,
                          Count(dbo_applicantactions.statusid) AS CVSentCount
                   FROM   dbo_applicantactions
                   WHERE  (( ( dbo_applicantactions.statusid ) = 29 ))
                   GROUP  BY dbo_applicantactions.jobid) AS CVCount
               ON AllJobs.jobid = CVCount.jobid)
ORDER  BY dbo_jobs.jobid DESC


问:
Chrome Dev Tools - Remembering the selected element through page reload
I am building my own type of Chrome dev tools (inspect element) which will also be in the form of a Chrome extension using JavaScript. I would like it to have some similar functionality to Chromes dev tools, one of which I'm finding hard to debunk how they have done it.

Basically, when you right click on any element and click "inspect element" it will open up the dev tools if not already open and hover over the HTML element your right click was targeting.

The bit that I want to replicate is when you refresh the page the while you still have the element selected in dev tools, it will reload all the HTML and directly go to the element you had selected in the dev tools before reloading.

Here is what I mean if it's a little unclear:

HTML:

```

If I was hovering over the div with class of "3" and refreshed the page, Chrome dev tools knows to reload with the dev tools highlighting that exact div. Even if there are multiple divs with that class or in a similar structure it will always hover the correct one.

Would anyone know if the best approach here is to have a big if statement which looks for certain traits of the element such as ideally an id but also a lot of fall-backs if the element does not have an id such as surrounding elements or unique classes/ attributes associated with that element?

I've tried searching for 'Chrome extension node selector' or similar variants but have not been able to find any information.

答:
There already exists a pretty good "inspect element" extension that you can find here. However, it does not have support for saving the inspected element. But since it's a bounty question I could give you a few hints for improving it towards a working solution.

The main problem I see here is "serializing" the element. A good answer on this topic can be found here. (see fiddle also) It basically sums up to "find the nearest ancestor with an ID and track the path downwards to the inspected element". In your case this could be:

```<code>tracePath: function (element, result) {
  if (element.id !== '') {
    result.push({
      id: element.id
    });
    return;
  }
  if (element === document.body) {
    result.push({
      tag: element.tagName
    });
    return;
  }

  var siblings = element.parentNode.childNodes;
  for (var i = 0; i < siblings.length; ++i) {
    var sibling = siblings[i];
    if (sibling === element) {
      result.push({
        index: i,
        tag: element.tagName
      });
      return this.tracePath(element.parentNode, result);
    }
  }
},
</code>```

The above just stores an array of nodes to follow during deserialization:

```<code>find: function (path) {
  var element;
  while (path.length) {
    var current = path.pop();

    if (!current) return element;
    if (current.id) element = document.getElementById(current.id);
    else if (element) {
      if (current.index < element.childNodes.length && current.tag === element.childNodes[current.index].tagName)
        element = element.childNodes[current.index];
      else
        return;
    } else {
      var matches = document.getElementsByTagName(current.tag);
      if (matches.length)
          element = matches[0];
    }
  }
  return element;
},
</code>```

Once we these two, we only need ways to store/load the selection:

```<code>store: function (path) {
  var selection = Object.create({});
  selection[window.location.href] = path;
  chrome.storage.local.set(selection, function () {
    if (chrome.runtime.lastError) {
      console.error(chrome.runtime.lastError)
    }
  })
},
</code>```

And load:

```<code>load: function () {
  var self = this, key = window.location.href;
  chrome.storage.local.get(key, function (found) {
    if (chrome.runtime.lastError) {
      console.error(chrome.runtime.lastError)
    } else if (found && found[key]) {
      var path = found[key],
        element = Util.find(path);

      if (element) {
        // zoom into inspected element
        element.scrollIntoView();
        // add selection to Inspector instance
        self.$selection = element;
        // function similar to layout() - highlights inspected element
        self.select();
      }
    }
  })
}
</code>```

You could then write a highlighting function, say select for highlighting the inspected element, similar to already existing layout which highlights the ruler.

Saving the element could be done when clicking on it:

```<code>registerEvents: function() {
  ...
  document.addEventListener('click', function () {
      var path = [];
      Util.tracePath(this.$target, path);
      this.$selection = this.$target;
      this.select(true);
      this.storeSelection(path);
  }.bind(this));
  ...
},
</code>```

There's a fork which contains the above modifications that you can find here. You can try it out by downloading it and loading the app folder as an unpacked extension in a new tab under chrome://extensions/. Enjoy!

Screenshots

Body:
I am building my own type of Chrome dev tools (inspect element) which will also be in the form of a Chrome extension using JavaScript. I would like it to have some similar functionality to Chromes dev tools, one of which I'm finding hard to debunk how they have done it.

Basically, when you right click on any element and click "inspect element" it will open up the dev tools if not already open and hover over the HTML element your right click was targeting.

The bit that I want to replicate is when you refresh the page the while you still have the element selected in dev tools, it will reload all the HTML and directly go to the element you had selected in the dev tools before reloading.

Here is what I mean if it's a little unclear:

HTML:

If I was hovering over the div with class of "3" and refreshed the page, Chrome dev tools knows to reload with the dev tools highlighting that exact div. Even if there are multiple divs with that class or in a similar structure it will always hover the correct one.

Would anyone know if the best approach here is to have a big if statement which looks for certain traits of the element such as ideally an id but also a lot of fall-backs if the element does not have an id such as surrounding elements or unique classes/ attributes associated with that element?

I've tried searching for 'Chrome extension node selector' or similar variants but have not been able to find any information.

Body:
There already exists a pretty good "inspect element" extension that you can find here. However, it does not have support for saving the inspected element. But since it's a bounty question I could give you a few hints for improving it towards a working solution.

The main problem I see here is "serializing" the element. A good answer on this topic can be found here. (see fiddle also) It basically sums up to "find the nearest ancestor with an ID and track the path downwards to the inspected element". In your case this could be:

tracePath: function (element, result) {
  if (element.id !== '') {
    result.push({
      id: element.id
    });
    return;
  }
  if (element === document.body) {
    result.push({
      tag: element.tagName
    });
    return;
  }

  var siblings = element.parentNode.childNodes;
  for (var i = 0; i < siblings.length; ++i) {
    var sibling = siblings[i];
    if (sibling === element) {
      result.push({
        index: i,
        tag: element.tagName
      });
      return this.tracePath(element.parentNode, result);
    }
  }
},

The above just stores an array of nodes to follow during deserialization:

find: function (path) {
  var element;
  while (path.length) {
    var current = path.pop();

    if (!current) return element;
    if (current.id) element = document.getElementById(current.id);
    else if (element) {
      if (current.index < element.childNodes.length && current.tag === element.childNodes[current.index].tagName)
        element = element.childNodes[current.index];
      else
        return;
    } else {
      var matches = document.getElementsByTagName(current.tag);
      if (matches.length)
          element = matches[0];
    }
  }
  return element;
},

Once we these two, we only need ways to store/load the selection:

store: function (path) {
  var selection = Object.create({});
  selection[window.location.href] = path;
  chrome.storage.local.set(selection, function () {
    if (chrome.runtime.lastError) {
      console.error(chrome.runtime.lastError)
    }
  })
},

And load:

load: function () {
  var self = this, key = window.location.href;
  chrome.storage.local.get(key, function (found) {
    if (chrome.runtime.lastError) {
      console.error(chrome.runtime.lastError)
    } else if (found && found[key]) {
      var path = found[key],
        element = Util.find(path);

      if (element) {
        // zoom into inspected element
        element.scrollIntoView();
        // add selection to Inspector instance
        self.$selection = element;
        // function similar to layout() - highlights inspected element
        self.select();
      }
    }
  })
}

You could then write a highlighting function, say select for highlighting the inspected element, similar to already existing layout which highlights the ruler.

Saving the element could be done when clicking on it:

registerEvents: function() {
  ...
  document.addEventListener('click', function () {
      var path = [];
      Util.tracePath(this.$target, path);
      this.$selection = this.$target;
      this.select(true);
      this.storeSelection(path);
  }.bind(this));
  ...
},

There's a fork which contains the above modifications that you can find here. You can try it out by downloading it and loading the app folder as an unpacked extension in a new tab under chrome://extensions/. Enjoy!

Screenshots


问:
The ExceptionHandled property of the MVC ActionExecutedContext class returns false
I have got an action as follows

```<code>[Audit()]
public ActionResult Submit(Employee employee)
{
     try
     {
          throw new Exception();
     }
     catch(Exception ex)
     {
          return new EmptyResult();
     }
}
</code>```

And action filter class as follows

```<code>public class AuditAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);

        if(filterContext.ExceptionHandled == true) // Do something
        else // Do something else
    }
}
</code>```

However the ExceptionHandled property is always returning false, even though the exception is handled as it is clear in code, any idea what could be the problem?

答:
In tha case you have overriden OnActionExecuted in your base class you should check if this implementation does not change the state of  filterContext.ExceptionHandled. If this is the case then you should call  base.OnActionExecuted(filterContext); right at the end of the method.

```<code>public class AuditAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //base.OnActionExecuted(filterContext);

        if(filterContext.ExceptionHandled == true) // Do something
        else // Do something else

        base.OnActionExecuted(filterContext);
    }
}
</code>```

Otherwise,  I would suggest you to check if there are exceptions at all in your ActionExecutedContext context:

```<code>public class AuditAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //base.OnActionExecuted(filterContext);

        if (filterContext.Exception == null) //Do something

        if(filterContext.ExceptionHandled == true) // Do something
        else // Do something else

        base.OnActionExecuted(filterContext);
    }
}
</code>```

Body:
I have got an action as follows

[Audit()]
public ActionResult Submit(Employee employee)
{
     try
     {
          throw new Exception();
     }
     catch(Exception ex)
     {
          return new EmptyResult();
     }
}

And action filter class as follows

public class AuditAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);

        if(filterContext.ExceptionHandled == true) // Do something
        else // Do something else
    }
}

However the ExceptionHandled property is always returning false, even though the exception is handled as it is clear in code, any idea what could be the problem?

Body:
In tha case you have overriden OnActionExecuted in your base class you should check if this implementation does not change the state of  filterContext.ExceptionHandled. If this is the case then you should call  base.OnActionExecuted(filterContext); right at the end of the method.

public class AuditAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //base.OnActionExecuted(filterContext);

        if(filterContext.ExceptionHandled == true) // Do something
        else // Do something else

        base.OnActionExecuted(filterContext);
    }
}

Otherwise,  I would suggest you to check if there are exceptions at all in your ActionExecutedContext context:

public class AuditAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //base.OnActionExecuted(filterContext);

        if (filterContext.Exception == null) //Do something

        if(filterContext.ExceptionHandled == true) // Do something
        else // Do something else

        base.OnActionExecuted(filterContext);
    }
}


问:
Using purrr::invoke() to supply different arguments to function.
I want to run the kmeans() function in R with different values of k (kmeans(x = iris[1:4], centers = k)). I know how to do this with dplyr or the do.call() function, however I can't get it to work with purrr::invoke() (I'm quite sure that invoke is the right function for this task). I could of course just use the dplyr approach (see this link), but it annoys me that I can't get it to work with purrr.

In the purrr::invoke() function reference, the following code-example is included:

```<code># Or the same function with different inputs:
invoke_map("runif", list(list(n = 5), list(n = 10)))
#> [[1]]
#> [1] 0.67176682 0.05861411 0.99706914 0.14903547 0.51855664
#>
#> [[2]]
#>  [1] 0.84612005 0.71826972 0.24131402 0.54704337 0.83480182 0.02795603
#>  [7] 0.46938430 0.80568003 0.81405131 0.40391100
#>
</code>```

When i try to do this with kmeans i get the following

```<code>> invoke(kmeans, list(list(centers = 1), list(centers = 2)), x = iris[1:4])
Error in sample.int(m, k) : invalid 'size' argument
</code>```

I have also tried

```<code>> invoke(kmeans, list(centers = 1:5), x = iris[1:4])
Error in (function (x, centers, iter.max = 10L, nstart = 1L,
algorithm = c("Hartigan-Wong",  : must have same number of columns in 'x' and 'centers'
</code>```

as a reality-check, i also tried doing a similar thing with paste

```<code>> invoke(paste, list(list(sep = "a"), list(sep = "b")), "word1", "word2")
[1] "a b word1 word2"
</code>```

where i would've expected word1aword2 and word1bword2. I have been reading all the function references and I'm currently not sure how to solve this problem.

答:
Why are you "quite sure that invoke is the right function for this task"?

A simple map does:

```<code>set.seed(123) ; res1 <- invoke_map(kmeans, transpose(list(centers = 1:10)), x = iris[1:4])

set.seed(123) ; res2 <- map(1:10, kmeans, x = iris[1:4])

identical(res1, res2)
# [1] TRUE
</code>```

Body:
I want to run the kmeans() function in R with different values of k (kmeans(x = iris[1:4], centers = k)). I know how to do this with dplyr or the do.call() function, however I can't get it to work with purrr::invoke() (I'm quite sure that invoke is the right function for this task). I could of course just use the dplyr approach (see this link), but it annoys me that I can't get it to work with purrr.

In the purrr::invoke() function reference, the following code-example is included:

# Or the same function with different inputs:
invoke_map("runif", list(list(n = 5), list(n = 10)))
#> [[1]]
#> [1] 0.67176682 0.05861411 0.99706914 0.14903547 0.51855664
#>
#> [[2]]
#>  [1] 0.84612005 0.71826972 0.24131402 0.54704337 0.83480182 0.02795603
#>  [7] 0.46938430 0.80568003 0.81405131 0.40391100
#>

When i try to do this with kmeans i get the following

> invoke(kmeans, list(list(centers = 1), list(centers = 2)), x = iris[1:4])
Error in sample.int(m, k) : invalid 'size' argument

I have also tried

> invoke(kmeans, list(centers = 1:5), x = iris[1:4])
Error in (function (x, centers, iter.max = 10L, nstart = 1L,
algorithm = c("Hartigan-Wong",  : must have same number of columns in 'x' and 'centers'

as a reality-check, i also tried doing a similar thing with paste

> invoke(paste, list(list(sep = "a"), list(sep = "b")), "word1", "word2")
[1] "a b word1 word2"

where i would've expected word1aword2 and word1bword2. I have been reading all the function references and I'm currently not sure how to solve this problem.

Body:
Why are you "quite sure that invoke is the right function for this task"?

A simple map does:

set.seed(123) ; res1 <- invoke_map(kmeans, transpose(list(centers = 1:10)), x = iris[1:4])

set.seed(123) ; res2 <- map(1:10, kmeans, x = iris[1:4])

identical(res1, res2)
# [1] TRUE


问:
how to display a bullet list using ionic framework?
Using ionic to build an app, and I have a need to display an actual bullet list:

item 1

item 2

item 3

However, it appears that the framework does some sort of CSS reset / magic on
 and
 elements such that they should only be used as structure elements (e.g. a list), rather  than as UI.

I ended up creating my own unordered-list CSS style to give me the UI I needed. Is that the right way to do-it-yourself - or does ionic have some CSS style buried deep inside that I should have used instead?

ty in advance.

答:
I could not see the bullets either, they were just not on the visible page. Adding some padding fixed it:</p>

```<code><style>
.my-modal-list {
    list-style-type: disc;
    padding: 20px;
}
</style>

<ul class="my-modal-list">
</code>```

Body:
I could not see the bullets either, they were just not on the visible page. Adding some padding fixed it:

<style>
.my-modal-list {
    list-style-type: disc;
    padding: 20px;
}
</style>

<ul class="my-modal-list">


问:
How to break line in JavaScript?
Please let me know how to break line in JavaScript.

```<code><input type='submit' name='Submit' value='Submit'
onClick="parent.location='mailto:er.saurav123@gmail.com?subject=Thanks for writing to me &body=I will get back to you soon. Thanks and Regards Saurav Kumar'">
</code>```

I want a break line in Subject. The output I need is:

```<code>I will get back to you soon
Thanks and Regards
Saurav Kumar
</code>```

答:
Here you are ;-)</p>

```<code><script type="text/javascript">
    alert("Hello there.\nI am on a second line ;-)")
</script>
</code>```

Title: How to break line in JavaScript?

Body:
Please let me know how to break line in JavaScript.

<input type='submit' name='Submit' value='Submit'
onClick="parent.location='mailto:er.saurav123@gmail.com?subject=Thanks for writing to me &body=I will get back to you soon. Thanks and Regards Saurav Kumar'">

I want a break line in Subject. The output I need is:

I will get back to you soon
Thanks and Regards
Saurav Kumar

Body:
Here you are ;-)

<script type="text/javascript">
    alert("Hello there.\nI am on a second line ;-)")
</script>


问:
Kivy: 'NoneType' object is not callable, on button deleting
I'm trying to code in Python with Kivy a simple interface, with 4 elements: a title bar at the top, a text-input at the bottom and next to it a little button "add". Between the top and the bottom I want a scroll view, and when we click on the button next to the text-input, it creates a new button in the scrollview, and next to it a little button to delete the line (line = the button + its delete button)
To understand:

When I click on the "X" button to delete, I have an error:

```<code> Traceback (most recent call last):
   File "nouv_test.py", line 39, in <module>
     RunApp().run()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\app.py", line 828, in run
     runTouchApp()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\base.py", line 504, in runTouchApp
     EventLoop.window.mainloop()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\core\window\window_sdl2.py", line 663, in mainloop
     self._mainloop()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\core\window\window_sdl2.py", line 405, in _mainloop
     EventLoop.idle()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\base.py", line 342, in idle
     self.dispatch_input()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\base.py", line 327, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\base.py", line 233, in post_dispatch_input
     listener.dispatch('on_motion', etype, me)
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\core\window\__init__.py", line 1192, in on_motion
     self.dispatch('on_touch_up', me)
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\core\window\__init__.py", line 1228, in on_touch_up
     if w.dispatch('on_touch_up', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\screenmanager.py", line 1199, in on_touch_up
     return super(ScreenManager, self).on_touch_up(touch)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\widget.py", line 479, in on_touch_up
     if child.dispatch('on_touch_up', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\relativelayout.py", line 304, in on_touch_up
     ret = super(RelativeLayout, self).on_touch_up(touch)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\widget.py", line 479, in on_touch_up
     if child.dispatch('on_touch_up', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\widget.py", line 479, in on_touch_up
     if child.dispatch('on_touch_up', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\scrollview.py", line 833, in on_touch_up
     if self.dispatch('on_scroll_stop', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\scrollview.py", line 872, in on_scroll_stop
     self.simulate_touch_down(touch)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\scrollview.py", line 596, in simulate_touch_down
     ret = super(ScrollView, self).on_touch_down(touch)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\widget.py", line 457, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\widget.py", line 457, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
     self.dispatch('on_press')
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
 TypeError: 'NoneType' object is not callable
</code>```

Here are my code (.py / .kv):

```<code># coding: utf-8

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder

from kivy.uix.button import Button

class GUI(ScreenManager):
    def __init__(self, **kwargs):
        super(GUI, self).__init__(**kwargs)

class Home(Screen):

    def __init__(self, **kwargs):
        super(Home, self).__init__(**kwargs)

    def add_btn(self, grid):
        left = Button(text="added", size = (32, 32), size_hint = (1, None)) # the green button
        right = Button(background_color = (1,0,0,1), text="X", size = (32, 32), size_hint = (None, None)) # the red DELETE button

        right.on_press = self.del_btn(grid, left, right)

        grid.add_widget(left)
        grid.add_widget(right)

    def del_btn(self, grid, L, R): # function called when I click on delete a line
        grid.remove_widget(L)
        grid.remove_widget(R)

Builder.load_file("nouv_test.kv")

class RunApp(App):
    def build(self):
        return GUI()

if __name__ == '__main__':
    RunApp().run()
</code>```

.KV:

```<code> #: kivy 1.10.0

    <GUI>:
        Home:
            name: "home_screen"
            id: home

    <Home>:

        GridLayout:
            rows: 3

            Button:
                text: u"Mes ann\u00e9es"
                size: (50, 50)
                size_hint: (1, None)
                background_color: (0,1,0,1)

            ScrollView:

                size_hint:(1, .8)
                pos_hint: {'center_x': 0.5, 'center_y': 0.5}
                do_scroll_x: False

                GridLayout:
                    id: home_scroll_grid
                    cols: 2
                    padding: 5
                    spacing: 5
                    height: self.minimum_height
                    size_hint: (1, None)

            BoxLayout:

                padding: 5
                spacing: 5
                size: (42, 42)
                size_hint: (1, None)

                TextInput:
                    size: (32, 32)
                    size_hint: (1, None)

                Button:
                    text: "+"
                    background_color: (0,1,0,1)
                    size: (32, 32)
                    size_hint: (None, None)
                    on_press: root.add_btn(home_scroll_grid)
</code>```

答:
You get a NoneType error, because in this statement: right.on_press = self.del_btn(grid, left, right), you actually called del_btn, and it returns nothing.

on_press takes a callable, not a called function. So it should rather look like this: right.on_press = self.del_btn.

But since you need to pass arguments to your callback, you can use partial.

And then use .bind instead of assigning to on_press.

Like this:

from functools import partial
```

<p>Then:</p>

<pre class="lang-python prettyprint-override"><code>right.bind(on_press=partial(self.del_btn, grid, left, right))
</code>```

Body:
I'm trying to code in Python with Kivy a simple interface, with 4 elements: a title bar at the top, a text-input at the bottom and next to it a little button "add". Between the top and the bottom I want a scroll view, and when we click on the button next to the text-input, it creates a new button in the scrollview, and next to it a little button to delete the line (line = the button + its delete button)
To understand:

When I click on the "X" button to delete, I have an error:

 Traceback (most recent call last):
   File "nouv_test.py", line 39, in <module>
     RunApp().run()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\app.py", line 828, in run
     runTouchApp()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\base.py", line 504, in runTouchApp
     EventLoop.window.mainloop()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\core\window\window_sdl2.py", line 663, in mainloop
     self._mainloop()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\core\window\window_sdl2.py", line 405, in _mainloop
     EventLoop.idle()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\base.py", line 342, in idle
     self.dispatch_input()
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\base.py", line 327, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\base.py", line 233, in post_dispatch_input
     listener.dispatch('on_motion', etype, me)
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\core\window\__init__.py", line 1192, in on_motion
     self.dispatch('on_touch_up', me)
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\core\window\__init__.py", line 1228, in on_touch_up
     if w.dispatch('on_touch_up', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\screenmanager.py", line 1199, in on_touch_up
     return super(ScreenManager, self).on_touch_up(touch)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\widget.py", line 479, in on_touch_up
     if child.dispatch('on_touch_up', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\relativelayout.py", line 304, in on_touch_up
     ret = super(RelativeLayout, self).on_touch_up(touch)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\widget.py", line 479, in on_touch_up
     if child.dispatch('on_touch_up', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\widget.py", line 479, in on_touch_up
     if child.dispatch('on_touch_up', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\scrollview.py", line 833, in on_touch_up
     if self.dispatch('on_scroll_stop', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\scrollview.py", line 872, in on_scroll_stop
     self.simulate_touch_down(touch)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\scrollview.py", line 596, in simulate_touch_down
     ret = super(ScrollView, self).on_touch_down(touch)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\widget.py", line 457, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\widget.py", line 457, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
   File "C:\Users\dvfrg\AppData\Local\Programs\Python\Python36\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
     self.dispatch('on_press')
   File "kivy\_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8191)
 TypeError: 'NoneType' object is not callable

Here are my code (.py / .kv):

# coding: utf-8

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder

from kivy.uix.button import Button

class GUI(ScreenManager):
    def __init__(self, **kwargs):
        super(GUI, self).__init__(**kwargs)

class Home(Screen):

    def __init__(self, **kwargs):
        super(Home, self).__init__(**kwargs)

    def add_btn(self, grid):
        left = Button(text="added", size = (32, 32), size_hint = (1, None)) # the green button
        right = Button(background_color = (1,0,0,1), text="X", size = (32, 32), size_hint = (None, None)) # the red DELETE button

        right.on_press = self.del_btn(grid, left, right)

        grid.add_widget(left)
        grid.add_widget(right)

    def del_btn(self, grid, L, R): # function called when I click on delete a line
        grid.remove_widget(L)
        grid.remove_widget(R)

Builder.load_file("nouv_test.kv")

class RunApp(App):
    def build(self):
        return GUI()

if __name__ == '__main__':
    RunApp().run()

.KV:

 #: kivy 1.10.0

    <GUI>:
        Home:
            name: "home_screen"
            id: home

    <Home>:

        GridLayout:
            rows: 3

            Button:
                text: u"Mes ann\u00e9es"
                size: (50, 50)
                size_hint: (1, None)
                background_color: (0,1,0,1)

            ScrollView:

                size_hint:(1, .8)
                pos_hint: {'center_x': 0.5, 'center_y': 0.5}
                do_scroll_x: False

                GridLayout:
                    id: home_scroll_grid
                    cols: 2
                    padding: 5
                    spacing: 5
                    height: self.minimum_height
                    size_hint: (1, None)

            BoxLayout:

                padding: 5
                spacing: 5
                size: (42, 42)
                size_hint: (1, None)

                TextInput:
                    size: (32, 32)
                    size_hint: (1, None)

                Button:
                    text: "+"
                    background_color: (0,1,0,1)
                    size: (32, 32)
                    size_hint: (None, None)
                    on_press: root.add_btn(home_scroll_grid)

Body:
You get a NoneType error, because in this statement: right.on_press = self.del_btn(grid, left, right), you actually called del_btn, and it returns nothing.

on_press takes a callable, not a called function. So it should rather look like this: right.on_press = self.del_btn.

But since you need to pass arguments to your callback, you can use partial.

And then use .bind instead of assigning to on_press.

Like this:

from functools import partial

Then:

right.bind(on_press=partial(self.del_btn, grid, left, right))


问:
Does Firebase support overwritten setter methods?
Can you use overwritten setter methods in your Java object (e.g. one that takes a String object and one that takes an int)? if you are going to load and read your object from the Firebase database? Does Firebase know which to use or is it all treated as int/String?

e.g:

```<code>public void setAppointStartTime(String appointStartTime) {
    this.appointStartTime = appointStartTime;
}

public void setAppointStartTime(int minutes) {
    this.appointStartTime = String.format("%02d",((minutes - (minutes % 60)) / 60)) + ":" + (String.format("%02d",(minutes%60)));
}
</code>```

答:
From the docs:

For basic write operations, you can use setValue() to save data to a
  specified reference, replacing any existing data at that path. You can
  use this method to:

Pass types that correspond to the available JSON types as follows:

String

Long

Double

Boolean

Map

List

Pass a
  custom Java object, if the class that defines it has a default
  constructor that takes no arguments and has public getters for the
  properties to be assigned.

Body:
Can you use overwritten setter methods in your Java object (e.g. one that takes a String object and one that takes an int)? if you are going to load and read your object from the Firebase database? Does Firebase know which to use or is it all treated as int/String?

e.g:

public void setAppointStartTime(String appointStartTime) {
    this.appointStartTime = appointStartTime;
}

public void setAppointStartTime(int minutes) {
    this.appointStartTime = String.format("%02d",((minutes - (minutes % 60)) / 60)) + ":" + (String.format("%02d",(minutes%60)));
}


问:
Is there a list for known CLSIDs of the windows registry?
In the windows registry reside many CLSID values (in HKEY_CLASSES_ROOT\CLSID) such as {16d51579-a30b-4c8b-a276-0ff4dc41e755}, many of which may belong to widely known or even built-in applications or libraries. Is there a list or database that contains a mapping of these?

Some usages would be, to present a more meaningful name in a registry viewer along with the key, or checking whether a particular application is present (or was present and not anymore) but has left some keys in the registry.

答:
It's in the registry. You could try:

```<code>Get-ItemProperty -Path "HKLM:\SOFTWARE\Classes\CLSID\*" `
    |select PSChildName,`(default`) |ft -auto *
</code>```

HKEY_CLASSES_ROOT is an alias for HKEY_LOCAL_MACHINE\SOFTWARE\Classes. There're other words stored in various key values under each CLSID, so you could get cleverer with the PowerShell, but this is a start.

Body:
It's in the registry. You could try:

Get-ItemProperty -Path "HKLM:\SOFTWARE\Classes\CLSID\*" `
    |select PSChildName,`(default`) |ft -auto *

HKEY_CLASSES_ROOT is an alias for HKEY_LOCAL_MACHINE\SOFTWARE\Classes. There're other words stored in various key values under each CLSID, so you could get cleverer with the PowerShell, but this is a start.

ContentLicense: CC BY-SA 4.0


问:
Trying to send checkbox value(s) from form to email in PHP
It has been years since I was in web development but have dabbled in PHP in the past, so I guess you could say I am a newbie at PHP. I am trying to build a simple form for a job application using PHP I want the form to be filled out and then emailed upon submit.

I have researched this site as well as others and am unable to get this to work. I cannot get the job value to show up in email:

Here is my HTML code:

```<code>            <label>Position: check all you are interested in </label><br>
            <input type="checkbox" name="job[]" value="General Pickle Production">General Pickle Production
            <input type="checkbox" name="job[]" value="Fryer">Fryer
            <input type="checkbox" name="job[]" value="Sales">Sales
            <input type="checkbox" name="job[]" value="Manager">Manager
            <input type="checkbox" name="job[]" value="Overnights">Overnights<br>
</code>```

Here is my PHP code:

```<code>    $aJob = $_POST['job'];
     if(empty($aJob))
   {
     echo("You didn't select any job position.");
   }
   else
   {
     $N = count($aJob);

     echo("You selected $N job(s): ");
     for($i=0; $i < $N; $i++)
     {
       echo($aJob[$i] . " ");
     }
   }
</code>```

When I hit submit on the form the above will show each job selected on the form page but I guess I am not sure how to send this to my email upon the submit. Below is the code I have sending the variables to my email:

```<code>    $content = $_POST['name'] . " " . $_POST['lastname'] . " \n";
    $content .= $_POST['address'] . " \n";
    $content .= "Position(s) applied for: " . $_POST['aJob'] . " \n";
</code>```

Do I need to put my for loop in $content section somewhere to display the jobs? I guess I am not sure what that format would look like here?

I appreciate any help you could offer.
Thank you. J

答:
In your example you use name="job[]" for the input elements. To get the values from the $_POST array, I think you should use $_POST['job'] instead of $_POST['aJob'].

If you want to separate them by comma, you could for example do it like this using implode:

```<code>if (isset($_POST['job'])) {
    $content .= "Position(s) applied for: " . implode(",", $_POST['job']) . " \n";
}
</code>```

Body:
It has been years since I was in web development but have dabbled in PHP in the past, so I guess you could say I am a newbie at PHP. I am trying to build a simple form for a job application using PHP I want the form to be filled out and then emailed upon submit.

I have researched this site as well as others and am unable to get this to work. I cannot get the job value to show up in email:

Here is my HTML code:

            Position: check all you are interested in

            <input type="checkbox" name="job[]" value="General Pickle Production">General Pickle Production
            <input type="checkbox" name="job[]" value="Fryer">Fryer
            <input type="checkbox" name="job[]" value="Sales">Sales
            <input type="checkbox" name="job[]" value="Manager">Manager
            <input type="checkbox" name="job[]" value="Overnights">Overnights

Here is my PHP code:

    $aJob = $_POST['job'];
     if(empty($aJob))
   {
     echo("You didn't select any job position.");
   }
   else
   {
     $N = count($aJob);

     echo("You selected $N job(s): ");
     for($i=0; $i < $N; $i++)
     {
       echo($aJob[$i] . " ");
     }
   }

When I hit submit on the form the above will show each job selected on the form page but I guess I am not sure how to send this to my email upon the submit. Below is the code I have sending the variables to my email:

    $content = $_POST['name'] . " " . $_POST['lastname'] . " \n";
    $content .= $_POST['address'] . " \n";
    $content .= "Position(s) applied for: " . $_POST['aJob'] . " \n";

Do I need to put my for loop in $content section somewhere to display the jobs? I guess I am not sure what that format would look like here?

I appreciate any help you could offer.
Thank you. J

Body:
In your example you use name="job[]" for the input elements. To get the values from the $_POST array, I think you should use $_POST['job'] instead of $_POST['aJob'].

If you want to separate them by comma, you could for example do it like this using implode:

if (isset($_POST['job'])) {
    $content .= "Position(s) applied for: " . implode(",", $_POST['job']) . " \n";
}


问:
Explain postgres query, why is the query that much longer with WHERE and LIMIT
I'm using postgres v9.6.5. I have a query which seems not that complicated and was wondering why is it so "slow" (it's not really that slow, but I don't have a lot of data actually - like a few thousand rows).

Here is the query:

```<code>SELECT o0.*
FROM "orders" AS o0
JOIN "balances" AS b1 ON b1."id" = o0."balance_id"
JOIN "users" AS u3 ON u3."id" = b1."user_id"
WHERE (u3."partner_id" = 3)
ORDER BY o0."id" DESC LIMIT 10;
</code>```

And that's query plan:

```<code>Limit  (cost=0.43..12.84 rows=10 width=148) (actual time=0.062..53.866 rows=4 loops=1)
  ->  Nested Loop  (cost=0.43..4750.03 rows=3826 width=148) (actual time=0.061..53.864 rows=4 loops=1)
        Join Filter: (b1.user_id = u3.id)
        Rows Removed by Join Filter: 67404
        ->  Nested Loop  (cost=0.43..3945.32 rows=17856 width=152) (actual time=0.025..38.457 rows=16852 loops=1)
              ->  Index Scan Backward using orders_pkey on orders o0  (cost=0.29..897.80 rows=17856 width=148) (actual time=0.016..11.558 rows=16852 loops=1)
              ->  Index Scan using balances_pkey on balances b1  (cost=0.14..0.16 rows=1 width=8) (actual time=0.001..0.001 rows=1 loops=16852)
                    Index Cond: (id = o0.balance_id)
        ->  Materialize  (cost=0.00..1.19 rows=3 width=4) (actual time=0.000..0.000 rows=4 loops=16852)
              ->  Seq Scan on users u3  (cost=0.00..1.18 rows=3 width=4) (actual time=0.023..0.030 rows=4 loops=1)
                    Filter: (partner_id = 3)
                    Rows Removed by Filter: 12
Planning time: 0.780 ms
Execution time: 54.053 ms
</code>```

I actually tried without LIMIT and I got quite different plan:

```<code>Sort  (cost=874.23..883.80 rows=3826 width=148) (actual time=11.361..11.362 rows=4 loops=1)
  Sort Key: o0.id DESC
  Sort Method: quicksort  Memory: 26kB
  ->  Hash Join  (cost=3.77..646.55 rows=3826 width=148) (actual time=11.300..11.346 rows=4 loops=1)
        Hash Cond: (o0.balance_id = b1.id)
        ->  Seq Scan on orders o0  (cost=0.00..537.56 rows=17856 width=148) (actual time=0.012..8.464 rows=16852 loops=1)
        ->  Hash  (cost=3.55..3.55 rows=18 width=4) (actual time=0.125..0.125 rows=24 loops=1)
              Buckets: 1024  Batches: 1  Memory Usage: 9kB
              ->  Hash Join  (cost=1.21..3.55 rows=18 width=4) (actual time=0.046..0.089 rows=24 loops=1)
                    Hash Cond: (b1.user_id = u3.id)
                    ->  Seq Scan on balances b1  (cost=0.00..1.84 rows=84 width=8) (actual time=0.011..0.029 rows=96 loops=1)
                    ->  Hash  (cost=1.18..1.18 rows=3 width=4) (actual time=0.028..0.028 rows=4 loops=1)
                          Buckets: 1024  Batches: 1  Memory Usage: 9kB
                          ->  Seq Scan on users u3  (cost=0.00..1.18 rows=3 width=4) (actual time=0.014..0.021 rows=4 loops=1)
                                Filter: (partner_id = 3)
                                Rows Removed by Filter: 12
Planning time: 0.569 ms
Execution time: 11.420 ms
</code>```

And also without WHERE (but with LIMIT):

```<code>Limit  (cost=0.43..4.74 rows=10 width=148) (actual time=0.023..0.066 rows=10 loops=1)
  ->  Nested Loop  (cost=0.43..7696.26 rows=17856 width=148) (actual time=0.022..0.065 rows=10 loops=1)
        Join Filter: (b1.user_id = u3.id)
        Rows Removed by Join Filter: 139
        ->  Nested Loop  (cost=0.43..3945.32 rows=17856 width=152) (actual time=0.009..0.029 rows=10 loops=1)
              ->  Index Scan Backward using orders_pkey on orders o0  (cost=0.29..897.80 rows=17856 width=148) (actual time=0.007..0.015 rows=10 loops=1)
              ->  Index Scan using balances_pkey on balances b1  (cost=0.14..0.16 rows=1 width=8) (actual time=0.001..0.001 rows=1 loops=10)
                    Index Cond: (id = o0.balance_id)
        ->  Materialize  (cost=0.00..1.21 rows=14 width=4) (actual time=0.001..0.001 rows=15 loops=10)
              ->  Seq Scan on users u3  (cost=0.00..1.14 rows=14 width=4) (actual time=0.005..0.007 rows=16 loops=1)
Planning time: 0.286 ms
Execution time: 0.097 ms
</code>```

As you can see, without WHERE it's much faster. Can someone provide me with some information where can I look for explanations for those plans to better understand them? And also what can I do to make those queries faster (or I shouldn't worry cause with like 100 times more data they will still be fast enough? - 50ms is fine for me tbh)

答:
PostgreSQL thinks that it will be fastest if it scans orders in the correct order until it finds a matching users entry that satisfies the WHERE condition.

However, it seems that the data distribution is such that it has to scan almost 17000 orders before it finds a match.

Since PostgreSQL doesn't know how values correlate across tables, there is nothing much you can do to change that.

You can force PostgreSQL to plan the query without the LIMIT clause like this:

```<code>SELECT *
FROM (<your query without ORDER BY and LIMIT> OFFSET 0) q
ORDER BY id DESC LIMIT 10;
</code>```

With a top-N-sort this should perform better.

Body:
I'm using postgres v9.6.5. I have a query which seems not that complicated and was wondering why is it so "slow" (it's not really that slow, but I don't have a lot of data actually - like a few thousand rows).

Here is the query:

SELECT o0.*
FROM "orders" AS o0
JOIN "balances" AS b1 ON b1."id" = o0."balance_id"
JOIN "users" AS u3 ON u3."id" = b1."user_id"
WHERE (u3."partner_id" = 3)
ORDER BY o0."id" DESC LIMIT 10;

And that's query plan:

Limit  (cost=0.43..12.84 rows=10 width=148) (actual time=0.062..53.866 rows=4 loops=1)
  ->  Nested Loop  (cost=0.43..4750.03 rows=3826 width=148) (actual time=0.061..53.864 rows=4 loops=1)
        Join Filter: (b1.user_id = u3.id)
        Rows Removed by Join Filter: 67404
        ->  Nested Loop  (cost=0.43..3945.32 rows=17856 width=152) (actual time=0.025..38.457 rows=16852 loops=1)
              ->  Index Scan Backward using orders_pkey on orders o0  (cost=0.29..897.80 rows=17856 width=148) (actual time=0.016..11.558 rows=16852 loops=1)
              ->  Index Scan using balances_pkey on balances b1  (cost=0.14..0.16 rows=1 width=8) (actual time=0.001..0.001 rows=1 loops=16852)
                    Index Cond: (id = o0.balance_id)
        ->  Materialize  (cost=0.00..1.19 rows=3 width=4) (actual time=0.000..0.000 rows=4 loops=16852)
              ->  Seq Scan on users u3  (cost=0.00..1.18 rows=3 width=4) (actual time=0.023..0.030 rows=4 loops=1)
                    Filter: (partner_id = 3)
                    Rows Removed by Filter: 12
Planning time: 0.780 ms
Execution time: 54.053 ms

I actually tried without LIMIT and I got quite different plan:

Sort  (cost=874.23..883.80 rows=3826 width=148) (actual time=11.361..11.362 rows=4 loops=1)
  Sort Key: o0.id DESC
  Sort Method: quicksort  Memory: 26kB
  ->  Hash Join  (cost=3.77..646.55 rows=3826 width=148) (actual time=11.300..11.346 rows=4 loops=1)
        Hash Cond: (o0.balance_id = b1.id)
        ->  Seq Scan on orders o0  (cost=0.00..537.56 rows=17856 width=148) (actual time=0.012..8.464 rows=16852 loops=1)
        ->  Hash  (cost=3.55..3.55 rows=18 width=4) (actual time=0.125..0.125 rows=24 loops=1)
              Buckets: 1024  Batches: 1  Memory Usage: 9kB
              ->  Hash Join  (cost=1.21..3.55 rows=18 width=4) (actual time=0.046..0.089 rows=24 loops=1)
                    Hash Cond: (b1.user_id = u3.id)
                    ->  Seq Scan on balances b1  (cost=0.00..1.84 rows=84 width=8) (actual time=0.011..0.029 rows=96 loops=1)
                    ->  Hash  (cost=1.18..1.18 rows=3 width=4) (actual time=0.028..0.028 rows=4 loops=1)
                          Buckets: 1024  Batches: 1  Memory Usage: 9kB
                          ->  Seq Scan on users u3  (cost=0.00..1.18 rows=3 width=4) (actual time=0.014..0.021 rows=4 loops=1)
                                Filter: (partner_id = 3)
                                Rows Removed by Filter: 12
Planning time: 0.569 ms
Execution time: 11.420 ms

And also without WHERE (but with LIMIT):

Limit  (cost=0.43..4.74 rows=10 width=148) (actual time=0.023..0.066 rows=10 loops=1)
  ->  Nested Loop  (cost=0.43..7696.26 rows=17856 width=148) (actual time=0.022..0.065 rows=10 loops=1)
        Join Filter: (b1.user_id = u3.id)
        Rows Removed by Join Filter: 139
        ->  Nested Loop  (cost=0.43..3945.32 rows=17856 width=152) (actual time=0.009..0.029 rows=10 loops=1)
              ->  Index Scan Backward using orders_pkey on orders o0  (cost=0.29..897.80 rows=17856 width=148) (actual time=0.007..0.015 rows=10 loops=1)
              ->  Index Scan using balances_pkey on balances b1  (cost=0.14..0.16 rows=1 width=8) (actual time=0.001..0.001 rows=1 loops=10)
                    Index Cond: (id = o0.balance_id)
        ->  Materialize  (cost=0.00..1.21 rows=14 width=4) (actual time=0.001..0.001 rows=15 loops=10)
              ->  Seq Scan on users u3  (cost=0.00..1.14 rows=14 width=4) (actual time=0.005..0.007 rows=16 loops=1)
Planning time: 0.286 ms
Execution time: 0.097 ms

As you can see, without WHERE it's much faster. Can someone provide me with some information where can I look for explanations for those plans to better understand them? And also what can I do to make those queries faster (or I shouldn't worry cause with like 100 times more data they will still be fast enough? - 50ms is fine for me tbh)

Body:
PostgreSQL thinks that it will be fastest if it scans orders in the correct order until it finds a matching users entry that satisfies the WHERE condition.

However, it seems that the data distribution is such that it has to scan almost 17000 orders before it finds a match.

Since PostgreSQL doesn't know how values correlate across tables, there is nothing much you can do to change that.

You can force PostgreSQL to plan the query without the LIMIT clause like this:

SELECT *
FROM (<your query without ORDER BY and LIMIT> OFFSET 0) q
ORDER BY id DESC LIMIT 10;

With a top-N-sort this should perform better.


问:
SQL Pivot: Combine One Column Content Concatenated into One Cell
I have a table with ID's in Column 1 and Codes in Column 2.  I'm Looking to get a list of the ID's with the code combination in the next column.  Example of the data can be found below:

```<code>ID  Code
211  901
211  902
211  903
208  605
208  606
</code>```

The Result I want would look like this, with the code combinations in one column:

```<code>ID     Code_Combo
211    901/902/903
208    605/606
</code>```

Any ideas?  Pretty lost here.

答:
Here is an example that uses your values. I used the XML PATH example outlined in the first answer of this post.</p>

```<code>CREATE TABLE #Test (ID int, Code int)

INSERT INTO #Test (ID, Code) VALUES
(211, 901),
(211, 902),
(211, 903),
(208, 605),
(208, 606)

SELECT
    ID,
    SUBSTRING(Codes, 2, LEN(Codes)) AS 'Codes'
FROM
    (
        SELECT DISTINCT ID,
            (
                SELECT '/' + CAST(Code AS varchar(10))
                FROM #Test AS MTI
                WHERE MTI.ID = MTO.ID
                ORDER BY MTI.ID
                FOR XML PATH ('')
            ) Codes
        FROM #Test AS MTO
    ) AS Final

DROP TABLE #Test
</code>```

Body:
I have a table with ID's in Column 1 and Codes in Column 2.  I'm Looking to get a list of the ID's with the code combination in the next column.  Example of the data can be found below:

ID  Code
211  901
211  902
211  903
208  605
208  606

The Result I want would look like this, with the code combinations in one column:

ID     Code_Combo
211    901/902/903
208    605/606

Any ideas?  Pretty lost here.

Body:
Here is an example that uses your values. I used the XML PATH example outlined in the first answer of this post.

CREATE TABLE #Test (ID int, Code int)

INSERT INTO #Test (ID, Code) VALUES
(211, 901),
(211, 902),
(211, 903),
(208, 605),
(208, 606)

SELECT
    ID,
    SUBSTRING(Codes, 2, LEN(Codes)) AS 'Codes'
FROM
    (
        SELECT DISTINCT ID,
            (
                SELECT '/' + CAST(Code AS varchar(10))
                FROM #Test AS MTI
                WHERE MTI.ID = MTO.ID
                ORDER BY MTI.ID
                FOR XML PATH ('')
            ) Codes
        FROM #Test AS MTO
    ) AS Final

DROP TABLE #Test


问:
How to allow text-selection of a DIV, but prevent the text-selection of the father DIV?
I would like to allow the users to select text that resides in multiple DIVs that are located one after the other with small gaps between them.
the problem is, that when the user drags the mouse to perform the selection, they pass over the "gaps", which causes the whole parent DIV is selected momentarily, until they enter into the following child DIV.
This causes "flickers" behaviour and bad user experience, because the parent DIV also has images, and for a moment, all of the images are being selected too.
I tried several method suggested in this forum, including:
-moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none;  user-select: none;
unselectable=on, and overriding the event onselectstart: return false;
Unfortunately, if I were to disable selecting text in the parent DIV, all the children DIVs immediately adopted that behaviour, and that is not what I meant.
I want that the parent DIV won't be selected, but its children will.
Thanks

Update:

The "onselectstart" is called only for the parent DIV (and spans/paragraphs beneath it), but it is NOT called when the image is being selected. Therefore, trying to manipulate it and use "return false;" is not relevant; the image simply won't get that event.

答:
-moz-user-select: -moz-none - The text of the element and sub-elements cannot be selected, but selection can be enabled on sub-elements using -moz-user-select:text.

Set -webkit-user-select: text for the children.

The unselectable attribute is not inherited.

Set onselectstart = null for the children, or if you are using listeners - check the target before returning false.

ContentLicense: CC BY-SA 2.5


问:
css being applied to all elements in array
When I run this function the CSS is being applied to all the buttons. How do I modify so that the CSS only gets modified for the buttons where the buttonAttr attribute equals disabled?</p>

```<code>$('.product_tile .addtocartbutton').each(function(){
    var $this = $(this);
    var buttonAttr = $this.attr('disabled');

    if($this.attr('disabled') = 'disabled'){
        $this.css('background','#ccc');
    } else {
        $this.css('background','#EEDED1');
    }
});
</code>```

答:
I would suggest this small modification;

```<code>$('.product_tile .addtocartbutton').each(function(){
    var $this = $(this);

    if($this.is(":disabled")){
        $this.css('background','#ccc');
    } else {
        $this.css('background','#EEDED1');
    }
});
</code>```

This takes advantage of the jquery :disabled selector, link to documentation.

Edit:
Another option is a solely CSS solution, taking advantage of the attribute selector

input[type='button'] {
  background: #eeded1;
}

input[type='button'][disabled] {
  background: #ccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type='button' value='Disabled' disabled='disabled' /><br /><br />
<input type='button' value='Active' /></code>```

Body:
When I run this function the CSS is being applied to all the buttons. How do I modify so that the CSS only gets modified for the buttons where the buttonAttr attribute equals disabled?

$('.product_tile .addtocartbutton').each(function(){
    var $this = $(this);
    var buttonAttr = $this.attr('disabled');

    if($this.attr('disabled') = 'disabled'){
        $this.css('background','#ccc');
    } else {
        $this.css('background','#EEDED1');
    }
});

Body:
I would suggest this small modification;

$('.product_tile .addtocartbutton').each(function(){
    var $this = $(this);

    if($this.is(":disabled")){
        $this.css('background','#ccc');
    } else {
        $this.css('background','#EEDED1');
    }
});

This takes advantage of the jquery :disabled selector, link to documentation.

Edit:
Another option is a solely CSS solution, taking advantage of the attribute selector

input[type='button'] {
  background: #eeded1;
}

input[type='button'][disabled] {
  background: #ccc;
}

<input type='button' value='Disabled' disabled='disabled' /><br /><br />
<input type='button' value='Active' />


问:
How do you handle files in a django test
I have a model that has a file field and I've been more or less testing the model like so:

```<code>def test_importing_file_and_processing(self):
    file_path = os.path.join(settings.BASE_DIR,
                             'myapp/tests/reports/test_input_file')
    report = IngestedFile(
        filename='test_file'
    )
    report.document.save('test_file', File(open(file_path)))
    report.save()
    report.do_stuff()
    self.assertStuf....
</code>```

Is there a "better" way to test the file? The way I'm testing things does look a little hacky.

答:
You can use tempfile module

```<code>import tempfile

tmp_file = tempfile.NamedTemporaryFile(suffix='.pdf')

with open(tmp_file.name, 'w') as f:
    f.write('test_content')

report.document = tmp_file
</code>```

or you can create isolated function for that

```<code>def generate_test_file(file_format='.pdf'):

    tmp_file = tempfile.NamedTemporaryFile(suffix=file_format)

    with open(tmp_file.name, 'w') as f:
        f.write('test_content')

    return tmp_file
</code>```

Body:
I have a model that has a file field and I've been more or less testing the model like so:

def test_importing_file_and_processing(self):
    file_path = os.path.join(settings.BASE_DIR,
                             'myapp/tests/reports/test_input_file')
    report = IngestedFile(
        filename='test_file'
    )
    report.document.save('test_file', File(open(file_path)))
    report.save()
    report.do_stuff()
    self.assertStuf....

Is there a "better" way to test the file? The way I'm testing things does look a little hacky.

Body:
You can use tempfile module

import tempfile

tmp_file = tempfile.NamedTemporaryFile(suffix='.pdf')

with open(tmp_file.name, 'w') as f:
    f.write('test_content')

report.document = tmp_file

or you can create isolated function for that

def generate_test_file(file_format='.pdf'):

    tmp_file = tempfile.NamedTemporaryFile(suffix=file_format)

    with open(tmp_file.name, 'w') as f:
        f.write('test_content')

    return tmp_file


问:
Is there any performance Impact of using spring boot web app with JDBC ignite instead of dot NET native approach of connecting to ignite?

Currently we are using the dot NET(c#) code to connect to Apache Ignite cluster using native approach as mentioned here dot NET Apache Ignite native client approach.

Now we have planned to migrate this dot NET code to Spring boot web app (Java) using JDBC approach of connecting to Apache Ignite  but wanted to know doing this same  will it have any performance drawbacks/benefits as compared to dot Net Native client approach of connecting to Apache Ignite ?

答:
Native .NET client runs JVM in process and interacts with it directly through shared memory.

JDBC Thin driver connects to Ignite node through a TCP socket, which is slower in general and has more overhead.

But you should measure your specific use case to make a decision.


问:
Using for loop for Rock Paper Scissors Game Java
I have been interested in Java for around 2 months now as I have done some courses online, I'm trying to create a game for Rock Paper Scissors. I want the game to be able to run 5 times by using the for loop, though I'm having trouble looping it; it keeps declaring the winner instead of repeating the game?

```<code>import java.util.Scanner;
import java.io.*;

public class Part2
{

    public static void main (String[]args)
    {
        Scanner scan = new Scanner(System.in);

        String userInput1 = " ";
        char player1Input;

        String userInput2 = " ";
        char player2Input;

        for(int i = 0; i < 5; i++) //Loop for game
        {

        System.out.println("Player 1: Please Enter e.g R for Rock:");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput1 = scan.next();
        player1Input = userInput1.charAt(0);

        System.out.println("Player 2: Please Enter e.g S for Scissors");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput2 = scan.next();
        player2Input = userInput2.charAt(0);

        }

        switch(player1Input)
        {
            case 'R':  System.out.println ("Player 1:Rock");

                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is Draw");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 1 Wins");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'P' : System.out.println ("Player 1:Paper");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Draw");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 2 Wins2");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'S' : System.out.println ("Player 1:Scissors");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println ("The Game Result is: Draw");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

        }
    }
}
</code>```

答: The switch statement is out of scope, which means that the program doesn't know where to look for it and for all intents and purposes, it's invisible to the program and the loop. If you move the bracket after the for loop to after the switch statement, it should run just fine. </p>

Body:
I have been interested in Java for around 2 months now as I have done some courses online, I'm trying to create a game for Rock Paper Scissors. I want the game to be able to run 5 times by using the for loop, though I'm having trouble looping it; it keeps declaring the winner instead of repeating the game?

import java.util.Scanner;
import java.io.*;

public class Part2
{

    public static void main (String[]args)
    {
        Scanner scan = new Scanner(System.in);

        String userInput1 = " ";
        char player1Input;

        String userInput2 = " ";
        char player2Input;

        for(int i = 0; i < 5; i++) //Loop for game
        {

        System.out.println("Player 1: Please Enter e.g R for Rock:");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput1 = scan.next();
        player1Input = userInput1.charAt(0);

        System.out.println("Player 2: Please Enter e.g S for Scissors");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput2 = scan.next();
        player2Input = userInput2.charAt(0);

        }

        switch(player1Input)
        {
            case 'R':  System.out.println ("Player 1:Rock");

                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is Draw");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 1 Wins");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'P' : System.out.println ("Player 1:Paper");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Draw");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 2 Wins2");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'S' : System.out.println ("Player 1:Scissors");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println ("The Game Result is: Draw");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

        }
    }
}


问:
Angular 4 add click event on button dynamically
Here is the code of button displayed from loop.

```<code>for( let k=0; k<this.newTmpArr.length; k++ ){
    myTable += "<tr>";
    for( let key2 in this.newTmpArr[k] ){
        if(this.newTmpArr[k][key2] == 'button' ){
          myTable += `<td><button (click)="test()">Click</button></td>`;
          break;
        }
        if(this.newTmpArr[k][key2] == 'link' ){
          myTable += `<td><a href="#" (click)="test()">Click</a></td>`;
          break;
        } else {
          myTable += "<td>" + this.newTmpArr[k][key2] + "</td>";
        }

    }
    myTable += "</tr>";
}

test(){
  alert("Working!");
}
</code>```

Here is the screenshot of the page look like after dynamic data rendered.

答:
I'm going to go ahead and post the way I feel this should be done, in the angular way.  Writing html in code almost always means you're doing something wrong.  This is template logic that should be done IN TEMPLATE, like this:

```<code><tr *ngFor="let row of newTmpArr">
  <td *ngFor="let cell of row">
    <ng-container [ngSwitch]="cell">
      <button *ngSwitchCase="'button'" (click)="test()">Click</button>
      <a *ngSwitchCase="'link'" href="#" (click)="test()">Click</a>
      <ng-container *ngSwitchDefault>{{ cell }}</ng-container>
    </ng-container>
  </td>
</tr>
</code>```

This is the angular way of achieving your goal, all done in template, using nested ng for loops and then an ngSwitch is the appropriate directive for this use case since you have 2 options and a default.  Now you do not need to fight the framework or use any hacks like binding functions to the window. Angular will bind functions appropriately using this method.  You also have the distinct advantage of your display being model driven, so you only need to ever update your model and the display will react accordingly, so you never need to worry about display and model falling out of sync.

For example if you were to remove row 5, you would need to manually redraw your table after updating your model, same if you added a new row, or if you edit cell 2 of row 3.  Using template, angular manages all of this in a transparent and reliable manner.

Body:
Here is the code of button displayed from loop.

for( let k=0; k<this.newTmpArr.length; k++ ){
    myTable += "
";
    for( let key2 in this.newTmpArr[k] ){
        if(this.newTmpArr[k][key2] == 'button' ){
          myTable += `<td><button (click)="test()">Click</button></td>`;
          break;
        }
        if(this.newTmpArr[k][key2] == 'link' ){
          myTable += `<td><a href="#" (click)="test()">Click</a></td>`;
          break;
        } else {
          myTable += "" + this.newTmpArr[k][key2] + "	";
        }

    }
    myTable += "
";
}

test(){
  alert("Working!");
}

Here is the screenshot of the page look like after dynamic data rendered.

Body:
I'm going to go ahead and post the way I feel this should be done, in the angular way.  Writing html in code almost always means you're doing something wrong.  This is template logic that should be done IN TEMPLATE, like this:

<tr *ngFor="let row of newTmpArr">
  <td *ngFor="let cell of row">
    <ng-container [ngSwitch]="cell">
      <button *ngSwitchCase="'button'" (click)="test()">Click</button>
      <a *ngSwitchCase="'link'" href="#" (click)="test()">Click</a>
      <ng-container *ngSwitchDefault>{{ cell }}</ng-container>
    </ng-container>
  </td>
</tr>

This is the angular way of achieving your goal, all done in template, using nested ng for loops and then an ngSwitch is the appropriate directive for this use case since you have 2 options and a default.  Now you do not need to fight the framework or use any hacks like binding functions to the window. Angular will bind functions appropriately using this method.  You also have the distinct advantage of your display being model driven, so you only need to ever update your model and the display will react accordingly, so you never need to worry about display and model falling out of sync.

For example if you were to remove row 5, you would need to manually redraw your table after updating your model, same if you added a new row, or if you edit cell 2 of row 3.  Using template, angular manages all of this in a transparent and reliable manner.