问:
Sending byte array of approximately fixed size everytime to another method
I have a method which takes a parameter which is Partition enum. This method will be called by multiple background threads (15 max) around same time period by passing different value of partition. Here dataHoldersByPartition is a ImmutableMap of Partition and ConcurrentLinkedQueue<DataHolder>.

```<code>  private final ImmutableMap<Partition, ConcurrentLinkedQueue<DataHolder>> dataHoldersByPartition;

  //... some code to populate entry in `dataHoldersByPartition` map

  private void validateAndSend(final Partition partition) {
    ConcurrentLinkedQueue<DataHolder> dataHolders = dataHoldersByPartition.get(partition);
    Map<byte[], byte[]> clientKeyBytesAndProcessBytesHolder = new HashMap<>();
    int totalSize = 0;
    DataHolder dataHolder;
    while ((dataHolder = dataHolders.poll())  != null) {
      byte[] clientKeyBytes = dataHolder.getClientKey().getBytes(StandardCharsets.UTF_8);
      if (clientKeyBytes.length > 255)
        continue;

      byte[] processBytes = dataHolder.getProcessBytes();
      int clientKeyLength = clientKeyBytes.length;
      int processBytesLength = processBytes.length;

      int additionalLength = clientKeyLength + processBytesLength;
      if (totalSize + additionalLength > 50000) {
        Message message = new Message(clientKeyBytesAndProcessBytesHolder, partition);
        // here size of `message.serialize()` byte array should always be less than 50k at all cost
        sendToDatabase(message.getAddress(), message.serialize());
        clientKeyBytesAndProcessBytesHolder = new HashMap<>();
        totalSize = 0;
      }
      clientKeyBytesAndProcessBytesHolder.put(clientKeyBytes, processBytes);
      totalSize += additionalLength;
    }
    // calling again with remaining values only if clientKeyBytesAndProcessBytesHolder is not empty
    if(!clientKeyBytesAndProcessBytesHolder.isEmpty()) {
        Message message = new Message(partition, clientKeyBytesAndProcessBytesHolder);
        // here size of `message.serialize()` byte array should always be less than 50k at all cost
        sendToDatabase(message.getAddress(), message.serialize());
    }
  }
</code>```

And below is my Message class:

```<code>public final class Message {
  private final byte dataCenter;
  private final byte recordVersion;
  private final Map<byte[], byte[]> clientKeyBytesAndProcessBytesHolder;
  private final long address;
  private final long addressFrom;
  private final long addressOrigin;
  private final byte recordsPartition;
  private final byte replicated;

  public Message(Map<byte[], byte[]> clientKeyBytesAndProcessBytesHolder, Partition recordPartition) {
    this.clientKeyBytesAndProcessBytesHolder = clientKeyBytesAndProcessBytesHolder;
    this.recordsPartition = (byte) recordPartition.getPartition();
    this.dataCenter = Utils.CURRENT_LOCATION.get().datacenter();
    this.recordVersion = 1;
    this.replicated = 0;
    long packedAddress = new Data().packAddress();
    this.address = packedAddress;
    this.addressFrom = 0L;
    this.addressOrigin = packedAddress;
  }

  // Output of this method should always be less than 50k always
  public byte[] serialize() {
    // 36 + dataSize + 1 + 1 + keyLength + 8 + 2;
    int bufferCapacity = getBufferCapacity(clientKeyBytesAndProcessBytesHolder);

    ByteBuffer byteBuffer = ByteBuffer.allocate(bufferCapacity).order(ByteOrder.BIG_ENDIAN);
    // header layout
    byteBuffer.put(dataCenter).put(recordVersion).putInt(clientKeyBytesAndProcessBytesHolder.size())
        .putInt(bufferCapacity).putLong(address).putLong(addressFrom).putLong(addressOrigin)
        .put(recordsPartition).put(replicated);

    // data layout
    for (Map.Entry<byte[], byte[]> entry : clientKeyBytesAndProcessBytesHolder.entrySet()) {
      byte keyType = 0;
      byte[] key = entry.getKey();
      byte[] value = entry.getValue();
      byte keyLength = (byte) key.length;
      short valueLength = (short) value.length;

      ByteBuffer dataBuffer = ByteBuffer.wrap(value);
      long timestamp = valueLength > 10 ? dataBuffer.getLong(2) : System.currentTimeMillis();

      byteBuffer.put(keyType).put(keyLength).put(key).putLong(timestamp).putShort(valueLength)
          .put(value);
    }
    return byteBuffer.array();
  }

  private int getBufferCapacity(Map<byte[], byte[]> clientKeyBytesAndProcessBytesHolder) {
    int size = 36;
    for (Entry<byte[], byte[]> entry : clientKeyBytesAndProcessBytesHolder.entrySet()) {
      size += 1 + 1 + 8 + 2;
      size += entry.getKey().length;
      size += entry.getValue().length;
    }
    return size;
  }

    // getters and to string method here
}
</code>```

Basically, what I have to make sure is whenever the sendToDatabase method is called in validateAndSend method, size of message.serialize() byte array should always be less than 50k at all cost. My sendToDatabase method sends byte array coming out from serialize method. So for example if I have 60k records in dataHolders CLQ then I will send in two chunks in validateAndSend method:

First, I will make a byte array  which is approx less than 50k (meaning byte array coming out from message.serialize() is less than 50k) and call sendToDatabase method on it.

Second, I will call sendToDatabase method for remianing part.

And to accomplish above things, I was having totalSize variable in validateAndSend method which is trying to measure 50k size but looks like my approach might not be right and I maybe dropping some records or sending more than 50k everytime I guess?

Looks like my Message class knows about clientKeyBytesAndProcessBytesHolder map and I can use this map to accurately define the size by calling getBufferCapacity method and if is approx less than 50k then call sendToDatabase method?

