问:
jquery validate show 1 message with total number of errors
Instead of showing a message under each form element, if there are more than 5 errors I would like to show 1 error message above the form with the total number of errors.

Reason: I have a large form and this can nearly double in height if there are lots of errors.

How would I get the total number of errors?

E.g something like this but this always returns 1.

```<code>errorPlacement: function(error, element) {
    var errorCount = 0;
    var i;
    for (i = 0; i < error.length; ++i) {
        errorCount++;
    }
}
</code>```

答:
In case someone else comes across this question, there was an error in szaboat's jsfiddle that caused a problem for me.

You need to pass a function to the invalidHandler option of the validate() method and the function should accept two arguments. The second argument is the validator itself which has a numberOfInvalids() method which returns the total error count.

Here is the example from the jQuery Validation Plugin Documentation.

```<code>$("#myform").validate({
  invalidHandler: function(event, validator) {
    // 'this' refers to the form
    var errors = validator.numberOfInvalids();
    if (errors) {
      var message = errors == 1
        ? 'You missed 1 field. It has been highlighted'
        : 'You missed ' + errors + ' fields. They have been highlighted';
      $("div.error span").html(message);
      $("div.error").show();
    } else {
      $("div.error").hide();
    }
  }
});
</code>```

Body:
Instead of showing a message under each form element, if there are more than 5 errors I would like to show 1 error message above the form with the total number of errors.

Reason: I have a large form and this can nearly double in height if there are lots of errors.

How would I get the total number of errors?

E.g something like this but this always returns 1.

errorPlacement: function(error, element) {
    var errorCount = 0;
    var i;
    for (i = 0; i < error.length; ++i) {
        errorCount++;
    }
}

Body:
In case someone else comes across this question, there was an error in szaboat's jsfiddle that caused a problem for me.

You need to pass a function to the invalidHandler option of the validate() method and the function should accept two arguments. The second argument is the validator itself which has a numberOfInvalids() method which returns the total error count.

Here is the example from the jQuery Validation Plugin Documentation.

$("#myform").validate({
  invalidHandler: function(event, validator) {
    // 'this' refers to the form
    var errors = validator.numberOfInvalids();
    if (errors) {
      var message = errors == 1
        ? 'You missed 1 field. It has been highlighted'
        : 'You missed ' + errors + ' fields. They have been highlighted';
      $("div.error span").html(message);
      $("div.error").show();
    } else {
      $("div.error").hide();
    }
  }
});


来源: stackexchange

问:
Celery: log each task run to its own file?
I want each job running to log to its own file in the logs/ directory where the filename is the taskid.

```<code>logger = get_task_logger(__name__)

@app.task(base=CallbackTask)
def calc(syntax):
    some_func()
    logger.info('started')
</code>```

In my worker, I set the log file to output to by using the -f argument. I want to make sure that it outputs each task to its own log file.

答:
Seems like I am 3 years late. Nevertheless here's my solution inspired from @Mikko Ohtamaa idea. I just made it little different by using Celery Signals and python's inbuilt logging framework for preparing and cleaning logging handle.

```<code>from celery.signals import task_prerun, task_postrun
import logging

# to control the tasks that required logging mechanism
TASK_WITH_LOGGING = ['Proj.tasks.calc']
@task_prerun.connect(sender=TASK_WITH_LOGGING)
def prepare_logging(signal=None, sender=None, task_id=None, task=None, args=None, kwargs=None):
    logger = logging.getLogger(task_id)
    formatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
    # optionally logging on the Console as well as file
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)
    stream_handler.setLevel(logging.INFO)
    # Adding File Handle with file path. Filename is task_id
    task_handler = logging.FileHandler(os.path.join('/tmp/', task_id+'.log'))
    task_handler.setFormatter(formatter)
    task_handler.setLevel(logging.INFO)
    logger.addHandler(stream_handler)
    logger.addHandler(task_handler)

@task_postrun.connect(sender=TASK_WITH_LOGGING)
def close_logging(signal=None, sender=None, task_id=None, task=None, args=None, kwargs=None, retval=None, state=None):
    # getting the same logger and closing all handles associated with it
    logger = logging.getLogger(task_id)
    for handler in logger.handlers:
        handler.flush()
        handler.close()
    logger.handlers = []

@app.task(base=CallbackTask, bind=True)
def calc(self, syntax):
    # getting logger with name Task ID. This is already
    # created and setup in prepare_logging
    logger = logging.getLogger(self.request.id)
    some_func()
    logger.info('started')
</code>```

The bind=True is necessary here in order to have id available within task. This will create individual log file with <task_id>.log every time the task calc is executed.

ContentLicense: CC BY-SA 4.0

Body:
I want each job running to log to its own file in the logs/ directory where the filename is the taskid.

logger = get_task_logger(__name__)

@app.task(base=CallbackTask)
def calc(syntax):
    some_func()
    logger.info('started')

In my worker, I set the log file to output to by using the -f argument. I want to make sure that it outputs each task to its own log file.

Body:
Seems like I am 3 years late. Nevertheless here's my solution inspired from @Mikko Ohtamaa idea. I just made it little different by using Celery Signals and python's inbuilt logging framework for preparing and cleaning logging handle.

from celery.signals import task_prerun, task_postrun
import logging

# to control the tasks that required logging mechanism
TASK_WITH_LOGGING = ['Proj.tasks.calc']
@task_prerun.connect(sender=TASK_WITH_LOGGING)
def prepare_logging(signal=None, sender=None, task_id=None, task=None, args=None, kwargs=None):
    logger = logging.getLogger(task_id)
    formatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
    # optionally logging on the Console as well as file
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)
    stream_handler.setLevel(logging.INFO)
    # Adding File Handle with file path. Filename is task_id
    task_handler = logging.FileHandler(os.path.join('/tmp/', task_id+'.log'))
    task_handler.setFormatter(formatter)
    task_handler.setLevel(logging.INFO)
    logger.addHandler(stream_handler)
    logger.addHandler(task_handler)

@task_postrun.connect(sender=TASK_WITH_LOGGING)
def close_logging(signal=None, sender=None, task_id=None, task=None, args=None, kwargs=None, retval=None, state=None):
    # getting the same logger and closing all handles associated with it
    logger = logging.getLogger(task_id)
    for handler in logger.handlers:
        handler.flush()
        handler.close()
    logger.handlers = []

@app.task(base=CallbackTask, bind=True)
def calc(self, syntax):
    # getting logger with name Task ID. This is already
    # created and setup in prepare_logging
    logger = logging.getLogger(self.request.id)
    some_func()
    logger.info('started')

The bind=True is necessary here in order to have id available within task. This will create individual log file with <task_id>.log every time the task calc is executed.


问:
Not sure why but .gitignore isn't working
I have added /build/ to my .gitingore but whenever I do build, git shows that my build folder is untracked. I have following folder hierarchy

```<code>~/workspace/ProjectName/ ➤ 617a838|mainline⚡
1361 ± : tree -La 1                                                                                [6d1h6m] ✭
.
├── .DS_Store
├── .git
├── .gitignore
├── Config
├── build
├── build.xml
├── checkstyle.xml
├── configuration
├── src
└── tst

5 directories, 5 files

~/workspace/ProjectName/ ➤ 617a838|mainline⚡
1362 ± : git status                                                                                [6d1h7m] ✭
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:
  (use "git add <file>..." to include in what will be committed)

        build

nothing added to commit but untracked files present (use "git add" to track)
</code>```

Here is content of .gitignore

```<code>/build/
/eclipse-bin/
</code>```

one thing that i did notice is that .gitingore is a hidden file. Does this even matter?

答:
Your .gitignore is fine for exculding a folder named build directly besides the .gitignore file and all its contents.

That the file is hidden is by definition. All files on *nix systems that start with a dot are considered hidden files and this does not interrupt the least.

That your ignore is not working is simply due to the fact that build is not a folder, but a file. The git status output says this at least and that is why the ignore is not working. If build would be a folder with some trackable content inside, it would appear as build/ in git status output, not as build.

If build actually is a symbolic link to another folder, that would also explain the situation, because a symbolic link is file that links to a folder, but is not a folder by itself. In that case you would need to exclude the file build instead of the folder build, or to be correct both, the file and the folder called build, as you can fix the type to be a folder by appending a slash as last character, but you cannot fix the type to be a file. So if this is your situation, change /build/ to /build and the symbolic link will be ignored.

ContentLicense: CC BY-SA 3.0

Body:
I have added /build/ to my .gitingore but whenever I do build, git shows that my build folder is untracked. I have following folder hierarchy

~/workspace/ProjectName/ ➤ 617a838|mainline⚡
1361 ± : tree -La 1                                                                                [6d1h6m] ✭
.
├── .DS_Store
├── .git
├── .gitignore
├── Config
├── build
├── build.xml
├── checkstyle.xml
├── configuration
├── src
└── tst

5 directories, 5 files

~/workspace/ProjectName/ ➤ 617a838|mainline⚡
1362 ± : git status                                                                                [6d1h7m] ✭
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:
  (use "git add <file>..." to include in what will be committed)

        build

nothing added to commit but untracked files present (use "git add" to track)

Here is content of .gitignore

/build/
/eclipse-bin/

one thing that i did notice is that .gitingore is a hidden file. Does this even matter?


问:
ARP in Linux creates FAILED entries
Under Linux-4.11 a locally generated ARP request would result in an ARP entry created with state FAILED (as seen by ip neigh show), when there's nobody to respond. Is this normal behaviour?

Also, flushing sudo ip neigh flush dev eth0 doesn't flush the entries, they are still there.

答:
To flush Entries, you must root user
like as "sudo ip neigh flush dev eth0"</p>

Title: ARP in Linux creates FAILED entries


问:
C# Gamepad Input/Output Class
I am trying to design a little program that takes input from two PS2 controllers from a USB converter. I would like to take input from all the buttons including pressing the joysticks in (L3, R3), and the joysticks position, and whether the analog is on. I would also like to send feedback back to the controllers and run the two vibration motors and possibly control the LED for analog.

What I'm looking for is a C# source code file that can do it all or an already compiled all-in-one DLL or even a beginners tutorial.

答: You will likely need to develop a .NET library of your own to interface with a PlayStation controller, and this could get pretty involved. This article can help get you started. Good luck!</p>

ContentLicense: CC BY-SA 2.5

Title: C# Gamepad Input/Output Class


问:
C# maskedTextbox, how to disable whitespaces?
I cant figure out how to disable whitespaces, I tried multiple things, and yes my mask is 00000000000 but still it allows whitespaces. Anyone know a fix?

