问:
ICMP Pinger Socket Program Application
I'm currently writing a relatively basic Socket program in python which is a Ping application using ICMP request and reply messages. I have most of the code finished, yet however I am getting some errors when I run my python file. Can anyone help me out? This is a screenshot of what the output should look like:

```<code>from socket import *
import os
import sys
import struct
import time
import select
import binascii
import socket

ICMP_ECHO_REQUEST = 8
timeRTT = []
packageSent =0;
packageRev = 0;

def checksum(str):
    csum = 0
    countTo = (len(str) / 2) * 2
    count = 0
    while count < countTo:
        thisVal = ord(str[count+1]) * 256 + ord(str[count])
        csum = csum + thisVal
        csum = csum & 0xffffffffL
        count = count + 2
    if countTo < len(str):
        csum = csum + ord(str[len(str) - 1])
        csum = csum & 0xffffffffL
    csum = (csum >> 16) + (csum & 0xffff)
    csum = csum + (csum >> 16)
    answer = ~csum
    answer = answer & 0xffff
    answer = answer >> 8 | (answer << 8 & 0xff00)
    return answer
def receiveOnePing(mySocket, ID, timeout, destAddr):
    global packageRev,timeRTT
    timeLeft = timeout
    while 1:
        startedSelect = time.time()
        whatReady = select.select([mySocket], [], [], timeLeft)
        howLongInSelect = (time.time() - startedSelect)
        if whatReady[0] == []: # Timeout
            return "0: Destination Network Unreachable,"
        timeReceived = time.time()
        recPacket, addr = mySocket.recvfrom(1024)
        #Fill in start
        #Fetch the ICMP header from the IP packet
        icmpHeader = recPacket[20:28]
        requestType, code, revChecksum, revId, revSequence = struct.unpack('bbHHh',icmpHeader)
        if ID == revId:
            bytesInDouble = struct.calcsize('d')
            timeData = struct.unpack('d',recPacket[28:28 + bytesInDouble])[0]
            timeRTT.append(timeReceived - timeData)
            packageRev += 1
            return timeReceived - timeData
        else:
            return "ID is not the same!"
        #Fill in end
        timeLeft = timeLeft - howLongInSelect
        if timeLeft <= 0:
            return "1: Destination Host Unreachable."
def sendOnePing(mySocket, destAddr, ID):
    global packageSent
    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    myChecksum = 0
    # Make a dummy header with a 0 checksum.
    # struct -- Interpret strings as packed binary data
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
    data = struct.pack("d", time.time())
    # Calculate the checksum on the data and the dummy header.
    myChecksum = checksum(header + data)
    # Get the right checksum, and put in the header
    if sys.platform == 'darwin':
        myChecksum = socket.htons(myChecksum) & 0xffff
        #Convert 16-bit integers from host to network byte order.
    else:
        myChecksum = socket.htons(myChecksum)
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
    packet = header + data
    mySocket.sendto(packet, (destAddr, 1))
    packageSent += 1
     # AF_INET address must be tuple, not str
    #Both LISTS and TUPLES consist of a number of objects
    #which can be referenced by their position number within the object
def doOnePing(destAddr, timeout):
    icmp = socket.getprotobyname("icmp")
#SOCK_RAW is a powerful socket type. For more details see:http://sock-raw.org/papers/sock_raw
    #Fill in start
    #Create Socket here
    try:
        mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            raise socket.error(msg)
    #Fill in end
    myID = os.getpid() & 0xFFFF  #Return the current process i
    sendOnePing(mySocket, destAddr, myID)
    delay = receiveOnePing(mySocket, myID, timeout, destAddr)
    mySocket.close()
    return delay
def ping(host, timeout=1):
    #timeout=1 means: If one second goes by without a reply from the server,
    dest = socket.gethostbyname(host)
    print "Pinging " + dest + " using Python:"
    print ""
    #Send ping requests to a server separated by approximately one second
    while 1 :
        delay = doOnePing(dest, timeout)
        print "RTT:",delay
        print "maxRTT:", (max(timeRTT) if len(timeRTT) > 0 else 0), "\tminRTT:", (min(timeRTT) if len(timeRTT) > 0 else 0), "\naverageRTT:", float(sum(timeRTT)/len(timeRTT) if len(timeRTT) > 0 else float("nan"))
        print "Package Lose Rate:", ((packageSent - packageRev)/packageSent if packageRev > 0 else 0)
        time.sleep(1)# one second
    return delay
# ping("www.google.com")
# ping("www.poly.edu")
ping("127.0.0.1")
</code>```

This is what I currently get as output:

```<code>[yanb@athena:31]> python ICMPPinger.py
Pinging 54.209.255.182 using Python:

Traceback (most recent call last):
  File "ICMPPinger.py", line 111, in <module>
    ping("www.poly.edu")
  File "ICMPPinger.py", line 104, in ping
    delay = doOnePing(dest, timeout)
  File "ICMPPinger.py", line 90, in doOnePing
    raise socket.error(msg)
socket.error: Operation not permitted
</code>```

答:
These could be due to following reasons:</p>

```<code>1. Lack of privileges try with root user.
2. A previous run version of your application is still holding the port in the background. Just check running processes and kill it & remember port is not instantly available after the socket is closed (server having been killed).
</code>```

Title: ICMP Pinger Socket Program Application

Body:
I'm currently writing a relatively basic Socket program in python which is a Ping application using ICMP request and reply messages. I have most of the code finished, yet however I am getting some errors when I run my python file. Can anyone help me out? This is a screenshot of what the output should look like:

from socket import *
import os
import sys
import struct
import time
import select
import binascii
import socket

ICMP_ECHO_REQUEST = 8
timeRTT = []
packageSent =0;
packageRev = 0;

def checksum(str):
    csum = 0
    countTo = (len(str) / 2) * 2
    count = 0
    while count < countTo:
        thisVal = ord(str[count+1]) * 256 + ord(str[count])
        csum = csum + thisVal
        csum = csum & 0xffffffffL
        count = count + 2
    if countTo < len(str):
        csum = csum + ord(str[len(str) - 1])
        csum = csum & 0xffffffffL
    csum = (csum >> 16) + (csum & 0xffff)
    csum = csum + (csum >> 16)
    answer = ~csum
    answer = answer & 0xffff
    answer = answer >> 8 | (answer << 8 & 0xff00)
    return answer
def receiveOnePing(mySocket, ID, timeout, destAddr):
    global packageRev,timeRTT
    timeLeft = timeout
    while 1:
        startedSelect = time.time()
        whatReady = select.select([mySocket], [], [], timeLeft)
        howLongInSelect = (time.time() - startedSelect)
        if whatReady[0] == []: # Timeout
            return "0: Destination Network Unreachable,"
        timeReceived = time.time()
        recPacket, addr = mySocket.recvfrom(1024)
        #Fill in start
        #Fetch the ICMP header from the IP packet
        icmpHeader = recPacket[20:28]
        requestType, code, revChecksum, revId, revSequence = struct.unpack('bbHHh',icmpHeader)
        if ID == revId:
            bytesInDouble = struct.calcsize('d')
            timeData = struct.unpack('d',recPacket[28:28 + bytesInDouble])[0]
            timeRTT.append(timeReceived - timeData)
            packageRev += 1
            return timeReceived - timeData
        else:
            return "ID is not the same!"
        #Fill in end
        timeLeft = timeLeft - howLongInSelect
        if timeLeft <= 0:
            return "1: Destination Host Unreachable."
def sendOnePing(mySocket, destAddr, ID):
    global packageSent
    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    myChecksum = 0
    # Make a dummy header with a 0 checksum.
    # struct -- Interpret strings as packed binary data
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
    data = struct.pack("d", time.time())
    # Calculate the checksum on the data and the dummy header.
    myChecksum = checksum(header + data)
    # Get the right checksum, and put in the header
    if sys.platform == 'darwin':
        myChecksum = socket.htons(myChecksum) & 0xffff
        #Convert 16-bit integers from host to network byte order.
    else:
        myChecksum = socket.htons(myChecksum)
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
    packet = header + data
    mySocket.sendto(packet, (destAddr, 1))
    packageSent += 1
     # AF_INET address must be tuple, not str
    #Both LISTS and TUPLES consist of a number of objects
    #which can be referenced by their position number within the object
def doOnePing(destAddr, timeout):
    icmp = socket.getprotobyname("icmp")
#SOCK_RAW is a powerful socket type. For more details see:http://sock-raw.org/papers/sock_raw
    #Fill in start
    #Create Socket here
    try:
        mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
    except socket.error, (errno, msg):
        if errno == 1:
            raise socket.error(msg)
    #Fill in end
    myID = os.getpid() & 0xFFFF  #Return the current process i
    sendOnePing(mySocket, destAddr, myID)
    delay = receiveOnePing(mySocket, myID, timeout, destAddr)
    mySocket.close()
    return delay
def ping(host, timeout=1):
    #timeout=1 means: If one second goes by without a reply from the server,
    dest = socket.gethostbyname(host)
    print "Pinging " + dest + " using Python:"
    print ""
    #Send ping requests to a server separated by approximately one second
    while 1 :
        delay = doOnePing(dest, timeout)
        print "RTT:",delay
        print "maxRTT:", (max(timeRTT) if len(timeRTT) > 0 else 0), "\tminRTT:", (min(timeRTT) if len(timeRTT) > 0 else 0), "\naverageRTT:", float(sum(timeRTT)/len(timeRTT) if len(timeRTT) > 0 else float("nan"))
        print "Package Lose Rate:", ((packageSent - packageRev)/packageSent if packageRev > 0 else 0)
        time.sleep(1)# one second
    return delay