答:
So here is my attempt (the question is probably better be addressed to the Code Review community, but anyway). It relies on some design changes to Message so that it becomes more like a Builder pattern. The buffer becomes part of the message. Its occupancy is controlled by reacting on BufferOverflowException exception. Once it occurs the buffer is rolled back to the last successfully added result, new message is allocated, and attempt to add the same piece of data is retried. Upon buffer completion the total number of records and the overall size are written to header, and the whole buffer is dumped to a byte array (I would probably try to avoid this extra conversion and operate on the buffer directly in sendToDatabase, but that's out of scope for now):

```<code>// TODO: structure has been adjusted for testing purposes
enum Partition
{
    A(0x1);

    private final int _partition;

    int getPartition()
    {
        return _partition;
    }

    Partition(final int partition)
    {
        _partition = partition;
    }
}

// TODO: structure has been adjusted for testing purposes
final static class DataHolder
{
    private final String _clientKey;
    private final byte[] _processBytes;

    public DataHolder(
        final String clientKey,
        final String value)
    {
        _clientKey = clientKey;
        byte[] valueBytes = value.getBytes();
        // simulate payload including extra bytes for the header
        final ByteBuffer buffer = ByteBuffer.allocate(4 + 8 + valueBytes.length)
                                            .order(ByteOrder.BIG_ENDIAN);
        buffer.putInt(0).putLong(System.currentTimeMillis()).put(valueBytes);
        _processBytes = readToBytes(buffer);
    }

    String getClientKey()
    {
        return _clientKey;
    }

    byte[] getProcessBytes()
    {
        return _processBytes;
    }
}

// API has been changed to something more like the Builder pattern
final static class Message
{
    private final long address;
    private final long addressFrom;
    private final long addressOrigin;
    private final byte recordsPartition;
    private final byte replicated;
    private final ByteBuffer buffer;
    private final int writeStatsPosition;
    private int payloadCount;

    Message(Partition recordPartition, int sizeLimit)
    {
        this.recordsPartition = (byte) recordPartition.getPartition();
        this.replicated = 0;
        // TODO: temporarily replaced with a hard-coded constant
        long packedAddress = 123456789L;
        this.address = packedAddress;
        this.addressFrom = 0L;
        this.addressOrigin = packedAddress;
        buffer = ByteBuffer.allocate(sizeLimit).order(ByteOrder.BIG_ENDIAN);
        // TODO: temporarily replaced with a hard-coded constant
        byte dataCenter = 0x1;
        byte recordVersion = 1;
        buffer.put(dataCenter).put(recordVersion);
        writeStatsPosition = buffer.position();
        buffer.putInt(datacenter).putInt(recordVersion);
        buffer.putLong(address).putLong(addressFrom).putLong(addressOrigin)
                  .put(recordsPartition).put(replicated);
    }

    /**
     * Tries to add another pair of client key and process bytes to
     * the current message. Returns true if successfully added, false -
     * if the data cannot be accommodated due to message binary size limit.
     */
    boolean add(byte[] key, byte[] value)
    {
        try
        {
            byte keyType = 0;
            byte keyLength = (byte) key.length;
            short valueLength = (short) value.length;
            ByteBuffer valueAsBuffer = ByteBuffer.wrap(value);
            long timestamp = valueAsBuffer.capacity() > 10 ? valueAsBuffer.getLong(2) : System.currentTimeMillis();
            payloadCount++;
            // remember position in the buffer to roll back to in case of overflow
            buffer.mark();
            buffer.put(keyType).put(keyLength).put(key);
            buffer.putLong(timestamp).putShort(valueLength).put(value);

            return true;
        }
        catch (BufferOverflowException e)
        {
            payloadCount--;
            buffer.reset();
            return false;
        }
    }

    byte[] serialize()
    {
        int finalPosition = buffer.position();
        // adjust the message header with the totals
        buffer.putInt(writeStatsPosition, payloadCount)
              .putInt(writeStatsPosition + 4, finalPosition);
        return readToBytes(buffer);
    }
}

static void validateAndSend(final Partition partition, final Supplier<Message> messageFactory)
    throws InterruptedException
{
    final ConcurrentLinkedQueue<DataHolder> dataHolders = dataHoldersByPartition.get(partition);
    Message message = messageFactory.get();
    DataHolder dataHolder;
    while ((dataHolder = dataHolders.poll()) != null)
    {
        final byte[] keyBytes = dataHolder.getClientKey()
                                    .getBytes(StandardCharsets.UTF_8);
        final int keyLength = keyBytes.length;
        if (keyLength > 255)
        {
            continue;
        }

        while (!message.add(keyBytes, dataHolder.getProcessBytes()))
        {
            // TODO: consider proper handling of the case when the buffer size is too small to accept even a single pair
            Preconditions.checkState(message.payloadCount > 0,
                "buffer size too small to accommodate payload");
            final byte[] serializedMessage = message.serialize();
            // TODO: makes sense to introduce a message consumer interface and call it here instead of sendToDatabase() - simplifies testing
            sendToDatabase(message.address, serializedMessage);
            message = messageFactory.get();
        }
    }
    if (message.payloadCount > 0)
    {
        byte[] serializedMessage = message.serialize();
        sendToDatabase(message.address, serializedMessage);
    }
}

static void sendToDatabase(long address, byte[] serializedMessage)
{
    // TODO: added simulating activity
    System.out.printf("Sending %d bytes to %d: %s%n",
        serializedMessage.length, address, DatatypeConverter.printHexBinary(serializedMessage));
}

static byte[] readToBytes(ByteBuffer buffer)
{
    buffer.flip();
    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);
    return bytes;
}

public static void main(String[] args)
    throws ExecutionException, InterruptedException
{
    // TODO: using small value for testing - must be set to 50K in real case
    final int maxMessageSize = 80;
    final Supplier<Message> messageFactory = new Supplier<Message>()
    {
        @Override
        public Message get()
        {
            return new Message(Partition.A, maxMessageSize);
        }
    };

    final ConcurrentLinkedQueue<DataHolder> dataHolders = dataHoldersByPartition.get(Partition.A);
    dataHolders.add(new DataHolder("0000000001", "alpha"));
    dataHolders.add(new DataHolder("0000000002", "bravo"));
    dataHolders.add(new DataHolder("0000000003", "charlie"));
    dataHolders.add(new DataHolder("0000000004", "delta"));
    dataHolders.add(new DataHolder("0000000005", "echo"));
    dataHolders.add(new DataHolder("0000000006", "foxtrot"));

    validateAndSend(Partition.A, messageFactory);
}
</code>```

Body:
I have a method which takes a parameter which is Partition enum. This method will be called by multiple background threads (15 max) around same time period by passing different value of partition. Here dataHoldersByPartition is a ImmutableMap of Partition and ConcurrentLinkedQueue<DataHolder>.

  private final ImmutableMap<Partition, ConcurrentLinkedQueue<DataHolder>> dataHoldersByPartition;

  //... some code to populate entry in `dataHoldersByPartition` map

  private void validateAndSend(final Partition partition) {
    ConcurrentLinkedQueue<DataHolder> dataHolders = dataHoldersByPartition.get(partition);
    Map<byte[], byte[]> clientKeyBytesAndProcessBytesHolder = new HashMap<>();
    int totalSize = 0;
    DataHolder dataHolder;
    while ((dataHolder = dataHolders.poll())  != null) {
      byte[] clientKeyBytes = dataHolder.getClientKey().getBytes(StandardCharsets.UTF_8);
      if (clientKeyBytes.length > 255)
        continue;

      byte[] processBytes = dataHolder.getProcessBytes();
      int clientKeyLength = clientKeyBytes.length;
      int processBytesLength = processBytes.length;

      int additionalLength = clientKeyLength + processBytesLength;
      if (totalSize + additionalLength > 50000) {
        Message message = new Message(clientKeyBytesAndProcessBytesHolder, partition);
        // here size of `message.serialize()` byte array should always be less than 50k at all cost
        sendToDatabase(message.getAddress(), message.serialize());
        clientKeyBytesAndProcessBytesHolder = new HashMap<>();
        totalSize = 0;
      }
      clientKeyBytesAndProcessBytesHolder.put(clientKeyBytes, processBytes);
      totalSize += additionalLength;
    }
    // calling again with remaining values only if clientKeyBytesAndProcessBytesHolder is not empty
    if(!clientKeyBytesAndProcessBytesHolder.isEmpty()) {
        Message message = new Message(partition, clientKeyBytesAndProcessBytesHolder);
        // here size of `message.serialize()` byte array should always be less than 50k at all cost
        sendToDatabase(message.getAddress(), message.serialize());
    }
  }

And below is my Message class:

public final class Message {
  private final byte dataCenter;
  private final byte recordVersion;
  private final Map<byte[], byte[]> clientKeyBytesAndProcessBytesHolder;
  private final long address;
  private final long addressFrom;
  private final long addressOrigin;
  private final byte recordsPartition;
  private final byte replicated;

  public Message(Map<byte[], byte[]> clientKeyBytesAndProcessBytesHolder, Partition recordPartition) {
    this.clientKeyBytesAndProcessBytesHolder = clientKeyBytesAndProcessBytesHolder;
    this.recordsPartition = (byte) recordPartition.getPartition();
    this.dataCenter = Utils.CURRENT_LOCATION.get().datacenter();
    this.recordVersion = 1;
    this.replicated = 0;
    long packedAddress = new Data().packAddress();
    this.address = packedAddress;
    this.addressFrom = 0L;
    this.addressOrigin = packedAddress;
  }

  // Output of this method should always be less than 50k always
  public byte[] serialize() {
    // 36 + dataSize + 1 + 1 + keyLength + 8 + 2;
    int bufferCapacity = getBufferCapacity(clientKeyBytesAndProcessBytesHolder);

    ByteBuffer byteBuffer = ByteBuffer.allocate(bufferCapacity).order(ByteOrder.BIG_ENDIAN);
    // header layout
    byteBuffer.put(dataCenter).put(recordVersion).putInt(clientKeyBytesAndProcessBytesHolder.size())
        .putInt(bufferCapacity).putLong(address).putLong(addressFrom).putLong(addressOrigin)
        .put(recordsPartition).put(replicated);

    // data layout
    for (Map.Entry<byte[], byte[]> entry : clientKeyBytesAndProcessBytesHolder.entrySet()) {
      byte keyType = 0;
      byte[] key = entry.getKey();
      byte[] value = entry.getValue();
      byte keyLength = (byte) key.length;
      short valueLength = (short) value.length;

      ByteBuffer dataBuffer = ByteBuffer.wrap(value);
      long timestamp = valueLength > 10 ? dataBuffer.getLong(2) : System.currentTimeMillis();

      byteBuffer.put(keyType).put(keyLength).put(key).putLong(timestamp).putShort(valueLength)
          .put(value);
    }
    return byteBuffer.array();
  }

  private int getBufferCapacity(Map<byte[], byte[]> clientKeyBytesAndProcessBytesHolder) {
    int size = 36;
    for (Entry<byte[], byte[]> entry : clientKeyBytesAndProcessBytesHolder.entrySet()) {
      size += 1 + 1 + 8 + 2;
      size += entry.getKey().length;
      size += entry.getValue().length;
    }
    return size;
  }

    // getters and to string method here
}

Basically, what I have to make sure is whenever the sendToDatabase method is called in validateAndSend method, size of message.serialize() byte array should always be less than 50k at all cost. My sendToDatabase method sends byte array coming out from serialize method. So for example if I have 60k records in dataHolders CLQ then I will send in two chunks in validateAndSend method:

First, I will make a byte array  which is approx less than 50k (meaning byte array coming out from message.serialize() is less than 50k) and call sendToDatabase method on it.

Second, I will call sendToDatabase method for remianing part.

And to accomplish above things, I was having totalSize variable in validateAndSend method which is trying to measure 50k size but looks like my approach might not be right and I maybe dropping some records or sending more than 50k everytime I guess?

Looks like my Message class knows about clientKeyBytesAndProcessBytesHolder map and I can use this map to accurately define the size by calling getBufferCapacity method and if is approx less than 50k then call sendToDatabase method?

Body:
So here is my attempt (the question is probably better be addressed to the Code Review community, but anyway). It relies on some design changes to Message so that it becomes more like a Builder pattern. The buffer becomes part of the message. Its occupancy is controlled by reacting on BufferOverflowException exception. Once it occurs the buffer is rolled back to the last successfully added result, new message is allocated, and attempt to add the same piece of data is retried. Upon buffer completion the total number of records and the overall size are written to header, and the whole buffer is dumped to a byte array (I would probably try to avoid this extra conversion and operate on the buffer directly in sendToDatabase, but that's out of scope for now):

// TODO: structure has been adjusted for testing purposes
enum Partition
{
    A(0x1);

    private final int _partition;

    int getPartition()
    {
        return _partition;
    }

    Partition(final int partition)
    {
        _partition = partition;
    }
}

// TODO: structure has been adjusted for testing purposes
final static class DataHolder
{
    private final String _clientKey;
    private final byte[] _processBytes;

    public DataHolder(
        final String clientKey,
        final String value)
    {
        _clientKey = clientKey;
        byte[] valueBytes = value.getBytes();
        // simulate payload including extra bytes for the header
        final ByteBuffer buffer = ByteBuffer.allocate(4 + 8 + valueBytes.length)
                                            .order(ByteOrder.BIG_ENDIAN);
        buffer.putInt(0).putLong(System.currentTimeMillis()).put(valueBytes);
        _processBytes = readToBytes(buffer);
    }

    String getClientKey()
    {
        return _clientKey;
    }

    byte[] getProcessBytes()
    {
        return _processBytes;
    }
}

// API has been changed to something more like the Builder pattern
final static class Message
{
    private final long address;
    private final long addressFrom;
    private final long addressOrigin;
    private final byte recordsPartition;
    private final byte replicated;
    private final ByteBuffer buffer;
    private final int writeStatsPosition;
    private int payloadCount;

    Message(Partition recordPartition, int sizeLimit)
    {
        this.recordsPartition = (byte) recordPartition.getPartition();
        this.replicated = 0;
        // TODO: temporarily replaced with a hard-coded constant
        long packedAddress = 123456789L;
        this.address = packedAddress;
        this.addressFrom = 0L;
        this.addressOrigin = packedAddress;
        buffer = ByteBuffer.allocate(sizeLimit).order(ByteOrder.BIG_ENDIAN);
        // TODO: temporarily replaced with a hard-coded constant
        byte dataCenter = 0x1;
        byte recordVersion = 1;
        buffer.put(dataCenter).put(recordVersion);
        writeStatsPosition = buffer.position();
        buffer.putInt(datacenter).putInt(recordVersion);
        buffer.putLong(address).putLong(addressFrom).putLong(addressOrigin)
                  .put(recordsPartition).put(replicated);
    }

    /**
     * Tries to add another pair of client key and process bytes to
     * the current message. Returns true if successfully added, false -
     * if the data cannot be accommodated due to message binary size limit.
     */
    boolean add(byte[] key, byte[] value)
    {
        try
        {
            byte keyType = 0;
            byte keyLength = (byte) key.length;
            short valueLength = (short) value.length;
            ByteBuffer valueAsBuffer = ByteBuffer.wrap(value);
            long timestamp = valueAsBuffer.capacity() > 10 ? valueAsBuffer.getLong(2) : System.currentTimeMillis();
            payloadCount++;
            // remember position in the buffer to roll back to in case of overflow
            buffer.mark();
            buffer.put(keyType).put(keyLength).put(key);
            buffer.putLong(timestamp).putShort(valueLength).put(value);

            return true;
        }
        catch (BufferOverflowException e)
        {
            payloadCount--;
            buffer.reset();
            return false;
        }
    }

    byte[] serialize()
    {
        int finalPosition = buffer.position();
        // adjust the message header with the totals
        buffer.putInt(writeStatsPosition, payloadCount)
              .putInt(writeStatsPosition + 4, finalPosition);
        return readToBytes(buffer);
    }
}

static void validateAndSend(final Partition partition, final Supplier<Message> messageFactory)
    throws InterruptedException
{
    final ConcurrentLinkedQueue<DataHolder> dataHolders = dataHoldersByPartition.get(partition);
    Message message = messageFactory.get();
    DataHolder dataHolder;
    while ((dataHolder = dataHolders.poll()) != null)
    {
        final byte[] keyBytes = dataHolder.getClientKey()
                                    .getBytes(StandardCharsets.UTF_8);
        final int keyLength = keyBytes.length;
        if (keyLength > 255)
        {
            continue;
        }

        while (!message.add(keyBytes, dataHolder.getProcessBytes()))
        {
            // TODO: consider proper handling of the case when the buffer size is too small to accept even a single pair
            Preconditions.checkState(message.payloadCount > 0,
                "buffer size too small to accommodate payload");
            final byte[] serializedMessage = message.serialize();
            // TODO: makes sense to introduce a message consumer interface and call it here instead of sendToDatabase() - simplifies testing
            sendToDatabase(message.address, serializedMessage);
            message = messageFactory.get();
        }
    }
    if (message.payloadCount > 0)
    {
        byte[] serializedMessage = message.serialize();
        sendToDatabase(message.address, serializedMessage);
    }
}

static void sendToDatabase(long address, byte[] serializedMessage)
{
    // TODO: added simulating activity
    System.out.printf("Sending %d bytes to %d: %s%n",
        serializedMessage.length, address, DatatypeConverter.printHexBinary(serializedMessage));
}

static byte[] readToBytes(ByteBuffer buffer)
{
    buffer.flip();
    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);
    return bytes;
}

public static void main(String[] args)
    throws ExecutionException, InterruptedException
{
    // TODO: using small value for testing - must be set to 50K in real case
    final int maxMessageSize = 80;
    final Supplier<Message> messageFactory = new Supplier<Message>()
    {
        @Override
        public Message get()
        {
            return new Message(Partition.A, maxMessageSize);
        }
    };

    final ConcurrentLinkedQueue<DataHolder> dataHolders = dataHoldersByPartition.get(Partition.A);
    dataHolders.add(new DataHolder("0000000001", "alpha"));
    dataHolders.add(new DataHolder("0000000002", "bravo"));
    dataHolders.add(new DataHolder("0000000003", "charlie"));
    dataHolders.add(new DataHolder("0000000004", "delta"));
    dataHolders.add(new DataHolder("0000000005", "echo"));
    dataHolders.add(new DataHolder("0000000006", "foxtrot"));

    validateAndSend(Partition.A, messageFactory);
}


来源: stackexchange

问:
How to extract apple's 1 billion countdown?
I've been trying to figure it out for hours and i didn't success, This Counter from Apple 1 billion downloads prize. doesn't use flash at all, only javascript and 0-9 images, which makes it really cool. Now after stackoverflow successed to extract google's pacman, can we do that?

P.S I can't even know if this is using prototype or scriptaculous since they're both included.

答: Looks like it's a JS counter coupled with CSS.</p>

ContentLicense: CC BY-SA 2.5


问:
C how to show all unused functions (including ones defined in h files)
Somewhat related to this, but it still doesn't quite answer my question

I have a C project, and i would like to enumerate all unreferenced functions (including non-static, so setting compiler option for werror=unused-function only partially works...) in order to identify and clean up the codebase.

One way I thought is to enumerate all the functions in the project, and then make a script to go through each and see if it is called via cscope... but I'm not sure how to get a list-form of all the functions in the first place. That link above has a solution that is failing for me.

Any other ideas are welcome.

答: You can try CppDepend, it will give you all the not used functions of your code base.</p>

ContentLicense: CC BY-SA 3.0


问:
How to get xpath in a site(like IRCTC) if right click is disabled and is there any way to handle captcha using webdriver
I just wrote some code to open IRCTC website. After this I would like to login but how can I get xpath? Also, is there any possibility to automate captcha?

```<code>public void login() {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.get("https://www.irctc.co.in/eticketing/loginHome.jsf");
}
</code>```

答: If you need to inspect the element using the firebug or firepath then press F12 key in the firefox. Then it opens up the inspector, click on firepath tab and inspect the element. You get the absolute path.

Body:
I just wrote some code to open IRCTC website. After this I would like to login but how can I get xpath? Also, is there any possibility to automate captcha?

public void login() {
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.get("https://www.irctc.co.in/eticketing/loginHome.jsf");
}


问:
How to force input to only allow Alpha Letters?
using jQuery here, however unable to prevent numbers from being typed into the input field

http://codepen.io/leongaban/pen/owbjg

Input

```<code><input type="text" name="field" maxlength="8"
    title="Only Letters"
    value="Type Letters Only"
    onkeydown="return alphaOnly(event);"
    onblur="if (this.value == '') {this.value = 'Type Letters Only';}"
    onfocus="if (this.value == 'Type Letters Only') {this.value = '';}"/>
</code>```

jQuery

```<code>function alphaOnly(event) {

  alert(event);

  var key;

  if (window.event) {
    key = window.event.key;
  } else if (e) {
    key = e.which;
  }
  //var key = window.event.key || event.key;
  alert(key.value);
  return ((key >= 65 && key <= 90) || (key >= 95 && key <= 122));

}
</code>```

I've seen plenty of examples here on how to restrict to only Numbers, and I'm using the correct key codes  for a-z and A-Z. Do you see what I'm doing wrong?

答:
```<code><input type="text" name="name" id="event" onkeydown="return alphaOnly(event);"   required />

function alphaOnly(event) {
  var key = event.keyCode;`enter code here`
  return ((key >= 65 && key <= 90) || key == 8);
};
</code>```

Body:
using jQuery here, however unable to prevent numbers from being typed into the input field

http://codepen.io/leongaban/pen/owbjg

Input

<input type="text" name="field" maxlength="8"
    title="Only Letters"
    value="Type Letters Only"
    onkeydown="return alphaOnly(event);"
    onblur="if (this.value == '') {this.value = 'Type Letters Only';}"
    onfocus="if (this.value == 'Type Letters Only') {this.value = '';}"/>

jQuery

function alphaOnly(event) {

  alert(event);

  var key;

  if (window.event) {
    key = window.event.key;
  } else if (e) {
    key = e.which;
  }
  //var key = window.event.key || event.key;
  alert(key.value);
  return ((key >= 65 && key <= 90) || (key >= 95 && key <= 122));

}

I've seen plenty of examples here on how to restrict to only Numbers, and I'm using the correct key codes  for a-z and A-Z. Do you see what I'm doing wrong?


问:
using the value of an argument to access an object property
This is the simple currency converter script which gets the currency rate from JS library - it's based on the last value in JSON chaining (PLN, EUR etc. ) ->

```<code>    var priceAmount = amount;
    var currencyRateUSDPLN = Currency.rates.PLN;
</code>```

I know that I can't pass the function argument straight to Currency.rates.PLN, what is the shortest way to achieve this functionality ?

```<code>function convertCurrency (amount, to) {
    var priceAmount = amount;
    // here I want to pass 'to' argument (EUR, PLN for example)
    var currencyRateUSDPLN = Currency.rates.to;
    var pricePLN = ( priceAmount / currencyRateUSDPLN ).toFixed(2);
    console.log(pricePLN + ' PLN');
}
</code>```

The Currency object contains -> link

答:
I'm assuming the question you are trying to ask is how can you use the value of an argument to access an object property.

you can do this using bracket notation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

```<code>function convertCurrency (amount, to) {
    var priceAmount = amount;
    // here I want to pass 'to' argument (EUR, PLN for example)

    var currencyRateUSDPLN = Currency.rates[to];
    // If 'to' argument passed in is "EUR" then this
    // will resolve to Currency.rates.EUR

    var pricePLN = ( priceAmount / currencyRateUSDPLN ).toFixed(2);
    console.log(pricePLN + ' PLN');
}
</code>```

Body:
This is the simple currency converter script which gets the currency rate from JS library - it's based on the last value in JSON chaining (PLN, EUR etc. ) ->

    var priceAmount = amount;
    var currencyRateUSDPLN = Currency.rates.PLN;

I know that I can't pass the function argument straight to Currency.rates.PLN, what is the shortest way to achieve this functionality ?

function convertCurrency (amount, to) {
    var priceAmount = amount;
    // here I want to pass 'to' argument (EUR, PLN for example)
    var currencyRateUSDPLN = Currency.rates.to;
    var pricePLN = ( priceAmount / currencyRateUSDPLN ).toFixed(2);
    console.log(pricePLN + ' PLN');
}

The Currency object contains -> link

Body:
I'm assuming the question you are trying to ask is how can you use the value of an argument to access an object property.

you can do this using bracket notation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

function convertCurrency (amount, to) {
    var priceAmount = amount;
    // here I want to pass 'to' argument (EUR, PLN for example)

    var currencyRateUSDPLN = Currency.rates[to];
    // If 'to' argument passed in is "EUR" then this
    // will resolve to Currency.rates.EUR

    var pricePLN = ( priceAmount / currencyRateUSDPLN ).toFixed(2);
    console.log(pricePLN + ' PLN');
}


问:
Django: Why 'Class' object is not iterable
I built a dictionary list like this

```<code>lst = [{'name': nameobj, Classobj1: "string", Classobj2: "string"}, \
{'name': nameobj, Classobj1: "string", Classobj2: "string"}]
</code>```

and I'm using

```<code>for dic in lst:
   for k,v in dic:   # here is the line has probloem! What it happens?
       #process
</code>```

The error message is like "Classname" object is not iterable.

答:
Try to use </p>

```<code>for dic in lst:
    for key in dic.keys():
     /* process dic[key] */
</code>```

Body:
I built a dictionary list like this

lst = [{'name': nameobj, Classobj1: "string", Classobj2: "string"}, \
{'name': nameobj, Classobj1: "string", Classobj2: "string"}]

and I'm using

for dic in lst:
   for k,v in dic:   # here is the line has probloem! What it happens?
       #process

The error message is like "Classname" object is not iterable.

Body:
Try to use

for dic in lst:
    for key in dic.keys():
     /* process dic[key] */


问:
Javascript multiplying incorrectly, causing incorrect rounding
When I pull the values I want to multiply, they're strings. So I pull them, parse them as floats (to preserve the decimal places), and multiply them together.

```<code>LineTaxRate = parseFloat(myRate) * parseFloat(myQuantity) * parseFloat(myTaxRateRound);
</code>```

This has worked for 99% of my invoices but I discovered one very odd problem.

When it multiplied: 78 * 7 * 0.0725

Javascript is returning: 39.584999999999994

When you normally do the math in a calculator its: 39.585

When all is said and done, I take that number and round it using .toFixed(2)

Because Javascript is returning that number, it's not rounding to the desired value of: $39.59

I tried Math.round() the total but I still get the same number.

I have thought of rounding the number to 3 decimals then two, but that seems hacky to me.

I have searched everywhere and all I see is people mention parseFloat loses its precision, and to use .toFixed, however in the example above, that doesn't help.

Here is my test script i made to recreate the issue:

```<code><script>
var num1 = parseFloat("78");
var num2 = parseFloat("7");
var num3 = parseFloat("0.0725");
var myTotal = num1 * num2 * num3;
var result = Math.round(myTotal*100)/100

alert(myTotal);
alert(myTotal.toFixed(2));
alert(result);
</script>
</code>```

答:
JavaScript/TypeScript have only one Number class which is not that good. I have the same problem as I am using TypeScript. I solved my problem by using decimal.js-light library. </p>

```<code>new Decimal(78).mul(7).mul(0.0725) returns as expected 39.585
</code>```

Body:
When I pull the values I want to multiply, they're strings. So I pull them, parse them as floats (to preserve the decimal places), and multiply them together.

LineTaxRate = parseFloat(myRate) * parseFloat(myQuantity) * parseFloat(myTaxRateRound);

This has worked for 99% of my invoices but I discovered one very odd problem.

When it multiplied: 78 * 7 * 0.0725

Javascript is returning: 39.584999999999994

When you normally do the math in a calculator its: 39.585

When all is said and done, I take that number and round it using .toFixed(2)

Because Javascript is returning that number, it's not rounding to the desired value of: $39.59

I tried Math.round() the total but I still get the same number.

I have thought of rounding the number to 3 decimals then two, but that seems hacky to me.

I have searched everywhere and all I see is people mention parseFloat loses its precision, and to use .toFixed, however in the example above, that doesn't help.

Here is my test script i made to recreate the issue:

Body:
JavaScript/TypeScript have only one Number class which is not that good. I have the same problem as I am using TypeScript. I solved my problem by using decimal.js-light library.

new Decimal(78).mul(7).mul(0.0725) returns as expected 39.585


问:
difference beetwen path.join(__dirname , 'views') and path.join(__dirname + 'views') in node.js
im stuck with node.js again.

i try the first path.join in my code for setup view engine its not working, the index won't showing up, then i change to path.join(__dirname , 'views'); and its working well, the index showing, i dont know how

can someone explain how this work ?

```<code>path.join(__dirname + 'views');

path.join(__dirname, 'views');
</code>```

this is my script

```<code>app.set('views', path.join(__dirname, 'views')); //its work
app.set('views', path.join(__dirname + 'views')); // if i change like this, its not work
</code>```

答:
for know  the difference on this function, you have the official node.JS documentation

The first method using the Javascript concatenation have a different result that using a method parameters:

Using standard javascript :

```<code>let folder = '/folder';
let subFolder = 'sub';

path.join(folder + sub ) // result : /foldersub
</code>```

But, with properly use the paramters of this method, the path is different: This method format all parameters for create a standard part with /

```<code>let folder = '/folder';
let subFolder = 'sub';

path.join(folder, sub) // result : /folder/sub
</code>```

Don't forget you cano use the console.log(path) for debug in Javascript... link for using it here

Body:
im stuck with node.js again.

i try the first path.join in my code for setup view engine its not working, the index won't showing up, then i change to path.join(__dirname , 'views'); and its working well, the index showing, i dont know how

can someone explain how this work ?

path.join(__dirname + 'views');

path.join(__dirname, 'views');

this is my script

app.set('views', path.join(__dirname, 'views')); //its work
app.set('views', path.join(__dirname + 'views')); // if i change like this, its not work

Body:
for know  the difference on this function, you have the official node.JS documentation

The first method using the Javascript concatenation have a different result that using a method parameters:

Using standard javascript :

let folder = '/folder';
let subFolder = 'sub';

path.join(folder + sub ) // result : /foldersub

But, with properly use the paramters of this method, the path is different: This method format all parameters for create a standard part with /

let folder = '/folder';
let subFolder = 'sub';

path.join(folder, sub) // result : /folder/sub

Don't forget you cano use the console.log(path) for debug in Javascript... link for using it here


问:
Trouble with getting an instance of a room-Database
I unfortunately have big issues with getting an instance of a Room-Database for my android project. I followed the instructions on https://developer.android.com/training/data-storage/room/index.html
But the last step won't work for me:

```<code>AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name").build();
</code>```

Their AppDatabase.java looks like this

```<code>@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
</code>```

My Problem: At "AppDatabase db" I get the error 'cannot resolve symbol "AppDatabase" '. This is quite senseful, because AppDatabase is just an abstract class. But how is this supposed to work in the tutorial?
I tried to get the instance in the onCreate method of my MainActivity.
Here are my gradlefiles:
    buildscript {

```<code>    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
       // NOTE: Do not place your application dependencies here; they belong
      // in the individual module build.gradle files
    }
}

ext {
    buildToolsVersion = "25.0.2"
    supportLibVersion = "25.3.1"
    archRoomVersion = "1.0.0-alpha1"
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

and the second one:

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.fabian.kohlmannkonstruktionen"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
compile 'android.arch.persistence.room:runtime:' +
rootProject.archRoomVersion
annotationProcessor 'android.arch.persistence.room:compiler:' +
rootProject.archRoomVersion

}
</code>```

MainActivity.java

```<code>package com.example.fabian.kohlmannkonstruktionen;

import android.app.AlertDialog;
import android.content.DialogInterface;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.content.Context;

public class MainActivity extends AppCompatActivity {

AppDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = AppDatabase.getInMemoryDatabase(getApplicationContext());
}
...
</code>```

AppDatabase.java

```<code>package com.example.fabian.kohlmannkonstruktionen;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.content.Context;

public class MainActivity extends AppCompatActivity {
    AppDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = AppDatabase.getInMemoryDatabase(getApplicationContext());
}
</code>```

Projekt.java

```<code>import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;

/**
 * Created by Fabian on 14.11.2017.
 */
@Entity
public class Projekt {
    @PrimaryKey(autoGenerate = true)
    Integer id;

    Integer projektnummer;
    Integer lohn,arbeitszeit;
    String projektname, firma;
    Boolean abgeschlossen;
    public Projekt(String projektname,String firma,Integer projektnummer){
        this.abgeschlossen=false;
        this.projektname=projektname;
        this.projektnummer=projektnummer;
        this.firma=firma;
    }
...getters and setters...
</code>```

ProjektDao.java

```<code>import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;

import java.util.List;

/**
 * Created by Fabian on 15.11.2017.
 */
@Dao
public interface ProjektDao {
    @Query("SELECT * FROM Projekt")
    List<Projekt> getAll();

    @Query("SELECT * FROM Projekt where id LIKE  :id")
    Projekt findByID(String id);

    @Query("SELECT COUNT(*) from Projekt")
    int countUsers();

    @Insert
    void insertAll(Projekt... projekts);

    @Delete
    void delete(Projekt projekt);
}
</code>```

Termin and TerminDao looks the same

This is the text from the gradle console:

```<code>Executing tasks: [assemble]

Configuration on demand is an incubating feature.
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.
:app:compileDebugJavaWithJavac
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\TerminDao.java:14: warning: The query returns some columns [pausenzeit, startzeit, endzeit, lohnproh, mitarbeiter, standort] which are not use by Projekt. You can use @ColumnInfo annotation on the fields to specify the mapping. Projekt has some fields [projektnummer, lohn, arbeitszeit, projektname, firma, abgeschlossen] which are not returned by the query. If they are not supposed to be read from the result, you can mark them with @Ignore annotation. You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: id, pausenzeit, startzeit, endzeit, lohnproh, mitarbeiter, standort. Fields in Projekt: id, projektnummer, lohn, arbeitszeit, projektname, firma, abgeschlossen.
    List<Projekt> getAll();
                  ^
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\AppDatabase.java:13: warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide `room.schemaLocation` annotation processor argument OR set exportSchema to false.
public abstract class AppDatabase extends RoomDatabase {
                ^
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\com\example\fabian\kohlmannkonstruktionen\MainActivity.java:13: error: cannot find symbol
    AppDatabase db = AppDatabase.getInMemoryDatabase(getApplicationContext());
    ^
  symbol:   class AppDatabase
  location: class MainActivity
1 error
2 warnings

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 5s

14 actionable tasks: 1 executed, 13 up-to-date
</code>```

答:
Checkout my code that might help you.

AppDatabase.java

```<code>@Database(entities = {Product.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;

    public abstract ProductDao productDao();

    public static AppDatabase getInMemoryDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.inMemoryDatabaseBuilder(context.getApplicationContext(), AppDatabase.class).allowMainThreadQueries().build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}
</code>```

Mainactivity.java

```<code>AppDatabase db = AppDatabase.getInMemoryDatabase(getApplicationContext());
</code>```

Build.Gradle(Project)

```<code>allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}
</code>```

Build.Gradle(App)

```<code>// Room
compile 'android.arch.persistence.room:runtime:1.0.0'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
</code>```

This will create only one instance. this works well in my code.

Body:
I unfortunately have big issues with getting an instance of a Room-Database for my android project. I followed the instructions on https://developer.android.com/training/data-storage/room/index.html
But the last step won't work for me:

AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name").build();

Their AppDatabase.java looks like this

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}

My Problem: At "AppDatabase db" I get the error 'cannot resolve symbol "AppDatabase" '. This is quite senseful, because AppDatabase is just an abstract class. But how is this supposed to work in the tutorial?
I tried to get the instance in the onCreate method of my MainActivity.
Here are my gradlefiles:
    buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
       // NOTE: Do not place your application dependencies here; they belong
      // in the individual module build.gradle files
    }
}