Not much code to show, only:

Should only allow numbers to be entered, not whitespaces too :/

答:
Add the KeyDown Event to your textbox and then add the following Code in the created method: </p>

```<code>private void textBox_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyCode == Keys.Space)
  {
    e.Handled = true;
    e.SuppressKeyPress = true;
    return;
  }
}
</code>```

Body:
Add the KeyDown Event to your textbox and then add the following Code in the created method:

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyCode == Keys.Space)
  {
    e.Handled = true;
    e.SuppressKeyPress = true;
    return;
  }
}


问:
MySQL - Keep finding superiors of employees until the most superior employee is reached
I have an employees table in which all employees report to a superior except for one employee who reports to no one as he is the boss.

```<code>employeeNumber | reportsTo
---------------|-----------------
1002           | null
1056           | 1002
1143           | 1056
1165           | 1143
...
</code>```

I want to be able to show the employee numbers of all employees who are superiors of a particular employee. (i.e. the person he reportsTo, and the employee who that person reportsTo, ... all the way up)

For e.g. employeeNumber 1165 should yield

```<code>   | employeeNumber |
   |----------------|
   | null           |
   | 1002           |
   | 1056           |
   | 1143           |
</code>```

I have written a MySQL statement which carries out the query but I believe this is a bit too complex to read and understand:

```<code>select reportsTo as employeeNumber from employees where employeeNumber in
(select reportsTo from employees where employeeNumber in (select reportsTo from employees where
employeeNumber = 1165)) union select reportsTo from employees where employeeNumber in
(select reportsTo from employees where employeeNumber = 1165) union select reportsTo from employees
where employeeNumber = 1165;
</code>```

What simple MySQL statement can I use to get the same result?

答:
It's been a while since I've written actual SQL code (thanks you Enitity Framework), so I'll try to write this a bit in pseudo code which will probably lean towards C#. Sorry for that.
Maybe somebody can translate it for me?

```<code>int EmployeeNumber = 1165;
int bigChiefNumber = GetChiefOf(EmployeeNumber);

private int GetChiefOf(int EmployeeNumber)
{
    if(employeeNumber.reportsTo == null)
    {
        return employeeNumber;
    } else
    {
        return GetChiefOf(employeeNumber.reportsTo);
    }
}
</code>```

Or somewhat shorter:

```<code>int BigChiefNumber = GetChiefOf(1165);

private int GetChiefOf(int employeeNumber)
{
    return (employeeNumber.reportsTo == null)
        ? employeeNumber
        : GetChiefOf(employeeNumber.reportsTo);
}
</code>```

I guess in SQL you'd need to create a nested stored procedure.
I hope this gets you the right direction :).

Edit: So, I didn't notice the MySQL part. I'm used to TSQL. I didn't know MySQL doesn't support recursive queries (not even with Stored Procedures ?).
This means you can safely ignore my answer :(.

Body:
I have an employees table in which all employees report to a superior except for one employee who reports to no one as he is the boss.

employeeNumber | reportsTo
---------------|-----------------
1002           | null
1056           | 1002
1143           | 1056
1165           | 1143
...

I want to be able to show the employee numbers of all employees who are superiors of a particular employee. (i.e. the person he reportsTo, and the employee who that person reportsTo, ... all the way up)

For e.g. employeeNumber 1165 should yield

   | employeeNumber |
   |----------------|
   | null           |
   | 1002           |
   | 1056           |
   | 1143           |

I have written a MySQL statement which carries out the query but I believe this is a bit too complex to read and understand:

select reportsTo as employeeNumber from employees where employeeNumber in
(select reportsTo from employees where employeeNumber in (select reportsTo from employees where
employeeNumber = 1165)) union select reportsTo from employees where employeeNumber in
(select reportsTo from employees where employeeNumber = 1165) union select reportsTo from employees
where employeeNumber = 1165;

What simple MySQL statement can I use to get the same result?

Body:
It's been a while since I've written actual SQL code (thanks you Enitity Framework), so I'll try to write this a bit in pseudo code which will probably lean towards C#. Sorry for that.
Maybe somebody can translate it for me?

int EmployeeNumber = 1165;
int bigChiefNumber = GetChiefOf(EmployeeNumber);

private int GetChiefOf(int EmployeeNumber)
{
    if(employeeNumber.reportsTo == null)
    {
        return employeeNumber;
    } else
    {
        return GetChiefOf(employeeNumber.reportsTo);
    }
}

Or somewhat shorter:

int BigChiefNumber = GetChiefOf(1165);

private int GetChiefOf(int employeeNumber)
{
    return (employeeNumber.reportsTo == null)
        ? employeeNumber
        : GetChiefOf(employeeNumber.reportsTo);
}

I guess in SQL you'd need to create a nested stored procedure.
I hope this gets you the right direction :).