# ping("www.google.com")
# ping("www.poly.edu")
ping("127.0.0.1")

This is what I currently get as output:

[yanb@athena:31]> python ICMPPinger.py
Pinging 54.209.255.182 using Python:

Traceback (most recent call last):
  File "ICMPPinger.py", line 111, in <module>
    ping("www.poly.edu")
  File "ICMPPinger.py", line 104, in ping
    delay = doOnePing(dest, timeout)
  File "ICMPPinger.py", line 90, in doOnePing
    raise socket.error(msg)
socket.error: Operation not permitted

Body:
These could be due to following reasons:

1. Lack of privileges try with root user.
2. A previous run version of your application is still holding the port in the background. Just check running processes and kill it & remember port is not instantly available after the socket is closed (server having been killed).


来源: stackexchange

问:
How can I count the number of requests in the last second, minute and hour?
I have a web server which supports only one very simple API- count the number of requests received in the last hour, minute and second.
This server is very popular in the world and received thousands of requests per second.

Aim it to find how to return accurately these 3 values to every request?

Requests are coming all the time, so the window of one hour, one minute and one second is different per request.
How to manage a different window per request so that the counts are correct per request?

答:
One solution is like this:

Use a circular array of length 3600 (60 * 60 seconds in an hour) to hold the data for each second in last hour.

To record the data for a new second, drop the last second's data in the circular array by moving the circular array's head pointer.

In each element of the circular array, instead of holding the number of requests in a particular second, we record the cumulative sum for the number of requests we see previously, and the number of requests for a period can be calculated by requests_sum.get(current_second) - requests_sum.get(current_second - number_of_seconds_in_this_period)

All of the operations like increment(), getCountForLastMinute(), getCountForLastHour() can be done in O(1) time.

=========================================================================

Here is an example for how this works.

If we have request count in recent 3 seconds like this:

```<code>1st second: 2 requests
2nd second: 4 requests
3rd second: 3 requests
</code>```

The circular array will look like this:
sum = [2, 6, 9]
where 6 = 4 + 2 and 9 = 2 + 4 + 3

In this case:

if you want to get the last second's request count (the 3rd second's request count), simply calculating sum[2] - sum[1] = 9 - 6 = 3

if you want to get the last two seconds' request count (the 3rd second's request count and the 2nd second's request count), simply calculating sum[2] - sum[0] = 9 - 2 = 7

ContentLicense: CC BY-SA 4.0

Body:
One solution is like this:

Use a circular array of length 3600 (60 * 60 seconds in an hour) to hold the data for each second in last hour.

To record the data for a new second, drop the last second's data in the circular array by moving the circular array's head pointer.

In each element of the circular array, instead of holding the number of requests in a particular second, we record the cumulative sum for the number of requests we see previously, and the number of requests for a period can be calculated by requests_sum.get(current_second) - requests_sum.get(current_second - number_of_seconds_in_this_period)

All of the operations like increment(), getCountForLastMinute(), getCountForLastHour() can be done in O(1) time.

=========================================================================

Here is an example for how this works.

If we have request count in recent 3 seconds like this:

1st second: 2 requests
2nd second: 4 requests
3rd second: 3 requests

The circular array will look like this:
sum = [2, 6, 9]
where 6 = 4 + 2 and 9 = 2 + 4 + 3

In this case:

if you want to get the last second's request count (the 3rd second's request count), simply calculating sum[2] - sum[1] = 9 - 6 = 3

if you want to get the last two seconds' request count (the 3rd second's request count and the 2nd second's request count), simply calculating sum[2] - sum[0] = 9 - 2 = 7


问:
PHP $_POST function with a table
I have a table, in a grid of 4x4. Assume they're all black boxes. I now have it so that when I hover, they turn grey.

However, how would I make it so that if you click on a table cell, it stays grey, and I can somehow pass that cell's coordinates to a $_POST function? I hope I am being descriptive enough.

答: Make your table such that each cell has an onclick event defined. Call a function to submit the form through post when this function is called.

ContentLicense: CC BY-SA 2.5

Title: PHP $_POST function with a table