ext {
    buildToolsVersion = "25.0.2"
    supportLibVersion = "25.3.1"
    archRoomVersion = "1.0.0-alpha1"
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and the second one:

apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.fabian.kohlmannkonstruktionen"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
compile 'android.arch.persistence.room:runtime:' +
rootProject.archRoomVersion
annotationProcessor 'android.arch.persistence.room:compiler:' +
rootProject.archRoomVersion

}

MainActivity.java

package com.example.fabian.kohlmannkonstruktionen;

import android.app.AlertDialog;
import android.content.DialogInterface;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.content.Context;

public class MainActivity extends AppCompatActivity {

AppDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = AppDatabase.getInMemoryDatabase(getApplicationContext());
}
...

AppDatabase.java

package com.example.fabian.kohlmannkonstruktionen;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.content.Context;

public class MainActivity extends AppCompatActivity {
    AppDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = AppDatabase.getInMemoryDatabase(getApplicationContext());
}

Projekt.java

import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;

/**
 * Created by Fabian on 14.11.2017.
 */
@Entity
public class Projekt {
    @PrimaryKey(autoGenerate = true)
    Integer id;

    Integer projektnummer;
    Integer lohn,arbeitszeit;
    String projektname, firma;
    Boolean abgeschlossen;
    public Projekt(String projektname,String firma,Integer projektnummer){
        this.abgeschlossen=false;
        this.projektname=projektname;
        this.projektnummer=projektnummer;
        this.firma=firma;
    }
...getters and setters...

ProjektDao.java

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;

import java.util.List;

/**
 * Created by Fabian on 15.11.2017.
 */
@Dao
public interface ProjektDao {
    @Query("SELECT * FROM Projekt")
    List<Projekt> getAll();