Edit: So, I didn't notice the MySQL part. I'm used to TSQL. I didn't know MySQL doesn't support recursive queries (not even with Stored Procedures ?).
This means you can safely ignore my answer :(.


问:
Xcode 9 Beta - editor, column selection gone?
In previous versions of Xcode, we could hold down Alt/Option key, drag the mouse to select columns in the text editor. In Xcode 9 Beta this doesn't seem to work.

Is this gone now, or is it a different key combination? Any ideas?

答:
According to the Xcode 9 release notes it is a missing feature.  I can only assume it will be added back in before the official release.

From the Xcode 9 Release Notes (page 21):

Xcode 9’s new source editor does not yet support discontiguous or columnar selection. (30738532)


问:
Delay in gulp watch
Currently I'm working true ftp and running gulp watch on te server, now te problem is that when my gulp watch is detecting changes the file is not ready with uploading, so I need to have a delay in my gulp watch.

```<code>gulp.task('watch', function() {
  setTimeout(function() {
    gulp.watch(config.js.app.pathIn + '/**/*.js', ['js_app']);
    gulp.watch(config.js.vendor.pathIn + '/**/*.js', ['js_vendor']);
    gulp.watch(config.scss.pathIn + '/**/*.scss', ['scss']);
  }, 3000);
});
</code>```

This is not delaying the rendering of the files, how can I make sure to have a delay when rending the files?

答:
Gulp-wait looks like it could work for you.  Insert it into the top of your three tasks.

```<code>gulp.task('watch', function() {
   gulp.watch(config.js.app.pathIn + '/**/*.js', setTimeout(function() {
     gulp.start('scss')
  }, 3000)
});
</code>```

Above might work if you want a setTimeout method but it uses gulp.start - to be removed from gulp4.0.  Much easier if you used gulp4 and just made a function call here to your task instead of to gulp.start.

But I suggest gulp-wait.

Title: Delay in gulp watch

Body:
Currently I'm working true ftp and running gulp watch on te server, now te problem is that when my gulp watch is detecting changes the file is not ready with uploading, so I need to have a delay in my gulp watch.

gulp.task('watch', function() {
  setTimeout(function() {
    gulp.watch(config.js.app.pathIn + '/**/*.js', ['js_app']);
    gulp.watch(config.js.vendor.pathIn + '/**/*.js', ['js_vendor']);
    gulp.watch(config.scss.pathIn + '/**/*.scss', ['scss']);
  }, 3000);
});

This is not delaying the rendering of the files, how can I make sure to have a delay when rending the files?

Body:
Gulp-wait looks like it could work for you.  Insert it into the top of your three tasks.

gulp.task('watch', function() {
   gulp.watch(config.js.app.pathIn + '/**/*.js', setTimeout(function() {
     gulp.start('scss')
  }, 3000)
});

Above might work if you want a setTimeout method but it uses gulp.start - to be removed from gulp4.0.  Much easier if you used gulp4 and just made a function call here to your task instead of to gulp.start.

But I suggest gulp-wait.


问:
How to create an accordion menu in HTML without jQuery
How can I make an accordion in plain HTML?</p>

```<code>- <table border="1">
       <tr>
         <th><input name="checkbox" type="checkbox" id="selectall"/></th>
         <th>Multipal Row </th>
         <th>Rating</th>
       </tr>
       <tr>
         <td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
         <td>First Chek </td>
         <td>1</td>
       </tr>
       <tr>
         <td align="center"><input type="checkbox" class="case" name="case" value="13"/></td>
         <td>Thirty Chek </td>
         <td>13</td>
       </tr>   </table>
</code>```

答:
I would recommend the following tutorial : https://codepen.io/abergin/pen/ihlDf?editors=1100#0 it does exactly what you want.

The HTML code :

```<code><h1>CSS + HTML only Accordion Element</h1>
<ul>
  <li>
    <input type="checkbox" checked>
    <i></i>
    <h2>Languages Used</h2>
    <p>This page was written in HTML and CSS. The CSS was compiled from SASS. I used Normalize as my CSS reset and -prefix-free to save myself some headaches. I haven't quite gotten the hang of Slim for compiling into HTML, but someday I'll use it since its syntax compliments that of SASS. Regardless, this could all be done in plain HTML and CSS.</p>
  </li>
  <li>
    <input type="checkbox" checked>
    <i></i>
    <h2>How it Works</h2>
    <p>Using the sibling and checked selectors, we can determine the styling of sibling elements based on the checked state of the checkbox input element. One use, as demonstrated here, is an entirely CSS and HTML accordion element. Media queries are used to make the element responsive to different screen sizes.</p>
  </li>
  <li>
    <input type="checkbox" checked>
    <i></i>
    <h2>Points of Interest</h2>
    <p>By making the open state default for when :checked isn't detected, we can make this system accessable for browsers that don't recognize :checked. The fallback is simply an open accordion. The accordion can be manipulated with Javascript (if needed) by changing the "checked" property of the input element.</p>
  </li>
</ul>
</code>```

And a heavier use of CSS :

```<code>$white: rgba(254,255,250,1)
$grey: rgba(220,231,235,1)
$red: rgba(255,104,115,1)
$black: rgba(48,69,92,0.8)
$sans: 'Titillium Web', sans-serif

.transition
  transition: all 0.25s ease-in-out

.flipIn
  animation: flipdown 0.5s ease both

.no-select
  -webkit-tap-highlight-color: rgba(0,0,0,0)
  -webkit-touch-callout: none
  -webkit-user-select: none
  -khtml-user-select: none
  -moz-user-select: none
  -ms-user-select: none
  user-select: none

html
  width: 100%
  height: 100%
  perspective: 900
  overflow-y: scroll
  background-color: $grey
  font-family: $sans
  color: $black

body
  min-height: 0
  display: inline-block
  position: relative
  left: 50%
  margin: 90px 0
  transform: translate( -50% , 0 )
  box-shadow: 0 10px 0 0 $red inset
  background-color: $white
  max-width: 450px
  padding: 30px

  @media ( max-width:550px )
    box-sizing: border-box
    transform: translate( 0 , 0 )
    max-width: 100%
    min-height: 100%
    margin: 0
    left: 0

h1 , h2
  color: $red

h1
  text-transform: uppercase
  font-size: 36px
  line-height: 42px
  letter-spacing: 3px
  font-weight: 100
  @extend .flipIn

h2
  font-size: 26px
  line-height: 34px
  font-weight: 300
  letter-spacing: 1px
  display: block
  background-color: $white
  margin: 0
  cursor: pointer
  @extend .no-select

p
  color: $black
  font-size: 17px
  line-height: 26px
  letter-spacing: 1px
  position: relative
  overflow: hidden
  max-height: 800px
  @extend .transition
  opacity: 1
  transform: translate( 0 , 0 )
  margin-top: 14px
  z-index: 2

ul
  list-style: none
  perspective: 900
  padding: 0
  margin: 0

  li
    position: relative
    padding: 0
    margin: 0
    padding-bottom: 4px
    padding-top: 18px
    border-top: 1px dotted $grey
    @extend .flipIn

    &:nth-of-type(1)
      animation-delay: 0.5s

    &:nth-of-type(2)
      animation-delay: 0.75s

    &:nth-of-type(3)
      animation-delay: 1.0s

    &:last-of-type
      padding-bottom: 0

    i
      position: absolute
      transform: translate( -6px , 0 )
      margin-top: 16px
      right: 0

      &:before , &:after
        content: ""
        @extend .transition
        position: absolute
        background-color: $red
        width: 3px
        height: 9px

      &:before
        transform: translate( -2px , 0 ) rotate( 45deg )

      &:after
        transform: translate( 2px , 0 ) rotate( -45deg )

    input[type=checkbox]
      position: absolute
      cursor: pointer
      width: 100%
      height: 100%
      z-index: 1
      opacity: 0

      &:checked
        &~p
          margin-top: 0
          max-height: 0
          opacity: 0
          transform: translate( 0 , 50% )

        &~i
          &:before
            transform: translate( 2px , 0 ) rotate( 45deg )

          &:after
            transform: translate( -2px , 0 ) rotate( -45deg )

@keyframes flipdown
  0%
    opacity: 0
    transform-origin: top center
    transform: rotateX(-90deg)
  5%
    opacity: 1
  80%
    transform: rotateX(8deg)
  83%
    transform: rotateX(6deg)
  92%
    transform: rotateX(-3deg)
  100%
    transform-origin: top center
    transform: rotateX(0deg)
</code>```

Body:
How can I make an accordion in plain HTML?

-

         <input name="checkbox" type="checkbox" id="selectall"/>
         Multipal Row
         Rating

         <input type="checkbox" class="case" name="case" value="1"/>
         First Chek
         1

         <input type="checkbox" class="case" name="case" value="13"/>
         Thirty Chek
         13

Body:
I would recommend the following tutorial : https://codepen.io/abergin/pen/ihlDf?editors=1100#0 it does exactly what you want.

The HTML code :

<h1>CSS + HTML only Accordion Element</h1>
<ul>
  <li>
    <input type="checkbox" checked>
    <i></i>
    <h2>Languages Used</h2>
    <p>This page was written in HTML and CSS. The CSS was compiled from SASS. I used Normalize as my CSS reset and -prefix-free to save myself some headaches. I haven't quite gotten the hang of Slim for compiling into HTML, but someday I'll use it since its syntax compliments that of SASS. Regardless, this could all be done in plain HTML and CSS.</p>
  </li>
  <li>
    <input type="checkbox" checked>
    <i></i>
    <h2>How it Works</h2>
    <p>Using the sibling and checked selectors, we can determine the styling of sibling elements based on the checked state of the checkbox input element. One use, as demonstrated here, is an entirely CSS and HTML accordion element. Media queries are used to make the element responsive to different screen sizes.</p>
  </li>
  <li>
    <input type="checkbox" checked>
    <i></i>
    <h2>Points of Interest</h2>
    <p>By making the open state default for when :checked isn't detected, we can make this system accessable for browsers that don't recognize :checked. The fallback is simply an open accordion. The accordion can be manipulated with Javascript (if needed) by changing the "checked" property of the input element.</p>
  </li>
</ul>

And a heavier use of CSS :

$white: rgba(254,255,250,1)
$grey: rgba(220,231,235,1)
$red: rgba(255,104,115,1)
$black: rgba(48,69,92,0.8)
$sans: 'Titillium Web', sans-serif

.transition
  transition: all 0.25s ease-in-out

.flipIn
  animation: flipdown 0.5s ease both

.no-select
  -webkit-tap-highlight-color: rgba(0,0,0,0)
  -webkit-touch-callout: none
  -webkit-user-select: none
  -khtml-user-select: none
  -moz-user-select: none
  -ms-user-select: none
  user-select: none

html
  width: 100%
  height: 100%
  perspective: 900
  overflow-y: scroll
  background-color: $grey
  font-family: $sans
  color: $black

body
  min-height: 0
  display: inline-block
  position: relative
  left: 50%
  margin: 90px 0
  transform: translate( -50% , 0 )
  box-shadow: 0 10px 0 0 $red inset
  background-color: $white
  max-width: 450px
  padding: 30px

  @media ( max-width:550px )
    box-sizing: border-box
    transform: translate( 0 , 0 )
    max-width: 100%
    min-height: 100%
    margin: 0
    left: 0

h1 , h2
  color: $red

h1
  text-transform: uppercase
  font-size: 36px
  line-height: 42px
  letter-spacing: 3px
  font-weight: 100
  @extend .flipIn

h2
  font-size: 26px
  line-height: 34px
  font-weight: 300
  letter-spacing: 1px
  display: block
  background-color: $white
  margin: 0
  cursor: pointer
  @extend .no-select

p
  color: $black
  font-size: 17px
  line-height: 26px
  letter-spacing: 1px
  position: relative
  overflow: hidden
  max-height: 800px
  @extend .transition
  opacity: 1
  transform: translate( 0 , 0 )
  margin-top: 14px
  z-index: 2

ul
  list-style: none
  perspective: 900
  padding: 0
  margin: 0

  li
    position: relative
    padding: 0
    margin: 0
    padding-bottom: 4px
    padding-top: 18px
    border-top: 1px dotted $grey
    @extend .flipIn

    &:nth-of-type(1)
      animation-delay: 0.5s

    &:nth-of-type(2)
      animation-delay: 0.75s

    &:nth-of-type(3)
      animation-delay: 1.0s

    &:last-of-type
      padding-bottom: 0

    i
      position: absolute
      transform: translate( -6px , 0 )
      margin-top: 16px
      right: 0

      &:before , &:after
        content: ""
        @extend .transition
        position: absolute
        background-color: $red
        width: 3px
        height: 9px

      &:before
        transform: translate( -2px , 0 ) rotate( 45deg )

      &:after
        transform: translate( 2px , 0 ) rotate( -45deg )

    input[type=checkbox]
      position: absolute
      cursor: pointer
      width: 100%
      height: 100%
      z-index: 1
      opacity: 0

      &:checked
        &~p
          margin-top: 0
          max-height: 0
          opacity: 0
          transform: translate( 0 , 50% )

        &~i
          &:before
            transform: translate( 2px , 0 ) rotate( 45deg )

          &:after
            transform: translate( -2px , 0 ) rotate( -45deg )

@keyframes flipdown
  0%
    opacity: 0
    transform-origin: top center
    transform: rotateX(-90deg)
  5%
    opacity: 1
  80%
    transform: rotateX(8deg)
  83%
    transform: rotateX(6deg)
  92%
    transform: rotateX(-3deg)
  100%
    transform-origin: top center
    transform: rotateX(0deg)


问:
Why does Pythons "any()" function work on numpy array?
Why is it possible to use any directly as a function on a numpy array?

```<code>In [30]: any(np.zeros(4))>0
Out[30]: False
</code>```

I thought numpy's any()-method was on the array itself?

Is this the python function or the actual numpy method?

答:
For one-dimensional arrays it works because the built-in Python-any-function just requires an iterable with items that can be cast to bools (and a one-dimensional array satisfies these conditions) but for multidimensional arrays it won't work:

```<code>>>> import numpy as np

>>> any(np.ones((10, 10)))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> np.any(np.ones((10, 10)))
True
</code>```

That's because if you iterate over a array you iterate over the first dimension, if you have a multidimensional array you'll get an array (not a number) in each iteration. These arrays can't be cast to bools. So it throws the exception.

But np.any will be faster (in most cases) on arrays than any because it's aware of the input-type (array) and it can avoid the python iteration that any needs:

```<code>In [0]: arr = np.zeros((1000))

In [1]: %timeit any(arr)
Out[1]: 215 µs ± 4.29 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [2]: %timeit np.any(arr)
Out[2]: 31.2 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

As a side note, you probably wanted to use any(np.zeros(4) > 0) instead of any(np.zeros(4))>0.

The first one checks if any element in your array is above zero, while the second checks if the result of any (True if any element is not zero) is above zero.

Body:
Why is it possible to use any directly as a function on a numpy array?

In [30]: any(np.zeros(4))>0
Out[30]: False

I thought numpy's any()-method was on the array itself?

Is this the python function or the actual numpy method?

Body:
For one-dimensional arrays it works because the built-in Python-any-function just requires an iterable with items that can be cast to bools (and a one-dimensional array satisfies these conditions) but for multidimensional arrays it won't work:

>>> import numpy as np

>>> any(np.ones((10, 10)))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> np.any(np.ones((10, 10)))
True

That's because if you iterate over a array you iterate over the first dimension, if you have a multidimensional array you'll get an array (not a number) in each iteration. These arrays can't be cast to bools. So it throws the exception.

But np.any will be faster (in most cases) on arrays than any because it's aware of the input-type (array) and it can avoid the python iteration that any needs:

In [0]: arr = np.zeros((1000))

In [1]: %timeit any(arr)
Out[1]: 215 µs ± 4.29 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [2]: %timeit np.any(arr)
Out[2]: 31.2 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

As a side note, you probably wanted to use any(np.zeros(4) > 0) instead of any(np.zeros(4))>0.

The first one checks if any element in your array is above zero, while the second checks if the result of any (True if any element is not zero) is above zero.


问:
How to get an Android WakeLock to work?
My WakeLock isn't keeping my device awake.

In OnCreate() I've got:

```<code>PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "My Tag");
mWakeLock.acquire();
</code>```

then:

```<code>new CountDownTimer(1320000, 200) {

    public void onTick(long millisUntilFinished) {
        // I update a progress bar here.
    }

    public void onFinish() {
        // I finish updating the progress bar.
        mWakeLock.release();
    }
}.start();
</code>```

The screen turns off before the timer finishes, how can I make the screen stay visible?

mWakeLock is a field previously declared like so:

```<code>private PowerManager.WakeLock mWakeLock;
</code>```

My device uses Android 1.6.  I would really appreciate any help to resolve this.

答:
Keep the Screen On

First way:

```<code>getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
</code>```

Second way:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>
</code>```

Keep the CPU On:

```<code><uses-permission android:name="android.permission.WAKE_LOCK" />
</code>```

and

```<code>PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
wakeLock.acquire();
</code>```

To release the wake lock, call wakelock.release(). This releases your claim to the CPU. It's important to release a wake lock as soon as your app is finished using it to avoid draining the battery.

Docs here.

Title: How to get an Android WakeLock to work?

Body:
My WakeLock isn't keeping my device awake.

In OnCreate() I've got:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "My Tag");
mWakeLock.acquire();

then:

new CountDownTimer(1320000, 200) {

    public void onTick(long millisUntilFinished) {
        // I update a progress bar here.
    }

    public void onFinish() {
        // I finish updating the progress bar.
        mWakeLock.release();
    }
}.start();

The screen turns off before the timer finishes, how can I make the screen stay visible?

mWakeLock is a field previously declared like so:

private PowerManager.WakeLock mWakeLock;

My device uses Android 1.6.  I would really appreciate any help to resolve this.

Body:
Keep the Screen On

First way:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Second way:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true">
    ...
</RelativeLayout>

Keep the CPU On:

<uses-permission android:name="android.permission.WAKE_LOCK" />

and

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
wakeLock.acquire();

To release the wake lock, call wakelock.release(). This releases your claim to the CPU. It's important to release a wake lock as soon as your app is finished using it to avoid draining the battery.

Docs here.


问:
401 Unauthorized when connecting to API through Azure Traffic Manager in C#
I have the following code that successfully connects to a third party API in C#:

```<code>using (var client = new WebClient())
{
    client.Credentials = new NetworkCredential(login.Username, login.Password);

    var xml = client.DownloadString(url);
    Debug.Write(xml);
}
</code>```

This works fine when connecting directly to the API. However, I'm trying to utilize Azure Traffic Manager to spread the load to multiple endpoints, and I'm getting 401 Unauthorized exceptions when doing this. It appears to work correctly using tools like Postman and configuring Basic Auth in the request.

I tried to convert the code to RestSharp but it appears to have the same symptoms.

Here are the request from Fiddler using a few different techniques:

C#/WebClient directly to API endpoint (Success)

```<code>GET <ApiUrl> HTTP/1.1
Host: <ApiHost>
Connection: Keep-Alive

401 Unauthorized

GET <ApiUrl> HTTP/1.1
Authorization: Basic <AuthToken>
Host: <ApiHost>
</code>```

C#/WebClient to Azure Traffic Manager (401 Unauthorized)

```<code>GET <TrafficManagerApiUrl> HTTP/1.1
Host: <TrafficManagerApiHost>

401 Unauthorized

GET <ApiUrl> HTTP/1.1
Host: <ApiHost>
</code>```

Postman to Azure Traffic Manager (Success)

```<code>GET <TrafficManagerApiUrl> HTTP/1.1
Host: <TrafficManagerApiHost>
Connection: keep-alive
Authorization: Basic <AuthToken>
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Postman-Token: 13396800-33ab-8d7b-664f-68b99e8f4ac1
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

302 Redirect

GET <ApiUrl> HTTP/1.1
Host: <ApiHost>
Connection: keep-alive
Authorization: Basic <AuthToken>
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Postman-Token: 13396800-33ab-8d7b-664f-68b99e8f4ac1
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=<jsessionid>
</code>```

答:
I wasn't properly handling the redirect of the Azure Traffic Manager.

The answer is detailed here:

https://stackoverflow.com/a/28671822/86191

Body:
I have the following code that successfully connects to a third party API in C#:

using (var client = new WebClient())
{
    client.Credentials = new NetworkCredential(login.Username, login.Password);

    var xml = client.DownloadString(url);
    Debug.Write(xml);
}

This works fine when connecting directly to the API. However, I'm trying to utilize Azure Traffic Manager to spread the load to multiple endpoints, and I'm getting 401 Unauthorized exceptions when doing this. It appears to work correctly using tools like Postman and configuring Basic Auth in the request.

I tried to convert the code to RestSharp but it appears to have the same symptoms.

Here are the request from Fiddler using a few different techniques:

C#/WebClient directly to API endpoint (Success)

GET <ApiUrl> HTTP/1.1
Host: <ApiHost>
Connection: Keep-Alive

401 Unauthorized

GET <ApiUrl> HTTP/1.1
Authorization: Basic <AuthToken>
Host: <ApiHost>

C#/WebClient to Azure Traffic Manager (401 Unauthorized)

GET <TrafficManagerApiUrl> HTTP/1.1
Host: <TrafficManagerApiHost>

401 Unauthorized

GET <ApiUrl> HTTP/1.1
Host: <ApiHost>

Postman to Azure Traffic Manager (Success)

GET <TrafficManagerApiUrl> HTTP/1.1
Host: <TrafficManagerApiHost>
Connection: keep-alive
Authorization: Basic <AuthToken>
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Postman-Token: 13396800-33ab-8d7b-664f-68b99e8f4ac1
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

302 Redirect

GET <ApiUrl> HTTP/1.1
Host: <ApiHost>
Connection: keep-alive
Authorization: Basic <AuthToken>
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Postman-Token: 13396800-33ab-8d7b-664f-68b99e8f4ac1
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=<jsessionid>


问:
How can I change Angular Material button background color on hover state?
I have an Angular button:

```<code><button md-button class="link-btn" >Cancel</button>

.link-btn {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}

.link-btn:hover {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}
</code>```

Normally it is setting transparent background, but in hover state, gray background is shown? How to remove that?

答:
The button styles are encapsulated, so you have to use /deep/ selector to change internal styles.

Try this:

```<code>.link-btn /deep/ .mat-button-focus-overlay {
    background-color:transparent;
}
</code>```

Plnkr

Update:

As of Angular v4.3.0 the /deep/ selector is deprecated and will be replaced by the ::ng-deep selector. You can find more info in the documentation: Angular Documentation

Body:
I have an Angular button:

<button md-button class="link-btn" >Cancel</button>

.link-btn {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}

.link-btn:hover {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}

Normally it is setting transparent background, but in hover state, gray background is shown? How to remove that?

Body:
The button styles are encapsulated, so you have to use /deep/ selector to change internal styles.

Try this:

.link-btn /deep/ .mat-button-focus-overlay {
    background-color:transparent;
}

Plnkr

Update:

As of Angular v4.3.0 the /deep/ selector is deprecated and will be replaced by the ::ng-deep selector. You can find more info in the documentation: Angular Documentation


问:
Kohana 2.3.4 ORM sql injection protection
Kohana mentions they use mysql_real_escape_string to sanitize database inputs in their documentation. However, while tasting some basic queries through a form they were entered in the database exactly as I entered them. For instance:

```<code>SELECT * FROM users WHERE username='admin' AND password='' OR ''=''
</code>```

is entered into that mysql data exactly as it appears. I was expecting to see:

```<code>SELECT * FROM users WHERE username=\'admin\' AND password=\'\' OR \'\'=\'\'
</code>```

I'm using the ORM library instead of the database, but I know they work together. Also, I'm using the built in Input library ($this->input-post) to collect the data from forms. I haven't changed any controllers or libraries that relate to security.

I haven't combed the source code yet, but does Kohana escape the string and then remove the slashes before entering it into a db field? I'm somewhat convinced that this is the case, but I want to be certain.

Thanks

答:
When you escape an SQL query, you are escaping the literal data so that it does not conflict with the SQL syntax, for example so that apostrophes are not interpreted as string delimiters. MySQL can store unescaped apostrophes and anything else really without the data needing to be stored with escaping in tact. It would be a mistake to store the data in its escaped form just so you would have to unescape it again after retrieving it.

Though I am not familiar with Kohana, you can rest assured that it is handling your input properly if you asked it to store a query and it give you the exact same query back.

Body:
Kohana mentions they use mysql_real_escape_string to sanitize database inputs in their documentation. However, while tasting some basic queries through a form they were entered in the database exactly as I entered them. For instance:

SELECT * FROM users WHERE username='admin' AND password='' OR ''=''

is entered into that mysql data exactly as it appears. I was expecting to see:

SELECT * FROM users WHERE username=\'admin\' AND password=\'\' OR \'\'=\'\'

I'm using the ORM library instead of the database, but I know they work together. Also, I'm using the built in Input library ($this->input-post) to collect the data from forms. I haven't changed any controllers or libraries that relate to security.

I haven't combed the source code yet, but does Kohana escape the string and then remove the slashes before entering it into a db field? I'm somewhat convinced that this is the case, but I want to be certain.

Thanks


答: Might want to consider using a user defined function with a while loop. The loop would recurse until it reaches a stop value (perhaps 0?) and the udf would return a single scalar that could be incorporated into the select clause.</p>

Title: MySQL - Keep finding superiors of employees until the most superior employee is reached


问:
In R only keep values that appear for at least 3 years, at least 10 times per year
Please see a general sample of my dataset below. I only want to keep count data from IDs that appear for at least 3 years, with at least 10 appearances during each of those years. So, here, I only want the data from ID 'a', and I want to remove the data with the ID of 'b' and 'c.'

I have some basic/general knowledge of r, python, and excel. Any way to do this using any of those three languages would be great. I guess r would be preferred. Thank you.

```<code>ID  year    count
a   2001    2
b   2001    3
a   2001    2
a   2001    1
a   2001    4
a   2001    0
a   2001    1
a   2001    3
a   2001    2
b   2001    3
b   2001    4
a   2001    5
b   2001    2
c   2001    3
a   2001    5
a   2001    1
c   2001    1
c   2002    2
a   2002    1
b   2002    2
c   2002    3
a   2002    2
a   2002    1
a   2002    3
a   2002    4
a   2002    3
a   2002    2
b   2002    4
b   2002    2
a   2002    1
b   2002    1
c   2002    2
a   2002    3
a   2002    4
a   2002    5
c   2002    2
a   2003    2
a   2003    1
a   2003    2
a   2003    4
c   2003    3
a   2003    2
a   2003    1
b   2003    3
a   2003    5
a   2003    3
a   2003    2
a   2003    1
a   2003    3
a   2003    2
c   2003    2
b   2003    2
b   2003    1
b   2003    4
c   2003    3
</code>```

答:
Python Pandas solution:

```<code>import pandas as pd
</code>```

Read the CSV file into a DataFrame:

```<code>df = pd.read_table('foo.csv', sep='\s+')
</code>```

Group by ID and year, select only those years and IDs that have the total count of at least 10:

```<code>df1 = df.groupby(['ID','year']).sum()
df2 = df1[df1 >= 10].dropna()
</code>```

Eliminate all variables that have fewer than 3 years:

```<code>df3 = df2.reset_index().groupby('ID').count()['count']
df3[df3 >= 3].index.values
</code>```

Result:

```<code>#array(['a'], dtype=object)
</code>```

Body:
Please see a general sample of my dataset below. I only want to keep count data from IDs that appear for at least 3 years, with at least 10 appearances during each of those years. So, here, I only want the data from ID 'a', and I want to remove the data with the ID of 'b' and 'c.'

I have some basic/general knowledge of r, python, and excel. Any way to do this using any of those three languages would be great. I guess r would be preferred. Thank you.

ID  year    count
a   2001    2
b   2001    3
a   2001    2
a   2001    1
a   2001    4
a   2001    0
a   2001    1
a   2001    3
a   2001    2
b   2001    3
b   2001    4
a   2001    5
b   2001    2
c   2001    3
a   2001    5
a   2001    1
c   2001    1
c   2002    2
a   2002    1
b   2002    2
c   2002    3
a   2002    2
a   2002    1
a   2002    3
a   2002    4
a   2002    3
a   2002    2
b   2002    4
b   2002    2
a   2002    1
b   2002    1
c   2002    2
a   2002    3
a   2002    4
a   2002    5
c   2002    2
a   2003    2
a   2003    1
a   2003    2
a   2003    4
c   2003    3
a   2003    2
a   2003    1
b   2003    3
a   2003    5
a   2003    3
a   2003    2
a   2003    1
a   2003    3
a   2003    2
c   2003    2
b   2003    2
b   2003    1
b   2003    4
c   2003    3

Body:
Python Pandas solution:

import pandas as pd

Read the CSV file into a DataFrame:

df = pd.read_table('foo.csv', sep='\s+')

Group by ID and year, select only those years and IDs that have the total count of at least 10:

df1 = df.groupby(['ID','year']).sum()
df2 = df1[df1 >= 10].dropna()

Eliminate all variables that have fewer than 3 years:

df3 = df2.reset_index().groupby('ID').count()['count']
df3[df3 >= 3].index.values

Result:

#array(['a'], dtype=object)


问:
Transform non numeric rows into columns with custom column name
I have a dataframe which looks something like this:

```<code>    df = pd.DataFrame([['7690d79f','Pos'],['7690d79f','Neg'],['7690d79f','Pos'],['7690d79f','Neu'],\
                       ['6690d79f','Pos'],['6690d79f','Neg'],['6690d79f','Pos'],['6690d79f','Neu']]\
                       ,columns=['id', 'vote'])
</code>```

which is:

```<code>    id         vote
0   7690d79f    Pos
1   7690d79f    Neg
2   7690d79f    Pos
3   7690d79f    Neu
4   6690d79f    Pos
5   6690d79f    Neg
6   6690d79f    Pos
7   6690d79f    Neu
</code>```

I want to pivot rows to columns such that, I get a resultDF as

```<code>id  vote_1 vote_2 vote_3 vote_4
7690d79f Pos  Neg Pos Neu
6690d79f Pos  Neg Pos Neu
</code>```

If it helps, there is no more than 4 votes per ids.

Though this is similar to

Python Pandas: Convert Rows as Column headers

Convert row to column in Python Pandas

But unfortunately, none of them works for me.

答:
Let's try this:

```<code>df1 = df.groupby('id')['vote'].apply(lambda x: pd.DataFrame(x.tolist())).unstack()
df1.columns = df1.columns.droplevel().values + 1
df1.add_prefix('vote_').reset_index()
</code>```

Output:

```<code>         id vote_1 vote_2 vote_3 vote_4
0  6690d79f    Pos    Neg    Pos    Neu
1  7690d79f    Pos    Neg    Pos    Neu
</code>```

Body:
I have a dataframe which looks something like this:

    df = pd.DataFrame([['7690d79f','Pos'],['7690d79f','Neg'],['7690d79f','Pos'],['7690d79f','Neu'],\
                       ['6690d79f','Pos'],['6690d79f','Neg'],['6690d79f','Pos'],['6690d79f','Neu']]\
                       ,columns=['id', 'vote'])

which is:

    id         vote
0   7690d79f    Pos
1   7690d79f    Neg
2   7690d79f    Pos
3   7690d79f    Neu
4   6690d79f    Pos
5   6690d79f    Neg
6   6690d79f    Pos
7   6690d79f    Neu

I want to pivot rows to columns such that, I get a resultDF as

id  vote_1 vote_2 vote_3 vote_4
7690d79f Pos  Neg Pos Neu
6690d79f Pos  Neg Pos Neu

If it helps, there is no more than 4 votes per ids.

Though this is similar to

Python Pandas: Convert Rows as Column headers

Convert row to column in Python Pandas

But unfortunately, none of them works for me.

Body:
Let's try this:

df1 = df.groupby('id')['vote'].apply(lambda x: pd.DataFrame(x.tolist())).unstack()
df1.columns = df1.columns.droplevel().values + 1
df1.add_prefix('vote_').reset_index()

Output:

         id vote_1 vote_2 vote_3 vote_4
0  6690d79f    Pos    Neg    Pos    Neu
1  7690d79f    Pos    Neg    Pos    Neu


问:
How to split a string and grouping all the info into a map with duplication values using Java 8 Stream?
I have the following string:

```<code>"id1:name1,id2:name1,id3:name2,id4:name2,id5:name2"
</code>```

and I want to convert this string into a map of the following form:

```<code>{name2=[id3, id4, id5], name1=[id1, id2]}
</code>```

My requirement is the same as this question: How to split a string into a map with a list of values? However, how can I do this using Java 8 Stream API?

答:
There is always a simpler way by StreamEx:</p>

```<code>StreamEx.of(text.split(",")).map(p -> p.split(":"))
                            .mapToEntry(p -> p[1], p -> p[0]).grouping();
</code>```

Body:
I have the following string:

"id1:name1,id2:name1,id3:name2,id4:name2,id5:name2"

and I want to convert this string into a map of the following form:

{name2=[id3, id4, id5], name1=[id1, id2]}

My requirement is the same as this question: How to split a string into a map with a list of values? However, how can I do this using Java 8 Stream API?

Body:
There is always a simpler way by StreamEx:

StreamEx.of(text.split(",")).map(p -> p.split(":"))
                            .mapToEntry(p -> p[1], p -> p[0]).grouping();


问:
Child views in ionic 3 tabs shows two headers when child component is viewed
i am building ionic 3 app, i have page that have three tabs, the tab contains orders, when an order is clicked, its details page is viewed but here two headers appear, one header of tab view and the other header of order's detail page. i am adding some screenshots to make the issue more clear.
First screen shows tab page with one order, Second screen appears when an order is clicked, third screen appears when back button of detail order page is clicked.

答:
i found a solution, i was navigating to order detail page like

```<code>this.navCtrl.push(OrderDetailPage);
</code>```

Now i am accessing detail page like below

```<code>this.navCtrl.parent.parent.push(OrderDetailPage);
</code>```

the issue no longer happens.
Hope it helps some one who have the same issue.

Body:
i found a solution, i was navigating to order detail page like

this.navCtrl.push(OrderDetailPage);

Now i am accessing detail page like below

this.navCtrl.parent.parent.push(OrderDetailPage);

the issue no longer happens.
Hope it helps some one who have the same issue.


问:
How to use HTML formatting with telegra.ph API
I am using the telegra.ph api to edit the page I have made. I want to format the text that I have on the page to align to the right of the page. Right now the content that I am sending through a Python request is:

```<code>from telegraph import Telegraph
tel = Telegraph(my_access_token)

content = [{"tag": "h4",
            "children": ["Hello, World!"]},
            "attrs": {"dir": "rtl"}
            }]

page = tel.edit_page(path='/url',
                     title='testing',
                     content=content,
                     )
</code>```

However the request completely ignores the "dir": "rtl" attribute, since "dir" is not one of the attributes that Telegraph accepts. How can one align the text to the right through telegra.ph?

答:
Telegraph only support limited HTML tag at this time, and you can't align via official editor too.

Please checkout available tag list

Body:
I am using the telegra.ph api to edit the page I have made. I want to format the text that I have on the page to align to the right of the page. Right now the content that I am sending through a Python request is:

from telegraph import Telegraph
tel = Telegraph(my_access_token)

content = [{"tag": "h4",
            "children": ["Hello, World!"]},
            "attrs": {"dir": "rtl"}
            }]