问:
Getting error: DLL load failed: The operating system cannot run %1 - Python 2.7; Scrapy Module; Importing Cryptography
I cannot successfully run the first command in the Scrapy tutorial (http://doc.scrapy.org/en/latest/intro/tutorial.html).  The code copy pasted below is the result (with the error at the end).

Python 2.7 is installed, and I followed the installation instructions for scrapy (http://doc.scrapy.org/en/latest/intro/install.html). I am running Python 2.7.6 32 bit on Windows 7 (64 bit).

Other aspects of installation:

Twisted-13.2.0.dist-info

zope.interface-4.1.1-py2.7

Scrapy-0.22.2-py2.7

lxml-3.3.3-py2.7

cssselect-0.9.1-py2.7

cryptography-0.3.dist-info

pyOpenSSL-0.14-py2.7

pywin32_system32

And here's the error message:

```<code>C:\Python27\Scripts>scrapy startproject tutorial
    Traceback (most recent call last):
      File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
        "__main__", fname, loader, pkg_name)
      File "C:\Python27\lib\runpy.py", line 72, in _run_code
        exec code in run_globals
      File "C:\Python27\lib\site-packages\scrapy\cmdline.py", line 9, in <module>
        from scrapy.crawler import CrawlerProcess
      File "C:\Python27\lib\site-packages\scrapy\crawler.py", line 3, in <module>
        from twisted.internet import reactor, defer
      File "twisted\internet\reactor.py", line 38, in <module>
        from twisted.internet import default
      File "twisted\internet\default.py", line 56, in <module>
        install = _getInstallFunction(platform)
      File "twisted\internet\default.py", line 50, in _getInstallFunction
        from twisted.internet.selectreactor import install
      File "twisted\internet\selectreactor.py", line 18, in <module>
        from twisted.internet import posixbase
      File "twisted\internet\posixbase.py", line 24, in <module>
        from twisted.internet import error, udp, tcp
      File "twisted\internet\tcp.py", line 29, in <module>
        from twisted.internet._newtls import (
      File "twisted\internet\_newtls.py", line 21, in <module>
        from twisted.protocols.tls import TLSMemoryBIOFactory, TLSMemoryBIOProtocol
      File "twisted\protocols\tls.py", line 40, in <module>
        from OpenSSL.SSL import Error, ZeroReturnError, WantReadError
      File "build\bdist.win32\egg\OpenSSL\__init__.py", line 8, in <module>
      File "build\bdist.win32\egg\OpenSSL\rand.py", line 11, in <module>
      File "build\bdist.win32\egg\OpenSSL\_util.py", line 4, in <module>
      File "C:\Python27\lib\site-packages\cryptography\hazmat\bindings\openssl\binding.py",      l3, in __init__
      self._ensure_ffi_initialized()
      File "C:\Python27\lib\site-packages\cryptography\hazmat\bindings\openssl\binding.py", l9, in _ensure_ffi_initialized libraries)
      File "C:\Python27\lib\site-packages\cryptography\hazmat\bindings\utils.py", line 77, ind_ffi
        ext_package="cryptography",
      File "C:\Python27\lib\site-packages\cffi\api.py", line 341, in verify
        lib = self.verifier.load_library()
      File "C:\Python27\lib\site-packages\cffi\verifier.py", line 75, in load_library
        return self._load_library()
      File "C:\Python27\lib\site-packages\cffi\verifier.py", line 151, in _load_library
        return self._vengine.load_library()
      File "C:\Python27\lib\site-packages\cffi\vengine_cpy.py", line 138, in load_library
        raise ffiplatform.VerificationError(error)

cffi.ffiplatform.VerificationError: importing 'C:\\Python27\\lib\\site-packages\\cryptogr
\_Cryptography_cffi_48bbf0ebx93c91939.pyd': DLL load failed: The operating system cannot
1.**
</code>```

答:
I ran across this error today on a Windows 7 system.  The problem for me was similar to @user2314737, @voetsjoeba, and @Olegp.  libeay32.dll and ssleay32.dll where in folders related to Intel that were in the Windows path environmental variable.

Unfortunately, my system is locked (work computer), so I could not move the files or alter the system's path variable.  Instead, I manually removed the Intel related items from the path variable that Python accesses using:

```<code>import os
os.environ['path'] = ';'.join(
    filter(lambda x: 'intel' not in x.lower(), os.environ['path'].split(';'))
    )
import OpenSSL
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I cannot successfully run the first command in the Scrapy tutorial (http://doc.scrapy.org/en/latest/intro/tutorial.html).  The code copy pasted below is the result (with the error at the end).

Python 2.7 is installed, and I followed the installation instructions for scrapy (http://doc.scrapy.org/en/latest/intro/install.html). I am running Python 2.7.6 32 bit on Windows 7 (64 bit).

Other aspects of installation:

Twisted-13.2.0.dist-info

zope.interface-4.1.1-py2.7

Scrapy-0.22.2-py2.7

lxml-3.3.3-py2.7

cssselect-0.9.1-py2.7

cryptography-0.3.dist-info

pyOpenSSL-0.14-py2.7

pywin32_system32

And here's the error message:

C:\Python27\Scripts>scrapy startproject tutorial
    Traceback (most recent call last):
      File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
        "__main__", fname, loader, pkg_name)
      File "C:\Python27\lib\runpy.py", line 72, in _run_code
        exec code in run_globals
      File "C:\Python27\lib\site-packages\scrapy\cmdline.py", line 9, in <module>
        from scrapy.crawler import CrawlerProcess
      File "C:\Python27\lib\site-packages\scrapy\crawler.py", line 3, in <module>
        from twisted.internet import reactor, defer
      File "twisted\internet\reactor.py", line 38, in <module>
        from twisted.internet import default
      File "twisted\internet\default.py", line 56, in <module>
        install = _getInstallFunction(platform)
      File "twisted\internet\default.py", line 50, in _getInstallFunction
        from twisted.internet.selectreactor import install
      File "twisted\internet\selectreactor.py", line 18, in <module>
        from twisted.internet import posixbase
      File "twisted\internet\posixbase.py", line 24, in <module>
        from twisted.internet import error, udp, tcp
      File "twisted\internet\tcp.py", line 29, in <module>
        from twisted.internet._newtls import (
      File "twisted\internet\_newtls.py", line 21, in <module>
        from twisted.protocols.tls import TLSMemoryBIOFactory, TLSMemoryBIOProtocol
      File "twisted\protocols\tls.py", line 40, in <module>
        from OpenSSL.SSL import Error, ZeroReturnError, WantReadError
      File "build\bdist.win32\egg\OpenSSL\__init__.py", line 8, in <module>
      File "build\bdist.win32\egg\OpenSSL\rand.py", line 11, in <module>
      File "build\bdist.win32\egg\OpenSSL\_util.py", line 4, in <module>
      File "C:\Python27\lib\site-packages\cryptography\hazmat\bindings\openssl\binding.py",      l3, in __init__
      self._ensure_ffi_initialized()
      File "C:\Python27\lib\site-packages\cryptography\hazmat\bindings\openssl\binding.py", l9, in _ensure_ffi_initialized libraries)
      File "C:\Python27\lib\site-packages\cryptography\hazmat\bindings\utils.py", line 77, ind_ffi
        ext_package="cryptography",
      File "C:\Python27\lib\site-packages\cffi\api.py", line 341, in verify
        lib = self.verifier.load_library()
      File "C:\Python27\lib\site-packages\cffi\verifier.py", line 75, in load_library
        return self._load_library()
      File "C:\Python27\lib\site-packages\cffi\verifier.py", line 151, in _load_library
        return self._vengine.load_library()
      File "C:\Python27\lib\site-packages\cffi\vengine_cpy.py", line 138, in load_library
        raise ffiplatform.VerificationError(error)

cffi.ffiplatform.VerificationError: importing 'C:\\Python27\\lib\\site-packages\\cryptogr
\_Cryptography_cffi_48bbf0ebx93c91939.pyd': DLL load failed: The operating system cannot
1.**

Body:
I ran across this error today on a Windows 7 system.  The problem for me was similar to @user2314737, @voetsjoeba, and @Olegp.  libeay32.dll and ssleay32.dll where in folders related to Intel that were in the Windows path environmental variable.

Unfortunately, my system is locked (work computer), so I could not move the files or alter the system's path variable.  Instead, I manually removed the Intel related items from the path variable that Python accesses using:

import os
os.environ['path'] = ';'.join(
    filter(lambda x: 'intel' not in x.lower(), os.environ['path'].split(';'))
    )
import OpenSSL


问:
Magento 2 - Get product details in list view adding custom block using plugin
I was trying to use plugin system to modify block of every product listed.

I was able to set it up in this way:

Vendor/Module/etc/frontend/di.xml

```<code><type name="Magento\Catalog\Block\Product\AbstractProduct">
    <plugin name="vendor.module.category.products.list" type="Vendor\Module\Plugin\Block\Product\AbstractProduct" />
</type>
</code>```

Vendor/Module/Plugin/Block/Product/AbstractProduct.php

```<code><?php

namespace Vendor\Module\Plugin\Block\Product;

class AbstractProduct
{
    public function afterGetProductDetailsHtml(
        \Magento\Catalog\Block\Product\AbstractProduct $subject,
        $result
    ) {
         // Here is where I want to pull product details like SKU
         // I also want to pull my custom helper method here
         return '<b>rendered additional html element</b>';
    }
}
</code>```

The problem is I am not able to pull product details in afterGetProductDetailsHtml.
Does anybody know how to do that? Thank you in advance

答:
You need to used arround plugin instade of after plugin like this,</p>

```<code><?php

namespace Vendor\Module\Plugin\Block\Product;

class AbstractProduct
{
    public function aroundGetProductDetailsHtml(
        \Magento\Catalog\Block\Product\AbstractProduct $subject,
        callable $proceed)
    ) {
         // Here is where I want to pull product details like SKU
         // I also want to pull my custom helper method here
         return '<b>rendered additional html element</b>';
    }
}
</code>```

Body:
I was trying to use plugin system to modify block of every product listed.

I was able to set it up in this way:

Vendor/Module/etc/frontend/di.xml

<type name="Magento\Catalog\Block\Product\AbstractProduct">
    <plugin name="vendor.module.category.products.list" type="Vendor\Module\Plugin\Block\Product\AbstractProduct" />
</type>

Vendor/Module/Plugin/Block/Product/AbstractProduct.php

<?php

namespace Vendor\Module\Plugin\Block\Product;

class AbstractProduct
{
    public function afterGetProductDetailsHtml(
        \Magento\Catalog\Block\Product\AbstractProduct $subject,
        $result
    ) {
         // Here is where I want to pull product details like SKU
         // I also want to pull my custom helper method here
         return 'rendered additional html element';
    }
}

The problem is I am not able to pull product details in afterGetProductDetailsHtml.
Does anybody know how to do that? Thank you in advance

Body:
You need to used arround plugin instade of after plugin like this,

<?php

namespace Vendor\Module\Plugin\Block\Product;

class AbstractProduct
{
    public function aroundGetProductDetailsHtml(
        \Magento\Catalog\Block\Product\AbstractProduct $subject,
        callable $proceed)
    ) {
         // Here is where I want to pull product details like SKU
         // I also want to pull my custom helper method here
         return '<b>rendered additional html element</b>';
    }
}


问:
Error during creation of VM with Xen
So, I've been following this tutorial: https://help.ubuntu.com/community/Xen to help me create a virtual machine using the Xen software installed in Ubuntu 16.04. I have managed to install Xen hypervisor without problems, and have created the virtual volume to install the VM, all according to the tutorial.

But in the section of the tutorial "Manually Create a PV Guest VM", I am supposed to modify a document called "ubud1.cfg" and paste some lines into this document. After I have this done, I'm supposed to install the VM through the terminal with the command:

```<code>sudo xl create -c /etc/xen/ubud1.cfg
</code>```

but this does not work. It produces the error messages

Parsing config from /etc/xen/ubud1.cfg
libxl: error: libxl_exec.c:118:libxl_report_child_exitstatus: /etc/xen/scripts/vif-openvswitch online [6473] exited with error status 1
libxl: error: libxl_device.c:1138:device_hotplug_child_death_cb: script: Unable to find ovs-vsctl tool
libxl: error: libxl_create.c:1384:domcreate_attach_vtpms: unable to add nic devices
libxl: error: libxl.c:1610:libxl__destroy_domid: non-existant domain 6
libxl: error: libxl.c:1568:domain_destroy_callback: unable to destroy guest with domid 6
libxl: error: libxl.c:1495:domain_destroy_cb: destruction of domain 6 failed

And I have no idea what I'm doing wrong. I have followed the tutorial and done everything according to it at this point, but I feel like I've missed something. I am not very knowledgeable in Ubuntu and I don't know what this error message produced in the terminal is supposed to mean, that's why I've come here for help.

答:
Had the same problem. Did you use the bridge-utils network bridging earlier in the tutorial and not openvswitch-switch? If so, comment out this line in the ubud1.cfg file.

# Custom option for Open vSwitch
vif = [ 'script=vif-openvswitch,bridge=ovsbr0' ]

It let the new VM start up, but I've apparently configured bridge-utils wrong so I don't have a network interface yet. Good luck.

Title: Error during creation of VM with Xen

Body:
So, I've been following this tutorial: https://help.ubuntu.com/community/Xen to help me create a virtual machine using the Xen software installed in Ubuntu 16.04. I have managed to install Xen hypervisor without problems, and have created the virtual volume to install the VM, all according to the tutorial.

But in the section of the tutorial "Manually Create a PV Guest VM", I am supposed to modify a document called "ubud1.cfg" and paste some lines into this document. After I have this done, I'm supposed to install the VM through the terminal with the command:

sudo xl create -c /etc/xen/ubud1.cfg

but this does not work. It produces the error messages

Parsing config from /etc/xen/ubud1.cfg
libxl: error: libxl_exec.c:118:libxl_report_child_exitstatus: /etc/xen/scripts/vif-openvswitch online [6473] exited with error status 1
libxl: error: libxl_device.c:1138:device_hotplug_child_death_cb: script: Unable to find ovs-vsctl tool
libxl: error: libxl_create.c:1384:domcreate_attach_vtpms: unable to add nic devices
libxl: error: libxl.c:1610:libxl__destroy_domid: non-existant domain 6
libxl: error: libxl.c:1568:domain_destroy_callback: unable to destroy guest with domid 6
libxl: error: libxl.c:1495:domain_destroy_cb: destruction of domain 6 failed

And I have no idea what I'm doing wrong. I have followed the tutorial and done everything according to it at this point, but I feel like I've missed something. I am not very knowledgeable in Ubuntu and I don't know what this error message produced in the terminal is supposed to mean, that's why I've come here for help.


问:
Storing data from the keyboard to an array while ignoring duplicates
So I have a program that I'm working on as an assignment, and part of the requirement is asking me to call a method that retrieve numbers from the user, and storing them into an array of size 20. I have to do this while not including any duplicate values in the array, and I will continue storing the users numbers until the array is full, or the user has entered a negative value. I'm running into a couple of issues.

The user has to be able to enter data through multiple lines of text (using the 'enter' key) without interruption, for example:

Enter the integers for the array:
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 18 18 18 18 19
20

That should store: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 into the array without duplicate values. The program didn't accept any other values because 20 unique digits had been entered, which filled the array.
I've tried to use different options such as nextInt(), nextLine(), and even storing the numbers as a List and then converting but I'm having so many issues.

So my question is, how do I allow the user to enter values across multiple lines of input as well as checking if the current value in the keyboard buffer is duplicate/negative, so I can know to skip that value in the buffer or end the program?

I'll include my code, but honestly I've tried reworking this so many times that it's an absolute mess. Any help will be more than welcomed.

```<code>    public static int getData(int [] set){
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter the integers for the array.");
    System.out.println("The program will stop accepting values when you enter a negative number or reach the 20 unique limit.");

    int usrInput=keyboard.nextInt(), arraySizeUsed = 0;

    for(int position = 0; position < 20; ) {

        if(!Arrays.asList(set).contains(usrInput)) {
            if(usrInput > -1) {

                set[position] = usrInput;
                position++;
                arraySizeUsed++;
            }

            else {
                return arraySizeUsed;
            }
        }
        else {
            continue;
        }
    }

    return arraySizeUsed;
}
</code>```

I don't think I should use 'continue' in the loop as I just want to keep the position from incrementing in the case that the current number in the keyboard buffer is already in the array. What am I missing?

答:
```<code>Set<Integer> values = new HashSet<>();
    Scanner sc  = new Scanner(System.in);
    int count = 0;
    do {
        int in = sc.nextInt();
        if(in>0 && count < 20) {
            values.add(in);
        }else {
            break;
        }
    }while(sc.hasNext());
</code>```

Body:
So I have a program that I'm working on as an assignment, and part of the requirement is asking me to call a method that retrieve numbers from the user, and storing them into an array of size 20. I have to do this while not including any duplicate values in the array, and I will continue storing the users numbers until the array is full, or the user has entered a negative value. I'm running into a couple of issues.

The user has to be able to enter data through multiple lines of text (using the 'enter' key) without interruption, for example:

Enter the integers for the array:
1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 18 18 18 18 19
20

That should store: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 into the array without duplicate values. The program didn't accept any other values because 20 unique digits had been entered, which filled the array.
I've tried to use different options such as nextInt(), nextLine(), and even storing the numbers as a List and then converting but I'm having so many issues.

So my question is, how do I allow the user to enter values across multiple lines of input as well as checking if the current value in the keyboard buffer is duplicate/negative, so I can know to skip that value in the buffer or end the program?

I'll include my code, but honestly I've tried reworking this so many times that it's an absolute mess. Any help will be more than welcomed.

    public static int getData(int [] set){
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter the integers for the array.");
    System.out.println("The program will stop accepting values when you enter a negative number or reach the 20 unique limit.");

    int usrInput=keyboard.nextInt(), arraySizeUsed = 0;

    for(int position = 0; position < 20; ) {

        if(!Arrays.asList(set).contains(usrInput)) {
            if(usrInput > -1) {

                set[position] = usrInput;
                position++;
                arraySizeUsed++;
            }

            else {
                return arraySizeUsed;
            }
        }
        else {
            continue;
        }
    }

    return arraySizeUsed;
}

I don't think I should use 'continue' in the loop as I just want to keep the position from incrementing in the case that the current number in the keyboard buffer is already in the array. What am I missing?


答:
jQuery fanboy here -

```<code> $('td').click(function() {
        $.post("table_process.php", { cell: $(this).attr("#cell_id") },
             function(data){
                 alert("Cell: " + data);
             });
    });
</code>```

Should be something like that.

http://api.jquery.com/jQuery.post/

Title: PHP $_POST function with a table

Body:
I have a table, in a grid of 4x4. Assume they're all black boxes. I now have it so that when I hover, they turn grey.

However, how would I make it so that if you click on a table cell, it stays grey, and I can somehow pass that cell's coordinates to a $_POST function? I hope I am being descriptive enough.

Body:
jQuery fanboy here -

 $('td').click(function() {
        $.post("table_process.php", { cell: $(this).attr("#cell_id") },
             function(data){
                 alert("Cell: " + data);
             });
    });

Should be something like that.

http://api.jquery.com/jQuery.post/


问:
Why is my output equaling zero? (student)
I am a student in my first year of CIS courses, so I am a begineer. We are supposed to get input from a text file with an employee, the employee's department, hourly salary, and hours worked in given week, that looks like:

```<code>EID001, 1, 10.00, 40
EID002, 2, 10.50, 35
EID003, 3, 11.00, 30
EID004, 4, 11.50, 25
EID005, 5, 12.00, 20
EID006, 6, 12.50, 40
EID007, 7, 11.00, 25
.
.
.
(Employee ID, Department, Hourly Salary, Hours Worked)
</code>```

Then separate each field into elements of an array, validate each field, and calculate the total gross pay (Hourly Salary * Hours Worked) for each of the 7 departments.

My code:

```<code>    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Project_3_rev
{
    class Program
    {
        const int DEPARTMENTS = 7;
        const int FIELDS = 4;
        static void Main(string[] args)
        {
            FileStream fStream = new FileStream("project3data.txt", FileMode.Open, FileAccess.Read);
            StreamReader inFile = new StreamReader(fStream);
            string input = "";
            string[] fields = new string[FIELDS];
            string employee = "";
            int department = 0;
            double salary = 0.00;
            int hours = 0;

            double totalSalary = 0.00;
            int totalHours = 0;
            double[] grossPayArray = new double[DEPARTMENTS];

            input = inFile.ReadLine();
            while(input != null)
            {
                fields = input.Split(',');

                checkEmployee(input, fields, employee);
                checkDepartment(input, fields, department);

                for(int x = 1; x <= DEPARTMENTS; x++)
                {
                    totalSalary = 0.00;
                    totalHours = 0;
                    while (department == x)
                    {

                        checkSalary(input, fields, salary, department, totalSalary);
                        checkHours(input, fields, hours, department, totalHours);
                        grossPayArray[x - 1] = totalSalary * totalHours;
                    }
                }

                input = inFile.ReadLine();
            }

            displayOutput(grossPayArray);

        }

        static void checkEmployee(string inp, string[] fieldsArray, string emp)
        {
            if(fieldsArray[0] == null)
                Console.WriteLine("An Employee ID is invalid.");
        }

        static void checkDepartment(string inp, string[] fieldsArray, int dept)
        {
            if((!int.TryParse(fieldsArray[1], out dept)) || dept < 0 || dept > DEPARTMENTS)
            {
                Console.WriteLine("Department field is invalid: " + fieldsArray[1]);
            }

        }

        static void checkSalary(string inp, string[] fieldsArray, double sal, int dept, double totSal)
        {

                    if ((double.TryParse(fieldsArray[2], out sal)) && sal >= 10.00)
                        totSal = totSal * sal;
                    else
                        Console.WriteLine("Salary field is invalid: " + fieldsArray[2]);

        }

        static void checkHours(string inp, string[] fieldsArray, int hrs, int dept, int totHrs)
        {

                    if ((int.TryParse(fieldsArray[3], out hrs)) && hrs >= 0)
                        totHrs = totHrs * hrs;

                    else
                        Console.WriteLine("Hours field is invalid: " +  fieldsArray[3]);

        }

        static void displayOutput(double[] grossArray)
        {
            for(int x = 1; x <= DEPARTMENTS; x++)
            {
                Console.WriteLine("Department " + x + ": Gross Pay = " + grossArray[x-1]);
            }
        }

    }
}
</code>```

My output:

```<code>Department 1: Gross Pay = 0
Department 2: Gross Pay = 0
Department 3: Gross Pay = 0
Department 4: Gross Pay = 0
Department 5: Gross Pay = 0
Department 6: Gross Pay = 0
Department 7: Gross Pay = 0
</code>```

Why are the Gross Pays equaling zero?

Please keep in mind that I am in my first year of computer science. I am only allowed to use what we have learned and I only know the basics. Please cut me a little slack if this code is messy or my logic is way off. Thanks ahead of time.

答:
Looks like you are multiplying 'grossPayArray[x - 1] = totalSalary * totalHours;' correctly, but it appears you are not updating totalSalary or totalHours from the initial value of 0.

You will need to read the file.
 Split the values.
  Update the variables, from zero.
   Perform your function, in this case, multipling.

Hope that helps

Body:
I am a student in my first year of CIS courses, so I am a begineer. We are supposed to get input from a text file with an employee, the employee's department, hourly salary, and hours worked in given week, that looks like:

EID001, 1, 10.00, 40
EID002, 2, 10.50, 35
EID003, 3, 11.00, 30
EID004, 4, 11.50, 25
EID005, 5, 12.00, 20
EID006, 6, 12.50, 40
EID007, 7, 11.00, 25
.
.
.
(Employee ID, Department, Hourly Salary, Hours Worked)

Then separate each field into elements of an array, validate each field, and calculate the total gross pay (Hourly Salary * Hours Worked) for each of the 7 departments.

My code:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Project_3_rev
{
    class Program
    {
        const int DEPARTMENTS = 7;
        const int FIELDS = 4;
        static void Main(string[] args)
        {
            FileStream fStream = new FileStream("project3data.txt", FileMode.Open, FileAccess.Read);
            StreamReader inFile = new StreamReader(fStream);
            string input = "";
            string[] fields = new string[FIELDS];
            string employee = "";
            int department = 0;
            double salary = 0.00;
            int hours = 0;

            double totalSalary = 0.00;
            int totalHours = 0;
            double[] grossPayArray = new double[DEPARTMENTS];

            input = inFile.ReadLine();
            while(input != null)
            {
                fields = input.Split(',');

                checkEmployee(input, fields, employee);
                checkDepartment(input, fields, department);

                for(int x = 1; x <= DEPARTMENTS; x++)
                {
                    totalSalary = 0.00;
                    totalHours = 0;
                    while (department == x)
                    {

                        checkSalary(input, fields, salary, department, totalSalary);
                        checkHours(input, fields, hours, department, totalHours);
                        grossPayArray[x - 1] = totalSalary * totalHours;
                    }
                }

                input = inFile.ReadLine();
            }

            displayOutput(grossPayArray);

        }

        static void checkEmployee(string inp, string[] fieldsArray, string emp)
        {
            if(fieldsArray[0] == null)
                Console.WriteLine("An Employee ID is invalid.");
        }

        static void checkDepartment(string inp, string[] fieldsArray, int dept)
        {
            if((!int.TryParse(fieldsArray[1], out dept)) || dept < 0 || dept > DEPARTMENTS)
            {
                Console.WriteLine("Department field is invalid: " + fieldsArray[1]);
            }

        }

        static void checkSalary(string inp, string[] fieldsArray, double sal, int dept, double totSal)
        {

                    if ((double.TryParse(fieldsArray[2], out sal)) && sal >= 10.00)
                        totSal = totSal * sal;
                    else
                        Console.WriteLine("Salary field is invalid: " + fieldsArray[2]);

        }

        static void checkHours(string inp, string[] fieldsArray, int hrs, int dept, int totHrs)
        {

                    if ((int.TryParse(fieldsArray[3], out hrs)) && hrs >= 0)
                        totHrs = totHrs * hrs;

                    else
                        Console.WriteLine("Hours field is invalid: " +  fieldsArray[3]);

        }

        static void displayOutput(double[] grossArray)
        {
            for(int x = 1; x <= DEPARTMENTS; x++)
            {
                Console.WriteLine("Department " + x + ": Gross Pay = " + grossArray[x-1]);
            }
        }

    }
}

My output:

Department 1: Gross Pay = 0
Department 2: Gross Pay = 0
Department 3: Gross Pay = 0
Department 4: Gross Pay = 0
Department 5: Gross Pay = 0
Department 6: Gross Pay = 0
Department 7: Gross Pay = 0

Why are the Gross Pays equaling zero?

Please keep in mind that I am in my first year of computer science. I am only allowed to use what we have learned and I only know the basics. Please cut me a little slack if this code is messy or my logic is way off. Thanks ahead of time.


问:
RecyclerView item background alternating color out of order
I want change my RecyclerView item background with alternating color.

Here is the method in Adapter.

```<code>public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<NewsModel> mNewsList;

class ViewHolder extends RecyclerView.ViewHolder {
    TextView newsNameText;
    TextView newsDataText;
    View listView;
    public ViewHolder(View newsView) {
        super(newsView);
        newsNameText = (TextView) newsView.findViewById(R.id.news_Name);
        newsDataText = (TextView) newsView.findViewById(R.id.news_Data);
        listView = newsView;
    }
}
public NewsAdapter(List<NewsModel> newsList) {
    mNewsList = newsList;
}
@Override
public  ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
    final ViewHolder holder = new ViewHolder(view);
    return holder;
}
public void setData(List<NewsModel> viewData) {
    mNewsList.clear();
    mNewsList.addAll(viewData);
    notifyDataSetChanged();
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    NewsModel news = mNewsList.get(position);
    holder.setIsRecyclable(true);
    if(position % 2 == 0){
        holder.listView.setBackgroundColor(0x80E0EEEE);
    }
    holder.newsNameText.setText(news.getName());
    holder.newsDataText.setText(news.getData());
}
@Override
public int getItemCount() {
    return mNewsList.size();
}
</code>```

}

The problem is when I touch the screen and swipe down to see more item, the item background color become out of order. It is not alternating.

Am I wrong in using this method?

Thanks!

答:
try this </p>

```<code>NewsModel news = mNewsList.get(getAdapterPosition());
holder.setIsRecyclable(true);
if(getAdapterPosition() % 2 == 0){
    holder.listView.setBackgroundColor(0x80E0EEEE);
}else{
     holder.listView.setBackgroundColor(000000); // use default color
}
</code>```

Body:
I want change my RecyclerView item background with alternating color.

Here is the method in Adapter.

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<NewsModel> mNewsList;

class ViewHolder extends RecyclerView.ViewHolder {
    TextView newsNameText;
    TextView newsDataText;
    View listView;
    public ViewHolder(View newsView) {
        super(newsView);
        newsNameText = (TextView) newsView.findViewById(R.id.news_Name);
        newsDataText = (TextView) newsView.findViewById(R.id.news_Data);
        listView = newsView;
    }
}
public NewsAdapter(List<NewsModel> newsList) {
    mNewsList = newsList;
}
@Override
public  ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
    final ViewHolder holder = new ViewHolder(view);
    return holder;
}
public void setData(List<NewsModel> viewData) {
    mNewsList.clear();
    mNewsList.addAll(viewData);
    notifyDataSetChanged();
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    NewsModel news = mNewsList.get(position);
    holder.setIsRecyclable(true);
    if(position % 2 == 0){
        holder.listView.setBackgroundColor(0x80E0EEEE);
    }
    holder.newsNameText.setText(news.getName());
    holder.newsDataText.setText(news.getData());
}
@Override
public int getItemCount() {
    return mNewsList.size();
}

}

The problem is when I touch the screen and swipe down to see more item, the item background color become out of order. It is not alternating.

Am I wrong in using this method?

Thanks!

Body:
try this

NewsModel news = mNewsList.get(getAdapterPosition());
holder.setIsRecyclable(true);
if(getAdapterPosition() % 2 == 0){
    holder.listView.setBackgroundColor(0x80E0EEEE);
}else{
     holder.listView.setBackgroundColor(000000); // use default color
}


问:
How to set tomcat springboot project upload file path?

I have a springboot project. Use WAR package, on the remote tomcat server webapps directory. ROOT is the WAR project, which has two folders, WEB-INF and META-INF.As shown below

Now there is a problem, I upload files on the project root directory 'upload-dir' directory (you can see the upload-dir position in the figure below). Not in the WAR package, and not on the remote server. Where should I create this new directory on the remote server?

I use Files.createDirectories to to create folders.

答:
On the Linux server, this folder is under the /root directory.

My English is not good. When I talk about my questions, I may not say it well enough. But I hope I can help other people who have the same problems.


问:
How can I set a thread's CPU affinity in Qt5?
Working with threads in Qt5, how can I set a single thread's CPU affinity?

I want to specify a mask of available CPU cores that the thread may run under.

In other words, what is the Qt5 equivalent to Posix thread's pthread_setaffinity_np() ?

Can I do this for threads managed by QThreadPool?

答:
Usually that sort of things is done by extracting the native thread handle and then doing whatever system specific stuff necessary, as no accepted cross-platform API exists for low level thread management.

Indeed, if we inspect the source for the qthread_unix.cpp we will see the following:

```<code>Qt::HANDLE QThread::currentThreadId() Q_DECL_NOTHROW
{
    // requires a C cast here otherwise we run into trouble on AIX
    return to_HANDLE(pthread_self());
}
</code>```

And in qthread_win.cpp the implementation will differ in the expected way:

```<code>Qt::HANDLE QThread::currentThreadId() Q_DECL_NOTHROW
{
    return reinterpret_cast<Qt::HANDLE>(quintptr(GetCurrentThreadId()));
}
</code>```

So, it is responsibility of the application code to do the proper low level actions pertaining to each platform it is expected to run on.

Body:
Usually that sort of things is done by extracting the native thread handle and then doing whatever system specific stuff necessary, as no accepted cross-platform API exists for low level thread management.

Indeed, if we inspect the source for the qthread_unix.cpp we will see the following:

Qt::HANDLE QThread::currentThreadId() Q_DECL_NOTHROW
{
    // requires a C cast here otherwise we run into trouble on AIX
    return to_HANDLE(pthread_self());
}

And in qthread_win.cpp the implementation will differ in the expected way:

Qt::HANDLE QThread::currentThreadId() Q_DECL_NOTHROW
{
    return reinterpret_cast<Qt::HANDLE>(quintptr(GetCurrentThreadId()));
}

So, it is responsibility of the application code to do the proper low level actions pertaining to each platform it is expected to run on.


问:
Can't use local annotation processor in Android kotlin project
I have an AS3 / gradle plugin 3 project where we recently introduced a local simple annotation processor. Works fine with gradles annotationProcessor dependancy directive.

I started adding Kotlin code and moved all annotationProcessor directives to kapt ones. Glide and logan-square use annotation processors with Kotlin without a problem, but our local AP project can't be executed by kapt:

```<code>:app:kaptGenerateStubsDebugKotlin
Using Kotlin incremental compilation