    @Query("SELECT * FROM Projekt where id LIKE  :id")
    Projekt findByID(String id);

    @Query("SELECT COUNT(*) from Projekt")
    int countUsers();

    @Insert
    void insertAll(Projekt... projekts);

    @Delete
    void delete(Projekt projekt);
}

Termin and TerminDao looks the same

This is the text from the gradle console:

Executing tasks: [assemble]

Configuration on demand is an incubating feature.
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.
:app:compileDebugJavaWithJavac
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\TerminDao.java:14: warning: The query returns some columns [pausenzeit, startzeit, endzeit, lohnproh, mitarbeiter, standort] which are not use by Projekt. You can use @ColumnInfo annotation on the fields to specify the mapping. Projekt has some fields [projektnummer, lohn, arbeitszeit, projektname, firma, abgeschlossen] which are not returned by the query. If they are not supposed to be read from the result, you can mark them with @Ignore annotation. You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: id, pausenzeit, startzeit, endzeit, lohnproh, mitarbeiter, standort. Fields in Projekt: id, projektnummer, lohn, arbeitszeit, projektname, firma, abgeschlossen.
    List<Projekt> getAll();
                  ^
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\AppDatabase.java:13: warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide `room.schemaLocation` annotation processor argument OR set exportSchema to false.
public abstract class AppDatabase extends RoomDatabase {
                ^
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\com\example\fabian\kohlmannkonstruktionen\MainActivity.java:13: error: cannot find symbol
    AppDatabase db = AppDatabase.getInMemoryDatabase(getApplicationContext());
    ^
  symbol:   class AppDatabase
  location: class MainActivity
1 error
2 warnings

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 5s

14 actionable tasks: 1 executed, 13 up-to-date

Body:
Checkout my code that might help you.

AppDatabase.java

@Database(entities = {Product.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;

    public abstract ProductDao productDao();

    public static AppDatabase getInMemoryDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.inMemoryDatabaseBuilder(context.getApplicationContext(), AppDatabase.class).allowMainThreadQueries().build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

Mainactivity.java

AppDatabase db = AppDatabase.getInMemoryDatabase(getApplicationContext());

Build.Gradle(Project)

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

Build.Gradle(App)

// Room
compile 'android.arch.persistence.room:runtime:1.0.0'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'

This will create only one instance. this works well in my code.


问:
How to change the order of words with alphabetic order
I got a dataset with a list of keywords (1 keyword / row).

I m looking for a way to create a new column (ALPHABETICAL) based on the KEYWORD column. The value of the ALPHABETICAL column should be auto generated based on the keyword, but words should be ordered alphabetically.

Like this :

```<code> | KEYWORD            | ALPHABETICAL       |
 | house blue         | blue house         |
 | blue house         | blue house         |
 | my blue house      | blue house my      |
 | this house is blue | blue house is this |
 | sky orange         | orange sky         |
 | orange sky         | orange sky         |
 | the orange sky     | orange sky the     |
</code>```

Thanks for your help!

答:
Iterate over rows to split by " "(strsplit), sort and collapse back:

```<code># Generate data
df <- data.frame(KEYWORD = c(paste(sample(letters, 3), collapse = " "),
                             paste(sample(letters, 3), collapse = " ")))
#  KEYWORD
#   z e s
#   d a u

df$ALPHABETICAL  <- apply(df, 1, function(x) paste(sort(unlist(strsplit(x, " "))),
                                                   collapse = " "))
#  KEYWORD ALPHABETICAL
#   z e s        e s z
#   d a u        a d u
</code>```

Body:
I got a dataset with a list of keywords (1 keyword / row).

I m looking for a way to create a new column (ALPHABETICAL) based on the KEYWORD column. The value of the ALPHABETICAL column should be auto generated based on the keyword, but words should be ordered alphabetically.

Like this :

 | KEYWORD            | ALPHABETICAL       |
 | house blue         | blue house         |
 | blue house         | blue house         |
 | my blue house      | blue house my      |
 | this house is blue | blue house is this |
 | sky orange         | orange sky         |
 | orange sky         | orange sky         |
 | the orange sky     | orange sky the     |

Thanks for your help!

Body:
Iterate over rows to split by " "(strsplit), sort and collapse back:

# Generate data
df <- data.frame(KEYWORD = c(paste(sample(letters, 3), collapse = " "),
                             paste(sample(letters, 3), collapse = " ")))
#  KEYWORD
#   z e s
#   d a u

df$ALPHABETICAL  <- apply(df, 1, function(x) paste(sort(unlist(strsplit(x, " "))),
                                                   collapse = " "))
#  KEYWORD ALPHABETICAL
#   z e s        e s z
#   d a u        a d u


问:
How to get return value each state changed in another componentin React
In a React Component Passed a value, if Component Change state, How to return a new value from this component.
If ScrollDetecter state changed how to return value this component?

```<code><ScrollDetector/>

export default class ScrollDetector extends React.Component {
 //Most impotant function only metioned
handleScroll() {
const windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight;
const body = document.body;
const html = document.documentElement;
const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight,  html.scrollHeight, html.offsetHeight);
const windowBottom = windowHeight + window.pageYOffset;
if (windowBottom >= docHeight) {

  this.setState({
    message:'bottom reached'
  });
} else {
  this.setState({
    message:'not at bottom'
  });
}
}
}
</code>```

How to a particular value to parent component return if bottom reached message state.?

答:
You could use and event handler / callback function and send a prop from parent to child so it notifies when bottom has been reached:

```<code>class ScrollDetector extendsReactComponent {
  handleScroll() {
    ...
    if (windowBottom >= docHeight) {
      this.props.onBottomReached()
    } else {
      ...
    }
  }
}
</code>```

and from your parent component:

```<code>class YourParent extends React.Component {
  render() {
    return (
      <div>
        <ScrollDetector
          onBottomReached={() => console.log('bottom reached!') }
        />
      </div>
    )
  }
}
</code>```

Body:
In a React Component Passed a value, if Component Change state, How to return a new value from this component.
If ScrollDetecter state changed how to return value this component?

<ScrollDetector/>

export default class ScrollDetector extends React.Component {
 //Most impotant function only metioned
handleScroll() {
const windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight;
const body = document.body;
const html = document.documentElement;
const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight,  html.scrollHeight, html.offsetHeight);
const windowBottom = windowHeight + window.pageYOffset;
if (windowBottom >= docHeight) {

  this.setState({
    message:'bottom reached'
  });
} else {
  this.setState({
    message:'not at bottom'
  });
}
}
}

How to a particular value to parent component return if bottom reached message state.?

Body:
You could use and event handler / callback function and send a prop from parent to child so it notifies when bottom has been reached:

class ScrollDetector extendsReactComponent {
  handleScroll() {
    ...
    if (windowBottom >= docHeight) {
      this.props.onBottomReached()
    } else {
      ...
    }
  }
}

and from your parent component:

class YourParent extends React.Component {
  render() {
    return (
      <div>
        <ScrollDetector
          onBottomReached={() => console.log('bottom reached!') }
        />
      </div>
    )
  }
}


问:
Wagtail customize file upload
I'm new in wagtail, I'm trying to customize the file upload event in admin side. How I can validate the file name (for image, document, or video) before to upload.</p>

答:
One way to this would be to build a custom document model where you can override the __init__ function and raise an exception if certain file extensions are used.

http://docs.wagtail.io/en/v1.13/advanced_topics/documents/custom_document_model.html

This might be a bit heavy handed though without knowing what you are trying to do exactly.

Title: Wagtail customize file upload


问:
jquery add remove form input on toggle
I have the following html and form elements

```<code><div class='ticket-sold' id='1' >RAFFLE-1-NOVEMBER</div>
<div class='ticket' id='2'>RAFFLE-2-NOVEMBER</div>
<div class='ticket' id='3'>RAFFLE-3-NOVEMBER</div>
<div class='ticket' id='4'>RAFFLE-4-NOVEMBER</div>
<div class='ticket' id='5'>RAFFLE-5-NOVEMBER</div>

<form class="paypal" action="./includes/gateways/payments.php" method="post" id="paypal_form" target="_blank">
    <input type="hidden" name="cmd" value="_xclick" />
    <input type="hidden" name="no_note" value="1" />
    <input type="hidden" name="lc" value="UK" />
    <input type="hidden" name="currency_code" value="GBP" />
    <input type="hidden" name="payer_email" value="customer@example.com"  />
   <input name="item_name_1" value="TICKET NUMBER 5" id="input_5" type="hidden">
   <input name="item_name_2" value="TICKET NUMBER 20" id="input_20" type="hidden">
   <input name="item_name_3" value="TICKET NUMBER 27" id="input_27" type="hidden">
   <input type="hidden" name="amount_1" value="10" id="input_5" />
   <input type="hidden" name="amount_2" value="10" id="input_20" />
   <input type="hidden" name="amount_3" value="10" id="input_27" />
   <input type="submit" name="submit" value="Submit Payment"/>
</form>
</code>```

Basically, I have jquery that when the Div class 'ticket' is selected, the 'amount' field is updated based on the number of 'ticket' elements selected.

```<code>var counter = 0;
$(".ticket").on("click", function() {
$(this).toggleClass("green");
$(this).toggleClass('selected');
var selectedIds = $('.selected').map(function() {
        return this.id;
}).get();
var id = $(this).attr('id');
if(!$(this).hasClass('selected')) {
    $('#paypal_form #input_' + id).remove();
    counter--;
} else {
    counter++;
    $('#paypal_form').append('<input type="hidden" name="item_name_'+counter+'" value="TICKET NUMBER ' + id + '" id="input_'+id+'">');
    $('#paypal_form').append('<input type="hidden" name="amount_'+counter+'" value="' + $(".ticketprice").text() +'" id="input_'+id +'">');
    }
    $(".totaltickets").text(selectedIds.length -1);
    $(".totalprice").text((selectedIds.length - 1)*$(".ticketprice").text());
</code>```

What I would like to do, is at the same time of the onclick function on the 'ticket' div, I would like another input type ie <input type="hidden" name="item_name" value="Selected ID from Div"> added dynamically to the Form ("paypal_form").  And if the 'ticket' DIV is toggled, ie Clicked to deselect the item, the added  element should be removed.

thanks
Craig.

答:
figured it out with the following

```<code>var ii = 1;
$("input[name^='item_name']").each(function(i){
    $(this).attr('name', 'item_name_' + ii++);
});
var ii = 1;
$("input[name^='amount']").each(function(i){
    $(this).attr('name','amount_' + ii++);
});
</code>```

thanks for your help :)

Title: jquery add remove form input on toggle

Body:
I have the following html and form elements

RAFFLE-1-NOVEMBER

RAFFLE-2-NOVEMBER

RAFFLE-3-NOVEMBER

RAFFLE-4-NOVEMBER

RAFFLE-5-NOVEMBER

<form class="paypal" action="./includes/gateways/payments.php" method="post" id="paypal_form" target="_blank">
    <input type="hidden" name="cmd" value="_xclick" />
    <input type="hidden" name="no_note" value="1" />
    <input type="hidden" name="lc" value="UK" />
    <input type="hidden" name="currency_code" value="GBP" />
    <input type="hidden" name="payer_email" value="customer@example.com"  />
   <input name="item_name_1" value="TICKET NUMBER 5" id="input_5" type="hidden">
   <input name="item_name_2" value="TICKET NUMBER 20" id="input_20" type="hidden">
   <input name="item_name_3" value="TICKET NUMBER 27" id="input_27" type="hidden">
   <input type="hidden" name="amount_1" value="10" id="input_5" />
   <input type="hidden" name="amount_2" value="10" id="input_20" />
   <input type="hidden" name="amount_3" value="10" id="input_27" />
   <input type="submit" name="submit" value="Submit Payment"/>
</form>

Basically, I have jquery that when the Div class 'ticket' is selected, the 'amount' field is updated based on the number of 'ticket' elements selected.

var counter = 0;
$(".ticket").on("click", function() {
$(this).toggleClass("green");
$(this).toggleClass('selected');
var selectedIds = $('.selected').map(function() {
        return this.id;
}).get();
var id = $(this).attr('id');
if(!$(this).hasClass('selected')) {
    $('#paypal_form #input_' + id).remove();
    counter--;
} else {
    counter++;
    $('#paypal_form').append('<input type="hidden" name="item_name_'+counter+'" value="TICKET NUMBER ' + id + '" id="input_'+id+'">');
    $('#paypal_form').append('<input type="hidden" name="amount_'+counter+'" value="' + $(".ticketprice").text() +'" id="input_'+id +'">');
    }
    $(".totaltickets").text(selectedIds.length -1);
    $(".totalprice").text((selectedIds.length - 1)*$(".ticketprice").text());

What I would like to do, is at the same time of the onclick function on the 'ticket' div, I would like another input type ie <input type="hidden" name="item_name" value="Selected ID from Div"> added dynamically to the Form ("paypal_form").  And if the 'ticket' DIV is toggled, ie Clicked to deselect the item, the added  element should be removed.

thanks
Craig.

Body:
figured it out with the following

var ii = 1;
$("input[name^='item_name']").each(function(i){
    $(this).attr('name', 'item_name_' + ii++);
});
var ii = 1;
$("input[name^='amount']").each(function(i){
    $(this).attr('name','amount_' + ii++);
});

thanks for your help :)


问:
Listbox in Grid Row with MaxHeight definded: Scrollbar disabled
I have the following Grid:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="300"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="20"></RowDefinition>
        <RowDefinition Height="60"></RowDefinition>
        <RowDefinition Height="*" MaxHeight="200"></RowDefinition>
        <RowDefinition Height="20"></RowDefinition>
        <RowDefinition Height="20"></RowDefinition>
    </Grid.RowDefinitions>
    ...
    <ListBox x:Name="lstAbweichungen" Grid.Row="2" Grid.Column="1" FontSize="14"
             ItemsSource="{Binding MyList}" ScrollViewer.VerticalScrollBarVisibility ="Visible" />
    ...
</Grid>
</code>```

The scrollbar in the ListBox is visible but not enabled, and the listbox stretches into the invisible area. I want the ListBox not to stretch beyond the 200 and the scrollbar working. Do you see what's wrong? Thanks, Anne

答:
With the code you supplied I was not able to reproduce the problem.

However, I found that if you place any control (ListBox, ScrollViewer, Grid) within a Stackpanel, ScrollViewer or a Listbox, the controls will behave exactly as you have described.

Does your main grid exist within another control? Maybe the User Control exists within a container such as the ones I have mentioned?

Body:
I have the following Grid:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="300"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="20"></RowDefinition>
        <RowDefinition Height="60"></RowDefinition>
        <RowDefinition Height="*" MaxHeight="200"></RowDefinition>
        <RowDefinition Height="20"></RowDefinition>
        <RowDefinition Height="20"></RowDefinition>
    </Grid.RowDefinitions>
    ...
    <ListBox x:Name="lstAbweichungen" Grid.Row="2" Grid.Column="1" FontSize="14"
             ItemsSource="{Binding MyList}" ScrollViewer.VerticalScrollBarVisibility ="Visible" />
    ...
</Grid>

The scrollbar in the ListBox is visible but not enabled, and the listbox stretches into the invisible area. I want the ListBox not to stretch beyond the 200 and the scrollbar working. Do you see what's wrong? Thanks, Anne


问:
Python equivalent of ruby rspec's "skip" and "pending"
I'm coming from ruby to python. With ruby's rspec, I am used to using skip and pending to denote tests which should be skipped / cannot currently be executed.

What are the equivalents in Python?

答:
Python's pytest allows:

Skipping test functions, eg:

```<code>pytest.skip("unsupported configuration")
</code>```

xfail for tests which are expected to fail, eg:

```<code>pytest.xfail("waiting for foo to be fixed")
</code>```

Body:
Python's pytest allows:

Skipping test functions, eg:

pytest.skip("unsupported configuration")

xfail for tests which are expected to fail, eg:

pytest.xfail("waiting for foo to be fixed")


问:
How can I Update value of key In JSON Object?
I am using _underscore. I want to rename value of particular key.

var users = [{
    "_id": { "$oid":"3426" },
    "name":"peeter"
}, {
    "_id": { "$oid":"5a027" },
    "name":"ken"
}, {
    "_id": { "$oid":"5999" },
    "name":"karmal"
}];

var index = _.find(users, function(o) { return o._id.$oid == '5999'; });
console.log(index);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script></code>```

In above output in console.log(index), I want to edit value of key(name), meaning add karmal-Copy.

Desired output

```<code>{
    "_id": {
        "$oid": "5999"
    },
    "name": "karmal-Copy"
}
</code>```

I want only add -Copy with key(name) value.

答:
With the power of Higher-order functions</p>

```<code>var users = [
    {"_id":{"$oid":"3426"},
    "name":"peeter"
    },
    {"_id":{"$oid":"5a027"},
    "name":"ken"
    },
    {"_id":{"$oid":"5999"},
    "name":"karmal"
    }
  ];

var getSpecific$oid=function(oid){
    return function(obj) { return obj["_id"]["$oid"]===oid; };
  }

var addExtensionInName=function(extension){
    return function(obj){
        var rObj = {};
        rObj["_id"]=obj["_id"]
        rObj["name"]=obj["name"] +"-"+extension;
        return rObj;
      };
  }

var index=users.filter(getSpecific$oid("5999")).map(addExtensionInName("copy"))
</code>```

Body:
I am using _underscore. I want to rename value of particular key.

var users = [{
    "_id": { "$oid":"3426" },
    "name":"peeter"
}, {
    "_id": { "$oid":"5a027" },
    "name":"ken"
}, {
    "_id": { "$oid":"5999" },
    "name":"karmal"
}];

var index = _.find(users, function(o) { return o._id.$oid == '5999'; });
console.log(index);

In above output in console.log(index), I want to edit value of key(name), meaning add karmal-Copy.

Desired output

{
    "_id": {
        "$oid": "5999"
    },
    "name": "karmal-Copy"
}

I want only add -Copy with key(name) value.

Body:
With the power of Higher-order functions

var users = [
    {"_id":{"$oid":"3426"},
    "name":"peeter"
    },
    {"_id":{"$oid":"5a027"},
    "name":"ken"
    },
    {"_id":{"$oid":"5999"},
    "name":"karmal"
    }
  ];

var getSpecific$oid=function(oid){
    return function(obj) { return obj["_id"]["$oid"]===oid; };
  }

var addExtensionInName=function(extension){
    return function(obj){
        var rObj = {};
        rObj["_id"]=obj["_id"]
        rObj["name"]=obj["name"] +"-"+extension;
        return rObj;
      };
  }

var index=users.filter(getSpecific$oid("5999")).map(addExtensionInName("copy"))


问:
REQUEST_METHOD default
Is
$_SERVER["REQUEST_METHOD"] set to 'GET' by default?

This code

```<code><?php echo $_SERVER["REQUEST_METHOD"]; ?>
</code>```

outputs 'GET' even if it is in an empty file with no other tags ( / <form> / <?php ?>)

答:
By default the request sent by browser is always GET. Take a look here

Look at this:

17.3 The FORM element

```<code><!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->
<!ATTLIST FORM
  %attrs;                              -- %coreattrs, %i18n, %events --
  action      %URI;          #REQUIRED -- server-side form handler --
  method      (GET|POST)     GET       -- HTTP method used to submit the form--
  enctype     %ContentType;  "application/x-www-form-urlencoded"
  accept      %ContentTypes; #IMPLIED  -- list of MIME types for file upload --
  name        CDATA          #IMPLIED  -- name of form for scripting --
  onsubmit    %Script;       #IMPLIED  -- the form was submitted --
  onreset     %Script;       #IMPLIED  -- the form was reset --
  accept-charset %Charsets;  #IMPLIED  -- list of supported charsets --
  >
</code>```

Title: REQUEST_METHOD default

Body:
Is
$_SERVER["REQUEST_METHOD"] set to 'GET' by default?

This code

<?php echo $_SERVER["REQUEST_METHOD"]; ?>

outputs 'GET' even if it is in an empty file with no other tags ( / <form> / <?php ?>)

Body:
By default the request sent by browser is always GET. Take a look here

Look at this:

17.3 The FORM element

<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->
<!ATTLIST FORM
  %attrs;                              -- %coreattrs, %i18n, %events --
  action      %URI;          #REQUIRED -- server-side form handler --
  method      (GET|POST)     GET       -- HTTP method used to submit the form--
  enctype     %ContentType;  "application/x-www-form-urlencoded"
  accept      %ContentTypes; #IMPLIED  -- list of MIME types for file upload --
  name        CDATA          #IMPLIED  -- name of form for scripting --
  onsubmit    %Script;       #IMPLIED  -- the form was submitted --
  onreset     %Script;       #IMPLIED  -- the form was reset --
  accept-charset %Charsets;  #IMPLIED  -- list of supported charsets --
  >


问:
How do I calculate hours from PM to AM using moment.js?
I've been working on calculating the total hours, minutes and seconds between two times using the moment.js library.  The problem I have is that the calculations don't recognise that it's a day and return more hours than what is there.  I'll give you an example:

I want to know how many hours are between 21:00 and 06:00, the answer is 9, however, the calculation brings back -15, this is also technically correct.  I need to tell moment that it should use a day to calculate this value.  I can get it to work if I use a DateTime picker but I don't want to use that as the user is only required to provide a time.

My application uses KendoUI for MVC and moment.js, moment.duration.format.js and moment.range.js

Here is my code which will return -15

```<code>@(Html.Kendo().TimePicker().Name("start").Value("21:00"))
@(Html.Kendo().TimePicker().Name("end").Value("06:00"))

<button class="btn btn-default btn-success" onclick="calc()">Plot</button>
</code>```

Here is the javascript that works with this.

```<code> function calc() {

   window['moment-range'].extendMoment(moment);

    console.clear();

    var dformat = "HH:mm:ss";
    var start = $("#start").data("kendoTimePicker").value();
    var end = $("#end").data("kendoTimePicker").value();

    var startTime = moment(kendo.toString(start));
    var endTime = moment(kendo.toString(end));
    var duration = moment.duration(endTime.diff(startTime));
    var hours = parseInt(duration.asHours());
    console.log(hours);
}
</code>```

If we change this to use DateTimePicker instead, it understands there is a day and calculates 9 hours.  So how do I get around this?  How can I achive this without using a datetime picker?  Can I leaverage moment.js startof day or something?

答:
Thanks to @VincenzoC I have managed to fix this problem.  Here is the code which checks if the end time is before the start time and if it is, add a single day.  This means the resulting time is accurate.</p>

```<code>var startTime = moment(start);
var endTime = moment(end);

if (endTime.isBefore(startTime))
{
    endTime.add(1, 'd');

}

//
//After the above condition has been passed, calculate the difference
var duration = moment.duration(endTime.diff(startTime));

//
//Any format you want
console.log(duration.format("HH"))
</code>```

Body:
I've been working on calculating the total hours, minutes and seconds between two times using the moment.js library.  The problem I have is that the calculations don't recognise that it's a day and return more hours than what is there.  I'll give you an example:

I want to know how many hours are between 21:00 and 06:00, the answer is 9, however, the calculation brings back -15, this is also technically correct.  I need to tell moment that it should use a day to calculate this value.  I can get it to work if I use a DateTime picker but I don't want to use that as the user is only required to provide a time.

My application uses KendoUI for MVC and moment.js, moment.duration.format.js and moment.range.js

Here is my code which will return -15

@(Html.Kendo().TimePicker().Name("start").Value("21:00"))
@(Html.Kendo().TimePicker().Name("end").Value("06:00"))

<button class="btn btn-default btn-success" onclick="calc()">Plot</button>

Here is the javascript that works with this.

 function calc() {

   window['moment-range'].extendMoment(moment);

    console.clear();

    var dformat = "HH:mm:ss";
    var start = $("#start").data("kendoTimePicker").value();
    var end = $("#end").data("kendoTimePicker").value();

    var startTime = moment(kendo.toString(start));
    var endTime = moment(kendo.toString(end));
    var duration = moment.duration(endTime.diff(startTime));
    var hours = parseInt(duration.asHours());
    console.log(hours);
}

If we change this to use DateTimePicker instead, it understands there is a day and calculates 9 hours.  So how do I get around this?  How can I achive this without using a datetime picker?  Can I leaverage moment.js startof day or something?

Body:
Thanks to @VincenzoC I have managed to fix this problem.  Here is the code which checks if the end time is before the start time and if it is, add a single day.  This means the resulting time is accurate.

var startTime = moment(start);
var endTime = moment(end);

if (endTime.isBefore(startTime))
{
    endTime.add(1, 'd');

}

//
//After the above condition has been passed, calculate the difference
var duration = moment.duration(endTime.diff(startTime));

//
//Any format you want
console.log(duration.format("HH"))


问:
firebase how to get child of child?
so i am stuck. i want to retrieve child of child from my firebase database.

my database struture looks like this

```<code>users{
    user1{
        name:
        regno:
        carmodel:
        caryear}
    user2{
        name:
        regno:
        carmodel:
        caryear}
    user3{
        name:
        regno:
        carmodel:
        caryear}}
</code>```

Regno = car registration number.

when i type in a "carreg no" and press ok. i want the code to search every carreg. if a match is found execute next set of codes.

so far i have tried to store it in a array. but the code seems to fail when i put reg or any variable name that exist.

```<code> public void input(){

    FirebaseDatabase firebase = FirebaseDatabase.getInstance();
    final DatabaseReference table_user = firebase.getReference("User");
    table_user.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //Get map of users in datasnapshot
                    collectPhoneNumbers((Map<String,Object>) dataSnapshot.getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    //handle databaseError
                }
            });

private void collectPhoneNumbers(Map<String,Object> users) {

        ArrayList<Long> phoneNumbers = new ArrayList<>();

        //iterate through each user, ignoring their UID
        for (Map.Entry<String, Object> entry : users.entrySet()){

            //Get user map
            Map singleUser = (Map) entry.getValue();
            //Get phone field and append to list
            phoneNumbers.add((Long) singleUser.get("namesd"));
        }

        System.out.println(phoneNumbers.toString());

        mVoiceInputTv.setText("" + phoneNumbers);
    }
}
</code>```

i got this from another stackflow. before this i tried creating a for look. it was successfull but result failed 80% of the time. (not always correct).

答:
```<code>private FirebaseDatabase mdatabase;

private DatabaseReference mdatabaseRef;

    mdatabase = FirebaseDatabase.getInstance();
    mdatabaseRef = mdatabase.getReference();
  mdatabaseRef.child("users").child("users1").orderByChild("regno").equalsTo(regno).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

    for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {

}
}
</code>```

Title: firebase how to get child of child?

Body:
so i am stuck. i want to retrieve child of child from my firebase database.

my database struture looks like this

users{
    user1{
        name:
        regno:
        carmodel:
        caryear}
    user2{
        name:
        regno:
        carmodel:
        caryear}
    user3{
        name:
        regno:
        carmodel:
        caryear}}

Regno = car registration number.

when i type in a "carreg no" and press ok. i want the code to search every carreg. if a match is found execute next set of codes.

so far i have tried to store it in a array. but the code seems to fail when i put reg or any variable name that exist.

 public void input(){

    FirebaseDatabase firebase = FirebaseDatabase.getInstance();
    final DatabaseReference table_user = firebase.getReference("User");
    table_user.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //Get map of users in datasnapshot
                    collectPhoneNumbers((Map<String,Object>) dataSnapshot.getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    //handle databaseError
                }
            });

private void collectPhoneNumbers(Map<String,Object> users) {

        ArrayList<Long> phoneNumbers = new ArrayList<>();

        //iterate through each user, ignoring their UID
        for (Map.Entry<String, Object> entry : users.entrySet()){

            //Get user map
            Map singleUser = (Map) entry.getValue();
            //Get phone field and append to list
            phoneNumbers.add((Long) singleUser.get("namesd"));
        }

        System.out.println(phoneNumbers.toString());

        mVoiceInputTv.setText("" + phoneNumbers);
    }
}

i got this from another stackflow. before this i tried creating a for look. it was successfull but result failed 80% of the time. (not always correct).


问:
Possible solution for bitbucket pipeline docker-run limitation
My integration tests are highly dependent of a elastic search, given that to build my integration tests on bitbucket pipeline I would have to execute the docker-run command to be able to spin up my elastic-search instance during my integration tests.

But as probably some of you know, there's a limitation on the bitbucket pipeline

See the Docker command line reference for information on how to use
  these commands. Other commands, such as docker run, are currently
  forbidden for security reasons on our shared build infrastructure.

So given that I don't know how can I spin-up my escluster with all configurations that I need inside, painless scripts, mappings, ports exposed to be available for my integrations tests.

Does someone have any idea how could i achieve this?

答:
You can try to define your elastic-search image as a service as described there:
Use services and databases in Bitbucket Pipelines</p>


问:
Magento 1.9: Get Up-sell products in the table, as select according to product name
Can I filter, how the Up-sell products /which I have set for a particular product/ will be displayed in my table according to the name of the product? My idea is to display only the products starting with a certain word, such as "Decor", the rest products do not show in the table. This is my code upsell.phtml:

```<code><?php if(count($this->getItemCollection()->getItems())): ?>
<div class="box-collateral box-up-sell">
    <h2><?php echo $this->__('') ?></h2>
    <table style=" border:4px solid white;border-right:4px solid green class="mini-products-grid" id="upsell-product-table">
    <?php // $this->setColumnCount(5); // uncomment this line if you want to have another number of columns. also can be changed in layout ?>
    <?php $this->resetItemsIterator() ?>
    <?php for($_i=0;$_i<$this->getRowCount();$_i++): ?>
        <tr style="white";>
        <?php for($_j=0;$_j<$this->getColumnCount();$_j++): ?>
            <?php if($_link=$this->getIterableItem()): ?>
            <td style=" border-top:4px solid white;border-right:4px solid green>
                <a href="<?php echo $_link->getProductUrl() ?>" title="<?php echo $this->escapeHtml($_link->getName()) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_link, 'small_image')->resize(250) ?>" width="170" height="170" alt="<?php echo $this->escapeHtml($_link->getName()) ?>" /></a>
                <h3 class="product-name"><a href="<?php echo $_link->getProductUrl() ?>" title="<?php echo $this->escapeHtml($_link->getName()) ?>"><?php echo $this->escapeHtml($_link->getName()) ?></a></h3>
                <?php echo $this->getPriceHtml($_link, true, '-upsell') ?>
                <?php echo $this->getReviewsSummaryHtml($_link) ?>
            </td>
            <?php else: ?>
            <td class="empty"> </td>
            <?php endif; ?>
        <?php endfor; ?>
        </tr>
    <?php endfor; ?>
    </table>
    <script type="text/javascript">decorateTable('upsell-product-table')</script>
</div>
<?php endif ?>
</code>```

I had an idea to use Regular Expressions.

答:
you can filter your collection of product-links with

```<code>->addAttributeToFilter('name', array('like' => '%Decor%'))
</code>```

however you should do this inside the view block, before collection is loaded

ContentLicense: CC BY-SA 4.0

Body:
Can I filter, how the Up-sell products /which I have set for a particular product/ will be displayed in my table according to the name of the product? My idea is to display only the products starting with a certain word, such as "Decor", the rest products do not show in the table. This is my code upsell.phtml:

<?php if(count($this->getItemCollection()->getItems())): ?>

<?php echo $this->__('') ?>