page = tel.edit_page(path='/url',
                     title='testing',
                     content=content,
                     )

However the request completely ignores the "dir": "rtl" attribute, since "dir" is not one of the attributes that Telegraph accepts. How can one align the text to the right through telegra.ph?


问:
Displaying Data on Website from Node.js (Without Frameworks)
I have a Node.js webserver and I am fetching data from a mysql Server. The fetched Data needs to be displayed now in the frontend as HTML. I am not allowed to use any 3rd Party node.js/JavaScript framework's.

I'm new to Webserver development and i'm having a hard time figuring out how to "transport" the Backend Data to the Frontend.

I have 2 Ideas in my mind but dont know what's the right way to approach this problem...

Send Data via JSON to Client and process it with JavaScript. (Possible? and if yes how?)

Before sending the HTTP response, parse the HTML and insert the data. (Complicated without using Frameworks and too costly ?)

What would be the right way to solve this problem ?

Any Help would be appreciated. Thank's.

答:
Solved it like this:

app.js

```<code>var http = require('http');
var url = require('url');

var server = http.createServer(function(req, res) {
    var q = url.parse(req.url, true);
    if(q.filename == "command"){
        res.writeHead(200, {'Content-Type':'application/json'});
        return res.end(some_json);
    }
}
</code>```