e: java.util.ServiceConfigurationError: javax.annotation.processing.Processor: Error reading configuration file
    at java.util.ServiceLoader.fail(ServiceLoader.java:232)
    at java.util.ServiceLoader.parse(ServiceLoader.java:309)
    at java.util.ServiceLoader.access$200(ServiceLoader.java:185)
    at java.util.ServiceLoader$LazyIterator.hasNextService(ServiceLoader.java:357)
    at java.util.ServiceLoader$LazyIterator.hasNext(ServiceLoader.java:393)
    at java.util.ServiceLoader$1.hasNext(ServiceLoader.java:474)
    at kotlin.collections.CollectionsKt___CollectionsKt.toCollection(_Collections.kt:1042)
    at kotlin.collections.CollectionsKt___CollectionsKt.toMutableList(_Collections.kt:1075)
    at kotlin.collections.CollectionsKt___CollectionsKt.toList(_Collections.kt:1066)
    at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.loadProcessors(Kapt3Extension.kt:92)
    at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:160)
    at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:82)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:96)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:106)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:83)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:377)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:68)
    at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:96)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:368)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:133)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:154)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:58)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:103)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:303)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:85)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:213)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.access$compileIncrementally(IncrementalCompilerRunner.kt:37)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner$compile$2.invoke(IncrementalCompilerRunner.kt:74)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:87)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.execIncrementalCompiler(CompileServiceImpl.kt:512)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$execIncrementalCompiler(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:399)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:889)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:916)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:888)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:398)
    at sun.reflect.GeneratedMethodAccessor87.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: JAR entry META-INF/services/javax.annotation.processing.Processor not found in /Users/kread/git/bgo/myrmecophaga-2.0/ejecta-v8/v8annotations-compiler/build/libs/v8annotations-compiler.jar
    at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:144)
    at sun.net.www.protocol.jar.JarURLConnection.getInputStream(JarURLConnection.java:152)
    at java.net.URL.openStream(URL.java:1045)
    at java.util.ServiceLoader.parse(ServiceLoader.java:304)
    ... 55 more