    <?php // $this->setColumnCount(5); // uncomment this line if you want to have another number of columns. also can be changed in layout ?>
    <?php $this->resetItemsIterator() ?>
    <?php for($_i=0;$_i<$this->getRowCount();$_i++): ?>

        <?php for($_j=0;$_j<$this->getColumnCount();$_j++): ?>
            <?php if($_link=$this->getIterableItem()): ?>

                <a href="<?php echo $_link->getProductUrl() ?>" title="<?php echo $this->escapeHtml($_link->getName()) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_link, 'small_image')->resize(250) ?>" width="170" height="170" alt="<?php echo $this->escapeHtml($_link->getName()) ?>" />

<a href="<?php echo $_link->getProductUrl() ?>" title="<?php echo $this->escapeHtml($_link->getName()) ?>"><?php echo $this->escapeHtml($_link->getName()) ?>

                <?php echo $this->getPriceHtml($_link, true, '-upsell') ?>
                <?php echo $this->getReviewsSummaryHtml($_link) ?>

            <?php else: ?>

            <?php endif; ?>
        <?php endfor; ?>

    <?php endfor; ?>

<?php endif ?>

I had an idea to use Regular Expressions.

Body:
you can filter your collection of product-links with

->addAttributeToFilter('name', array('like' => '%Decor%'))

however you should do this inside the view block, before collection is loaded


问:
Navbar growing wider than bootstrap column width
I am trying to position navbar fixed to the left-hand side of the screen effectively in a sidebar with the rest of the page content rendering to the right.

Currently, I have tried to split the page into two using bootstrap columns like so:

html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}