index.html

```<code><script>
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","http://localhost:8000/command", true);
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            //Process Data
            var jsonObj = JSON.parse(xmlhttp.responseText);
            document.getElementById("test").innerHTML = jsonObj;
        }
    }
    xmlhttp.send();
</script>

<div id="test"></div>
</code>```

Body:
Solved it like this:

app.js

var http = require('http');
var url = require('url');

var server = http.createServer(function(req, res) {
    var q = url.parse(req.url, true);
    if(q.filename == "command"){
        res.writeHead(200, {'Content-Type':'application/json'});
        return res.end(some_json);
    }
}

index.html

<script>
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","http://localhost:8000/command", true);
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            //Process Data
            var jsonObj = JSON.parse(xmlhttp.responseText);
            document.getElementById("test").innerHTML = jsonObj;
        }
    }
    xmlhttp.send();
</script>

<div id="test"></div>


问:
Differences between pattern matching and unification?
I thought I understand how pattern matching like found in Scala and Haskell is different from unification found in Prolog but my misunderstands of Prolog is great.  What is some simple problems solvable by one that cannot be solved by the other?
Thank you</p>

答:
Simple statement: pattern matching is one-way, unification is two-way. That is, in Prolog the right-hand side (the one being matched against) can include unbound variables. E.g., if you have two unbound variables X and Y, this will work fine:

```<code>X = Y,
X = 5,
%% Y = 5 now as well
</code>```

In Erlang (which uses pattern-matching with syntax close to Prolog), the line X = Y will produce an error: variable 'Y' is unbound. Note that X being unbound is fine: it is supposed to be pattern-matched.

This can be useful when you want to deal with partially-defined values. A very good example is difference lists.

This is also what allows use of Prolog predicate in multiple modes. E.g. in Scala/Haskell/Erlang, if you want to 1) find A ++ B, 2) solve the equation A ++ X == B, or 3) solve the equation X ++ A == B for given lists A and B, you need to write 3 separate functions; in Prolog, all these jobs (and more!) are done by one predicate.

Body:
Simple statement: pattern matching is one-way, unification is two-way. That is, in Prolog the right-hand side (the one being matched against) can include unbound variables. E.g., if you have two unbound variables X and Y, this will work fine:

X = Y,
X = 5,
%% Y = 5 now as well

In Erlang (which uses pattern-matching with syntax close to Prolog), the line X = Y will produce an error: variable 'Y' is unbound. Note that X being unbound is fine: it is supposed to be pattern-matched.

This can be useful when you want to deal with partially-defined values. A very good example is difference lists.

This is also what allows use of Prolog predicate in multiple modes. E.g. in Scala/Haskell/Erlang, if you want to 1) find A ++ B, 2) solve the equation A ++ X == B, or 3) solve the equation X ++ A == B for given lists A and B, you need to write 3 separate functions; in Prolog, all these jobs (and more!) are done by one predicate.


问:
How to click "Go" button on go to finder dialog by applescript?
How to click "Go" button on go to finder dialog by applescript?
I have below code: "dialogObj" is the dialog of Go to Finder dialog, but the "click button 1 of searchFor" does not work in here.</p>

```<code>-- Get the search for pop-up object
set searchFor to first sheet of dialogObj

-- Select all the text in the search field and press delete
key code 0 using command down
key code 51
delay 0.5
--Paste file name
keystroke "v" using {command down}
delay 0.5

-- Click the 'Go' button in the search for pop-up
set textField to value of first text field of first sheet of dialogObj
*click button 1 of searchFor*
delay 1
</code>```

答:
You asked: "How to click "Go" button on go to finder dialog by applescript?"
Did you mean "Go to Folder" dialog, like this:

If so, then a simple RETURN will "click" the Go button:

```<code>tell application "System Events"
  key code 36
end tell
</code>```

Body:
How to click "Go" button on go to finder dialog by applescript?
I have below code: "dialogObj" is the dialog of Go to Finder dialog, but the "click button 1 of searchFor" does not work in here.

-- Get the search for pop-up object
set searchFor to first sheet of dialogObj

-- Select all the text in the search field and press delete
key code 0 using command down
key code 51
delay 0.5
--Paste file name
keystroke "v" using {command down}
delay 0.5

-- Click the 'Go' button in the search for pop-up
set textField to value of first text field of first sheet of dialogObj
*click button 1 of searchFor*
delay 1

Body:
You asked: "How to click "Go" button on go to finder dialog by applescript?"
Did you mean "Go to Folder" dialog, like this:

If so, then a simple RETURN will "click" the Go button:

tell application "System Events"
  key code 36
end tell


问:
Karma unit testing showing broken UI overlaid in Angular 4.1.3
I'm pretty new to Angular and have been building a fun app on the side to get some practice in.

At the moment I'm trying to integrate proper unit-testing and am running into what appears to be some weirdness.

I've build this app using angular-cli and modified the generated unit tests to start fleshing out better code coverage for testing.

However, when running ng test the chrome browser then displays some html elements from my apps ui overlaid on top of the karma report.

I have a strong feeling this is likely due to me doing something wrong. My google-fu has been less than helpful in this situation. Is karma supposed to try to render the UI at all?

I reduced the testing to purely just a test against my main app.component and even then part of the ui tries to render. In the following code if I remove the reference to PlayerService then UI elements no longer render overlaid on top of the Karma output but of course then the tests fail.

app.component.spec.ts

```<code>import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { AppComponent } from './app.component';
import { NavigationComponent } from './navigation/navigation.component';
import { PlayerService } from './players/shared/player.service';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent,
        NavigationComponent
      ],
      providers: [ PlayerService ]
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
});
</code>```

This seems strange to me.

Full source code can be found here:

https://github.com/joshuahysong/TICompanion/tree/20170606_tests

Any suggestions?

Thanks!

答:
A couple ideas here. First, let's get your test working.

"can't bind ngModel to" is a schema error, in this case, input/select. I believe you can fix this with importing FormsModule into the TestBed configuration.

```<code>import { FormsModule } from '@angular/forms';
...
imports: [FormsModule]
</code>```

Anytime you get "can't bind to" errors, it means your Testbed lacked some way to process a DOM element. If you get into ion-buttons or md-material stuff, you'll see this all the time. Just import those modules into your testbed, and it will know how to process them.

You can also completely forego testing these elements by importing the NO_ERRORS_SCHEMA from @angular/core and putting that in your testbed configuration.

```<code>import { NO_ERRORS_SCHEMA } from '@angular/core';
...
schemas:[NO_ERRORS_SCHEMA]
</code>```

Personally, I don't like using this second option. If I'm going to incur the overhead costs of TestBed.createInstance(), then I want to know the template compiles correctly.

Here's a project by the Angular team that I found super helpful when figuring a lot of this out.

Body:
I'm pretty new to Angular and have been building a fun app on the side to get some practice in.

At the moment I'm trying to integrate proper unit-testing and am running into what appears to be some weirdness.

I've build this app using angular-cli and modified the generated unit tests to start fleshing out better code coverage for testing.

However, when running ng test the chrome browser then displays some html elements from my apps ui overlaid on top of the karma report.

I have a strong feeling this is likely due to me doing something wrong. My google-fu has been less than helpful in this situation. Is karma supposed to try to render the UI at all?

I reduced the testing to purely just a test against my main app.component and even then part of the ui tries to render. In the following code if I remove the reference to PlayerService then UI elements no longer render overlaid on top of the Karma output but of course then the tests fail.

app.component.spec.ts

import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { AppComponent } from './app.component';
import { NavigationComponent } from './navigation/navigation.component';
import { PlayerService } from './players/shared/player.service';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent,
        NavigationComponent
      ],
      providers: [ PlayerService ]
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
});

This seems strange to me.

Full source code can be found here:

https://github.com/joshuahysong/TICompanion/tree/20170606_tests

Any suggestions?

Thanks!

Body:
A couple ideas here. First, let's get your test working.

"can't bind ngModel to" is a schema error, in this case, input/select. I believe you can fix this with importing FormsModule into the TestBed configuration.

import { FormsModule } from '@angular/forms';
...
imports: [FormsModule]

Anytime you get "can't bind to" errors, it means your Testbed lacked some way to process a DOM element. If you get into ion-buttons or md-material stuff, you'll see this all the time. Just import those modules into your testbed, and it will know how to process them.

You can also completely forego testing these elements by importing the NO_ERRORS_SCHEMA from @angular/core and putting that in your testbed configuration.

import { NO_ERRORS_SCHEMA } from '@angular/core';
...
schemas:[NO_ERRORS_SCHEMA]

Personally, I don't like using this second option. If I'm going to incur the overhead costs of TestBed.createInstance(), then I want to know the template compiles correctly.

Here's a project by the Angular team that I found super helpful when figuring a lot of this out.


问:
SQL fetch two different rows side by side
I am getting back this result set from a SQL query:

```<code>TypeID  Address   CityID    Zip          isPreferred
----------------------------------------------------
  1     SA-09     17986     897464654         0
  2     FF-31     17987     564646656         0
</code>```

And the SQL query is

```<code>SELECT
    rAdrs.ContactTypeID, rAdrs.StreetAddress,
    rAdrs.CityID, rAdrs.Zip,  rAdrs.isPreferred
FROM
    [Address] AS rAdrs
WHERE
    rAdrs.Applicantid = 5 AND rAdrs.ContactTypeID = 1

UNION

SELECT
    mAdrs.ContactTypeID, mAdrs.StreetAddress,
    mAdrs.CityID, mAdrs.Zip,  mAdrs.isPreferred
FROM
    [Address] AS mAdrs
WHERE
    mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2
</code>```

BUT the result I want in this format:

```<code>TypeID  Address  CityID   Zip       TypeID    Address   CityID   Zip        Preferred
----------------------------------------------------------------------------------------
  1     SA-09    17986    897464654   2       FF-31     17987    564646656  2
</code>```

答:
A (implicit CROSS) JOIN works here as well:

```<code>SELECT rAdrs.ContactTypeID, rAdrs.StreetAddress, rAdrs.CityID, rAdrs.Zip, rAdrs.isPreferred,
       mAdrs.ContactTypeID, mAdrs.StreetAddress, mAdrs.CityID, mAdrs.Zip, mAdrs.isPreferred
  FROM [Address] AS rAdrs
  JOIN [Address] AS mAdrs on mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2
 WHERE rAdrs.Applicantid = 5
   AND rAdrs.ContactTypeID = 1
</code>```

Or an explicit one:

```<code>SELECT rAdrs.ContactTypeID, rAdrs.StreetAddress, rAdrs.CityID, rAdrs.Zip, rAdrs.isPreferred,
       mAdrs.ContactTypeID, mAdrs.StreetAddress, mAdrs.CityID, mAdrs.Zip, mAdrs.isPreferred
  FROM [Address] AS rAdrs
 CROSS JOIN [Address] AS mAdrs
 WHERE rAdrs.Applicantid = 5 AND rAdrs.ContactTypeID = 1
   AND mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2
</code>```

Body:
I am getting back this result set from a SQL query:

TypeID  Address   CityID    Zip          isPreferred
----------------------------------------------------
  1     SA-09     17986     897464654         0
  2     FF-31     17987     564646656         0

And the SQL query is

SELECT
    rAdrs.ContactTypeID, rAdrs.StreetAddress,
    rAdrs.CityID, rAdrs.Zip,  rAdrs.isPreferred
FROM
    [Address] AS rAdrs
WHERE
    rAdrs.Applicantid = 5 AND rAdrs.ContactTypeID = 1

UNION

SELECT
    mAdrs.ContactTypeID, mAdrs.StreetAddress,
    mAdrs.CityID, mAdrs.Zip,  mAdrs.isPreferred
FROM
    [Address] AS mAdrs
WHERE
    mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2

BUT the result I want in this format:

TypeID  Address  CityID   Zip       TypeID    Address   CityID   Zip        Preferred
----------------------------------------------------------------------------------------
  1     SA-09    17986    897464654   2       FF-31     17987    564646656  2

Body:
A (implicit CROSS) JOIN works here as well:

SELECT rAdrs.ContactTypeID, rAdrs.StreetAddress, rAdrs.CityID, rAdrs.Zip, rAdrs.isPreferred,
       mAdrs.ContactTypeID, mAdrs.StreetAddress, mAdrs.CityID, mAdrs.Zip, mAdrs.isPreferred
  FROM [Address] AS rAdrs
  JOIN [Address] AS mAdrs on mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2
 WHERE rAdrs.Applicantid = 5
   AND rAdrs.ContactTypeID = 1

Or an explicit one:

SELECT rAdrs.ContactTypeID, rAdrs.StreetAddress, rAdrs.CityID, rAdrs.Zip, rAdrs.isPreferred,
       mAdrs.ContactTypeID, mAdrs.StreetAddress, mAdrs.CityID, mAdrs.Zip, mAdrs.isPreferred
  FROM [Address] AS rAdrs
 CROSS JOIN [Address] AS mAdrs
 WHERE rAdrs.Applicantid = 5 AND rAdrs.ContactTypeID = 1
   AND mAdrs.Applicantid = 5 AND mAdrs.ContactTypeID = 2


问:
PHP Simple HTML DOM and cURL Not Working
I can't get my scraper to return the specific content I'm looking for. If I return $output, I see digg as though it's being hosted on my server, so I know I'm accessing the site properly, I'm just not able to then access elements from the new DOM. What am I doing wrong?

```<code><?php

include('simple_html_dom.php');

function curl_download($url) {

$ch = curl_init();                                              //creates a new cURL resource handle
curl_setopt($ch, CURLOPT_URL, "http://digg.com");               // Set URL to download
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                 //  TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");          // Set a referer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );                // Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_HEADER, 0);                            // Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_TIMEOUT, 10);                          // Timeout in seconds

$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

}

$html = new simple_html_dom();
$html->load($output, true, false );

    foreach($html->find('div.digg-story__kicker') as $article) {
        $article_title = $article->find('.digg-story__kicker')->innertext;
        return $article_title;
    }

    echo $article_title;

?>
</code>```

Edit: Okay, dumb mistake, I'm calling the function now:

```<code>$html = curl_download('http://digg.com')
</code>```

and if I echo $html I'm seeing the "mirrored site", but when I use str_get_html($html) which simple_html_dom.php says will //get html dom from stringI keep getting this error message:

Fatal error: Call to a member function str_get_html() on null in /home/andrew73124/public_html/scraper/scraper.php on line 31

答:
The curl function needed an additional setting - namely CURLOPT_FOLLOWLOCATION and the function itself needs to return a value in order that it's values can be used. In the code below I return an object with both the response and the info which allows you to test for the http_code before attempting to process the response data.
This uses standard DOMDocument but no doubt using simple_dom will be easy to do.

```<code>function curl_download( $url ) {

    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );/* NEW */
    curl_setopt( $ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0" );
    curl_setopt( $ch, CURLOPT_HEADER, 0 );
    curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );

    $output = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    return (object)array(
        'response'  =>  $output,
        'info'      =>  $info
    );
}

$output = curl_download( 'http://www.digg.com' );
if( $output->info['http_code']==200 ){

    libxml_use_internal_errors( true );

    $dom=new DOMDocument;

    $dom->preserveWhiteSpace = false;
    $dom->validateOnParse = false;
    $dom->standalone=true;
    $dom->strictErrorChecking=false;
    $dom->substituteEntities=true;
    $dom->recover=true;
    $dom->formatOutput=false;

    $dom->loadHTML( $output->response );

    libxml_clear_errors();

    $xp=new DOMXPath( $dom );
    $col=$xp->query('//div[@class="digg-story__kicker"]');
    if( !empty( $col ) ){
        foreach( $col as $node )echo $node->nodeValue;
    }
} else {
    echo '```',print_r($output->info,true),'
';
}
```

<p>Updated answer to include error mitigation code offered by <code>libxml</code> - weidly though the code as it was orginally ran without issue locally before adding the <code>libxml</code> error handling code....</p>

<p>Without the <code>CURLOPT_FOLLOWLOCATION</code> set I get:</p>

```Array
(
    [url] => http://www.digg.com
    [content_type] => text/html
    [http_code] => 301
    [header_size] => 191
    [request_size] => 79
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.421
    [namelookup_time] => 0.031
    [connect_time] => 0.234
    [pretransfer_time] => 0.234
    [size_upload] => 0
    [size_download] => 185
    [speed_download] => 439
    [speed_upload] => 0
    [download_content_length] => 185
    [upload_content_length] => 0
    [starttransfer_time] => 0.421
    [redirect_time] => 0
    [certinfo] => Array
        (
        )
)
```

<p>But with <code>CURLOPT_FOLLOWLOCATION</code> set as <code>true</code> I get</p>

```WE'VE SEEN BETTER ANIME TRIBUTE VIDEOS...<more>...RESIST THE URGE TO SUBTWEET A BAD APPLE
```

Body:
I can't get my scraper to return the specific content I'm looking for. If I return $output, I see digg as though it's being hosted on my server, so I know I'm accessing the site properly, I'm just not able to then access elements from the new DOM. What am I doing wrong?

<?php

include('simple_html_dom.php');

function curl_download($url) {

$ch = curl_init();                                              //creates a new cURL resource handle
curl_setopt($ch, CURLOPT_URL, "http://digg.com");               // Set URL to download
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                 //  TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");          // Set a referer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );                // Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_HEADER, 0);                            // Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_TIMEOUT, 10);                          // Timeout in seconds

$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

}

$html = new simple_html_dom();
$html->load($output, true, false );

    foreach($html->find('div.digg-story__kicker') as $article) {
        $article_title = $article->find('.digg-story__kicker')->innertext;
        return $article_title;
    }

    echo $article_title;

?>

Edit: Okay, dumb mistake, I'm calling the function now:

$html = curl_download('http://digg.com')

and if I echo $html I'm seeing the "mirrored site", but when I use str_get_html($html) which simple_html_dom.php says will //get html dom from stringI keep getting this error message:

Fatal error: Call to a member function str_get_html() on null in /home/andrew73124/public_html/scraper/scraper.php on line 31

Body:
The curl function needed an additional setting - namely CURLOPT_FOLLOWLOCATION and the function itself needs to return a value in order that it's values can be used. In the code below I return an object with both the response and the info which allows you to test for the http_code before attempting to process the response data.
This uses standard DOMDocument but no doubt using simple_dom will be easy to do.

function curl_download( $url ) {

    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );/* NEW */
    curl_setopt( $ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0" );
    curl_setopt( $ch, CURLOPT_HEADER, 0 );
    curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );

    $output = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    return (object)array(
        'response'  =>  $output,
        'info'      =>  $info
    );
}

$output = curl_download( 'http://www.digg.com' );
if( $output->info['http_code']==200 ){

    libxml_use_internal_errors( true );

    $dom=new DOMDocument;

    $dom->preserveWhiteSpace = false;
    $dom->validateOnParse = false;
    $dom->standalone=true;
    $dom->strictErrorChecking=false;
    $dom->substituteEntities=true;
    $dom->recover=true;
    $dom->formatOutput=false;

    $dom->loadHTML( $output->response );

    libxml_clear_errors();

    $xp=new DOMXPath( $dom );
    $col=$xp->query('//div[@class="digg-story__kicker"]');
    if( !empty( $col ) ){
        foreach( $col as $node )echo $node->nodeValue;
    }
} else {
    echo '<pre>',print_r($output->info,true),'</div>';
}

Updated answer to include error mitigation code offered by libxml - weidly though the code as it was orginally ran without issue locally before adding the libxml error handling code....

Without the CURLOPT_FOLLOWLOCATION set I get:

Array
(
    [url] => http://www.digg.com
    [content_type] => text/html
    [http_code] => 301
    [header_size] => 191
    [request_size] => 79
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.421
    [namelookup_time] => 0.031
    [connect_time] => 0.234
    [pretransfer_time] => 0.234
    [size_upload] => 0
    [size_download] => 185
    [speed_download] => 439
    [speed_upload] => 0
    [download_content_length] => 185
    [upload_content_length] => 0
    [starttransfer_time] => 0.421
    [redirect_time] => 0
    [certinfo] => Array
        (
        )
)

But with CURLOPT_FOLLOWLOCATION set as true I get

WE'VE SEEN BETTER ANIME TRIBUTE VIDEOS...<more>...RESIST THE URGE TO SUBTWEET A BAD APPLE


问:
Angular 2 disable sanitize
I am trying to render base64 string into <img src='data:image/png;base64,${Here}'.

But always when I try to render it, ng2 sanitizing my base64 string before rendering it adds something into my value before showing it in DOM.
I have found workaround(using DomSanitizer) but it doesn't work on latest versions.

Here is my markup:

```<code><img alt="RegularImage" src="data:image/png;base64,{{imgBase64}}">
</code>```

And here is my component part:

```<code>imgBase64="SomeBase64StringFetchedSomehow";
</code>```

But angular2 is showing in console next message - WARNING: sanitizing unsafe URL value

How to prevent NG2 from sanitizing my base64 string?

Update

```<code>get getImg() {
    return this._sanitizer.sanitize(SecurityContext.URL,`data:image/png;base64,${this.img}`);
}
</code>```

Doesn't solve this issue. DomSanitizer class does not exists anymore in RC6

答:
After unsuccessfully trying to get the bypassSecurityTrust... functions to work, I resorted to the following:</p>

```<code>@ViewChild('div_element_id') private div_element_id: ElementRef;
...