:app:kaptGenerateStubsDebugKotlin FAILED
</code>```

The created JAR file has the necessary META-INF JAR entry though:

```<code># jar tf /Users/kread/git/bgo/myrmecophaga-2.0/ejecta-v8/v8annotations-compiler/build/libs/v8annotations-compiler.jar
META-INF/
META-INF/MANIFEST.MF
ag/
ag/boersego/
ag/boersego/v8annotations/
ag/boersego/v8annotations/compiler/
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$1.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$AccessorTuple.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$AnnotationHolder.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor.class
META-INF/services/
META-INF/services/javax.annotation.processing.Processor
</code>```

Excerpt from main module build.gradle:

```<code>dependencies {
    // gazillions of compile / api / ...
    api project(':ejecta-v8:v8annotations')
    kapt project(':ejecta-v8:v8annotations-compiler')
}
</code>```

Module v8annotations build.gradle:

```<code>apply plugin: 'java-library'

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {}
</code>```

Module v8annotations-compiler build.gradle:

```<code>apply plugin: 'java'

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile project(':ejecta-v8:v8annotations')
    compile fileTree(dir: 'libs', include: ['*.jar'])
}
</code>```

I'm stumped :(

答:
It works for me </p>

```<code>pkill gradle
clean project
make project
</code>```

Body:
I have an AS3 / gradle plugin 3 project where we recently introduced a local simple annotation processor. Works fine with gradles annotationProcessor dependancy directive.

I started adding Kotlin code and moved all annotationProcessor directives to kapt ones. Glide and logan-square use annotation processors with Kotlin without a problem, but our local AP project can't be executed by kapt:

:app:kaptGenerateStubsDebugKotlin
Using Kotlin incremental compilation

e: java.util.ServiceConfigurationError: javax.annotation.processing.Processor: Error reading configuration file
    at java.util.ServiceLoader.fail(ServiceLoader.java:232)
    at java.util.ServiceLoader.parse(ServiceLoader.java:309)
    at java.util.ServiceLoader.access$200(ServiceLoader.java:185)
    at java.util.ServiceLoader$LazyIterator.hasNextService(ServiceLoader.java:357)
    at java.util.ServiceLoader$LazyIterator.hasNext(ServiceLoader.java:393)
    at java.util.ServiceLoader$1.hasNext(ServiceLoader.java:474)
    at kotlin.collections.CollectionsKt___CollectionsKt.toCollection(_Collections.kt:1042)
    at kotlin.collections.CollectionsKt___CollectionsKt.toMutableList(_Collections.kt:1075)
    at kotlin.collections.CollectionsKt___CollectionsKt.toList(_Collections.kt:1066)
    at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.loadProcessors(Kapt3Extension.kt:92)
    at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:160)
    at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:82)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:96)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:106)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:83)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:377)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:68)
    at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:96)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:368)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:133)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:154)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:58)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:103)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:303)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:85)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:213)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.access$compileIncrementally(IncrementalCompilerRunner.kt:37)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner$compile$2.invoke(IncrementalCompilerRunner.kt:74)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:87)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.execIncrementalCompiler(CompileServiceImpl.kt:512)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$execIncrementalCompiler(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:399)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:889)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:916)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:888)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:398)
    at sun.reflect.GeneratedMethodAccessor87.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: JAR entry META-INF/services/javax.annotation.processing.Processor not found in /Users/kread/git/bgo/myrmecophaga-2.0/ejecta-v8/v8annotations-compiler/build/libs/v8annotations-compiler.jar
    at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:144)
    at sun.net.www.protocol.jar.JarURLConnection.getInputStream(JarURLConnection.java:152)
    at java.net.URL.openStream(URL.java:1045)
    at java.util.ServiceLoader.parse(ServiceLoader.java:304)
    ... 55 more

:app:kaptGenerateStubsDebugKotlin FAILED

The created JAR file has the necessary META-INF JAR entry though:

# jar tf /Users/kread/git/bgo/myrmecophaga-2.0/ejecta-v8/v8annotations-compiler/build/libs/v8annotations-compiler.jar
META-INF/
META-INF/MANIFEST.MF
ag/
ag/boersego/
ag/boersego/v8annotations/
ag/boersego/v8annotations/compiler/
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$1.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$AccessorTuple.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$AnnotationHolder.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor.class
META-INF/services/
META-INF/services/javax.annotation.processing.Processor

Excerpt from main module build.gradle:

dependencies {
    // gazillions of compile / api / ...
    api project(':ejecta-v8:v8annotations')
    kapt project(':ejecta-v8:v8annotations-compiler')
}

Module v8annotations build.gradle:

apply plugin: 'java-library'

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {}

Module v8annotations-compiler build.gradle:

apply plugin: 'java'

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile project(':ejecta-v8:v8annotations')
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

I'm stumped :(

Body:
It works for me

pkill gradle
clean project
make project


问:
Querying mongodb for documents by age
On a monthly basis, I want to delete all documents older than 1 month from one of my collections. An example document from the collection looks something like this:

```<code>{
    _id: ObjectId("56e75f1ce851695805ead8ae"),
    createDate: ISODate("2016-03-15T01:02:20.821Z"),
    foo: "bar"
}
</code>```

I want to have this task be automatically scheduled to happen so it requires no human input--say, as a cron job--and so I would like for it to have as little logic as possible.

How would I query for documents where the createDate is older than 1 month? I had thought to try something like this:

```<code>db.col.find({createDate: {$lt: ISODate(ISODate().getTime() - 1000*3600*24*30)}});
</code>```

... where I create a new ISODate with the current time minus 1 month of milliseconds, but this isn't returning any data. It's also kinda ugly, even if it did work. How would I go about accomplishing this?

答:
You can create TTS index to delete data more than 30 days. It will delete data automatically after 30 days.

db.col.createIndex( { "createDate": 1 }, { expireAfterSeconds: 2592000 } )

Title: Querying mongodb for documents by age

Body:
On a monthly basis, I want to delete all documents older than 1 month from one of my collections. An example document from the collection looks something like this:

{
    _id: ObjectId("56e75f1ce851695805ead8ae"),
    createDate: ISODate("2016-03-15T01:02:20.821Z"),
    foo: "bar"
}

I want to have this task be automatically scheduled to happen so it requires no human input--say, as a cron job--and so I would like for it to have as little logic as possible.

How would I query for documents where the createDate is older than 1 month? I had thought to try something like this:

db.col.find({createDate: {$lt: ISODate(ISODate().getTime() - 1000*3600*24*30)}});

... where I create a new ISODate with the current time minus 1 month of milliseconds, but this isn't returning any data. It's also kinda ugly, even if it did work. How would I go about accomplishing this?


问:
Accessing Data from within angular 2 component
I'm having some trouble trying to figure this out, I'm trying to dynamically add user video data which contains a video URL. I'm trying to access the data from the component so I can interpolate it in my HTML. I'm not exactly sure how this works but Ive tried doing this..

app.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
   selector: 'app-video',
   templateUrl: './video.component.html',
   styleUrls: ['./video.component.scss'],
   providers: [
      DashboardServiceProxy
   ]
})

export class VideoComponent implements OnInit {
   videos: UserVideoDto[] = [];
   // videos: Array<UserVideoDto> = [];

constructor(
    private _dashboardService: DashboardServiceProxy
) {
    console.log(this.videos.VideoData); //data im trying to access
  }

  ngOnInit() {
    this.getVideos();
  }

  getVideos() {
    this._dashboardService.getAllUserVideos().subscribe((result) => {
    this.videos = result;
    console.log(this.videos);
  });
  }

  }
</code>```