/********************************************
*                                           *
*                                           *
*               WRAPPERS                    *
*                                           *
*                                           *
********************************************/

#sidebarWrapper {
  height: 100%;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  background-color: red;
  overflow-x: hidden;
  overflow-y: auto;
  transition: all 0.5s ease;
}

/********************************************
*                                           *
*                                           *
*             SIDEBAR NAV STYLE             *
*                                           *
*                                           *
********************************************/

.sidebar-nav {
  margin: 0;
  padding: 0;
  top: 0;
  list-style: none;
  position: absolute;
}

.sidebar-nav>li {
  display: inline-block;
  line-height: 20px;
  position: relative;
  width: 100%;
}

/********************************************
*                                           *
*                                           *
*                  DIV STYLE                *
*                                           *
*                                           *
********************************************/

.container-fluid {
  height: 100%;
}

.container-fluid h1 {
  padding: 0;
  margin: 0;
}

/********************************************
*                                           *
*                                           *
*              PAGE BODY STYLE              *
*                                           *
*                                           *
********************************************/

.header {
  height: 10%;
  background-color: yellow;
}

.contentBody {
  height: 80%;
  background-color: green;
}

.footer {
  height: 10%;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container-fluid">
  <div class="row">
    <div class="col-lg-2">
      <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="sidebarWrapper">
        <ul class="nav sidebar-nav">
          <li>
            Dashboard
          </li>
        </ul>
      </nav>
    </div>
    <div class="col-lg-10">
      <div class="header">
        <h1>Header</h1>
      </div>
      <div class="contentBody">
        <h1>Content</h1>
      </div>
      <div class="footer">
        <h1>Footer</h1>
      </div>
    </div>
  </div>
</div></code>```

However, as you can see from the snippet my navbar seems to brute force over any bootstrap column restrictions and takes the width of the whole page.

How can I prevent it from doing so, so that it takes 100% of the width of the bootstrap column but no more and no less?

答:
There's 2 changes you need to make to fix your problem.

First point to a working bootstrap stylesheet:

```<code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
</code>```

Secondly, don't use large bootstrap columns without supporting lesser screen sizes as well. To get your desired result however (and using Bootstrap 4), change to:

```<code>...<div class="col-2">...
...<div class="col-10">...
</code>```

Body:
I am trying to position navbar fixed to the left-hand side of the screen effectively in a sidebar with the rest of the page content rendering to the right.

Currently, I have tried to split the page into two using bootstrap columns like so:

html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}

/********************************************
*                                           *
*                                           *
*               WRAPPERS                    *
*                                           *
*                                           *
********************************************/

#sidebarWrapper {
  height: 100%;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  background-color: red;
  overflow-x: hidden;
  overflow-y: auto;
  transition: all 0.5s ease;
}

/********************************************
*                                           *
*                                           *
*             SIDEBAR NAV STYLE             *
*                                           *
*                                           *
********************************************/

.sidebar-nav {
  margin: 0;
  padding: 0;
  top: 0;
  list-style: none;
  position: absolute;
}

.sidebar-nav>li {
  display: inline-block;
  line-height: 20px;
  position: relative;
  width: 100%;
}

/********************************************
*                                           *
*                                           *
*                  DIV STYLE                *
*                                           *
*                                           *
********************************************/

.container-fluid {
  height: 100%;
}

.container-fluid h1 {
  padding: 0;
  margin: 0;
}

/********************************************
*                                           *
*                                           *
*              PAGE BODY STYLE              *
*                                           *
*                                           *
********************************************/

.header {
  height: 10%;
  background-color: yellow;
}

.contentBody {
  height: 80%;
  background-color: green;
}

.footer {
  height: 10%;
  background-color: blue;
}

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

            Dashboard

Header

Content

Footer

However, as you can see from the snippet my navbar seems to brute force over any bootstrap column restrictions and takes the width of the whole page.

How can I prevent it from doing so, so that it takes 100% of the width of the bootstrap column but no more and no less?

Body:
There's 2 changes you need to make to fix your problem.

First point to a working bootstrap stylesheet:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

Secondly, don't use large bootstrap columns without supporting lesser screen sizes as well. To get your desired result however (and using Bootstrap 4), change to:

...<div class="col-2">...
...<div class="col-10">...