this.div_element_id.nativeElement.innerHTML = bypass_security_for_this_html;
</code>```

Title: Angular 2 disable sanitize

Body:
I am trying to render base64 string into <img src='data:image/png;base64,${Here}'.

But always when I try to render it, ng2 sanitizing my base64 string before rendering it adds something into my value before showing it in DOM.
I have found workaround(using DomSanitizer) but it doesn't work on latest versions.

Here is my markup:

And here is my component part:

imgBase64="SomeBase64StringFetchedSomehow";

But angular2 is showing in console next message - WARNING: sanitizing unsafe URL value

How to prevent NG2 from sanitizing my base64 string?

Update

get getImg() {
    return this._sanitizer.sanitize(SecurityContext.URL,`data:image/png;base64,${this.img}`);
}

Doesn't solve this issue. DomSanitizer class does not exists anymore in RC6

Body:
After unsuccessfully trying to get the bypassSecurityTrust... functions to work, I resorted to the following:

@ViewChild('div_element_id') private div_element_id: ElementRef;
...

this.div_element_id.nativeElement.innerHTML = bypass_security_for_this_html;


问:
How do I scrape data being a login screen for different login names?
I'm trying to compile the results of my class from my college's results page (exam.msrit.edu).

The USNs for my class are from 1MS16CS001-100

Is there any way that I could go about writing a scraper program to enter different values in the USN box and gather data?

I am quite new to scraping but have decent enough exposure to Python and java

Any advice is much appreciated :)

答:
Not necessarily a scrape, but you can use Selenium Web Driver to browse to the page and input everything for you. Selenium Web Driver can be found here.

Essentially, once it is installed you only need to instantiate the driver and then loop through a list of values inputting them as you go.

```<code>from selenium import webdriver
# V sets up browser. If you want to use chrome addtional setup required
browser = webdriver.Firefox()
for i in len(100):               #loops to arbitrary amount
    browser.get("http://exam.msrit.edu/") #HTTP GET Request to page
    elem = browser.find_element_by_id('id') #This is an html id. Could also use name, xpath, etc.
    elem.send_keys("your string {}".format(i)) #sends up keys
    elem. browser.find_element_by_id('id) #id for search button
    elem.click() #clicks that element
</code>```

The documentation on selenium is pretty good. http://selenium-python.readthedocs.io/navigating.html

This will open a actual browser and will take some time to load so  it will not be the quickest way to do it but it will work. You can even take screenshots.

Body:
Not necessarily a scrape, but you can use Selenium Web Driver to browse to the page and input everything for you. Selenium Web Driver can be found here.

Essentially, once it is installed you only need to instantiate the driver and then loop through a list of values inputting them as you go.

from selenium import webdriver
# V sets up browser. If you want to use chrome addtional setup required
browser = webdriver.Firefox()
for i in len(100):               #loops to arbitrary amount
    browser.get("http://exam.msrit.edu/") #HTTP GET Request to page
    elem = browser.find_element_by_id('id') #This is an html id. Could also use name, xpath, etc.
    elem.send_keys("your string {}".format(i)) #sends up keys
    elem. browser.find_element_by_id('id) #id for search button
    elem.click() #clicks that element

The documentation on selenium is pretty good. http://selenium-python.readthedocs.io/navigating.html

This will open a actual browser and will take some time to load so  it will not be the quickest way to do it but it will work. You can even take screenshots.


问:
How to run a function for each row in a nested list?
I'm a Python newbie and trying to write code that checks if a nested list has a valid set of numbers. Each row and each column have to be valid. I have written a function called check_sequence which validates if a list has a valid set of numbers. How would I call that function from another to check to see if the row is valid? So for example, I need something like this for check_rows:

```<code>check_sequence(list):
  checks if list is valid

check_rows(list):
  For each of the rows in the nested list call check_sequence
</code>```

Here is my code for check_sequence:

```<code>def check_sequence(mylist):
    pos = 0
    sequence_counter = 1
    while pos < len(mylist):
        print "The pos is: " + " " + str(pos)
        print "The sequence_counter is:" + " " + str(sequence_counter)
        for number in mylist:
            print "The number is:" + " " + str(number)
            if number == sequence_counter:
                sequence_counter = sequence_counter + 1
                pos = pos + 1
                break
            else:
                # if list is at the last position on the last item
                if sequence_counter not in mylist:
                    print "The pos is:" + " " + str(pos) + " and the last position is:"  + " "  + str(mylist[len(mylist) - 1])
                    print "False"
                    return False
    print "True"
    return True
</code>```

So I'd call the main method like below:

```<code>check_square([[1, 2, 3],
           [2, 3, 1],
           [3, 1, 2]])

def check_square(list):
   if check_rows() and check_columns() == True:
       return True
   else:
       return False
</code>```

答:
Are you looking for an iterative for loop?</p>

```<code> check_sequence(list):
    #your check here

 check_rows(list):
     for row in list:
         if not check_sequence(row):
             return False
     return True
</code>```

Body:
I'm a Python newbie and trying to write code that checks if a nested list has a valid set of numbers. Each row and each column have to be valid. I have written a function called check_sequence which validates if a list has a valid set of numbers. How would I call that function from another to check to see if the row is valid? So for example, I need something like this for check_rows:

check_sequence(list):
  checks if list is valid

check_rows(list):
  For each of the rows in the nested list call check_sequence

Here is my code for check_sequence:

def check_sequence(mylist):
    pos = 0
    sequence_counter = 1
    while pos < len(mylist):
        print "The pos is: " + " " + str(pos)
        print "The sequence_counter is:" + " " + str(sequence_counter)
        for number in mylist:
            print "The number is:" + " " + str(number)
            if number == sequence_counter:
                sequence_counter = sequence_counter + 1
                pos = pos + 1
                break
            else:
                # if list is at the last position on the last item
                if sequence_counter not in mylist:
                    print "The pos is:" + " " + str(pos) + " and the last position is:"  + " "  + str(mylist[len(mylist) - 1])
                    print "False"
                    return False
    print "True"
    return True

So I'd call the main method like below:

check_square([[1, 2, 3],
           [2, 3, 1],
           [3, 1, 2]])

def check_square(list):
   if check_rows() and check_columns() == True:
       return True
   else:
       return False

Body:
Are you looking for an iterative for loop?

 check_sequence(list):
    #your check here

 check_rows(list):
     for row in list:
         if not check_sequence(row):
             return False
     return True


答:
Given the nested list is row oriented (the rows are the lowest dimension), you can simply use:

```<code>check_rows(list):
    return all(<b>check_sequence(sublist) for sublist in list</b>)</code>```

Here we thus use the all(..) builtin: it evaluates to True if and only if the truthiness of all elements the generator (boldface part) is True, otherwise the result is False. So from the moment one of the rows is not valid, the matrix is not valid.

If on the other hand the nested list is column oriented (the columns are the lowest dimension), we will first need to do a transpose using zip:

```<code>check_rows(list):
    return all(check_sequence(<b>list(sublist)</b>) for sublist in <b>zip(*</b>list<b>)</b>)</code>```

The zip(*..) transposes the list and we use list(..) to make sure that check_sequence(..) is still working with lists (if any iterable is sufficient, the list(..) part can be omitted.

Title: How to run a function for each row in a nested list?

Body:
Given the nested list is row oriented (the rows are the lowest dimension), you can simply use:

check_rows(list):
    return all(check_sequence(sublist) for sublist in list)

Here we thus use the all(..) builtin: it evaluates to True if and only if the truthiness of all elements the generator (boldface part) is True, otherwise the result is False. So from the moment one of the rows is not valid, the matrix is not valid.

If on the other hand the nested list is column oriented (the columns are the lowest dimension), we will first need to do a transpose using zip:

check_rows(list):
    return all(check_sequence(list(sublist)) for sublist in zip(*list))

The zip(*..) transposes the list and we use list(..) to make sure that check_sequence(..) is still working with lists (if any iterable is sufficient, the list(..) part can be omitted.


问:
How to add disappearing and reappearing text on swift
I'm currently trying to create a clicker game which shows how much money you receive when clicking. I'm new to Xcode and swift, but this seems like it should be pretty easy. I would like the score to show how much you earn each time you click it. These labels would appear then disappear quickly. Here is what it would look like:

Any and all help in furthering the clicker game (tips, etc.) would be greatly appreciated :)

答: you can add a tap gesture to your view controller and in that UITapGestureRecognizer selector you can do your code to increment count.</p>


问:
What permission is required for a service account to deploy to Google App Engine using gcloud?
I have created a service account in order to deploy a project to google app engine.

The service account I have created has these two roles:

App Engine -> App Engine Deployer

Storage -> Storage Object Admin

I downloaded the json key file, and then run these commands:

```<code>gcloud auth activate-service-account --key-file key.json
gcloud -q app deploy app_deploy.yaml --version 1.0 --promote
</code>```

I got this error message:

```<code>ERROR: (gcloud.app.deploy) Error Response: [403] Operation not allowed

Details: [
  [
    {
      "@type": "type.googleapis.com/google.rpc.ResourceInfo",
      "description": "The \"appengine.applications.get\" permission is required.",
      "resourceType": "gae.api"
    }
  ]
]
</code>```

What role did I miss to add?

答:
I'm still parsing all of the various docs about this myself, but I stumbled upon this list of predefined GAE roles, complete with the definition of the permissions they had. "Deployer" seems like kind of a misnomer...they maybe should have called it "NewDeployer" or something like that. Hope this helps!

EDIT - here's also the App Engine-specific list of roles.

Cheers!
inger

Body:
I have created a service account in order to deploy a project to google app engine.

The service account I have created has these two roles:

App Engine -> App Engine Deployer

Storage -> Storage Object Admin

I downloaded the json key file, and then run these commands:

gcloud auth activate-service-account --key-file key.json
gcloud -q app deploy app_deploy.yaml --version 1.0 --promote

I got this error message:

ERROR: (gcloud.app.deploy) Error Response: [403] Operation not allowed

Details: [
  [
    {
      "@type": "type.googleapis.com/google.rpc.ResourceInfo",
      "description": "The \"appengine.applications.get\" permission is required.",
      "resourceType": "gae.api"
    }
  ]
]

What role did I miss to add?