at the moment im just trying to console.log the data but Im getting an error that says [ts] Property 'videoData' does not exist on type 'UserVideoDto[]'

this is the UserVideoDto[] class

```<code>public class UserVideoDto : EntityDto
  {
    public long UserId { get; set; }

    public DateTime CreationTime { get; set; }

    public int TenantId { get; set; }

    public string VideoData { get; set; }

    public string Thumbnail { get; set; }

    public String Name { get; set; }

    public String Series { get; set; }

    public String Subname { get; set; }

    public UserVideoDto()
    { }

  }
</code>```

Any help would be appreciated.

答:
As yfranz just mentioned you are trying to access a property that doesn't exist in your UserVideoDto[] which is an array.

Also your console.log is in the constructor, if you try to access the content there you won't get the data that you need because you are fetching the videos using the getVideos method inside ngOnInit. Any data manipulation for 'videos' should be done after you actually fetch the data inside the subscribe callback of _dashboardService.getAllUserVideos()

Body:
I'm having some trouble trying to figure this out, I'm trying to dynamically add user video data which contains a video URL. I'm trying to access the data from the component so I can interpolate it in my HTML. I'm not exactly sure how this works but Ive tried doing this..

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
   selector: 'app-video',
   templateUrl: './video.component.html',
   styleUrls: ['./video.component.scss'],
   providers: [
      DashboardServiceProxy
   ]
})

