问:
How to restart jquery delay.fadeout
When a user clicks a button, we do a

```<code>$('#element').show().delay(5000).fadeOut();
</code>```

If they click the button within 5 seconds, we would like to restart the effect, but as it is written now, the first one completes and the second effect does not happen.

答:
Following the official doc, https://api.jquery.com/delay/, the delay is not cancelable :

The .delay() method is best for delaying between queued jQuery
  effects. Because it is limited—it doesn't, for example, offer a way to
  cancel the delay—.delay() is not a replacement for JavaScript's native
  setTimeout function, which may be more appropriate for certain use
  cases.

You have to use a timeout instead :

var myTimer;
$('#stop').on('click', function(){
    $('#tohide').show();
     clearTimeout(myTimer);
});
$('#show').on('click', function(){
   $('#tohide').show();
    myTimer = setTimeout(function(){$('#tohide').fadeOut();}, 2000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button id="tohide" style="display:none">to hide</button>
<button id="stop">stop</button>
<button id="show">show</button></code>```

Title: How to restart jquery delay.fadeout

Body:
When a user clicks a button, we do a

$('#element').show().delay(5000).fadeOut();

If they click the button within 5 seconds, we would like to restart the effect, but as it is written now, the first one completes and the second effect does not happen.

Body:
Following the official doc, https://api.jquery.com/delay/, the delay is not cancelable :

The .delay() method is best for delaying between queued jQuery
  effects. Because it is limited—it doesn't, for example, offer a way to
  cancel the delay—.delay() is not a replacement for JavaScript's native
  setTimeout function, which may be more appropriate for certain use
  cases.

You have to use a timeout instead :

var myTimer;
$('#stop').on('click', function(){
    $('#tohide').show();
     clearTimeout(myTimer);
});
$('#show').on('click', function(){
   $('#tohide').show();
    myTimer = setTimeout(function(){$('#tohide').fadeOut();}, 2000);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button id="tohide" style="display:none">to hide</button>
<button id="stop">stop</button>
<button id="show">show</button>


来源: stackexchange

问:
Performance penalty of long list in python logging.debug()
How lazy is evaluation in Python? If I have code that looks like

logging.debug('My very long list: %s' % list(x for x in long_generator))

and the logging effective level is such that debug messages are ignored, do I incur a performance penalty for having this line?

答:
This will not be lazily evaluated, but Python logging has a solution to this problem: isEnabledFor().

```<code>if logger.isEnabledFor(logging.DEBUG):
    logger.debug('My very long list: %s' % list(x for x in long_generator))
</code>```

Your list will be built and formatted only if logger's level is higher than DEBUG.

ContentLicense: CC BY-SA 3.0

Body:
This will not be lazily evaluated, but Python logging has a solution to this problem: isEnabledFor().

if logger.isEnabledFor(logging.DEBUG):
    logger.debug('My very long list: %s' % list(x for x in long_generator))

Your list will be built and formatted only if logger's level is higher than DEBUG.


问:
Unable to get links working in Google Apps Script when using sandbox mode of "IFRAME"
In Google Apps Script, the code below works for me in the default sandbox mode, but when I change the sandbox mode to IFRAME, the code does not work.  In IE11, I get a blank page after clicking on the first button.  In Chrome, the first button works but clicking the subsequent button brings up a blank page.

The code below was taken from this post

Code.gs

```<code>/**
 * Get the URL for the Google Apps Script running as a WebApp.
 */
function getScriptUrl() {
 var url = ScriptApp.getService().getUrl();
 return url;
}

/**
 * Get "home page", or a requested page.
 * Expects a 'page' parameter in querystring.
 *
 * @param {event} e Event passed to doGet, with querystring
 * @returns {String/html} Html to be served
 */
function doGet(e) {
  Logger.log( Utilities.jsonStringify(e) );
  if (!e.parameter.page) {
    // When no specific page requested, return "home page"
    return HtmlService.createTemplateFromFile('my1').evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
  }
  // else, use page parameter to pick an html file from the script
  return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
</code>```

my1.html

```<code><html>
  <body>
    <h1>Source = my1.html</h1>
    <?var url = getScriptUrl();?><a href='<?=url?>?page=my2'> <input type='button' name='button' value='my2.html'></a>
  </body>
</html>
</code>```

my2.html

```<code><html>
  <body>
    <h1>Source = my2.html</h1>
    <?var url = getScriptUrl();?><a href='<?=url?>?page=my1'> <input type='button' name='button' value='my1.html'></a>
  </body>
</html>
</code>```

答: Apps Script now only supports IFRAME mode. NATIVE support is gone. See here</p>

Body:
In Google Apps Script, the code below works for me in the default sandbox mode, but when I change the sandbox mode to IFRAME, the code does not work.  In IE11, I get a blank page after clicking on the first button.  In Chrome, the first button works but clicking the subsequent button brings up a blank page.

The code below was taken from this post

Code.gs

/**
 * Get the URL for the Google Apps Script running as a WebApp.
 */
function getScriptUrl() {
 var url = ScriptApp.getService().getUrl();
 return url;
}

/**
 * Get "home page", or a requested page.
 * Expects a 'page' parameter in querystring.
 *
 * @param {event} e Event passed to doGet, with querystring
 * @returns {String/html} Html to be served
 */
function doGet(e) {
  Logger.log( Utilities.jsonStringify(e) );
  if (!e.parameter.page) {
    // When no specific page requested, return "home page"
    return HtmlService.createTemplateFromFile('my1').evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
  }
  // else, use page parameter to pick an html file from the script
  return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

my1.html

Source = my1.html

    <?var url = getScriptUrl();?><a href='<?=url?>?page=my2'> <input type='button' name='button' value='my2.html'>

my2.html

Source = my2.html

    <?var url = getScriptUrl();?><a href='<?=url?>?page=my1'> <input type='button' name='button' value='my1.html'>


问:
Is it possible to create a google map from python?
I am using pygeocoder to get the lat and long of addresses using code like.

```<code>from pygeocoder import Geocoder

for a in address:
    result = Geocoder.geocode(a)
    print(result[0].coordinates)
</code>```

This works very well. Is there some way to then actually produce the google maps web page with these points on it from within python? It would be great to be able to stay in one programming language as far as possible.

I have searched a lot online for a solution but have not found anything suitable.  Maybe it's not possible?

答:
You can use the gmplot library

https://github.com/vgm64/gmplot

It generates an html document with scripts connected to the google maps API. You can create dynamic maps with markers, scattered points, lines, polygons and heatmaps.

Example:

```<code>import gmplot

gmap = gmplot.GoogleMapPlotter(37.428, -122.145, 16)

gmap.plot(latitudes, longitudes, 'cornflowerblue', edge_width=10)
gmap.scatter(more_lats, more_lngs, '#3B0B39', size=40, marker=False)
gmap.scatter(marker_lats, marker_lngs, 'k', marker=True)
gmap.heatmap(heat_lats, heat_lngs)

gmap.draw("mymap.html")
</code>```

Heatmap example (static image)

Body:
I am using pygeocoder to get the lat and long of addresses using code like.

from pygeocoder import Geocoder

for a in address:
    result = Geocoder.geocode(a)
    print(result[0].coordinates)

This works very well. Is there some way to then actually produce the google maps web page with these points on it from within python? It would be great to be able to stay in one programming language as far as possible.

I have searched a lot online for a solution but have not found anything suitable.  Maybe it's not possible?

Body:
You can use the gmplot library

https://github.com/vgm64/gmplot

It generates an html document with scripts connected to the google maps API. You can create dynamic maps with markers, scattered points, lines, polygons and heatmaps.

Example:

import gmplot

gmap = gmplot.GoogleMapPlotter(37.428, -122.145, 16)

gmap.plot(latitudes, longitudes, 'cornflowerblue', edge_width=10)
gmap.scatter(more_lats, more_lngs, '#3B0B39', size=40, marker=False)
gmap.scatter(marker_lats, marker_lngs, 'k', marker=True)
gmap.heatmap(heat_lats, heat_lngs)

gmap.draw("mymap.html")

Heatmap example (static image)


问:
Hadoop Datanodes cannot find NameNode
I've set up a distributed Hadoop environment within VirtualBox: 4 virtual Ubuntu 11.10 installations, one acting as the master node, the other three as slaves. I followed this tutorial to get the single-node version up and running and then converted to the fully-distributed version. It was working just fine when I was running 11.04; however, when I upgraded to 11.10, it broke. Now all my slaves' logs show the following error message, repeated ad nauseum:

```<code>INFO org.apache.hadoop.ipc.Client: Retrying connect to server: master/192.168.1.10:54310. Already tried 0 time(s).
INFO org.apache.hadoop.ipc.Client: Retrying connect to server: master/192.168.1.10:54310. Already tried 1 time(s).
INFO org.apache.hadoop.ipc.Client: Retrying connect to server: master/192.168.1.10:54310. Already tried 2 time(s).
</code>```

And so on. I've found other instances of this error message on the Internet (and StackOverflow) but none of the solutions have worked (tried changing the core-site.xml and mapred-site.xml entries to be the IP address rather than hostname; quadruple-checked /etc/hosts on all slaves and master; master can SSH password-less into all slaves). I even tried reverting each slave back to a single-node setup, and they would all work fine in this case (on that note, the master always works fine as both a Datanode and the Namenode).

The only symptom I've found that would seem to give a lead is that from any of the slaves, when I attempt a telnet 192.168.1.10 54310, I get Connection refused, suggesting there is some rule blocking access (which must have gone into effect when I upgraded to 11.10).

My /etc/hosts.allow has not changed, however. I tried the rule ALL: 192.168.1., but it did not change the behavior.

Oh yes, and netstat on the master clearly shows tcp ports 54310 and 54311 are listening.

Anyone have any suggestions to get the slave Datanodes to recognize the Namenode?

EDIT #1: In doing some poking around with nmap (see comments on this post), I'm thinking the issue is in my /etc/hosts files. This is what is listed for the master VM:

```<code>127.0.0.1    localhost
127.0.1.1    master
192.168.1.10 master
192.168.1.11 slave1
192.168.1.12 slave2
192.168.1.13 slave3
</code>```

For each slave VM:

```<code>127.0.0.1    localhost
127.0.1.1    slaveX
192.168.1.10 master
192.168.1.1X slaveX
</code>```

Unfortunately, I'm not sure what I changed, but the NameNode is now always dying with the exception of trying to bind a port "that's already in use" (127.0.1.1:54310). I'm clearly doing something wrong with the hostnames and IP addresses, but I'm really not sure what it is. Thoughts?

答:
I also faced similar issue. (I am using ubuntu 17.0)
I kept only the entries of master and slaves in /etc/hosts file. (in both master and slave machines)

```<code>127.0.0.1  localhost
192.168.201.101 master
192.168.201.102 slave1
192.168.201.103 slave2
</code>```

secondly, > sudo gedit /etc/hosts.allow
and add the entry :  ALL:192.168.201.

thirdly, disabled the firewall using sudo ufw disable

finally, I deleted both namenode and datanode folders from all the nodes in cluster, and rerun

```<code>$HADOOP_HOME/bin> hdfs namenode -format -force
$HADOOP_HOME/sbin> ./start-dfs.sh
$HADOOP_HOME/sbin> ./start-yarn.sh
</code>```

To check the health report from command line (which I would recommend)

```<code>$HADOOP_HOME/bin> hdfs dfsadmin -report
</code>```

and I got all the nodes working correctly.

Title: Hadoop Datanodes cannot find NameNode

Body:
I've set up a distributed Hadoop environment within VirtualBox: 4 virtual Ubuntu 11.10 installations, one acting as the master node, the other three as slaves. I followed this tutorial to get the single-node version up and running and then converted to the fully-distributed version. It was working just fine when I was running 11.04; however, when I upgraded to 11.10, it broke. Now all my slaves' logs show the following error message, repeated ad nauseum:

INFO org.apache.hadoop.ipc.Client: Retrying connect to server: master/192.168.1.10:54310. Already tried 0 time(s).
INFO org.apache.hadoop.ipc.Client: Retrying connect to server: master/192.168.1.10:54310. Already tried 1 time(s).
INFO org.apache.hadoop.ipc.Client: Retrying connect to server: master/192.168.1.10:54310. Already tried 2 time(s).

And so on. I've found other instances of this error message on the Internet (and StackOverflow) but none of the solutions have worked (tried changing the core-site.xml and mapred-site.xml entries to be the IP address rather than hostname; quadruple-checked /etc/hosts on all slaves and master; master can SSH password-less into all slaves). I even tried reverting each slave back to a single-node setup, and they would all work fine in this case (on that note, the master always works fine as both a Datanode and the Namenode).

The only symptom I've found that would seem to give a lead is that from any of the slaves, when I attempt a telnet 192.168.1.10 54310, I get Connection refused, suggesting there is some rule blocking access (which must have gone into effect when I upgraded to 11.10).

My /etc/hosts.allow has not changed, however. I tried the rule ALL: 192.168.1., but it did not change the behavior.

Oh yes, and netstat on the master clearly shows tcp ports 54310 and 54311 are listening.

Anyone have any suggestions to get the slave Datanodes to recognize the Namenode?

EDIT #1: In doing some poking around with nmap (see comments on this post), I'm thinking the issue is in my /etc/hosts files. This is what is listed for the master VM:

127.0.0.1    localhost
127.0.1.1    master
192.168.1.10 master
192.168.1.11 slave1
192.168.1.12 slave2
192.168.1.13 slave3

For each slave VM:

127.0.0.1    localhost
127.0.1.1    slaveX
192.168.1.10 master
192.168.1.1X slaveX

Unfortunately, I'm not sure what I changed, but the NameNode is now always dying with the exception of trying to bind a port "that's already in use" (127.0.1.1:54310). I'm clearly doing something wrong with the hostnames and IP addresses, but I'm really not sure what it is. Thoughts?

Body:
I also faced similar issue. (I am using ubuntu 17.0)
I kept only the entries of master and slaves in /etc/hosts file. (in both master and slave machines)

127.0.0.1  localhost
192.168.201.101 master
192.168.201.102 slave1
192.168.201.103 slave2

secondly, > sudo gedit /etc/hosts.allow
and add the entry :  ALL:192.168.201.

thirdly, disabled the firewall using sudo ufw disable

finally, I deleted both namenode and datanode folders from all the nodes in cluster, and rerun

$HADOOP_HOME/bin> hdfs namenode -format -force
$HADOOP_HOME/sbin> ./start-dfs.sh
$HADOOP_HOME/sbin> ./start-yarn.sh

To check the health report from command line (which I would recommend)

$HADOOP_HOME/bin> hdfs dfsadmin -report

and I got all the nodes working correctly.


问:
set initial sort order in Silverlight DataGrid?
When I first load data into a Silverlight DataGrid control, how can I make the screen look exactly as if the user had just clicked the header of the first column?  In other words, the data should be sorted in ascending order according to that column's values, AND the little sort arrow should be displayed in the first column's header.

Assuming that's possible, can I also make it look as if the user had clicked the first column and then shift-clicked the second?  In other words, can I programatically apply a two-part sort and have the screen look as if the user had done it?

答:
I needed to do this as well, and looked hard and deep at whether the DataGrid could do this.

There IS in fact an appropriate method on the DataGridColumnHeader class, namely InvokeProcessSort, but it's internal and not surfaced anywhere else in the DataGrid classes.

All I've been able to do is pre-sort the data just before I bind it. I'm using a custom data collection that implements ICollectionView as well as ObservableCollection<>, and this works OK - but it's not optimal, and a load of work that's not necessarily needed.

Also, providing a pre-sorted collection means the grid doesn't show the sort marker.

I'll raise this as an issue on the DataGrid bug-tracker - this is a fairly major omission that'd be quite easy to fix - MS just needs to expose appropriate methods on DataGridColumn and DataGrid classes.

OwnerDisplayName: Eric

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Rammesses


问:
Parallel.ForEach and ListView Control
I am having an issue getting the Parallel.ForEach to work properly. I have a listview control that loads a files contents or mutliple files contents (each file represents a log file) into a richtextbox. Had it all working with a Foreach loop but decided that the parallel operation would cut down on the loadtime when loading 100+ files.

Here is the code block I was using for the foreach loop. How do I get a Parallel.Foreach working?

```<code>//Set cursor to WaitCursor Style
this.Cursor = Cursors.WaitCursor;

//Clear Messages RichTexBox
this.rtbMessages.Clear();

//Loop through each selected file
foreach (ListViewItem Item in lvMessageFiles.Items)
{
    //Check if item is selected in the listview
    if (Item.Selected && rtbMessages.TextLength < rtbMessages.MaxLength)
    {
        //Get Path to message file
        filename = String.Format("{0}\\Data\\Log\\{1}.log", Global.AppPath, Item.SubItems[0].Text);

        //Set Timeline Events calendar to selected items created date
        cvTimeline.ShowDate(Convert.ToDateTime(lvMessageFiles.SelectedItems[0].SubItems[2].Text));

        //Check if file exists
        if (File.Exists(filename))
        {
            //streamreader to read the file
            reader = new StreamReader(filename);

            //to copy the read content in to richtextbox
            string MessageContents = String.Format("{0}\n{1}\n", ("file:///" + filename.Replace(" ", "%20").Replace("\\", "/")), reader.ReadToEnd());
            rtbMessages.Text += MessageContents;

            // closing streamreader
            reader.Close();
        }
    }

}

//Set cursor to WaitCursor Style
this.Cursor = Cursors.Default;
</code>```

答: You're not allowed to update UI from a non-UI thread, which threads in a Parallel.ForEach obviously will be. Instead use the Invoke method to set the Text of rtbMessages and call cvTimeline.ShowDate

Title: Parallel.ForEach and ListView Control

Body:
I am having an issue getting the Parallel.ForEach to work properly. I have a listview control that loads a files contents or mutliple files contents (each file represents a log file) into a richtextbox. Had it all working with a Foreach loop but decided that the parallel operation would cut down on the loadtime when loading 100+ files.

Here is the code block I was using for the foreach loop. How do I get a Parallel.Foreach working?

//Set cursor to WaitCursor Style
this.Cursor = Cursors.WaitCursor;

//Clear Messages RichTexBox
this.rtbMessages.Clear();

//Loop through each selected file
foreach (ListViewItem Item in lvMessageFiles.Items)
{
    //Check if item is selected in the listview
    if (Item.Selected && rtbMessages.TextLength < rtbMessages.MaxLength)
    {
        //Get Path to message file
        filename = String.Format("{0}\\Data\\Log\\{1}.log", Global.AppPath, Item.SubItems[0].Text);

        //Set Timeline Events calendar to selected items created date
        cvTimeline.ShowDate(Convert.ToDateTime(lvMessageFiles.SelectedItems[0].SubItems[2].Text));

        //Check if file exists
        if (File.Exists(filename))
        {
            //streamreader to read the file
            reader = new StreamReader(filename);

            //to copy the read content in to richtextbox
            string MessageContents = String.Format("{0}\n{1}\n", ("file:///" + filename.Replace(" ", "%20").Replace("\\", "/")), reader.ReadToEnd());
            rtbMessages.Text += MessageContents;

            // closing streamreader
            reader.Close();
        }
    }

}

//Set cursor to WaitCursor Style
this.Cursor = Cursors.Default;


问:
How to check a SQL CASE with multiple conditions?
I have two tables. Accounts ACC and FinancialTrans FT

The FinancialTrans table is as follows:

```<code>AcctID  TransTypeCode   DateOfTrans
123     TOLL            2016-06-06 00:00:00.000
123     TOLL            2016-06-02 00:00:00.000
123     TOLL            2016-04-28 00:00:00.000
123     PYMT            2016-03-11 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
</code>```

The requirement is:

When any Accounts have NO 'TOLL' or 'PYMT' in the last 2 years print 'Flag'

```<code>SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,CASE WHEN
        (SELECT Max(DateOfTrans) FROM FinanceTrans FT
         WHERE ACC.AccountID = FT.AcctID
               AND (TransTypeCode = 'TOLL' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
               AND (TransTypeCode = 'PYMT' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
             GROUP BY AcctID, TransTypeCode) IS NULL
        THEN 'Flag'
        ELSE ''
       AND AS NoNo_Flag

FROM Accounts ACC

WHERE Condition 1, Condition 2...
</code>```

答:
try this one:</p>

```<code>SELECT
    acc.*,
    CASE WHEN f.acctid IS NULL THEN 'flag' ELSE '' END AS flag_noTollOrPmt
FROM
    accounts acc LEFT OUTER JOIN
    (SELECT
        AcctID,
        MAX(DateOfTrans) AS max_dateOfTrans_TollOrPmt
    FROM
        FinanceTrans
    WHERE
        DateOfTrans >= DATEADD(YEAR, -2, GETDATE()) AND
        TransTypeCode IN( 'TOLL' , 'PYMT')
    GROUP BY
        AcctID) f ON
    acc.acctid = f.acctid
</code>```

Body:
I have two tables. Accounts ACC and FinancialTrans FT

The FinancialTrans table is as follows:

AcctID  TransTypeCode   DateOfTrans
123     TOLL            2016-06-06 00:00:00.000
123     TOLL            2016-06-02 00:00:00.000
123     TOLL            2016-04-28 00:00:00.000
123     PYMT            2016-03-11 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000

The requirement is:

When any Accounts have NO 'TOLL' or 'PYMT' in the last 2 years print 'Flag'

SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,CASE WHEN
        (SELECT Max(DateOfTrans) FROM FinanceTrans FT
         WHERE ACC.AccountID = FT.AcctID
               AND (TransTypeCode = 'TOLL' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
               AND (TransTypeCode = 'PYMT' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
             GROUP BY AcctID, TransTypeCode) IS NULL
        THEN 'Flag'
        ELSE ''
       AND AS NoNo_Flag

FROM Accounts ACC

WHERE Condition 1, Condition 2...

Body:
try this one:

SELECT
    acc.*,
    CASE WHEN f.acctid IS NULL THEN 'flag' ELSE '' END AS flag_noTollOrPmt
FROM
    accounts acc LEFT OUTER JOIN
    (SELECT
        AcctID,
        MAX(DateOfTrans) AS max_dateOfTrans_TollOrPmt
    FROM
        FinanceTrans
    WHERE
        DateOfTrans >= DATEADD(YEAR, -2, GETDATE()) AND
        TransTypeCode IN( 'TOLL' , 'PYMT')
    GROUP BY
        AcctID) f ON
    acc.acctid = f.acctid


问:
Add a class to expanded row using vanilla JS
In my angular application I am attempting a workaround because the ag-Grid api getRowClass() is not working at intended.  All I need to do is add a css class to an expanded row and remove it when the row is collapsed.

The original method using ag-Grid api that does not work looks as follows:

```<code>setRowNode(params) {
    this.gridOptions.getRowStyle = (params) => {
        if(params.node.expanded) {
            return { background: 'red' };
        }
    }
}
</code>```

Ideally I would be able to selected the DOM and append a class to it.  I tried this with some JQuery and it worked, but for obvious reasons I do not want to have JQuery in this app.  I wrote something along these lines:

```<code>$('.ag-row[row="'+params.node.id+'"]',self.api.grid.gridPanel.eBodyContainer).addClass('ag-row-focus');
</code>```

How would I fulfill this req using vanilla JS?

答:
You can do it by creating a custom directive, like this one :

```<code>//row-focus.directive.ts

import { Directive, HostBinding, HostListener } from '@angular/core';

@Directive({
  selector: '[appRowFocus]' // you can target classes, id etc.: '.grid-Holdings' for example
})
export class RowFocusDirective {
  @HostBinding('class.ag-row-focus') isFocused = false;

  @HostListener('click') toggleOpen() {
    this.isFocused = !this.isFocused;
  }
}
</code>```

Import this directive on your module, and then attach the directive to your elements :

```<code>// your-component.component.ts :

<div class="row" appRowFocus>
</code>```

These elements will toggle the ag-row-focus on click. You can add different @HostListener for other events.

Body:
In my angular application I am attempting a workaround because the ag-Grid api getRowClass() is not working at intended.  All I need to do is add a css class to an expanded row and remove it when the row is collapsed.

The original method using ag-Grid api that does not work looks as follows:

setRowNode(params) {
    this.gridOptions.getRowStyle = (params) => {
        if(params.node.expanded) {
            return { background: 'red' };
        }
    }
}

Ideally I would be able to selected the DOM and append a class to it.  I tried this with some JQuery and it worked, but for obvious reasons I do not want to have JQuery in this app.  I wrote something along these lines:

$('.ag-row[row="'+params.node.id+'"]',self.api.grid.gridPanel.eBodyContainer).addClass('ag-row-focus');

How would I fulfill this req using vanilla JS?

Body:
You can do it by creating a custom directive, like this one :

//row-focus.directive.ts

import { Directive, HostBinding, HostListener } from '@angular/core';

@Directive({
  selector: '[appRowFocus]' // you can target classes, id etc.: '.grid-Holdings' for example
})
export class RowFocusDirective {
  @HostBinding('class.ag-row-focus') isFocused = false;

  @HostListener('click') toggleOpen() {
    this.isFocused = !this.isFocused;
  }
}

Import this directive on your module, and then attach the directive to your elements :

// your-component.component.ts :

<div class="row" appRowFocus>

These elements will toggle the ag-row-focus on click. You can add different @HostListener for other events.


问:
Is there a way to mark TODO complete in Android studio?
I'm trying to track TODOs in Android studio.

Is there a way to mark them 'complete' without simply deleting them?

答:
I extended the solution of setting a new pattern of TODO by adding a MACRO to making the process automatic.

At first we have to have set a new pattern for TODO as I mentioned at the beginning.

Then we have to make a macro by executing the following steps:

Go to: EDIT -> MACROS -> Start Macro Recording

Since now your actions are recording by Android Studio. Set the cursor on the “TODO” word and press: Left Alt + J // FOR MAC OS X: Ctrl + G / Shift + Ctrl + G (TODO word will be highlighted)
See the screenshot #1

Now press the CAPS LOCK key button to turn on CAPS LOCK (or use SHIFT button instead of CAPS LOCK for typing capital letters)

…and type COMPLETED (or other word which you used in your own TODO pattern)
See the screenshot #2

Now press the CAPS LOCK key button again to turn off CAPS LOCK (or release the SHIFT button)

Go to: EDIT -> MACROS -> Stop Macro Recording

Enter a name for your macro
See the screenshot #3

Go to: FILE -> SETTINGS -> KEYMAP (If you can’t find it, use the search field)
See the screenshot #4

Add your own Keyboard Shortcut
See the screenshot #5

Click APPLY

THAT’S ALL! Set the cursor on TODO word in your code and press your preselected shortcut.


问:
adding datasources in jboss-as-7.1.1.Final
I want to configure a datasource through the datasource subsystem in a jboss-as-7.1.1.Final server installed on a Mac V 10.13.1
I already provided a JDBC driver

So I added this piece of code in the file standalone.xml

```<code><server xmlns="urn:jboss:domain:1.2">

    <datasources>
   <datasource jndi-name="java:jboss/datasources/MySqlDS" pool-name="MySqlDS">
      <connection-url>jdbc:mysql://localhost:3306/EJB3</connection-url>
         <driver>com.mysql</driver>
      <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
      <pool>
        <min-pool-size>10</min-pool-size>
        <max-pool-size>100</max-pool-size>
        <prefill>true</prefill>
      </pool>
      <security>
        <user-name>test</user-name>
        <password>test</password>
      </security>
      <statement>
        <prepared-statement-cache-size>32</prepared-statement-cache-size>
        <share-prepared-statements/>
      </statement>
    </datasource>
    <drivers>
      <driver name="com.mysql" module="com.mysql">
        <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
      </driver>
    </drivers>
</datasources>

    <extensions>
       ...
</server>
</code>```

But when I run the serverI got this error:

```<code>14:28:35,894 ERROR [org.jboss.as.server] JBAS015956: Caught exception during boot: org.jboss.as.controller.persistence.ConfigurationPersistenceException: JBAS014676: Failed to parse configuration
    at org.jboss.as.controller.persistence.XmlConfigurationPersister.load(XmlConfigurationPersister.java:141) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.ServerService.boot(ServerService.java:266) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.controller.AbstractControllerService$1.run(AbstractControllerService.java:155) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_75]
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[5,5]
Message: JBAS014789: Unexpected element '{urn:jboss:domain:1.2}datasources' encountered
    at org.jboss.as.controller.parsing.ParseUtils.unexpectedElement(ParseUtils.java:85) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.parsing.StandaloneXml.readServerElement_1_1(StandaloneXml.java:351) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.parsing.StandaloneXml.readElement(StandaloneXml.java:127) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.parsing.StandaloneXml.readElement(StandaloneXml.java:100) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.staxmapper.XMLMapperImpl.processNested(XMLMapperImpl.java:110) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
    at org.jboss.staxmapper.XMLMapperImpl.parseDocument(XMLMapperImpl.java:69) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
    at org.jboss.as.controller.persistence.XmlConfigurationPersister.load(XmlConfigurationPersister.java:133) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final]
    ... 3 more
</code>```

答:
standalone.xml already has a section for datasources.

You shoud look for <subsystem xmlns="urn:jboss:domain:datasources:1.0"> section and add it there

Body:
I want to configure a datasource through the datasource subsystem in a jboss-as-7.1.1.Final server installed on a Mac V 10.13.1
I already provided a JDBC driver

So I added this piece of code in the file standalone.xml

<server xmlns="urn:jboss:domain:1.2">

    <datasources>
   <datasource jndi-name="java:jboss/datasources/MySqlDS" pool-name="MySqlDS">
      <connection-url>jdbc:mysql://localhost:3306/EJB3</connection-url>
         <driver>com.mysql</driver>
      <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
      <pool>
        <min-pool-size>10</min-pool-size>
        <max-pool-size>100</max-pool-size>
        <prefill>true</prefill>
      </pool>
      <security>
        <user-name>test</user-name>
        <password>test</password>
      </security>
      <statement>
        <prepared-statement-cache-size>32</prepared-statement-cache-size>
        <share-prepared-statements/>
      </statement>
    </datasource>
    <drivers>
      <driver name="com.mysql" module="com.mysql">
        <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
      </driver>
    </drivers>
</datasources>

    <extensions>
       ...
</server>

But when I run the serverI got this error:

14:28:35,894 ERROR [org.jboss.as.server] JBAS015956: Caught exception during boot: org.jboss.as.controller.persistence.ConfigurationPersistenceException: JBAS014676: Failed to parse configuration
    at org.jboss.as.controller.persistence.XmlConfigurationPersister.load(XmlConfigurationPersister.java:141) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.ServerService.boot(ServerService.java:266) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.controller.AbstractControllerService$1.run(AbstractControllerService.java:155) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_75]
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[5,5]
Message: JBAS014789: Unexpected element '{urn:jboss:domain:1.2}datasources' encountered
    at org.jboss.as.controller.parsing.ParseUtils.unexpectedElement(ParseUtils.java:85) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.parsing.StandaloneXml.readServerElement_1_1(StandaloneXml.java:351) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.parsing.StandaloneXml.readElement(StandaloneXml.java:127) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.server.parsing.StandaloneXml.readElement(StandaloneXml.java:100) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.staxmapper.XMLMapperImpl.processNested(XMLMapperImpl.java:110) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
    at org.jboss.staxmapper.XMLMapperImpl.parseDocument(XMLMapperImpl.java:69) [staxmapper-1.1.0.Final.jar:1.1.0.Final]
    at org.jboss.as.controller.persistence.XmlConfigurationPersister.load(XmlConfigurationPersister.java:133) [jboss-as-controller-7.1.1.Final.jar:7.1.1.Final]
    ... 3 more


问:
Compare two hashmaps by keys and return keys which do not have same frequencies
I would like to sort two HashMaps by keys and compare their values and print out all the keys which do not have same value. Could you help me how to do this. Here is my code as below. I am new to Java and learning data structures one by one. Thanks for the help.

Code :-

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

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

        int n = scan.nextInt();
        HashMap<Integer,Integer> h1 = new HashMap<Integer,Integer>();

        for( int i=0;i<n;i++ ) {
             val = scan.nextInt();
             if(!h1.containsKey(val)) {
                 h1.put(val,1);
             }
            else {
                h1.put(val,h1.get(val)+1);
            }
         }

        int m = scan.nextInt();

        HashMap<Integer,Integer> h2 = new HashMap<Integer,Integer>();

         for( int i=0;i<m;i++ ) {
             val = scan.nextInt();
             if(!h2.containsKey(val)) {
                 h2.put(val,1);
             }
            else {
                h2.put(val,h2.get(val)+1);
            }
         }

        System.out.println(h1.keySet());
        System.out.println(h1.values());
        System.out.println(h2.keySet());
        System.out.println(h2.values());

        }
}
</code>```

答:
Should allow you to sort the maps.

```<code>SortedSet<Integer> values1 = new TreeSet<Integer>(h1.keySet());
SortedSet<Integer> values2 = new TreeSet<Integer>(h2.keySet());
</code>```

Should return a set with the unique values of the two sets.

```<code>    Set<Integer> result = new SortedSet<Integer>(values1);
    for (Integer element : values2) {
        if (!h1.containsValue(h2.get(element)) {  //If they don't share same value, add it to this new Set
            result.add(element);
        }
        result.remove(element);  //If they both share same value, remove it
    }
</code>```

Finally, to print:

```<code>Iterator iter = result.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}
</code>```

Body:
I would like to sort two HashMaps by keys and compare their values and print out all the keys which do not have same value. Could you help me how to do this. Here is my code as below. I am new to Java and learning data structures one by one. Thanks for the help.

Code :-

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

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

        int n = scan.nextInt();
        HashMap<Integer,Integer> h1 = new HashMap<Integer,Integer>();

        for( int i=0;i<n;i++ ) {
             val = scan.nextInt();
             if(!h1.containsKey(val)) {
                 h1.put(val,1);
             }
            else {
                h1.put(val,h1.get(val)+1);
            }
         }

        int m = scan.nextInt();

        HashMap<Integer,Integer> h2 = new HashMap<Integer,Integer>();

         for( int i=0;i<m;i++ ) {
             val = scan.nextInt();
             if(!h2.containsKey(val)) {
                 h2.put(val,1);
             }
            else {
                h2.put(val,h2.get(val)+1);
            }
         }

        System.out.println(h1.keySet());
        System.out.println(h1.values());
        System.out.println(h2.keySet());
        System.out.println(h2.values());

        }
}

Body:
Should allow you to sort the maps.

SortedSet<Integer> values1 = new TreeSet<Integer>(h1.keySet());
SortedSet<Integer> values2 = new TreeSet<Integer>(h2.keySet());

Should return a set with the unique values of the two sets.

    Set<Integer> result = new SortedSet<Integer>(values1);
    for (Integer element : values2) {
        if (!h1.containsValue(h2.get(element)) {  //If they don't share same value, add it to this new Set
            result.add(element);
        }
        result.remove(element);  //If they both share same value, remove it
    }

Finally, to print:

Iterator iter = result.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}


问:
Print character in a for loop c++
This is a pretty basic question as I am new to the C++ language but I have a program that takes a function to print a single character in a for loop. My code is shown below:

```<code>void printBar(const char symbol, int count){
    for (int i = 0;i <= count; i++){
        cout << symbol;
    }
}
</code>```

and my main function is this:

```<code>int main(){
    int size = 8;
    const char* sym = "*":
    printBar(sym,size);
</code>```

I want my result to look like this:

```<code>********
</code>```

What am I doing wrong here?

答:
For starters there is a typo

```<code>const char* sym = "*":
                    ^^^
</code>```

There shall be a semicolon.

The loop in the function should look like

```<code>void printBar(const char symbol, int count){
    for (int i = 0; i < count; i++){
                    ^^^^^^^^^
        cout << symbol;
    }
}
</code>```

And the qualifier const in the first parameter declaration may be removed.

```<code>void printBar(char symbol, int count){
</code>```

If the variable sym declared like

```<code>const char* sym = "*":
</code>```

then the function should be called like

```<code>printBar(*sym,size);
</code>```

or

```<code>printBar(sym[0],size);
</code>```

that is you need to pass to the function just one character instead of the pointer.

Another approach to write the function can look as it is shown in the demonstrative program

```<code>#include <iostream>
#include <iomanip>

std::ostream & printBar( char symbol, size_t count, std::ostream &os = std::cout )
{
    if ( count )
    {
        os << std::setw( count ) << std::setfill( symbol ) << symbol;
    }

    return os;
}

int main()
{
    size_t size = 8;
    const char *sym = "*";

    printBar( *sym, size ) << std::endl;

    return 0;
}
</code>```

Its output is

```<code>********
</code>```

Title: Print character in a for loop c++

Body:
This is a pretty basic question as I am new to the C++ language but I have a program that takes a function to print a single character in a for loop. My code is shown below:

void printBar(const char symbol, int count){
    for (int i = 0;i <= count; i++){
        cout << symbol;
    }
}

and my main function is this:

int main(){
    int size = 8;
    const char* sym = "*":
    printBar(sym,size);

I want my result to look like this:

********

What am I doing wrong here?

Body:
For starters there is a typo

const char* sym = "*":
                    ^^^

There shall be a semicolon.

The loop in the function should look like

void printBar(const char symbol, int count){
    for (int i = 0; i < count; i++){
                    ^^^^^^^^^
        cout << symbol;
    }
}

And the qualifier const in the first parameter declaration may be removed.

void printBar(char symbol, int count){

If the variable sym declared like

const char* sym = "*":

then the function should be called like

printBar(*sym,size);

or

printBar(sym[0],size);

that is you need to pass to the function just one character instead of the pointer.

Another approach to write the function can look as it is shown in the demonstrative program

#include <iostream>
#include <iomanip>

std::ostream & printBar( char symbol, size_t count, std::ostream &os = std::cout )
{
    if ( count )
    {
        os << std::setw( count ) << std::setfill( symbol ) << symbol;
    }

    return os;
}

int main()
{
    size_t size = 8;
    const char *sym = "*";

    printBar( *sym, size ) << std::endl;

    return 0;
}

Its output is

********


答:
You can use finish() to make the previous action play to completion immediately. Ref. http://api.jquery.com/finish/

$('#target').on('click', function(){
  $('#element').finish().show().delay(5000).fadeOut();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#element {
  display: none;
}</code>```

<button id="target">Do It</button>

Element
```

Title: How to restart jquery delay.fadeout

Body:
When a user clicks a button, we do a

$('#element').show().delay(5000).fadeOut();

If they click the button within 5 seconds, we would like to restart the effect, but as it is written now, the first one completes and the second effect does not happen.

Body:
You can use finish() to make the previous action play to completion immediately. Ref. http://api.jquery.com/finish/

$('#target').on('click', function(){
  $('#element').finish().show().delay(5000).fadeOut();
});

#element {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="target">Do It</button>
<div id="element">Element</div>


问:
Advantages of UI component libraries like Bootstrap-Vue and React-Bootstrap
What are the benefits of using a framework like Bootstrap-Vue as opposed to regular bootstrap?

Is it in order to remove jQuery dependency?

答: Bootstrap-Vue is just a library of Vue components that are styled using Bootstrap. Looks like they were able to remove the jquery dependency (I would personally consider this a pro cause im not a big jquery fan, but in all reality this is pretty neutral). My reason for using it would just to be able to use useful, common UI components inside my vue application. If you are building all the components yourself then I would just use regular Bootstrap to style them.</p>


答:
You should say what goes wriong. Errors, wrong output.... But I can guess

First this loop is wrong

```<code>void printBar(const char symbol, int count){
    for (int i = 0;i <= count; i++){
        cout << symbol;
    }
}
</code>```

it will print one too many char. You should have i < count

Second your function needs a char, but you pass in a char*

Do this

```<code>int main(){

int size = 8;
const char sym = '*':
printBar(sym,size);
</code>```

Title: Print character in a for loop c++

Body:
You should say what goes wriong. Errors, wrong output.... But I can guess

First this loop is wrong

void printBar(const char symbol, int count){
    for (int i = 0;i <= count; i++){
        cout << symbol;
    }
}

it will print one too many char. You should have i < count

Second your function needs a char, but you pass in a char*

Do this

int main(){

int size = 8;
const char sym = '*':
printBar(sym,size);


问:
Serialport DataRecieved threads ending before execution
I have noticed that when the new thread is started from serialport Data received event that if the plan of execution includes just a few methods that may change some value and send on another port then it works fine, but if the method needs to do more extensive processing like sending on another port and waiting for ACK, send again and receiving decent sized amounts of data (20KB) in 256 byte packets then the thread just stops somewhere and never completes. When the code is stepped through it seems to work fine. I have read other topics of people asking about this issue but there was no "solution" just to use another method like timers to poll the ports instead. I even made a workaround by having the main thread "poll" a variable that is changed from the event rather then having the event do the work and this seems to work, but when using a windows form I had to create a new thread which seems to be doing the same thing and either not completing the code or not executing the new thread which is just a while look that runs forever checking a variable. I can provide code if needed just wanted some insight on how to address this properly.</p>

答: Nobody here knew the answer to the questions or explained limitations, but i was able to get around the issues using timers to run while loops checking for variable changes and starting threads that did the same.</p>


问:
C++ how to use a pointer to circular shift array element
```<code>#include <iostream>
using namespace std;

void RotateLeft(unsigned char* in)
{
    unsigned int* q= (unsigned int*)in;
    *q = (*q >> 8)|((*q & 0xff) << 24);
}
int main() {
    unsigned char temp[4] = {'a', 'b', 'c', 'd'};
    RotateLeft(temp);
    for (int i=0; i<4; i++) {
        cout<<temp[i]<<endl;
    }
}
</code>```

the output is: b c d a.

Could you explain how does this line work:

```<code>*q = (*q >> 8)|((*q & 0xff) << 24);
</code>```

?

答:
How can this work ?

The pointer in to the array looks like:

```<code>         +---+---+---+---+
in -->   | a | b | c | d |
         +---+---+---+---+
</code>```

Let's assuming that each char would be coded as a sequence of 8 bits (ok, language-lawyers would argue that a byte is not necessarily 8 bits, but in practice, it's quite often the case).  So in binary it would look like:

```<code>         +----------+----------+----------+----------+
in -->   | 01100001 | 01100010 | 01100011 | 01100100 |
         +----------+----------+----------+----------+
</code>```

Let's assume that the int is made of 32 bits.  The ugly casting trick with unsigned int* q= (unsigned int*)in; is to instruct the compiler to handle the pointer as if it would point to an int, combining several char in a single value:

```<code>         +----------+----------+----------+----------+
q  -->   | 01100001   01100010   01100011   01100100 |
         +----------+----------+----------+----------+

</code>```

Attention:  for the sake of simplicity, I'll assume here a big endian CPU architecture. But I'll come back later on this by explaining how it works with little endian.

This binary coded number in the example represents 1633837924 in decimal notation.

If you now perform  (*q >> 8) it will shift the bits of this integer to the right by 8 bits, injecting 0 bits on the left:

```<code>         +----------+----------+----------+----------+
*q >>8 = | 00000000   01100001   01100010   01100011 |
         +----------+----------+----------+----------+
                        'a'         'b'        'c'
</code>```

Now 0xff in binary in 11111111. If you now perform the following bitwise and operation (*q & 0xff) you will set all the bits to 0, except the last 8 bits:

```<code>            +----------+----------+----------+----------+
(*q&0xff) = | 00000000   00000000   00000000   01100100 |
            +----------+----------+----------+----------+
                                                 'd'
</code>```

if you combine this with ...<<24, you shift all the bits to the left by 24 positions, by injecting 0 to the right:

```<code>                +----------+----------+----------+----------+
(*q&0xff)<<24 = | 01100100   00000000   00000000   00000000 |
                +----------+----------+----------+----------+
                     'd'
</code>```

If you now combine these two terms with a bitwise or, you'll obtain:

```<code>                +----------+----------+----------+----------+
*q >>8 =        | 00000000   01100001   01100010   01100011 |
                +----------+----------+----------+----------+
                             'a'         'b'        'c'
                +----------+----------+----------+----------+
(*q&0xff)<<24 = | 01100100   00000000   00000000   00000000 |
                +----------+----------+----------+----------+
                     'd'
                +----------+----------+----------+----------+
| (bitwise or)  | 01100100   01100001   01100010   01100011 |
                +----------+----------+----------+----------+
                     'd'        'a'         'b'        'c'
</code>```

So in this case it rotates right.  This is the consequence of the big-endian assumption that I made.

But is this safe ?

The problem with this code is that it assumes a lot of things which are not guaranteed by standard C++. So it is not guaranteed to work.   It works only if:

a char is 8 bits long (because the shift right and shift left are multiples of 8).

an int is 32 bits long (because it assumes that the combination of shifts corresponds to exactly 32 bits).

the direction of the rotation depends on endianness.  Only little endian ensures a rotation to the left.

Here the impact on endianness:

In my step by step explanations, I've used big-endian, where the bytes are taken sequentially in the right order to form the integer.  THe rotation is done towards the right.

If you have a little endian architecture, which is much more probable, the bytes would be loaded into the register as an integer in the reverse order (e.g. a b c d in memory order would be loaded as d c b a for the calculations) , the bytes would then be shifted and combined as explained to the right (e.g. a d c b), but when stored back into memory, the bytes would again be reversed (e.g. b c d a), so the rotate right that is done on the integer results in a rotate left if looking at the individual chars.

Body:
#include <iostream>
using namespace std;

void RotateLeft(unsigned char* in)
{
    unsigned int* q= (unsigned int*)in;
    *q = (*q >> 8)|((*q & 0xff) << 24);
}
int main() {
    unsigned char temp[4] = {'a', 'b', 'c', 'd'};
    RotateLeft(temp);
    for (int i=0; i<4; i++) {
        cout<<temp[i]<<endl;
    }
}

the output is: b c d a.

Could you explain how does this line work:

*q = (*q >> 8)|((*q & 0xff) << 24);

?

Body:
How can this work ?

The pointer in to the array looks like:

         +---+---+---+---+
in -->   | a | b | c | d |
         +---+---+---+---+

Let's assuming that each char would be coded as a sequence of 8 bits (ok, language-lawyers would argue that a byte is not necessarily 8 bits, but in practice, it's quite often the case).  So in binary it would look like:

         +----------+----------+----------+----------+
in -->   | 01100001 | 01100010 | 01100011 | 01100100 |
         +----------+----------+----------+----------+

Let's assume that the int is made of 32 bits.  The ugly casting trick with unsigned int* q= (unsigned int*)in; is to instruct the compiler to handle the pointer as if it would point to an int, combining several char in a single value:

         +----------+----------+----------+----------+
q  -->   | 01100001   01100010   01100011   01100100 |
         +----------+----------+----------+----------+

Attention:  for the sake of simplicity, I'll assume here a big endian CPU architecture. But I'll come back later on this by explaining how it works with little endian.

This binary coded number in the example represents 1633837924 in decimal notation.

If you now perform  (*q >> 8) it will shift the bits of this integer to the right by 8 bits, injecting 0 bits on the left:

         +----------+----------+----------+----------+
*q >>8 = | 00000000   01100001   01100010   01100011 |
         +----------+----------+----------+----------+
                        'a'         'b'        'c'

Now 0xff in binary in 11111111. If you now perform the following bitwise and operation (*q & 0xff) you will set all the bits to 0, except the last 8 bits:

            +----------+----------+----------+----------+
(*q&0xff) = | 00000000   00000000   00000000   01100100 |
            +----------+----------+----------+----------+
                                                 'd'

if you combine this with ...<<24, you shift all the bits to the left by 24 positions, by injecting 0 to the right:

                +----------+----------+----------+----------+
(*q&0xff)<<24 = | 01100100   00000000   00000000   00000000 |
                +----------+----------+----------+----------+
                     'd'

If you now combine these two terms with a bitwise or, you'll obtain:

                +----------+----------+----------+----------+
*q >>8 =        | 00000000   01100001   01100010   01100011 |
                +----------+----------+----------+----------+
                             'a'         'b'        'c'
                +----------+----------+----------+----------+
(*q&0xff)<<24 = | 01100100   00000000   00000000   00000000 |
                +----------+----------+----------+----------+
                     'd'
                +----------+----------+----------+----------+
| (bitwise or)  | 01100100   01100001   01100010   01100011 |
                +----------+----------+----------+----------+
                     'd'        'a'         'b'        'c'

So in this case it rotates right.  This is the consequence of the big-endian assumption that I made.

But is this safe ?

The problem with this code is that it assumes a lot of things which are not guaranteed by standard C++. So it is not guaranteed to work.   It works only if:

a char is 8 bits long (because the shift right and shift left are multiples of 8).

an int is 32 bits long (because it assumes that the combination of shifts corresponds to exactly 32 bits).

the direction of the rotation depends on endianness.  Only little endian ensures a rotation to the left.

Here the impact on endianness:

In my step by step explanations, I've used big-endian, where the bytes are taken sequentially in the right order to form the integer.  THe rotation is done towards the right.

If you have a little endian architecture, which is much more probable, the bytes would be loaded into the register as an integer in the reverse order (e.g. a b c d in memory order would be loaded as d c b a for the calculations) , the bytes would then be shifted and combined as explained to the right (e.g. a d c b), but when stored back into memory, the bytes would again be reversed (e.g. b c d a), so the rotate right that is done on the integer results in a rotate left if looking at the individual chars.


问:
Rails 5: nested resources undefined method _path
I have three tables: users, observative_sessions and observations.

In each respective model there's

users.rb

```<code>has_many :observative_sessions, dependent: :destroy
has_many :observations, through: :observative_sessions, dependent: :destroy
</code>```

observative_sessions.rb

```<code>belongs_to :user
has_many :observations, dependent: :destroy
</code>```

observations.rb

```<code>belongs_to :observative_session
belongs_to :user
</code>```

In routes.rb I nested observations in observative_sessions

```<code>resources :observative_sessions do
  resources :observations
end
</code>```

I show the list of possible observations for each observative_session so I created the partial (observations/_index.html.erb) to render in the show page of observative session.

```<code><%= render 'observations/index' %>
</code>```

and a button to create new observations

```<code><button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#new-observation-modal">Create</button>
</code>```

observative_sessions_controller.rb

```<code>def show
   @q = Observation.ransack([:observative_session])
   @observations = @s.result.order(params[:order]).paginate(page: params[:page]) if params[:q].present?
   @observations = @s.result.order(params[:order]).paginate(page: params[:page]) unless params[:q].present?
   @observation = Observation.new
end
</code>```

Now I have a problem, when I try to create a new observation the button calls the new_modal which renders the form

```<code><%= render 'observations/form' %>
</code>```

observations/_form.html.erb

```<code><%= bootstrap_form_for ([@observative_session, @observation]) do |f| %>
</code>```

And here I get the error Undefined method 'observations_path'
This is how I defined the creation method in observations_controller.rb

```<code>def create
  @observation = Observation.new(observation_params)

respond_to do |format|
  if @observation.save
    format.html { redirect_to [@observative_session, @observation], notice: 'Observation was successfully created.' }
    format.json { render :show, status: :created, location: @observation }
  else
    format.html { render :new }
    format.json { render json: @observation.errors, status: :unprocessable_entity }
  end
end
</code>```

end

Thank you so much for any help.

答:
My bad the error was on new.html.erb I passed

```<code><%= render 'form', observation: @observation %>
</code>```

instead of

```<code><%= render 'form', observation: ([@observative_session, @observation]) %>
</code>```

and in observations_controller.rb I had to add

```<code>    @observative_session = ObservativeSession.find(params[:observative_session_id])
    @observation = @observative_session.observations.build(observation_params)
</code>```

By the way before I was trying to use thinking of passing the id of the session

```<code>ObservativeSession.find(params[:id])
</code>```

instead it should be

```<code>ObservativeSession.find(params[:observative_session_id])
</code>```

Body:
I have three tables: users, observative_sessions and observations.

In each respective model there's

users.rb

has_many :observative_sessions, dependent: :destroy
has_many :observations, through: :observative_sessions, dependent: :destroy

observative_sessions.rb

belongs_to :user
has_many :observations, dependent: :destroy

observations.rb

belongs_to :observative_session
belongs_to :user

In routes.rb I nested observations in observative_sessions

resources :observative_sessions do
  resources :observations
end

I show the list of possible observations for each observative_session so I created the partial (observations/_index.html.erb) to render in the show page of observative session.

<%= render 'observations/index' %>

and a button to create new observations

<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#new-observation-modal">Create</button>

observative_sessions_controller.rb

def show
   @q = Observation.ransack([:observative_session])
   @observations = @s.result.order(params[:order]).paginate(page: params[:page]) if params[:q].present?
   @observations = @s.result.order(params[:order]).paginate(page: params[:page]) unless params[:q].present?
   @observation = Observation.new
end

Now I have a problem, when I try to create a new observation the button calls the new_modal which renders the form

<%= render 'observations/form' %>

observations/_form.html.erb

<%= bootstrap_form_for ([@observative_session, @observation]) do |f| %>

And here I get the error Undefined method 'observations_path'
This is how I defined the creation method in observations_controller.rb

def create
  @observation = Observation.new(observation_params)

respond_to do |format|
  if @observation.save
    format.html { redirect_to [@observative_session, @observation], notice: 'Observation was successfully created.' }
    format.json { render :show, status: :created, location: @observation }
  else
    format.html { render :new }
    format.json { render json: @observation.errors, status: :unprocessable_entity }
  end
end

end

Thank you so much for any help.

Body:
My bad the error was on new.html.erb I passed

<%= render 'form', observation: @observation %>

instead of

<%= render 'form', observation: ([@observative_session, @observation]) %>

and in observations_controller.rb I had to add

    @observative_session = ObservativeSession.find(params[:observative_session_id])
    @observation = @observative_session.observations.build(observation_params)

By the way before I was trying to use thinking of passing the id of the session

ObservativeSession.find(params[:id])

instead it should be

ObservativeSession.find(params[:observative_session_id])


问:
Error when adding reference to class library in visual studio 2017
I have created a class library to a current solution in visual studio 2017 and I have added a reference to it in my main application.

But when I build I get this error

Severity Code Description Project File Line Suppression State Error Project 'C:\Users\declanmarks\Documents\oversurgeryassignment\OverSurgeryAssignment\Utility\Utility.csproj' targets '.NETStandard,Version=v2.0'. It cannot be referenced by a project that targets '.NETFramework,Version=v4.5.2'. OverSurgeryAssignment

I cannot figure out how to fix this.

答:
Make sure the Target framework version of the project that is referencing the class library matches the version in the class library.

You can get to the Target framework option by right-clicking the project in the solution explorer and clicking on Properties. The Target framework option is on the Application tab of the project properties window.


问:
how to convert this String to Decimal
i have this String '5666,232343' and i want to convert it to Decimal, i use cast('5666,232343' as decimal(7,5)) but it returns NULL value.
Do you know why it doesn't work with CAST

答:
You need to cast to a decimal that can hold the value of 5666.232343.

  DECIMAL(7,5) allows numbers in this format: ##.#####.  The biggest number you can have then is 99.99999.  You also need to take the comma out and replace it with a period:

```<code>SELECT CAST('5666.232343' as decimal(16,6)) AS [DecimalValue]
</code>```

Title: how to convert this String to Decimal

Body:
You need to cast to a decimal that can hold the value of 5666.232343.

  DECIMAL(7,5) allows numbers in this format: ##.#####.  The biggest number you can have then is 99.99999.  You also need to take the comma out and replace it with a period:

SELECT CAST('5666.232343' as decimal(16,6)) AS [DecimalValue]


问:
Constructor not found - How to add CPP file to Qt build process
This question led me on a wild goose chase, so I wanted to revise it to get the facts straight.

I am working with a set of classes which were arranged like this

```<code>//third party .h file
class ChildX : public ParentY {
  public:
    OtherClass member;
}

//third party .h file
class ParentY {
  protected:
     ParentY();
  //other public attributes
}

//third party .cpp file
ParentY::ParentY {
}
</code>```

Any time I tried to compile one of these classes I got an unhelpful error message

```<code>Undefined reference to 'ParentY::ParentY()' in function 'SomeClass::DoX()';
</code>```

The error is completely unhelpful, but I have finally determined that the problem is caused by the constructor in the CPP file. Apparently the code which includes the ChildX.h file does not link with the constructor hidden in the ParentY.cpp file. The solution (e.g. https://ubuntuforums.org/showthread.php?t=1966081) seems to require that the cpp file in question be compiled before running the rest of the build.

So now that I have figured out WHAT the error is and how to resolve it, I just need to figure out how to do it in QtCreator

答:
The solution comes in three parts.

Separately compile the cpp file into a .o object. I'm not going to talk about this step as I was able to use pre-compiled .o files for the third party library I was using. Apparently they were aware of the issue as well and prepared .o files for all their classes.

Following the advice of How to add object files to a project in Qt add the .o files to the LIBS portion of Qt's .pro file.

You may have additional dependencies between the .o file you compiled and other .o objects. If you can get all of them in one place you can get all the dependencies at once with a single line in the .pro file.

LIBS += /path/to/object/files

Body:
This question led me on a wild goose chase, so I wanted to revise it to get the facts straight.

I am working with a set of classes which were arranged like this

//third party .h file
class ChildX : public ParentY {
  public:
    OtherClass member;
}

//third party .h file
class ParentY {
  protected:
     ParentY();
  //other public attributes
}

//third party .cpp file
ParentY::ParentY {
}

Any time I tried to compile one of these classes I got an unhelpful error message

Undefined reference to 'ParentY::ParentY()' in function 'SomeClass::DoX()';

The error is completely unhelpful, but I have finally determined that the problem is caused by the constructor in the CPP file. Apparently the code which includes the ChildX.h file does not link with the constructor hidden in the ParentY.cpp file. The solution (e.g. https://ubuntuforums.org/showthread.php?t=1966081) seems to require that the cpp file in question be compiled before running the rest of the build.

So now that I have figured out WHAT the error is and how to resolve it, I just need to figure out how to do it in QtCreator


问:
New to CSS, issues with nav bar
I am new to CSS and can't work out a kink. I am having several issues with my nav css. The hover state is not inline with the normal state, and the last item is pushed onto a new line rather than equally spacing across a single bar.

JSFiddle

```<code>ul {
    left: 20%;
    top: 10%;
    list-style-type: none;
    margin: 0;
    padding: 0;
    text-align: center;
    overflow: hidden;
    background: radial-gradient(circle, #505050, #3E3E3E);
    width: 50%;
}

li {
    display: inline-block;
    float: left;
    width: 24%;
    margin: 0;
    padding: 0;
    border-right: 1px solid #232323;
}

/* Remove border from last tab */
li:last-child {
    border: none;
}

li:first-child {
    border: none;
}

/* Setting up the text on the menu */
li a {
    text-align: center;
    font: Verdana;
    font-size: 16px;
    display: inline-block;
    color: #EAE0D2;
    margin: 0;
    padding: 20px 20px;
    text-decoration: none;
    width: 25%;
}

/* Change the link color on hover */
li a:hover {

    background: linear-gradient(#2B2B2B, #232323);
    border:none;
    width: 83%;
}

/* Color the active tab */
.active {
    background: linear-gradient(#3E3E3E, #2B2B2B);
    color: #white;
}
</code>```

答:
Another approach to the others would be to calculate the widths minus the border like so:</p>

```<code>li {
  display: inline-block;
  float: left;
  width: calc( 25% - 3px ); /* 1px per border as specified */
  margin: 0;
  padding: 0;
  border-right: 1px solid #232323;
}
</code>```

Title: New to CSS, issues with nav bar

Body:
I am new to CSS and can't work out a kink. I am having several issues with my nav css. The hover state is not inline with the normal state, and the last item is pushed onto a new line rather than equally spacing across a single bar.

JSFiddle

ul {
    left: 20%;
    top: 10%;
    list-style-type: none;
    margin: 0;
    padding: 0;
    text-align: center;
    overflow: hidden;
    background: radial-gradient(circle, #505050, #3E3E3E);
    width: 50%;
}

li {
    display: inline-block;
    float: left;
    width: 24%;
    margin: 0;
    padding: 0;
    border-right: 1px solid #232323;
}

/* Remove border from last tab */
li:last-child {
    border: none;
}

li:first-child {
    border: none;
}

/* Setting up the text on the menu */
li a {
    text-align: center;
    font: Verdana;
    font-size: 16px;
    display: inline-block;
    color: #EAE0D2;
    margin: 0;
    padding: 20px 20px;
    text-decoration: none;
    width: 25%;
}

/* Change the link color on hover */
li a:hover {

    background: linear-gradient(#2B2B2B, #232323);
    border:none;
    width: 83%;
}

/* Color the active tab */
.active {
    background: linear-gradient(#3E3E3E, #2B2B2B);
    color: #white;
}

Body:
Another approach to the others would be to calculate the widths minus the border like so:

li {
  display: inline-block;
  float: left;
  width: calc( 25% - 3px ); /* 1px per border as specified */
  margin: 0;
  padding: 0;
  border-right: 1px solid #232323;
}


问:
Use VBA to hide/unhide columns (named ranges) in a table based on selection made in a separate cell on a different sheet
I have a selection criteria cell on Sheet1 and have a table on Sheet 2. Sheet 1 Cell B3 will have a dropdown with different options. I want to be able to make a selection in this dropdown which will accordingly hide/unhide certain columns in the table on Sheet2. So far the code i have below is based on selections being made on the same sheet as the table and i'm stuck as the code isnt working as i expect it to.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 2 And Target.Row = 3 And Target.Value = "CustomView" Then

Range("Fruits", "Months").Select

Application.Selection.EntireColumn.Hidden = True

Else

Range("Fruits", "Months").Select

Application.Selection.EntireColumn.Hidden = False

End If

End Sub
</code>```

The named ranges i specified using the formulas section. "Months" is in column G, and "Fruits" is in column I, yet the code currently hides columns G, H and I, instead of just column G and column I. Furthermore, everytime i try to move the selection criteria to a separate sheet, i get errors. Any help or suggestions would be appreciated.

答: Your range selection is incorrect.  Instead of Range("Fruits", "Months").Select you need to instead do Range("Fruits, Months").Select

Body:
I have a selection criteria cell on Sheet1 and have a table on Sheet 2. Sheet 1 Cell B3 will have a dropdown with different options. I want to be able to make a selection in this dropdown which will accordingly hide/unhide certain columns in the table on Sheet2. So far the code i have below is based on selections being made on the same sheet as the table and i'm stuck as the code isnt working as i expect it to.

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 2 And Target.Row = 3 And Target.Value = "CustomView" Then

Range("Fruits", "Months").Select

Application.Selection.EntireColumn.Hidden = True

Else

Range("Fruits", "Months").Select

Application.Selection.EntireColumn.Hidden = False

End If

End Sub

The named ranges i specified using the formulas section. "Months" is in column G, and "Fruits" is in column I, yet the code currently hides columns G, H and I, instead of just column G and column I. Furthermore, everytime i try to move the selection criteria to a separate sheet, i get errors. Any help or suggestions would be appreciated.


问:
JavaScript regex multiline text between two tags
I wrote a regex to fetch string from HTML, but it seems the multiline flag doesn't work.

This is my pattern and I want to get the text in h1 tag.

```<code>var pattern= /<div class="box-content-5">.*<h1>([^<]+?)<\/h1>/mi
m = html.search(pattern);
return m[1];
</code>```

I created a string to test it. When the string contains "\n", the result is always null. If I removed all the "\n"s, it gave me the right result, no matter with or without the /m flag.

What's wrong with my regex?

答:
[\s\S] did not work for me in nodejs 6.11.3.  Based on the RegExp documentation, it says to use [^] which does work for me.

(The dot, the decimal point) matches any single character except line
  terminators: \n, \r, \u2028 or \u2029.

Inside a character set, the dot loses its special meaning and matches
  a literal dot.

Note that the m multiline flag doesn't change the dot behavior. So to
  match a pattern across multiple lines, the character set [^] can be
  used (if you don't mean an old version of IE, of course), it will
  match any character including newlines.

For example:

/This is on line 1[^]*?This is on line 3/m

where the *? is the non-greedy grab of 0 or more occurrences of [^].

OwnerDisplayName: wangyh

ContentLicense: CC BY-SA 4.0

Body:
I wrote a regex to fetch string from HTML, but it seems the multiline flag doesn't work.

This is my pattern and I want to get the text in h1 tag.

var pattern= /
.*
([^<]+?)<\/h1>/mi
m = html.search(pattern);
return m[1];

I created a string to test it. When the string contains "\n", the result is always null. If I removed all the "\n"s, it gave me the right result, no matter with or without the /m flag.

What's wrong with my regex?


答:
I am new to CSS

Welcome onboard then!

To create a multiple row layout you may want to use flexbox, it's quite easy. See below an example and the explanations on how it's working:

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background: radial-gradient(circle, #505050, #3E3E3E);
  width: 100%;
  display: flex;
}

li {
  display: inline-block;
  flex-basis: 25%;
  border-right: 1px solid #232323;
  text-align: center;
}

/* Remove border from last tab */

li:last-child {
  border: none;
}

li:first-child {
  border: none;
}

/* Setting up the text on the menu */

li a {
  display: inline-block;
  font: Verdana;
  font-size: 16px;
  color: #EAE0D2;
  margin: 0;
  padding: 20px 20px;
  text-decoration: none;
}

/* Change the link color on hover */

li:hover {
  background: linear-gradient(#2B2B2B, #232323);
}

/* Color the active tab */

.active {
  background: linear-gradient(#3E3E3E, #2B2B2B);
  color: #white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="menu">
  <li class="active">HOME</li>
  <li>GALLERY</li>
  <li>ART</li>
  <li>CONTACT</li>
</ul></code>```

Wait, what?

We first set the container to display: flex

Then, tanks to flex-basis: 25%, we tell every element of the container (ul li {...}) to fit 25% of the total width of the container.

We move the text-align: center from ul {...} to ul li {...} and remove the width: 25% from li a {...} so the text inside the list items is correctly justified.

EDIT:

And finally (to fix hover issues), we change

```<code>li a:hover {
  background: linear-gradient(#2B2B2B, #232323);
  border:none;
  width: 83%;
}
</code>```

to

```<code>li:hover {
  background: linear-gradient(#2B2B2B, #232323);
}
</code>```

Title: New to CSS, issues with nav bar

Body:
I am new to CSS

Welcome onboard then!

To create a multiple row layout you may want to use flexbox, it's quite easy. See below an example and the explanations on how it's working:

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background: radial-gradient(circle, #505050, #3E3E3E);
  width: 100%;
  display: flex;
}

li {
  display: inline-block;
  flex-basis: 25%;
  border-right: 1px solid #232323;
  text-align: center;
}

/* Remove border from last tab */

li:last-child {
  border: none;
}

li:first-child {
  border: none;
}

/* Setting up the text on the menu */

li a {
  display: inline-block;
  font: Verdana;
  font-size: 16px;
  color: #EAE0D2;
  margin: 0;
  padding: 20px 20px;
  text-decoration: none;
}

/* Change the link color on hover */

li:hover {
  background: linear-gradient(#2B2B2B, #232323);
}

/* Color the active tab */

.active {
  background: linear-gradient(#3E3E3E, #2B2B2B);
  color: #white;
}

<ul id="menu">
  <li class="active"><a href="#">HOME</a></li>
  <li><a href="#">GALLERY</a></li>
  <li><a href="#">ART</a></li>
  <li><a href="#">CONTACT</a></li>
</ul>

Wait, what?

We first set the container to display: flex

Then, tanks to flex-basis: 25%, we tell every element of the container (ul li {...}) to fit 25% of the total width of the container.

We move the text-align: center from ul {...} to ul li {...} and remove the width: 25% from li a {...} so the text inside the list items is correctly justified.

EDIT:

And finally (to fix hover issues), we change

li a:hover {
  background: linear-gradient(#2B2B2B, #232323);
  border:none;
  width: 83%;
}

to

li:hover {
  background: linear-gradient(#2B2B2B, #232323);
}


问:
Hibernate xml set mapping problems
I just learn Hibernate, and have some problems with xml mapping.Error code:

```<code>Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
</code>```

Part of database which i want to map looks like this
part of db

In java application i have two entity class, for each of this tables. I donot insert getters setter and constructor here for better readability.

```<code> public class OccupiedBedsEntity {
    private int id;
    private Timestamp since;
    private Timestamp to;
    private int id_room;
}

  public class RoomEntity {
        private int id;
        private int roomNumber;
        private Integer numberOfBeds;
        private int id_department;
        private int idResponsibleDoctor;
        private Set beds;
    }
</code>```

Xml mapping looks like this.

```<code>    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping default-cascade="all">
        <class name="entity.RoomEntity" table="room" schema="" catalog="medicine">
            <id name="id">
                <column name="id" sql-type="int unsigned" not-null="true"/>
                <generator class="native"/>
            </id>
            <property name="roomNumber">
                <column name="room_number" sql-type="int unsigned" not-null="true"/>
            </property>
            <property name="numberOfBeds">
                <column name="number_of_beds" sql-type="int unsigned"/>
            </property>
            <property name="idResponsibleDoctor">
                <column name="id_responsible_doctor" sql-type="int unsigned" not-null="true"/>
            </property>
            <property name="id_department">
                <column name="id_department" sql-type="int unsigned" not-null="true"/>
            </property>
            <set name="beds">
                <key column="id_room"></key>
                <one-to-many class="entity.OccupiedBedsEntity"/>
            </set>
        </class>
    </hibernate-mapping>

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" enter code here"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-cascade="all">
<class name="entity.OccupiedBedsEntity" table="occupied_beds" schema="medicine" catalog="medicine">
    <id name="id">
        <column name="id" sql-type="int unsigned" not-null="true"/>
        <generator class="native"/>
    </id>
    <property name="since">
        <column name="since_" sql-type="datetime" not-null="true"/>
    </property>
    <property name="to">
        <column name="to_" sql-type="datetime" not-null="true"/>
    </property>
    <property name="id_room">
        <column name="id_room" sql-type="int unsigned" not-null="true"></column>
    </property>
</class>
</hibernate-mapping>
</code>```

Maybe i have to change something not in xml, but in java classes?

答:
Error was in this line in occupiesBebsEntity xml mapper.

```<code><class name="entity.OccupiedBedsEntity" table="occupied_beds" schema="medicine" catalog="medicine">
</code>```

Code should looks like this.

```<code><class name="entity.OccupiedBedsEntity" table="occupied_beds" schema="" catalog="medicine">
</code>```

Title: Hibernate xml set mapping problems

Body:
I just learn Hibernate, and have some problems with xml mapping.Error code:

Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement

Part of database which i want to map looks like this
part of db

In java application i have two entity class, for each of this tables. I donot insert getters setter and constructor here for better readability.

 public class OccupiedBedsEntity {
    private int id;
    private Timestamp since;
    private Timestamp to;
    private int id_room;
}

  public class RoomEntity {
        private int id;
        private int roomNumber;
        private Integer numberOfBeds;
        private int id_department;
        private int idResponsibleDoctor;
        private Set beds;
    }

Xml mapping looks like this.

    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping default-cascade="all">
        <class name="entity.RoomEntity" table="room" schema="" catalog="medicine">
            <id name="id">
                <column name="id" sql-type="int unsigned" not-null="true"/>
                <generator class="native"/>
            </id>
            <property name="roomNumber">
                <column name="room_number" sql-type="int unsigned" not-null="true"/>
            </property>
            <property name="numberOfBeds">
                <column name="number_of_beds" sql-type="int unsigned"/>
            </property>
            <property name="idResponsibleDoctor">
                <column name="id_responsible_doctor" sql-type="int unsigned" not-null="true"/>
            </property>
            <property name="id_department">
                <column name="id_department" sql-type="int unsigned" not-null="true"/>
            </property>
            <set name="beds">
                <key column="id_room"></key>
                <one-to-many class="entity.OccupiedBedsEntity"/>
            </set>
        </class>
    </hibernate-mapping>

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" enter code here"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-cascade="all">
<class name="entity.OccupiedBedsEntity" table="occupied_beds" schema="medicine" catalog="medicine">
    <id name="id">
        <column name="id" sql-type="int unsigned" not-null="true"/>
        <generator class="native"/>
    </id>
    <property name="since">
        <column name="since_" sql-type="datetime" not-null="true"/>
    </property>
    <property name="to">
        <column name="to_" sql-type="datetime" not-null="true"/>
    </property>
    <property name="id_room">
        <column name="id_room" sql-type="int unsigned" not-null="true"></column>
    </property>
</class>
</hibernate-mapping>

Maybe i have to change something not in xml, but in java classes?

Body:
Error was in this line in occupiesBebsEntity xml mapper.

<class name="entity.OccupiedBedsEntity" table="occupied_beds" schema="medicine" catalog="medicine">

Code should looks like this.

<class name="entity.OccupiedBedsEntity" table="occupied_beds" schema="" catalog="medicine">


答:
change your width in li to 24%

```<code>width:24%;
</code>```

http://jsfiddle.net/HBXku/360/

Update: you have li a set to a width of 25% so the link was only 25% of the size of the box. i changed it to 80% and it works fine.

Title: New to CSS, issues with nav bar

Body:
change your width in li to 24%

width:24%;

http://jsfiddle.net/HBXku/360/

Update: you have li a set to a width of 25% so the link was only 25% of the size of the box. i changed it to 80% and it works fine.


问:
MVC3 Plugin architecture recommendations
I am trying to find some more information on approaches to creating a plugin architecture.

I've seen some good articles on MEF and MVC2 and Phil Haack mentioned some new extensibilty hooks available in MVC3 (http://haacked.com/archive/2010/05/16/three-hidden-extensibility-gems-in-asp-net-4.aspx)

Has anyone seen some good references on creating a plugin architecture for a MVC3 project?

I'd prefer to use technologies specific to MVC3, not to just hack a MVC2 solution in to the MVC2 framework.

Any ideas and suggestions would be greatly appreciated!

答:
We're using a combination of MVCContrib Portable Areas and Mono.Addins for our plugin framework.

It is working wonderfully.


问:
Using Polymer <app-route> element outside an app?
I'm building a website (not a single page app) which uses Polymer Elements. The website "app" is not contained in a <dom-module>, but I still want to make use of the <app-route> element.

How can I do that without creating a custom "app-element" that contains the entire site (I tried putting it all into a <dom-module> but got loads of errors)?

If I simply use <app-route> and <app-location> within the  tag I get a

```<code>Uncaught TypeError: Cannot read property 'length' of undefined
</code>```

even if I try binding the route/data/tail attributes programmatically instead of using e.g. route="{{route}}".

答:
Polymer elements that do not sit within a context of another Polymer managed element are seen from the perspective of a browser simply as custom tags.
Each of them is encapsulated and has their own separate internal context and by design elements do not interact with external context other than by sending events.

Polymer implements a mediator pattern so elements are not communicating directly even though it may appear so but instead there are various observers set up implicilty.
Thus to make that communication to actually happen you need to make sure that your elements are wrapped in some kind of Polymer-managed element - which in your case may be as pointed out by Kuba Šimonovský a dom-bind helper element.

If for whatever reason you do not want to use that element you may implement your own event driven mediator for your elements (not really recommended).

Body:
I'm building a website (not a single page app) which uses Polymer Elements. The website "app" is not contained in a <dom-module>, but I still want to make use of the <app-route> element.

How can I do that without creating a custom "app-element" that contains the entire site (I tried putting it all into a <dom-module> but got loads of errors)?

If I simply use <app-route> and <app-location> within the  tag I get a

Uncaught TypeError: Cannot read property 'length' of undefined

even if I try binding the route/data/tail attributes programmatically instead of using e.g. route="{{route}}".


问:
Most efficient way of storing exact set membership?
I have N slots.  There are M slots occupied.

I want to be able to tell exactly whether each slot is occupied.  (No Bloom filter answers, please.)

What is the absolute most storage-space efficient way of storing this information for M << N?

Guess 0: A bitmap of N bits.

Guess 1: An array of the positions of the occupied slots.  Reasonably good for small M.

Guess 2: p0 + (M-1)p1 + (M-1)(M-2)p2 + ... where pX is the position of an occupied slot, among the remaining unoccupied slots.  This is slightly more efficient than guess 1, as the choice of unoccupied slot narrows as slots are filled.

Guess 2 still has a lot of waste; it includes the order in which the slots were filled, which is information that is not required.

What method is more efficient than Guess 2?

答:
If M and N are known, then one way of achieving the best compression is to store the index of the combination.

There are t= N!/((N-M)!*M!) ways of choosing the M slots to be filled, so you will always need at least log2(t) bits to represent this information.

Storing the index of the combination allows you to use exactly ceil(log2(t))bits.


问:
Node.js Route to specific div on page
I have a website with a page with different parts that I want my links on my navbar to go to when clicked.  I know in html you can use  to go to an Id on the page, but this won't work when on another page.  I use node.js for my back-end.

```<code>app.get("/", function(req, res){
res.render("index");
});

app.get('/portfolio', function(req, res){
res.render('portfolio');
});
</code>```

As you can see I have two routes, one for my homepage and one for my portfolio page.  On my homepage I use the html I said earlier to go to certain divs on my page.  However, on my portfolio page I can't use the same html and have to use my node routes to go to my index page.  Is there a way in node to have the page load on a certain div?

答:
hello my dear friend first of all you have to use a View Engine for rendering html pages and you can active it in express with app.set('view engine', 'pug') and with this way you can use id like this to open a certain div

/portfolio/#firstDiv

Title: Node.js Route to specific div on page

Body:
I have a website with a page with different parts that I want my links on my navbar to go to when clicked.  I know in html you can use  to go to an Id on the page, but this won't work when on another page.  I use node.js for my back-end.

app.get("/", function(req, res){
res.render("index");
});

app.get('/portfolio', function(req, res){
res.render('portfolio');
});

As you can see I have two routes, one for my homepage and one for my portfolio page.  On my homepage I use the html I said earlier to go to certain divs on my page.  However, on my portfolio page I can't use the same html and have to use my node routes to go to my index page.  Is there a way in node to have the page load on a certain div?


问:
reactJS disable console.log system wide
I have console.log all over the place. Removing them all is not good as I might need them again. Is there way I can do something like this for entire react app?</p>

```<code>if(env === 'production'){
  console.log= function(){}
}
</code>```

答:
```<code>export function consoleLog() {
  const args = [...arguments];
  for (let i = 0; i < args.length; i++) {
    console.log(args[i]);
  }
}
</code>```

save this is a file somewhere, then search all of your files for console.log and replace with consoleLog and make sure you import it at the top of each file where you want to use it.

When you build your production bundle you can simply change it to...

```<code>export function consoleLog() {
  // const args = [...arguments];
  // for (let i = 0; i < args.length; i++) {
  //  console.log(args[i]);
  // }
}
</code>```

Title: reactJS disable console.log system wide

Body:
I have console.log all over the place. Removing them all is not good as I might need them again. Is there way I can do something like this for entire react app?

if(env === 'production'){
  console.log= function(){}
}

Body:
export function consoleLog() {
  const args = [...arguments];
  for (let i = 0; i < args.length; i++) {
    console.log(args[i]);
  }
}

save this is a file somewhere, then search all of your files for console.log and replace with consoleLog and make sure you import it at the top of each file where you want to use it.

When you build your production bundle you can simply change it to...

export function consoleLog() {
  // const args = [...arguments];
  // for (let i = 0; i < args.length; i++) {
  //  console.log(args[i]);
  // }
}


问:
Pandas iterrows get row string as list
I have a df in pandas which looks like:

```<code>id  name  values

1    a    cat dog
2    b    bird fly
</code>```

I'm currently doing:

```<code>for index, row in df.iterrows():
     print row["values"]
</code>```

However, that prints the entire cell: "cat dog" or "bird fly".

I've tried doing:

```<code>print row["values"][0]
</code>```

That instead prints a single character, so "c" and "b".

How can I get instead something like ["cat", "dog"] and ["bird", "fly"]

答:
You need to split the data

```<code>df['values'].str.split()

0     [cat, dog]
1    [bird, fly]
</code>```

To get the individual element,

```<code>df['values'].str.split().str[0]
</code>```

And you get

```<code>0     cat
1    bird
</code>```

Title: Pandas iterrows get row string as list

Body:
I have a df in pandas which looks like:

id  name  values

1    a    cat dog
2    b    bird fly

I'm currently doing:

for index, row in df.iterrows():
     print row["values"]

However, that prints the entire cell: "cat dog" or "bird fly".

I've tried doing:

print row["values"][0]

That instead prints a single character, so "c" and "b".

How can I get instead something like ["cat", "dog"] and ["bird", "fly"]

Body:
You need to split the data

df['values'].str.split()

0     [cat, dog]
1    [bird, fly]

To get the individual element,

df['values'].str.split().str[0]

And you get

0     cat
1    bird


问:
HTTP TRACE / TRACK Methods Enabled vulnerability in Coldfusion server
I keep getting HTTP TRACE / TRACK Methods Enabled vulnerability in Coldfusion server. Any suggestions to fix this would be of great help.</p>

答:
The blanket disallowing of these methods is more the concern of the HTTP server (IIS, Apache, NGINX ) than the application server (Coldfusion, Lucee). There may be use cases where these HTTP verbs might be legitimately in use.

You can, however, handle this from within the onRequestStart method of Application.cfc with a few lines of code.

```<code>var disallowVerbs = [ "TRACE", "TRACK" ];
if( arrayContains( disallowVerbs, cgi.request_method ) ){
    cfheader( statusCode=403, statusText="Method Not Allowed" );
}
</code>```

Body:
The blanket disallowing of these methods is more the concern of the HTTP server (IIS, Apache, NGINX ) than the application server (Coldfusion, Lucee). There may be use cases where these HTTP verbs might be legitimately in use.

You can, however, handle this from within the onRequestStart method of Application.cfc with a few lines of code.

var disallowVerbs = [ "TRACE", "TRACK" ];
if( arrayContains( disallowVerbs, cgi.request_method ) ){
    cfheader( statusCode=403, statusText="Method Not Allowed" );
}


问:
Using a C++11 shared library in a C++03 application that was compiled with gcc 4.1 in Linux?
Having gone through a number of similar questions (see below), I don't think any of them cover this case.

Problem

Is it possible to dlopen and use a C++11 shared library compiled using gcc 4.9 from a C++03 application compiled with gcc 4.1? Both the library and application use libstdc++, including on the API (but not std::list, which is apparently a problem). I can't change the way the application is compiled (sadly), and must be certain that existing code doesn't break (e.g. if it ends up dynamically linking to a new version of libstdc++.so).

As far as I understand it (which is not very), on Linux the dynamic linker uses a flat namespace, meaning that is not possible to have the same symbol defined in two libraries. Does statically linking the library against the newer libstdc++ help at all here, or is there perhaps some other way?

Some similar questions that don't seem to answer this

C++11 backwards compatibility

C++03 library with C++11 source code

C++11 compatibility with existing libraries/frameworks

Can a compiled C++11 library (lib,dll,etc.) be linked in older C++ compilers? [softwareengineering.stackexchange.com]

答:
If you do that, you definitely need to use the newer libstdc++.so.6, which should be compatible with the system libstdc++.so.6 based on GCC 4.1 (in the sense that GCC upstream intends to preserve ABI compatibility for the library).  It would be a very good idea to use the libstdc++.so.6 library that came with the GCC 4.9 compiler.

Once you do that, it is supposed to work, unless you hit the few of the compatibility gotchas you already listed, and as long as the C++ part of the library interface actually sticks to the C++98 subset and does not use any constructs which are not expressible in the language subset.

All this assumes that the library was actually compiled on the the system which uses GCC 4.1, which probably has something like glibc 2.5.  If the library was compiled on a completely different, newer system, then you will likely run into library compatibility issues beyond libstdc++.so.6, and these libraries tend to be even harder to upgrade.

(There is also the possibility that the library was explicitly compiled for use with the 4.1-based system libstdc++.so.6 and everything just works, just as if by magic, but then you wouldn't be asking here, I suppose.)