export class VideoComponent implements OnInit {
   videos: UserVideoDto[] = [];
   // videos: Array<UserVideoDto> = [];

constructor(
    private _dashboardService: DashboardServiceProxy
) {
    console.log(this.videos.VideoData); //data im trying to access
  }

  ngOnInit() {
    this.getVideos();
  }

  getVideos() {
    this._dashboardService.getAllUserVideos().subscribe((result) => {
    this.videos = result;
    console.log(this.videos);
  });
  }

  }

at the moment im just trying to console.log the data but Im getting an error that says [ts] Property 'videoData' does not exist on type 'UserVideoDto[]'

this is the UserVideoDto[] class

public class UserVideoDto : EntityDto
  {
    public long UserId { get; set; }

    public DateTime CreationTime { get; set; }

    public int TenantId { get; set; }

    public string VideoData { get; set; }

    public string Thumbnail { get; set; }

    public String Name { get; set; }

    public String Series { get; set; }

    public String Subname { get; set; }

    public UserVideoDto()
    { }

  }

Any help would be appreciated.


问:
How can I pause an entire script, then continuing the script
What I have is many scripts that has several thousand calls to the setTimeout() function that basically draws animated lines on a canvas. It works beautifully on a computer (of course), and also on mobile devices if the user doesn't touch anything. That being the case I added an touchstart event listener, that will start the entire animation over (they are all about 30 to 40 seconds long) when anything is touched. Works well once again. Issue being is that almost everyone has there mobile devices screen dim then shut off before the animation is complete, and of course when you see the screen dim you touch the screen to prevent it from shutting off, hence the animation starts over !!

I have fooled around with clearTimeout() function, the best I can do is clear all the calls to it at once, then start it over again. This is what I have noticed, I sometimes throw an alert(whatever) in the code to debug it and I have noticed that when the box pops up on a mobile device it actually pauses the entire javascript INCLUDING all thousands of the setTimeout calls, then when you press ok on the alert box, the script continues on its merry way exactly from where it stopped. That's what I want.

Question is, is there  global script pause function that will SIMULATE an alert box that will pause the entire script on a touch (allowing a user to say scroll the page or fill in a text box or whatever) then continue on from where it left off ?

Just adding a complaint here: Why would scrolling a page on a mobile device or zooming or simply clicking a text box which brings up the keyboard affect in anyway the timing in the setTimeout() function, it is all loaded into memory from the get go, time is absolute, it keeps going and going, makes no sense.

Thank you for reading.

答:
The "Global Pause" will happen automatically on all browsers (bar Firefox) when/if the screen goes to sleep. (I believe Firefox behaviour is a bug and sort of permanent wake lock)

You can detect if visibility has changed with: -

```<code>    document.addEventListener("visibilitychange", visibilityChange);
</code>```

This won't help on the initial dim but I suggest that you touch event simply ask for re-start confirmation before going back to the beginning and re-initializing.

Body:
The "Global Pause" will happen automatically on all browsers (bar Firefox) when/if the screen goes to sleep. (I believe Firefox behaviour is a bug and sort of permanent wake lock)

You can detect if visibility has changed with: -

    document.addEventListener("visibilitychange", visibilityChange);

This won't help on the initial dim but I suggest that you touch event simply ask for re-start confirmation before going back to the beginning and re-initializing.


问:
Table Sorter sorting and filtering didn't work
I have dynamically table and I use table sorter pager is working well, but when I try to filter some columns it just returns me to page 0 and nothing happened. Somewhere I try to sort them by clicking on th and other strange thing is when I type in the input box debug mode on table sorter say is ok. </p>

```<code>       var $table = $(".track-grid table.tablesorter");
        var pagesize = $('.pagesize').val();
        $table.tablesorter({
            widthFixed: true,
            cssChildRow: 'infoRow',
            widgets: ['filter'],
            debug: true,
            widgetOptions: {

                filter_hideFilters: true,
                // filter_anyMatch replaced! Instead use the filter_external option
                // Set to use a jQuery selector (or jQuery object) pointing to the
                // external filter (column specific or any match)
                filter_external: '.search',
                // add a default type search to the first name column
                //filter_defaultFilter: { 1: '~{query}' },
                // include column filters
                filter_ignoreCase:false

            }

        });

        $table.on('filterInit', function () {
            $table.tablesorterPager({
                container: $(".pager"),
                ajaxUrl: `track/getEvents?page={page}&size={size}&totalCount=` + totalCount,

                customAjaxUrl: function (table, url) {
                    return url;
                },
                ajaxProcessing: function (data) {

                    $('.tablesorter tbody').html(data.result.eventsHtml);

                    $('#trackOverlay').hide();
                    return [parseInt(data.result.totalEventsCount)];
                },
                page: 0,
                processAjaxOnInit: true,
                output: '{startRow} - {endRow} / {filteredRows} ({totalRows})',
                updateArrows: true,
                fixedHeight: false,
                removeRows: false,
                savePages: false,
                cssNext: '.next',  // next page arrow
                cssPrev: '.prev',  // previous page arrow
                cssFirst: '.first', // go to first page arrow
                cssLast: '.last',  // go to last page arrow
                cssGoto: '.gotoPage', // page select dropdown - select dropdown that set the "page" option

                cssPageDisplay: '.pagedisplay', // location of where the "output" is displayed
                cssPageSize: '.pagesize', // page size selector - select dropdown that sets the "size" option
                cssDisabled: 'disabled', // Note there is no period "." in front of this class name
                cssErrorRow: 'tablesorter-errorRow' // error information row

            });
        });
</code>```

答:
The ajaxUrl option needs to include a filter value. If you look at the example in the documentation, you'll see this:

```<code>ajaxUrl: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}",
</code>```

The {filterList:fcol} adds the filter to the server request.

If the built-in implementation doesn't work for you, use the customAjaxUrl callback to modify the ajax url.

Body:
I have dynamically table and I use table sorter pager is working well, but when I try to filter some columns it just returns me to page 0 and nothing happened. Somewhere I try to sort them by clicking on th and other strange thing is when I type in the input box debug mode on table sorter say is ok.

       var $table = $(".track-grid table.tablesorter");
        var pagesize = $('.pagesize').val();
        $table.tablesorter({
            widthFixed: true,
            cssChildRow: 'infoRow',
            widgets: ['filter'],
            debug: true,
            widgetOptions: {

                filter_hideFilters: true,
                // filter_anyMatch replaced! Instead use the filter_external option
                // Set to use a jQuery selector (or jQuery object) pointing to the
                // external filter (column specific or any match)
                filter_external: '.search',
                // add a default type search to the first name column
                //filter_defaultFilter: { 1: '~{query}' },
                // include column filters
                filter_ignoreCase:false

            }

        });

        $table.on('filterInit', function () {
            $table.tablesorterPager({
                container: $(".pager"),
                ajaxUrl: `track/getEvents?page={page}&size={size}&totalCount=` + totalCount,

                customAjaxUrl: function (table, url) {
                    return url;
                },
                ajaxProcessing: function (data) {

                    $('.tablesorter tbody').html(data.result.eventsHtml);

                    $('#trackOverlay').hide();
                    return [parseInt(data.result.totalEventsCount)];
                },
                page: 0,
                processAjaxOnInit: true,
                output: '{startRow} - {endRow} / {filteredRows} ({totalRows})',
                updateArrows: true,
                fixedHeight: false,
                removeRows: false,
                savePages: false,
                cssNext: '.next',  // next page arrow
                cssPrev: '.prev',  // previous page arrow
                cssFirst: '.first', // go to first page arrow
                cssLast: '.last',  // go to last page arrow
                cssGoto: '.gotoPage', // page select dropdown - select dropdown that set the "page" option

                cssPageDisplay: '.pagedisplay', // location of where the "output" is displayed
                cssPageSize: '.pagesize', // page size selector - select dropdown that sets the "size" option
                cssDisabled: 'disabled', // Note there is no period "." in front of this class name
                cssErrorRow: 'tablesorter-errorRow' // error information row

            });
        });

Body:
The ajaxUrl option needs to include a filter value. If you look at the example in the documentation, you'll see this:

ajaxUrl: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}",

The {filterList:fcol} adds the filter to the server request.

If the built-in implementation doesn't work for you, use the customAjaxUrl callback to modify the ajax url.


问:
without declaration the function first, I can swap the value of the variables?
```<code>#include <iostream>

using namespace std;

void swap(int, int);

int main()
{
    int a=10;
    int b=20;

    swap (a, b);

    cout << "a: " << a << endl;
    cout << "b: " << b << endl;

    return 0;
}

void swap(int x, int y)
{
    int t;
    t = x;
    x = y;
    y = t;
}
</code>```

those code above can't swap the value of a and b.
but my question is , when I forgot to type the third line "void swap(int, int);
" , the values of a and b swaped !! why?

答:
```<code>#include <iostream>

using namespace std;

int main()
{
    int a = 10;
    int b = 20;
    cout << "a: " << a << endl;
    cout << "b: " << b << endl;
    system("pause");
    swap(a, b);

    cout << "a: " << a << endl;
    cout << "b: " << b << endl;
    system("pause");
    return 0;
}
</code>```

<p>void swap is unnecessary  </p>

Body:
#include <iostream>

using namespace std;

void swap(int, int);

int main()
{
    int a=10;
    int b=20;

    swap (a, b);

    cout << "a: " << a << endl;
    cout << "b: " << b << endl;

    return 0;
}

void swap(int x, int y)
{
    int t;
    t = x;
    x = y;
    y = t;
}

those code above can't swap the value of a and b.
but my question is , when I forgot to type the third line "void swap(int, int);
" , the values of a and b swaped !! why?

Body:
#include <iostream>

using namespace std;

int main()
{
    int a = 10;
    int b = 20;
    cout << "a: " << a << endl;
    cout << "b: " << b << endl;
    system("pause");
    swap(a, b);

    cout << "a: " << a << endl;
    cout << "b: " << b << endl;
    system("pause");
    return 0;
}

void swap is unnecessary


问:
Copy constructor and cascaded function calls
I ran this example:

```<code>#include <cstdlib>
#include <iostream>
#include <istream>
#include <ostream>
using namespace std;
class Weight {
    int k;
    char a[100];
public:
    Weight(int kilos = 0)
        :k(kilos) {}
    Weight(const Weight& w)
        : k(w.k) {
        for(int i = 0; i < 100; ++i) this->a[i] = 'a';
        cout << "WCC\n";
    }
    friend Weight operator+(const Weight& a, const Weight& b);
    Weight& operator=(const Weight & w) {
        this->k = w.k;
        return *this;
    }
    friend ostream& operator<<(ostream&, const Weight&);
};
Weight operator+(const Weight& a, const Weight& b) {
    cout << "FP\n";
    int newkg = a.k + b.k;
    return Weight(newkg);
}
ostream& operator<<(ostream& out, const Weight& w) {
    out << w.k << " KGs";
    return out;
}
class Container{
    Weight w;
    static Weight totalW;
    static int count;
public:
    Container(){++count;}
    ~Container(){cout << "CD\n";}
    Container& add(Weight weight) {
        this->w = this->w + weight;
        totalW = totalW + weight;
        cout << "Just added a new item that weighs " << weight << endl;
        return *this;
    }
    static void print() {
        cout << "We have " << count << " Containers with a total weight "
                << totalW << endl;
    }
    friend ostream& operator<<(ostream&, const Container&);
};
Weight Container::totalW;
int Container::count = 0;
ostream& operator<<(ostream& out, const Container& c){
    out << "This container's " << c.w;
    return out;
}
int main(int argc, char** argv) {
    Container c1;

    Weight *w1 = new Weight(1);
    Weight *w2 = new Weight(2);
    Weight *w3 = new Weight(3);

    cout << "Adding items to container...\n";
    c1.add(*w1).add(*w2).add(*w3);

    cout << c1 << endl;

    Container::print();
    return 0;
}
</code>```

And I got this output:

```<code>Adding items to container...
WCC
WCC
WCC
FP
FP
Just added a new item that weighs 1 KGs
FP
FP
Just added a new item that weighs 2 KGs
FP
FP
Just added a new item that weighs 3 KGs
This container's 6 KGs
We have 1 Containers with a total weight 6 KGs
CD
</code>```

You can see that the copy constructor for the Weight class was called three times (Output lines 2-4) before any of the cascaded functions was called. I always thought that the left most function call will be performed before any copy constructor is called up to setup the second function call.

To be more specific, I thought this what should have happened:
WCC -> c1.add(*w1) -> WCC -> .add(*w2) -> WCC -> .add(*w3).

I thought this was necessary because the function argument will be stored in the function's stack frame. So, a stack frame needs to be setup before the copy constructor for the argument is called. Apparently, I am mistaken.

This makes me think that function arguments are store somewhere else other than the stack frame. So, where?

Do not mind the horrific coding style. This, obviously, is not meant to be in production code.

答: I think this is a basic compiler optimization. Since there's no requirement when a function's parameters should be initialized from supplied arguments, a compiler can do necessary optimization by rearranging them. That's why you see the copy constructors called all at once.</p>

Body:
I ran this example:

#include <cstdlib>
#include <iostream>
#include <istream>
#include <ostream>
using namespace std;
class Weight {
    int k;
    char a[100];
public:
    Weight(int kilos = 0)
        :k(kilos) {}
    Weight(const Weight& w)
        : k(w.k) {
        for(int i = 0; i < 100; ++i) this->a[i] = 'a';
        cout << "WCC\n";
    }
    friend Weight operator+(const Weight& a, const Weight& b);
    Weight& operator=(const Weight & w) {
        this->k = w.k;
        return *this;
    }
    friend ostream& operator<<(ostream&, const Weight&);
};
Weight operator+(const Weight& a, const Weight& b) {
    cout << "FP\n";
    int newkg = a.k + b.k;
    return Weight(newkg);
}
ostream& operator<<(ostream& out, const Weight& w) {
    out << w.k << " KGs";
    return out;
}
class Container{
    Weight w;
    static Weight totalW;
    static int count;
public:
    Container(){++count;}
    ~Container(){cout << "CD\n";}
    Container& add(Weight weight) {
        this->w = this->w + weight;
        totalW = totalW + weight;
        cout << "Just added a new item that weighs " << weight << endl;
        return *this;
    }
    static void print() {
        cout << "We have " << count << " Containers with a total weight "
                << totalW << endl;
    }
    friend ostream& operator<<(ostream&, const Container&);
};
Weight Container::totalW;
int Container::count = 0;
ostream& operator<<(ostream& out, const Container& c){
    out << "This container's " << c.w;
    return out;
}
int main(int argc, char** argv) {
    Container c1;

    Weight *w1 = new Weight(1);
    Weight *w2 = new Weight(2);
    Weight *w3 = new Weight(3);

    cout << "Adding items to container...\n";
    c1.add(*w1).add(*w2).add(*w3);

    cout << c1 << endl;

    Container::print();
    return 0;
}

And I got this output:

Adding items to container...
WCC
WCC
WCC
FP
FP
Just added a new item that weighs 1 KGs
FP
FP
Just added a new item that weighs 2 KGs
FP
FP
Just added a new item that weighs 3 KGs
This container's 6 KGs
We have 1 Containers with a total weight 6 KGs
CD

You can see that the copy constructor for the Weight class was called three times (Output lines 2-4) before any of the cascaded functions was called. I always thought that the left most function call will be performed before any copy constructor is called up to setup the second function call.

To be more specific, I thought this what should have happened:
WCC -> c1.add(*w1) -> WCC -> .add(*w2) -> WCC -> .add(*w3).

I thought this was necessary because the function argument will be stored in the function's stack frame. So, a stack frame needs to be setup before the copy constructor for the argument is called. Apparently, I am mistaken.

This makes me think that function arguments are store somewhere else other than the stack frame. So, where?

Do not mind the horrific coding style. This, obviously, is not meant to be in production code.


问:
Join two git repositories with sequential history
I had a git repository (call this repository A) for a project which is nearing public release. Over time, the repository has contained information which I would not like to make public (not passwords/SSH keys, but think similar). At one point in the past (when I thought we were nearing release), I created a new repository without the old history by running git clone --depth=1 (call this repository B). No development has occurred on repository A, but development continued on repository B. Now we are actually nearing release, and my boss would like to do this again, to create repository C.

I would like to join repositories A and B together to contain a single "legacy" repository containing the entire history from the beginning of the project to the first commit of repository C. The last commit of repository A and the first commit of repository B have the same hash. How can I create a new repository AB, which contains the entire history of the project, starting from the first commit of repository A to the last commit of repository B?

I have tried the following:

Adding repo B as a remote of repo A, then fetching and mergeing B/master into A/master; git just reports Already up-to-date., but HEAD and A/master remain at the last commit of repo A.

Adding repo A as a remote of repo B, then fetching and mergeing B/master into A/master, which git only allows if I use --allow-unrelated-histories. This just generates a giant merge conflict, with every file modified since the beginning of repo B listed as in conflict. I suppose if I could resolve all conflicts in favor of repo B, this would be an acceptable solution, but I'm not actually sure what the history tree would look like after this merge.

Is there any better way to do what I'm trying to accomplish?

答:
If the history is literally sequential, and repo B was made as a shallow clone of repo A (git clone --shallow <url of repo A>), all you have to do is un-shallow-ize repo B:

```<code>$ cd path/to/repo/B
$ git fetch --unshallow origin
</code>```

to make B be a complete (no longer shallow) repository that contains all of the commits that are in A, plus any additional commits made to B.

On the other hand, you talk about adding repo A as a remote of repo B—but if you made repo B with git clone --shallow, A should already be a remote.  So something is missing from your problem description.

Body:
If the history is literally sequential, and repo B was made as a shallow clone of repo A (git clone --shallow <url of repo A>), all you have to do is un-shallow-ize repo B:

$ cd path/to/repo/B
$ git fetch --unshallow origin

to make B be a complete (no longer shallow) repository that contains all of the commits that are in A, plus any additional commits made to B.

On the other hand, you talk about adding repo A as a remote of repo B—but if you made repo B with git clone --shallow, A should already be a remote.  So something is missing from your problem description.