Q: Kafka commits transaction after LeaveGroup due to max.poll.interval.ms is exceeded I am using transaction in kafka. I have provided my consumer container with a ChainedKafkaTransactionManager which consist of JpaTransactionManager and KafkaTransactionManager.
I am trying to learn how transactions are affected when a consumer is stuck and therefore send LeaveGroup and disables heartbeat thread.
I have set max.poll.interval.ms to 10 seconds.
I have not changed session.timeout.ms. It is 10 seconds per default.
I have two applications with one consumer each. Both consumers are transactional. Consumer A is rigged to process for 30 seconds and Consumer B process it within 1 second. Both consumers read from the same topic, which as 3 partitions.

*

*Send a record to Kafka

*Consumer A receives the record.

*Consumer A starts to process the record.

*Consumer A processing time exceed max.poll.interval.ms

*Consumer A send LeaveGroup and heartbeat stops.

*Kafka rebalances. All partitions are now assigned to Consumer B.

*Consumer B receives the same record and process it.

*Consumer B commits the transaction.

*Consumer A has now finished processing(30 seconds).

*Consumer A commits the transaction.

*Kafka rebalances. Partitions are reassigned to both consumers.

The transaction is processed and committed twice. Both consumers should be idempotent to ensure processing the same record have no consequences.
My hypothesis was that Consumer A would throw an exception due to LeaveGroup and stopping the heartbeat. This is however not the case. I have tested this with unique transaction IDs and transaction ID being identical in both applications - same result.
Why does Consumer A commit the transaction after LeaveGroup has been sent?
I am not entirely sure if this is a bug. I have however submitted this odd behaviour or bug to Apache Kafka
Log for Consumer A
2018-07-11 11:59:22.365 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Received: 1 records
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager          : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-1, transactionalId=transactionId420] Transition from state READY to IN_TRANSACTION
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager          : Created Kafka transaction on producer [brave.kafka.clients.TracingProducer@631071b0]
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Opened new EntityManager [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for JPA transaction
2018-07-11 11:59:22.366 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.h.e.t.internal.TransactionImpl         : begin
2018-07-11 11:59:22.367 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@4eef56f0]
2018-07-11 11:59:22.427 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] l.a.BatchMessagingMessageListenerAdapter : Processing [GenericMessage [payload=[data], headers={kafka_offset=[34], kafka_consumer=brave.kafka.clients.TracingConsumer@1484643f, kafka_timestampType=[CREATE_TIME], kafka_receivedMessageKey=[null], kafka_receivedPartitionId=[1], kafka_receivedTopic=[trans-topic], kafka_receivedTimestamp=[1531299912221], kafka_batchConvertedHeaders=[{X-B3-SpanId=[B@1e664339, X-B3-ParentSpanId=[B@73f2c38a, X-B3-Sampled=[B@5f0ca155, X-B3-TraceId=[B@68ac877c}]}]]

...
2018-07-11 11:59:30.503 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-1, groupId=mygrp42] Sending Heartbeat request to coordinator localhost:9092 (id: 2147483647 rack: null)
2018-07-11 11:59:30.608 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-1, groupId=mygrp42] Received successful Heartbeat response
2018-07-11 11:59:32.256 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-1, groupId=mygrp42] Sending LeaveGroup request to coordinator localhost:9092 (id: 2147483647 rack: null)
2018-07-11 11:59:32.256 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [hread | mygrp42] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-1, groupId=mygrp42] Disabling heartbeat thread
2018-07-11 11:59:37.458 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Sending offsets to transaction: {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}}
2018-07-11 11:59:37.465 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-1, transactionalId=transactionId420] Begin adding offsets {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}} for consumer group mygrp42 to transaction
2018-07-11 11:59:37.465 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-1, transactionalId=transactionId420] Enqueuing transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId420, producerId=0, producerEpoch=64, consumerGroupId=mygrp42)
2018-07-11 11:59:37.465 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.clients.producer.internals.Sender  : [Producer clientId=producer-1, transactionalId=transactionId420] Sending transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId420, producerId=0, producerEpoch=64, consumerGroupId=mygrp42) to node localhost:9092 (id: 0 rack: null)
2018-07-11 11:59:37.467 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-1, transactionalId=transactionId420] Successfully added partition for consumer group mygrp42 to transaction
2018-07-11 11:59:37.467 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.clients.producer.internals.Sender  : [Producer clientId=producer-1, transactionalId=transactionId420] Sending transactional request (type=TxnOffsetCommitRequest, transactionalId=transactionId420, producerId=0, producerEpoch=64, consumerGroupId=mygrp42, offsets={trans-topic-0=CommittedOffset(offset=408, metadata='')}) to node localhost:9092 (id: 0 rack: null)
2018-07-11 11:59:37.469 DEBUG [kafka-transaction-microservice-example,,,] 46299 --- [ad | producer-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-1, transactionalId=transactionId420] Successfully added offsets {trans-topic-0=CommittedOffset(offset=408, metadata='')} from consumer group mygrp42 to transaction.

Log for Consumer B
2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Received: 1 records
2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager          : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-2, transactionalId=transactionId421] Transition from state READY to IN_TRANSACTION
2018-07-11 11:59:33.777 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.k.t.KafkaTransactionManager          : Created Kafka transaction on producer [brave.kafka.clients.TracingProducer@30b6dff4]
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Opened new EntityManager [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for JPA transaction
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.h.e.t.internal.TransactionImpl         : begin
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.s.orm.jpa.JpaTransactionManager        : Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@2b0eff5d]
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] l.a.BatchMessagingMessageListenerAdapter : Processing [GenericMessage [payload=[data], headers={kafka_offset=[407], kafka_consumer=brave.kafka.clients.TracingConsumer@103b53ce, kafka_timestampType=[CREATE_TIME], kafka_receivedMessageKey=[null], kafka_receivedPartitionId=[0], kafka_receivedTopic=[trans-topic], kafka_receivedTimestamp=[1531299562360], kafka_batchConvertedHeaders=[{X-B3-SpanId=[B@38658f41, X-B3-ParentSpanId=[B@2faeb13a, X-B3-Sampled=[B@29e18244, X-B3-TraceId=[B@75496432}]}]]
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] essageListenerContainer$ListenerConsumer : Sending offsets to transaction: {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}}
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-2, transactionalId=transactionId421] Begin adding offsets {trans-topic-0=OffsetAndMetadata{offset=408, metadata=''}} for consumer group mygrp42 to transaction
2018-07-11 11:59:33.778 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ntainer#0-0-C-1] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-2, transactionalId=transactionId421] Enqueuing transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId421, producerId=1, producerEpoch=11, consumerGroupId=mygrp42)
2018-07-11 11:59:33.779 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.clients.producer.internals.Sender  : [Producer clientId=producer-2, transactionalId=transactionId421] Sending transactional request (type=AddOffsetsToTxnRequest, transactionalId=transactionId421, producerId=1, producerEpoch=11, consumerGroupId=mygrp42) to node localhost:9092 (id: 0 rack: null)
2018-07-11 11:59:33.780 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-2, transactionalId=transactionId421] Successfully added partition for consumer group mygrp42 to transaction
2018-07-11 11:59:33.780 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.clients.producer.internals.Sender  : [Producer clientId=producer-2, transactionalId=transactionId421] Sending transactional request (type=TxnOffsetCommitRequest, transactionalId=transactionId421, producerId=1, producerEpoch=11, consumerGroupId=mygrp42, offsets={trans-topic-0=CommittedOffset(offset=408, metadata='')}) to node localhost:9092 (id: 0 rack: null)
2018-07-11 11:59:33.781 DEBUG [kafka-transaction-microservice-example,,,] 46288 --- [ad | producer-2] o.a.k.c.p.internals.TransactionManager   : [Producer clientId=producer-2, transactionalId=transactionId421] Successfully added offsets {trans-topic-0=CommittedOffset(offset=408, metadata='')} from consumer group mygrp42 to transaction.


Q: Ignore No Subdomain In htaccess RewriteCond I've got htaccess set up that redirects all subdomains except www to https. However I'd also like it to ignore http://domain.com - currently it redirects to https://domain.com which is no good for what I'm doing.
Any idea what the rewrite condition is for that?
I've tried:
RewriteCond %{HTTP_HOST} !^domain.com [NC]

RewriteCond %{HTTP_HOST} !^http://domain.com [NC]

But neither of those work.
Here's what I'm using at the minute.
# Redirect subdomains to https
RewriteCond %{SERVER_PORT} =80
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^domain.com [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

A: I think your problem is that you need to escape the dot in domain.com, so domain\.com.
# Redirect subdomains to https
RewriteCond %{SERVER_PORT} =80
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^domain\.com [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

You used a 301 (permanent) and not a 302, so you may have your browser not even trying to send requests to the http domain until you close. You should use 302 while testing and put the 301 only wen it's ok.

A: Try this:
RewriteCond %{HTTPS} =off
RewriteCond %{HTTP_HOST} !^(www\.)?domain\.com [NC]
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


Q: React Lazy loading and infinite scoll to top I am currently working on a messaging platform and previously, we just load all the messages at once as there are not that many messages. Now that that there are many messages, it is starting to take a long time to load everything.
As such, I would like to implement lazy loading but I can't find any documentation explaining how I can do load the latest 20 messages and load more when I scroll up to view the earlier messages (Just like any messaging platform). Is there any way to implement this?


Q: Keeping file permissions with FTP Is there a way I can upload my files from my computer to my server without losing the permissions? Everything is linux.
Thank you!

A: You are aware that ftp is not the program to use on the internet in 2011. The password will be send in cleartext. (In a wired or WPA Enterprise protected wireless network you might be OK as long as all your traffic stays inhouse)
sftp is the secure replacement (based on ssh). put and get commands have the -P option to preserve the permissions.

A: Basically all FTP clients (cute, filezilla, smart, yafc, etc) have the option to set file permissions.
I have not yet seen any feature / option to permanently persist the file permissions from your computer to the server. However you can in filezilla and in cuteftp ( i use these 2) set an advanced property which will auto apply a permission set of your choice to all files uploaded.
Also, i think this is not likely to ever be released as a feature since file permissions are also based on user! Different users on your computers and different users on your server all of which may or may not have differing permissions.
Hope this helped. Cheers.
PS: let me know if you can't find the option in filezilla or cuteftp

A: It depends on your FTP client. I'm sure nearly all FTP clients have this option. For example, my favorite command-line FTP client, Yafc, lets you:
put -p filename

to put while preserving file permissions.


Q: Generate unique ID of an object that stays the same across instances I am generating an object from the database using the following:
$game = $this->game_model->get_by('slug', 'some-title');

I am also using a cache library in Codeigniter where I write to a cache file by:
$this->cache->write($game, $cache);

where $game is the object and $cache is an identifier for that object.
I would like to generate a unique ID for this object to use as the cache name. Something like spl_object_hash but that will stay the same across subsequent instances.
For example if I do:
$cache = spl_object_hash($game);

// Cache object
$this->cache->write($game, $cache);

It will generate 000000006c5ce27300000000564a8706.cache as the unique ID, but if I reload the page, I get a different ID, which defeats the purpose of the cache.
How can I get a consistent unique ID for an object?

A: You can use serialize() and then hash it.
$cache = hash('sha1', serialize($game));


Q: Update Frame of Rotated UIView I am trying to update the size of rotated UIView. I tried using CGAffineTransform for rotation but whenever I tried updating the size after rotation it messed up the frame.
I somehow managed to update size of rotated view using this stackoverflow answer: rotate-uiimage-and-move which suggests:

*

*Preserving original transform and assigning .identity to the view's transform

*Updating frame of view

*Reassign original transform

Here is my final code which is working perfectly:
    func handlePinch(_ gesture: UIPinchGestureRecognizer) {
        // Preserve previous transform and assign .identity
        let transform = myView.transform
        myView.transform = .identity

        // Compute new frame
        let updatedOrigin = myView.frame.origin.applying(transform.scaledBy(x: gesture.scale, y: gesture.scale))
        let updatedSize = CGSize(width: myView.frame.width * gesture.scale, height: myView.frame.height * gesture.scale)
        myView.bounds = CGRect(origin: updatedOrigin, size: updatedSize)

        // Assign back original transform
        textView.transform = transform

        gesture.scale = 1

    }

Questions:

*

*Is this the right approach to do that? To me it seems like a hack as transform using frame's origin to compute new origin which only works fine when assigned to bounds origin.

*What is the best way to achieve resizing a rotated view?


Q: Bug in Storyboards? I'm trying to follow a YouTube tutorial on using constraints, etc and it gets you to set up a basic Storyboard along with some different coloured views. I can set them up fine, and put the widths, and heights in but as soon as I try to resize a view by the resizing arrows that appear around it's edge, all the other views disappear because their widths/heights are reset to zero. Am I causing this or is it a bug?


Q: GWT + JDO + ArrayList I'm getting a Null ArrayList in a program i'm developing. For testing purposes I created this really small example that still has the same problem. I already tried diferent Primary Keys, but the problem persists.
Any ideas or suggestions?
1-Employee class
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Employee {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    @Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
    private String key;

    @Persistent
    private ArrayList<String> nicks;

    public Employee(ArrayList<String> nicks) {
        this.setNicks(nicks);
    }

    public String getKey() {
        return key;
    }

    public void setNicks(ArrayList<String> nicks) {
        this.nicks = nicks;
    }

    public ArrayList<String> getNicks() {
        return nicks;
    }
}

2-EmployeeService
public class BookServiceImpl extends RemoteServiceServlet implements
EmployeeService {

    public void addEmployee(){

        ArrayList<String> nicks = new ArrayList<String>();
        nicks.add("name1");
        nicks.add("name2");

        Employee employee = new Employee(nicks);

        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(employee);
        } finally {
            pm.close();
        }
    }

    /**
     * @return
     * @throws NotLoggedInException
     * @gwt.typeArgs <Employee>
     */
    public Collection<Employee> getEmployees() {

        PersistenceManager pm = getPersistenceManager();

        try {
            Query q = pm.newQuery("SELECT FROM " + Employee.class.getName());

            Collection<Employee> list =
                pm.detachCopyAll((Collection<Employee>)q.execute());

            return list;

        } finally {
            pm.close();
        }
    }
}

A: Your Employee class did not have detachable = "true".
You should change
@PersistenceCapable(identityType = IdentityType.APPLICATION)

to
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true")

A: Is it significant that in addEmployee, you obtain the persistenceManager like this:
PersistenceManager pm = PMF.get().getPersistenceManager();

but in getEmployees you call it like this
PersistenceManager pm = getPersistenceManager();

without using PMF.get().

A: I changed the code a bit, and everything is normal now, still I don't know what caused this problem.
I'm using Lists now instead of the collections**(1), I return everything as a simple array trough the RPC(2)** and I changed the way I did the query**(3)**.
(1) List results = (List) query.execute();
(2) return (Employee[]) employees.toArray(new Employee[0]);
(3) Query query = pm.newQuery(Employee.class);


Q: Show all data in a single object instead of nested object I am using sequelize ORM and for DB I am using MySQL, in which I have associated two tables and getting the data, but I want 2nd data (another table's data) should not come in like nested object instead could we show all data in a single object (both table data).
let me show the screen shot.

What I want to something like.

Ignore the keys and values of data, but my question here, could we here show the data of another table (think like inner join) in the same object, not something like in nested object.
Any suggestion would be appreciable thanks.

A: I'm not sure what you exactly want but according to your input/output I think you want to flatten the nested object(?) and for that you can use the next piece of code-
nested_obj = {"message": "Hey you", "nested_obj": {"id": 1}}

flattened_obj = Object.assign(
    {},
    ...function _flatten(o) {
      return [].concat(...Object.keys(o)
        .map(k =>
          typeof o[k] === 'object' ?
            _flatten(o[k]) :
            ({[k]: o[k]})
        )
      );
    }(nested_obj)
  )

console.log(JSON.stringify(flattened_obj));


Q: Selecting property of anonymous type using LINQ throws exception My Linq query (i want to get list of items sorted by number of orders)
var x = context.Items.Include("Item_qualities").Join(
               context.Orders,
               i => i.Id,
               o => o.Item_id,
               (i, o) => new { i, o }
               )
               .GroupBy(e => new { e.i })
               .Select(w => new { w.Key.i, c = w.Count() })
               .OrderByDescending(y => y.c)
               .ToList().Select(u=>u.i);

Last part Select(u=>u.i) throws exception

The text, ntext, and image data types cannot be compared or sorted,
  except when using IS NULL or LIKE operator.

A: That error is pretty clear:
The text data type, which is deprecated as of SQL Server 2005, is not suitable for comparison so it is not possible to do sorting on it. The same goes for image data type. Read this for more details. In other words the database engine cannot do the sorting based on the column you have specified.


Q: What's the Return of GetQueuedCompletionStatus when the I/O is cancelled via CancelIoEx? Imagine I have a thread waiting for some I/O packets with GetQueuedCompletionStatus().  Another thread uses CancelIoEx() with lpOverlapped == nullptr to cancel all of the I/Os that the first thread initiated.
Will GetQueuedCompletionStatus() return immediately, and is there an appropriate error-code with GetLastError()?  Or will CancelIoEx() prevent the I/Os from ever finishing and GetQueuedCompletionStatus() will remain pending for further I/O?

A: The answers to all of your questions are clearly stated in Microsoft's documentation.
CancelIoEx():

The CancelIoEx function allows you to cancel requests in threads other than the calling thread. The CancelIo function only cancels requests in the same thread that called the CancelIo function. CancelIoEx cancels only outstanding I/O on the handle, it does not change the state of the handle; this means that you cannot rely on the state of the handle because you cannot know whether the operation was completed successfully or canceled.
If there are any pending I/O operations in progress for the specified file handle, the CancelIoEx function marks them for cancellation. Most types of operations can be canceled immediately; other operations can continue toward completion before they are actually canceled and the caller is notified. The CancelIoEx function does not wait for all canceled operations to complete.
If the file handle is associated with a completion port, an I/O completion packet is not queued to the port if a synchronous operation is successfully canceled. For asynchronous operations still pending, the cancel operation will queue an I/O completion packet.
The operation being canceled is completed with one of three statuses; you must check the completion status to determine the completion state. The three statuses are:

*

*The operation completed normally. This can occur even if the operation was canceled, because the cancel request might not have been submitted in time to cancel the operation.

*The operation was canceled. The GetLastError function returns ERROR_OPERATION_ABORTED.

*The operation failed with another error. The GetLastError function returns the relevant error code.

GetQueuedCompletionStatus():

If the GetQueuedCompletionStatus function succeeds, it dequeued a completion packet for a successful I/O operation from the completion port and has stored information in the variables pointed to by the following parameters: lpNumberOfBytes, lpCompletionKey, and lpOverlapped. Upon failure (the return value is FALSE), those same parameters can contain particular value combinations as follows:

*

*If *lpOverlapped is NULL, the function did not dequeue a completion packet from the completion port. In this case, the function does not store information in the variables pointed to by the lpNumberOfBytes and lpCompletionKey parameters, and their values are indeterminate.

*If *lpOverlapped is not NULL and the function dequeues a completion packet for a failed I/O operation from the completion port, the function stores information about the failed operation in the variables pointed to by lpNumberOfBytes, lpCompletionKey, and lpOverlapped. To get extended error information, call GetLastError.

So, this means that CancelIoEx() will simply mark existing asynchronous operations for cancellation, and IF THE DRIVER ACTUALLY CANCELS THEM then completion statuses WILL be posted back to you indicating the operations were cancelled.
If GetQueuedCompletionStatus() returns TRUE, that means an I/O packet with a success status was dequeued.
If GetQueuedCompletionStatus() returns FALSE AND OUTPUTS A NON-NULL OVERLAPPED* pointer, that means an I/O packet with a failure status was dequeued, so all of the output values are valid, and you can use GetLastError() to get the error code for that packet.
If GetQueuedCompletionStatus() returns FALSE AND OUTPUTS A NULL OVERLAPPED* pointer, that means GetQueuedCompletionStatus() itself failed, so all of the output values are indeterminate and should be ignored, and you can use GetLastError() to get the error code for the failure.

A: GetQueuedCompletionStatus return when I/O finished.  if initial code of I/O operation was ERROR_IO_PENDING and file bind to IOCP -when I/O finished - packet will be queued to IOCP and GetQueuedCompletionStatus return (for this I/O operation).
so question better be next:
Will I/O will be completed immediately if we call CancelIoEx on file ?
this already depend from concrete diver: are it registered cancel routine (IoSetCancelRoutine) on IRP for which he return STATUS_PENDING.
are this driver immediately IofCompleteRequest when it  CancelRoutine called for IRP. any good designed driver must do both. so if you do I/O request on say some built-in windows driver - answer - yes - I/O will be completed immediately.
about error code - usually (almost always) this will be STATUS_CANCELLED - with this status driver complete canceled IRP. the GetQueuedCompletionStatus conver error NTSTATUS  to win32 errors. so STATUS_CANCELLED will be converted to ERROR_OPERATION_ABORTED.
so if in short

Will GetQueuedCompletionStatus return immediately

yes (almost always, but depend from driver, from this api - nothing depend)

is there an appropropate error-code ?

yes - almost always this will be ERROR_OPERATION_ABORTED(but again depend from driver and not depend from this api)


Q: Data-Visualization Python

*Plot 4 different line plots for the 4 companies in dataframe open_prices. Year would be on X-axis, stock price on Y axis, you will need (2,2) plot. Set figure size to 10, 8 and share X-axis for better visualization
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from nsepy import get_history
import datetime as dt
%matplotlib inline
start = dt.datetime(2015, 1, 1)
end = dt.datetime.today()
infy = get_history(symbol='INFY', start = start, end = end)
infy.index = pd.to_datetime(infy.index)
hdfc = get_history(symbol='HDFC', start = start, end = end)
hdfc.index = pd.to_datetime(hdfc.index)
reliance = get_history(symbol='RELIANCE', start = start, end = end)
reliance.index = pd.to_datetime(reliance.index)
wipro = get_history(symbol='WIPRO', start = start, end = end)
wipro.index = pd.to_datetime(wipro.index)
open_prices = pd.concat([infy['Open'], hdfc['Open'],reliance['Open'],
wipro['Open']], axis = 1)
open_prices.columns = ['Infy', 'Hdfc', 'Reliance', 'Wipro']
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
axes[0, 0].plot(open_prices.index.year,open_prices.INFY)
axes[0, 1].plot(open_prices.index.year,open_prices.HDB)
axes[1, 0].plot(open_prices.index.year,open_prices.TTM)
axes[1, 1].plot(open_prices.index.year,open_prices.WIT)

Blank graph is coming.Please help....?!??

A: Below code works fine , I have changed the following things
a) axis should be ax b) DF column names were incorrect c) for any one to try this example would also need to install lxml library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from nsepy import get_history
import datetime as dt

start = dt.datetime(2015, 1, 1)
end = dt.datetime.today()
infy = get_history(symbol='INFY', start = start, end = end)
infy.index = pd.to_datetime(infy.index)
hdfc = get_history(symbol='HDFC', start = start, end = end)
hdfc.index = pd.to_datetime(hdfc.index)
reliance = get_history(symbol='RELIANCE', start = start, end = end)
reliance.index = pd.to_datetime(reliance.index)
wipro = get_history(symbol='WIPRO', start = start, end = end)
wipro.index = pd.to_datetime(wipro.index)
open_prices = pd.concat([infy['Open'], hdfc['Open'],reliance['Open'],
wipro['Open']], axis = 1)
open_prices.columns = ['Infy', 'Hdfc', 'Reliance', 'Wipro']
print(open_prices.columns)

ax=[]
f, ax = plt.subplots(2, 2, sharey=True)
ax[0,0].plot(open_prices.index.year,open_prices.Infy)
ax[1,0].plot(open_prices.index.year,open_prices.Hdfc)
ax[0,1].plot(open_prices.index.year,open_prices.Reliance)
ax[1,1].plot(open_prices.index.year,open_prices.Wipro)
plt.show()


Q: Recommended video profile We are encoding our videos thinking about being played on Android and iOS native apps, and with bitmovin player on browsers (desktop and mobile). Which video profile should we use? Will the high profile be supported on all devices (Android 4.1+)? We are encoding on h264 and mp4 format.
Thanks a lot!

A: official documentations explains everything (for android)
You can see that H.265 main profile is supported by 5.0+ devices. Also some other profiles are supported by some devices, but their support is implemented by the manufacturers. The documentation lists the formats that are granted to be played. All other formats may be playable, or not depending on the device model and manufacturer. So if you want to support at least most part of the devices, you'll have to follow that table.


Q: I was training an Ann machine learning model using GridSearchCV and got stuck with an IndexError in gridSearchCV My model starts to train and while executing for sometime it gives an error :-
IndexError: index 37 is out of bounds for axis 0 with size 37
It executes properly for my model without using gridsearchCV with fixed parameters

Here is my code
    from keras.wrappers.scikit_learn import KerasClassifier
    from sklearn.model_selection import GridSearchCV
    from keras.models import Sequential
    from keras.layers import Dense
    def build_classifier(optimizer, nb_layers,unit):
        classifier = Sequential()
        classifier.add(Dense(units = unit, kernel_initializer = 'uniform', activation = 'relu', input_dim = 14))
        i = 1
        while i <= nb_layers:
            classifier.add(Dense(activation="relu", units=unit, kernel_initializer="uniform"))
            i += 1
        classifier.add(Dense(units = 38, kernel_initializer = 'uniform', activation = 'softmax'))
        classifier.compile(optimizer = optimizer, loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])
        return classifier
    classifier = KerasClassifier(build_fn = build_classifier)
    parameters = {'batch_size': [10,25],
                  'epochs': [100,200],
                  'optimizer': ['adam'],
                  'nb_layers': [5,6,7],
                  'unit':[48,57,76]
                 }
    grid_search = GridSearchCV(estimator = classifier,
                               param_grid = parameters,
                               scoring = 'accuracy',
                              cv=5,n_jobs=-1)
    grid_search = grid_search.fit(X_train, y_train)
    best_parameters = grid_search.best_params_
    best_accuracy = grid_search.best_score_

A: The error IndexError: index 37 is out of bounds for axis 0 with size 37 means that there is no element with index 37 in your object.
In python, if you have an object like array or list, which has elements indexed numerically, if it has n elements, indexes will go from 0 to n-1 (this is the general case, with the exception of reindexing in dataframes).
So, if you ahve 37 elements you can only retrieve elements from 0-36.

A: This is a multi-class classifier with a huge Number of Classes (38 classes). It seems like GridSearchCV isn't spliting your dataset by stratified sampling, may be because you haven't enough data and/or your dataset isn't class-balanced.
According to the documentation:

For integer/None inputs, if the estimator is a classifier and y is
  either binary or multiclass, StratifiedKFold is used. In all other
  cases, KFold is used.

By using categorical_crossentropy, KerasClassifier will convert targets (a class vector (integers)) to binary class matrix using keras.utils.to_categorical. Since there are 38 classes, each target will be converted to a binary vector of dimension 38 (index from 0 to 37).
I guess that in some splits, the validation set doesn't have samples from all the 38 classes, so targets are converted to vectors of dimension < 38, but since GridSearchCV is fitted with samples from all the 38 classes, it expects vectors of dimension = 38, which causes this error.

A: Take a look at the shape of your y_train. It need to be a some sort of one hot with shape (,37)


Q: Is there a way to specify an editor on a git command in a one-off style As mentioned above, I am looking for something like this:

$ git commit -m "my first commit" --editor="vim"

that will allow me to one-off swap editor for a single run. Examples where this might be useful is when squashing lengthy histories or writing up messages for a feature commit.

A: You can override EDITOR environment variable just for one git execution:
EDITOR=nano git commit -a


Q: Obtain Date value from HTML form and pass it in PHP I'm trying to get a date from an HTML form into PHP, to then pass it to a MYSQL database. In PHP I get the date with a POST method.
$Data = $_POST['Data']; //Data

In HTML i made up this:
<input type="date" name="Data" id="Data" required/>

When I try to send it to my database with the mysqli_query() method, I always get this error:

Incorrect date value: '' for column 'Data' at row 1

Can you please help me?
This is the query if you are interested. All the other variables work.
INSERT INTO 'table_name' ('col1', 'col2', 'col3', Data, 'col5', 'col6')

VALUES ('$var1', '$var2', '$var3', '$Data', '$var5', '$var6')";

EDIT: (Whole Form)
    <form action="insert.php">

Prenota pasti al Podere Diamante

Nome

            <input type="text" name="Nome" placeholder="Nome" required/>

Numero Telefonico

          <input type="text" name="NTelefonico" placeholder="### ### ####" required/>

Data di prenotazione

          <input type="date" name="Data" id="Data" required/>

Orario di prenotazione

          <input type="time" name="NGruppo" required min="19:00" max="21:30" step="1800"/>

Con quante persone sarai?

          <input type="number" name="NPersone" min="1" max="150" required/>

Note aggiuntive

          <textarea rows="3" name="Note"></textarea>

          <button type="submit" href="/">Invia</button>

      </form>

A: Change
<form action="insert.php">

to
<form action="insert.php" method="post">

The default HTTP method of a form is GET. You must specify POST since you are accessing it using $_POST. Then you should be able to get the value of the Data field in $Data.
If it doesn't fix the errors, try the following:
1 Check the datatype of Data column in your MySQL table, and make sure that your $Data is in correct format.
For example: If your Data column is a DATE column, $Data should be in YYYY-mm-dd format.
Other Date - Time types and format is given here:
Date and Time Types                          Description
-----------------------------------------------------------------
 DATE                         A date value in CCYY-MM-DD format
-----------------------------------------------------------------
 TIME                           A time value in hh:mm:ss format
-----------------------------------------------------------------
 DATETIME     A date and time value inCCYY-MM-DD hh:mm:ss format
-----------------------------------------------------------------
 TIMESTAMP      A timestamp value in CCYY-MM-DD hh:mm:ss format
-----------------------------------------------------------------
 YEAR                         A year value in CCYY or YY format
-----------------------------------------------------------------

Extra Read: Methods GET and POST in HTML forms - what's the difference?http://jkorpela.fi/forms/methods.html

A: In the database you need to set the date field to  type date and in the input field of the form you need to capture the correct date format.  Or alternatively use a date picker field

        Date

              <input type="date" name="date">

A: If you need the current date just you the built-in date in php
$now = date('Y-m-d');

Else check your sql date column and make sure it's Varchar then do this
<form action="insert.php"
method="post">
//in your insert try using
'".$Data."' in place of '$Data'


Q: Changing Alpha of UITableView Section on Cell Select I have an issue when using multiple table view sections. I am trying to change the alpha for a cell when the user taps it. Each section in the table view has one row.
Here is my code.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  NSIndexPath *indexPathInSection = [NSIndexPath indexPathForRow:0  inSection:indexPath.section];
  [tableView cellForRowAtIndexPath:indexPathInSection].contentView.alpha = 0.2f;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
  NSIndexPath *indexPathInSection = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
  [tableView cellForRowAtIndexPath:indexPathInSection].contentView.alpha = 1.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   MatchCell *cell = (MatchCell *)[self cellForIdentifier:tableView:@"MatchCell"];
   MatchedUser *user = (MatchedUser *)(self.matches)[indexPath.section];

  [self configureMatchCell:cell :user :tableView];

  NSIndexPath *selection = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
  if (selection.section == indexPath.section && cell.isSelected){
    cell.contentView.alpha = 0.2f;
  }else{
    cell.contentView.alpha = 1.0f;
  }
  return cell;
}

The alpha is applied to the cell that is tapped but other cells are also changed. This is because it is applied according to the row number not the section and row number. How can I specify the cell at the section and row index only?
Thanks.


Q: Jenkins - shell script - find parameter format not correct
hope one of you can help - I'm running a script in jenkins pipeline, so that I can upload source maps to rollbar, so I need to loop through the minified js files - I'm trying to do this with the FIND command but it keeps giving me an error: find parameter format not correct - script below:
stages {
    stage('Set correct environment link') {
        steps {
            script {
                buildTarget = params.targetEnv
                if(params.targetEnv.equals("prj1")){
                    linkTarget = "http://xxx.xxx.xx/xxx/"
                } else if(params.targetEnv.equals(.......)..etc.
    stage('Uploading source maps to Rollbar') {
        steps {
                sh ''' #!/bin/bash
                    # Save a short git hash, must be run from a git
                    # repository (or a child directory)
                    version=$(git rev-parse --short HEAD)

                    # Use the post_server_time access token, you can
                    # find one in your project access token settings
                    post_server_item=e1d04646bf614e039d0af3dec3fa03a7

                    echo "Uploading source maps for version $version!"

                    # We upload a source map for each resulting JavaScript
                    # file; the path depends on your build config
                    for path in $(find dist/renew -name "*.js"); do
                      # URL of the JavaScript file on the web server
                      url=${linkTarget}/$path

                      # a path to a corresponding source map file
                      source_map="@$path.map"

                      echo "Uploading source map for $url"

                      curl --silent --show-error https://api.rollbar.com/api/1/sourcemap \
                        -F access_token=$post_server_item \
                        -F version=$version \
                        -F minified_url=$url \
                        -F source_map=$source_map \
                        > /dev/null
                    done
                '''
        }
    }
    stage('Deploy') {
        steps {
            echo 'Deploying....'

From Bash CLI

A: With the help of @jeb I managed to resolve this FIND issue on jenkins by placing the absolute path for (find) in the shell script - initially it was using the windows FIND cmd, so i needed to point to cygwin find cmd
before: for path in $(find dist/renew -name "*.js"); do
and after: for path in $(/usr/bin/find dist/renew -name "*.js"); do
Thaks to all that commented


Q: How do I deal with app state in a multi-"page" application? I'm having trouble envisioning application state.
For a multi-page application, should each page only load a chunk of the app state?
For example, let's say I have an app that manages my favorite things, books, movies, and games. Each one of those domains will have their own page to manage them. Is the idea that only portions of app state are loaded based on what's needed in the current context?
My app state would look something like this, conceptually.
{
    currentUser: { id: 9, userName: 'JUtah' },
    books: {},
    movies: {},
    games: {}
}

However, if I browsed to Books Management, the app state would look like this:
{
    currentUser: { id: 9, userName: 'JUtah' },
    books: {
        1: { title: 'Kung Fu for Kittens', author: 'Dr. Meowrtin Kibble' }
    },
    movies: {},
    games: {}
}

If I browsed to Movie Management, this:
{
    currentUser: { id: 9, userName: 'JUtah' },
    books: {}
    },
    movies: {
        1: { title: 'John Wick', star: 'Keanu Reeves' }
    },
    games: {}
}

and so on.
Is this correct? I'm struggling to determine what app state holds at any given time.

A: First of all, React's local state and Redux's global state are different things.
Let's assume you don't use Redux for the moment. State management is up to you totally. But, try to construct your components as pure as possible and use the state where do you really need it. For example, think about a favorites app as you said. The decision is, do you want to show all the favorites categories in the same UI? If yes, then you need to keep all of them in one place, in the App. Then you will pass those state pieces your other components: Book, Movie, etc. Book get the book part of your state for example. They won't have any state, your App does. Here, App is the container component, others are presentational ones or dumb ones.
Is your data really big? Then you will think about other solutions like not fetching all of them (from an API endpoint or from your DB) but fetch part by part then update your state when the client wants more.
But, if you don't plan to show all of them in one place, then you can let your components have their state maybe. Once the user goes to Book component, maybe you fetch only the book data then set its state according to that. As you can see there are pros and cons, in the first method you are doing one fetch and distributing your data to your components, in the second method you are doing multiple fetches. So, think about which one suits you.
I can see you removed the Redux tag, but with Redux you will have one global state in the store. Again, in one point you are doing some fetch then update your state. Then, you will connect your components when they need any data from the state. But again, you can have container/presentational components here, too. One container connects to your store then pass the data to your components. Or, you can connect multiple components to your store. As you examine the examples, you will see best practices about those.
If you are new don't think too much :) Just follow the official documentation, read or watch some good tutorials and try to write your app. When you realize you need to extract some component do it, then think about if you need any state there or not?
So, once the question is very broad then you get an answer which is too broad, some text blocks :) You can't see so many answers like that, because here we share our specific problems. Again, don't bloat yourself with so many thoughts. As you code, you will understand it better.


Q: Uploading string value into azure storage location as a file content I want to upload a string value as file content into azure storage location but without writing any code and using azure components only. Is there any option available?

A: There are a lot of ways to do this：

*

*Write a string into .txt file and upload the file to a storage container on Azure Portal.

*Generate a long lifetime SAS token on Azure Portal:

and use blob rest API to upload it to a blob, you can do it directly in postman:

Result:

*Use Azure Logic App to do this. Let me know if you have any more questions.

Let me know if you have any more questions.


Q: Dialog dismiss animation not applying I have a DialogFragment whose only child is a StackView. The dialog is launched when a button is clicked in the parent fragment.
I tried to add animations to the fragment via getWindow().setWindowAnimations() but for some reason it was not working.
The approach that I took is to animate the Window's decorView:
public class TrailerDialogFragment extends DialogFragment {

    private static final String VIDEOS_EXTRA = "videos extra";

    private List<Video> mVideos = new ArrayList<>();

    @BindView(R.id.stack_view)
    StackView mStackView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        List<Video> videos = getArguments().getParcelableArrayList(VIDEOS_EXTRA);
        if (videos != null) {mVideos.addAll(videos);}
    }

    public static TrailerDialogFragment newInstance(List<Video> videos) {
        Bundle bundle = new Bundle();
        ArrayList<Video> arrayList = new ArrayList<>();
        arrayList.addAll(videos);
        bundle.putParcelableArrayList(VIDEOS_EXTRA, arrayList);
        TrailerDialogFragment fragment = new TrailerDialogFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.dialog_stackview, container, false);

        ButterKnife.bind(this, rootView);
        mStackView.setAdapter(new VideoAdapter(mVideos));

        return rootView;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        return dialog;
    }

    @Override
    public void onStart() {
        super.onStart();
        final View decorView = getDialog()
                .getWindow()
                .getDecorView();

        ObjectAnimator scaleDown = ObjectAnimator.ofPropertyValuesHolder(decorView,
                PropertyValuesHolder.ofFloat("scaleX", 0.0f, 1.0f),
                PropertyValuesHolder.ofFloat("scaleY", 0.0f, 1.0f),
                PropertyValuesHolder.ofFloat("alpha", 0.0f, 1.0f));
        scaleDown.setDuration(500);
        scaleDown.start();
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        final View decorView = getDialog()
                .getWindow()
                .getDecorView();

        ObjectAnimator scaleDown = ObjectAnimator.ofPropertyValuesHolder(decorView,
                PropertyValuesHolder.ofFloat("scaleX", 1.0f, 0.0f),
                PropertyValuesHolder.ofFloat("scaleY", 1.0f, 0.0f),
                PropertyValuesHolder.ofFloat("alpha", 1.0f, 0.0f));
        scaleDown.setDuration(500);
        scaleDown.start();
        super.onCancel(dialog);
    }

    private static class VideoAdapter extends BaseAdapter {

        List<Video> mVideos = new ArrayList<>();

        public VideoAdapter(List<Video> videos) {
            mVideos.addAll(videos);
        }

        @Override
        public int getCount() {
            return mVideos.size();
        }

        @Override
        public Object getItem(int i) {
            return mVideos.get(i);
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View resultView;
            if (view == null) {
                resultView = LayoutInflater.from(viewGroup.getContext()).inflate(
                        R.layout.dummy_view, viewGroup, false);
            } else  {
                resultView = view;
            }
            TextView tv = (TextView) resultView.findViewById(R.id.trailer_title);
            ImageView image = (ImageView) resultView.findViewById(R.id.trailer_image);

            tv.setText(mVideos.get(i).name());
            ViewUtil.loadThumbnail(mVideos.get(i).key(), resultView.getContext(), image);
            return resultView;
        }
    }
}

When I click outside of dialog fragment, the onCancel callback is triggered, but for some reason the animation doesn't play. The DialogFragment simply dissappears.
Do you know why this could happen?


Q: Wordpress xmlrpc SSL Certificate Error (Only On 1 Machine) I'm using the Wordpress xmlrpc Python module on Python 3.6 to automatically write and publish blog posts to my Wordpress site (hosted directly by Wordpress).
The program runs great on one of my Windows machines, but when I try to run it using my second Windows machine, with the exact same code, on the same network, I receive an SSL error. Details below:
import ssl

import wordpress_xmlrpc
from wordpress_xmlrpc import Client
from wordpress_xmlrpc import WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts
from wordpress_xmlrpc.methods.posts import NewPost
from wordpress_xmlrpc.methods.users import GetUserInfo
from wordpress_xmlrpc.methods import posts
from wordpress_xmlrpc.compat import xmlrpc_client

wp = Client("https://website.io/xmlrpc.php", "wordpressusername", "wordpresspassword")

post = WordPressPost()
post.title = "title"
post.content = content

post.post_status = 'publish'
status_draft = 0
status_published = 1
wp.call(NewPost(post))

Here's the error:
File "C:\Python36\Lib\http\client.py", line 964, in send
    self.connect()
  File "C:\Python36\Lib\http\client.py", line 1400, in connect
    server_hostname=server_hostname)
  File "C:\Python36\Lib\ssl.py", line 401, in wrap_socket
    _context=self, _session=session)
  File "C:\Python36\Lib\ssl.py", line 808, in __init__
    self.do_handshake()
  File "C:\Python36\Lib\ssl.py", line 1061, in do_handshake
    self._sslobj.do_handshake()
  File "C:\Python36\Lib\ssl.py", line 683, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748)

I've used pip list to view all installed modules on both machines and everything matches exactly. The code is stored on a synced Google Drive folder, so it's literally the exact same .py file both times. I can't understand why it works on one machine but not the other.
I've read the thread here but I don't believe it applies to the wordpress xmlrpc tool. I've read through the documentation here but I can't see anything helpful.
Is this something I have to tweak/delete/refresh the ssl certificates in Chrome or something? Any answers or insight much appreciated. Thanks in advance

A: So, 3 weeks later, I finally found a way to fix this.
I ended up completely uninstalling/deleting Python on my secondary machine and reinstalling everything (along with reinstalling all modules, and confirming via pip list) and now it works (no more SSL error).
For what it's worth, and I can't be sure this is what was causing the issue in the first place, but previously, I was running Python 3.6.1 on the working machine and python 3.6.2 on the other, non-working machine.
When I reinstalled everything, I reinstalled Python 3.6.1 (to match the working machine) and it worked on both.


Q: When to split users into several Devise models? I have an Rails app with two types of users: customers and suppliers. Each type has access to completely different controllers.
I'm in doubt know if I create one Devise model or two.
Are there any conventions when to use more than one controller in Devise?
I know that this is a general question and very subjective. Nevertheless I would like to know if there is any official guidelines for this? This question has been keeping me thinking for a long time already.
If there eis any forum on SE that is more appropriated for this question, please let me know.

A: I'm guessing that your customers and suppliers have some things in common (username and password, logging in to your site, etc), but they are just able to access different controllers/views/features etc. If you were to create two Devise models, it seems like you'd be creating a bunch of repetition.
This seems like a great fit for role-based authorization. There's a nice description of role-based authorization in the cancan docs: even if you're not using cancan, their docs give some nice examples that could be a starting point for a larger conversation.


Q: R DT datatable - conditional colour format for continuous value I would like to apply conditional formatting using the datatable function in R. Consider the following scenario:
test <- data.frame(
  var1 = sapply(1:L, function(x)
    paste("<X>",paste0(x,
                       letters,
                       LETTERS,
                       "\n",
                       collapse=" "))),
  var2 = round(rnorm(L),2)
)

test$var2 <- ifelse(test$var2 > 1, 1, test$var2)
test$var2 <- ifelse(test$var2 < -1, -1, test$var2)
test$tmp  <- test$var2*255
test$R    <- test$G <- 0
test$R    <- ifelse(test$tmp < 0, round(abs(test$tmp)), test$R)
test$G    <- ifelse(test$tmp > 0, round(test$tmp), test$G)
test$col  <- paste0("rgb(",test$R,",",test$G,",0)")

test <- test[,c("var1","var2","col")]

datatable(test)

I would like to font colour of var1 to take values from the col variables (which I don't actually need in the final data table).
Is this possible to achieve?
Many thanks in advance.

A: Take a look to the DT doc
2.9 Escaping table content
You will see that you can put HTML content to your table and by using escape=Fmake it readable in HTML.
and you can do something like this on the varibles of your dataframe.
apply(yourMatrix,2,function(x) ifelse(x>value,
paste0('',x,''),
paste0('',x,'')
)

For example if you have a vector x <- c(1,2,3,4) and want value higher than 0 be red you will have
[1] "1"
[2] "2"
[3] "3"
[4] "4"

and then
datatable(yourMatrix, escape = FALSE)


Q: HTML5 input type range is not setting to initial value of model AngularJS I am using HTML5 input type of range for slider functionality and binding it to my model.
By default my model will have a value in it, but slider is taking only min and max not value. When I go back from that screen and coming back, slider goes to left end but value remains what I gave last time only.

$scope.maxAmt = $rootScope.maxAmt;
$scope.minAmt = $rootScope.minAmt;
$scope.loanAmt = 5000;
<input type="range" min="{{minAmt}}" max="{{maxAmt}}"
                     value="{{loanAmt}}" step="500"
                     ng-model="loanAmt"
                     >
<output name="loanAmt">{{loanAmt}}</output>


Q: Get single value count across the whole dataset I'm new at pandas and surveying the internet for my learning I've used count(), value_counts() to count values column wise but now I'm stuck in a problem. I've a car crash reporting dataset that has it's empty value replaced with "Not Reported" so I wanted to count the number of cells that have this value across the whole data set and show it column wise.Is there any way for me to achieve such out come?
The dataset has values like this
| Location     | Severity     | Time         | Outcome      | Substance Used | Traffic Signal |
| --------     | --------     | ----------   | -----------  | -------------- | -------------- |
| New York     | Level 1      | Not Reported | Casualty     | Alcohol        | Red            |
| Texas        | Not Reported |  7:00:00     | Minor Injury | Not Reported   | Green          |
| Not Reported | Level 4      | Not Reported | Not Reported | Smoking        | Yellow         |

The output required is this.
| Column         | Value        | Count |
| -------------- | ------------ | ----- |
| Location       | Not Reported | 1     |
| Severity       | Not Reported | 1     |
| Time           | Not Reported | 2     |
| Outcome        | Not Reported | 1     |
| Substance Used | Not Reported | 1     |
| Traffic Signal | Not Reported | 0     |

A: You can use:
(df.where(df.eq('Not Reported')).stack(dropna=False)
   .groupby(level=1).agg(Value='first', Count='count')
   .reset_index()
)

Output:
            index         Value  Count
0        Location  Not Reported      1
1         Outcome  Not Reported      1
2        Severity  Not Reported      1
3  Substance Used  Not Reported      1
4            Time  Not Reported      2
5  Traffic Signal          None      0

A: You can count Not Reported by compare all values by Not Reported with sum, no groupby necessary:
s = df.eq('Not Reported').sum()
print (s)
Location          1
Severity          1
Time              2
Outcome           1
Substance Used    1
Traffic Signal    0
dtype: int64

Your expected ouput is possible get in DataFrame constructor:
df1 = pd.DataFrame({'Column': s.index, 'Value':'Not Reported', 'Count': s.to_numpy()})
print (df1)
           Column         Value  Count
0        Location  Not Reported      1
1        Severity  Not Reported      1
2            Time  Not Reported      2
3         Outcome  Not Reported      1
4  Substance Used  Not Reported      1
5  Traffic Signal  Not Reported      0


Q: Resolving component from class name in Angular 4 Is it possible to resolve a component from string?
Previously in Angular 2, we are able to do this see here. However, in Angular 4, the same method will throw error.
private resolver: ComponentFactoryResolver

var factories = Array.from(this.resolver['_factories'].keys());
var factoryClass = <Type<any>>factories.find((x: any) => x.name === this.comp);
const factory = this.resolver.resolveComponentFactory(factoryClass);
const compRef = this.vcRef.createComponent(factory);

A: It looks like you might be relying on an implementation detail. However, to get around the error, you can explicitly cast the type to any in order to access the indexer.  Assuming there is a _factories property, this should work:
var factories = Array.from((<any>this.resolver)['_factories'].keys());


Q: Finding the prime numbers used in RSA I got this question in a local hacking event, but I couldn't solve it.
Problem Statement ----
Continuing their snooping habit, NSA kept bugging Alice's communication. Resorting to the age old RSA encryption, Alice used 128-bit RSA encryption to exchange messages. Alice shares her public key as

$0xffffffa95256a837568a41c265f4fe27110814aae19f144762d5cc0bcb931807$

and her public key exponent $\phi(n)$ as $0x11$ with Warden.
However, NSA, with its enormous resource, cracked this 128 bit encryption super easily. Seeing your work on the previous ciphers, NSA decided to offer you a job in their Cryptography group. As a final test, NSA shared this public key which they intercepted from Alice and Warden's conversation. They also gave away the private key that they computed from their message exchange.

$Public$ $Key -
  (0xffffffa95256a837568a41c265f4fe27110814aae19f144762d5cc0bcb931807,
  0x11)$
$Private$ $Key -
  (0xffffffa95256a837568a41c265f4fe27110814aae19f144762d5cc0bcb931807,$
                        $0xc3c3c3817b3335577e69b9d0e48e2bc1fdf71f1f4f73a38a7d628d39739bbaf1)$

What are the values of $p$ and $q$? (the prime numbers used in key generation)


Q: Volta with yarn run build system cannot find the path specified This is the first time I'm using Volta, so bear with me.
I have installed globally typescript, node and yarn
yarn -v >> 1.22.10
node -v >> v14.15.4
npm -v >> 6.14.10

These commands work inside and outside my project folder, with the same results.
However if I use yarn build from inside vscode the output is an error stating:
System cannot find the path specified

If I do the same from outside vscode I get the same result:

If I go to the node_modules/.bin folder inside vscode, the command still doesn't work (this time I just only run tsc). The error is the following:
The term tsc is not a cmdlet recognized command, function, script file or executable program. Verify if the name is written correctly or, if there is an access route, verify the route is correct and try again.

But if the command is executed from outside vscode in a cmd window, it works as expected, because tsc is really there:

Additionally, if I run npm run build inside vscode, the command works as expected. This is my package.json:
{
  "name": "socket-server",
  "version": "1.0.0",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "license": "MIT",
  "scripts": {
    "build": "tsc",
    "dev": "yarn build --watch --preserveWatchOutput",
    "lint": "eslint src --ext js,ts",
    "test": "jest"
  },
  "devDependencies": {
    "eslint": "^7.19.0",
    "jest": "^26.6.3",
    "typescript": "^4.1.3"
  },
  "volta": {
    "node": "14.15.4",
    "yarn": "1.22.10"
  }
}

I do suspect of volta because volta is managing yarn version, but no npm; but I don't really know what's the issue.
I'm using Windows and my PATH has the following entries:

What am I doing wrong?
Edit: Yes, Shell command shortcut exists:

A: the problem is about vsCode, you should run code . in cmd because if you Open the Command Palette (Ctrl + Shift + P) and type
Shell Command: Install 'code' command in PATH

you won't see noting, after running code . in cmd when you should see like this photo, every things will be fine

A: I’m not sure for Windows, but usually the scripts in node_modules/.bin are symbolic links to scripts. For instance, node_modules/.bin/tsc might point to node_modules/typescript/bin/tsc.
It works outside of the directory because then it uses the global version of tsc.
Seeing your error, I’m suspecting that the symlinks are broken. Maybe just try to remove node_modules directory and redo an npm install.
PS: I’m not familiar with Volta, but it looks more like an NPM problem.


Q: giving a default value for an angular number formcontrol I am working with angular. I am astonished that we cannot give an empty default value for an angular number formcontrol. At the beginning, I set it to 0, but it isn't my requirement, since my input display 0 before entering anything. It must be a solution

A: You can create a FormControl in a reactive form using an empty value, empty string, or even undefined:
Component:
foo = new FormControl();

Template:
<input type="number" [formControl]="foo" />

Here is an example in action that demonstrates the number input being initialized without any value.
Hopefully that helps!


Q: why does tar command in bash script with file list within quotes not work In the code below:
#!/bin/bash

echo AAAAAA > a.txt
echo BBBBBB > b.txt
echo CCCCCC > c.txt

files="a.txt b.txt c.txt"

tar -cvf archive1.tar $files  # this line works

tar -cvf archive2.tar "$files"  # this line doesn't work - why???

the first tar command works fine, but the 2nd tar line, with "$files" does not.  Why is this?


Q: PHP and OpenSSL stopped working after service change Recently I asked my hosting company to setup a new package and since then my existing package is now giving me errors with anything to do with using openSSL.
For instance, I have a function to generate a GUID:
function generateGUIDV4($data)
{
    assert(strlen($data) == 16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

$newID = generateGUIDV4(openssl_random_pseudo_bytes(16));

This now throws an error: Fatal error: Call to undefined function openssl_random_pseudo_bytes(). From what I've researched this has to do with Fatal error: Call to undefined function openssl_random_pseudo_bytes().
Now I'm also getting an error now when I call any web services from my application which again point to the openSSL.
Error:
Objectfaultcode: "WSDL"faultstring: "SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://*******'"__proto__: Object

.I've hidden the web service as it's not public. From what I've researched this points to OpenSSL again: SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>.
PHP Ini is showing openSSL IS installed
OpenSSL support enabled
OpenSSL Version OpenSSL 0.9.8b 04 May 2006

Anyone have any ideas or point me in the right direction? I've got the hosting company looking into this.

A: I've fixed this and it had nothing to do with the hosting company.
I published a new version of the site, but in the publish profile I told it to delete all files which deleted the .htaccess file which contained the version of PHP in.
Unfortunately, I needed version 5.4 or above to run my code but since the file was removed it dropped down to 5.2 of PHP.
So I've uploaded a new .htaccess file with the correct version in and everything is working.
Hopefully this may help someone if they're as daft as I am.


Q: Loop in property in constructor If you have a look at my code below. Is there ANY way to write some kind of loop instead of having repeat Row and ColumnDefinitions?
var grid = new Grid
            {
                RowSpacing = 12,
                ColumnSpacing = 12,
                VerticalOptions = LayoutOptions.FillAndExpand,
                RowDefinitions =
            {
                new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
                new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
                new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
            },
                ColumnDefinitions =
            {
                new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
            }
            };

A: You can use loops to create an array of rows and an array of columns beforehand and assign these to the RowDefinitions and ColumnDefinitions properties.
I should have thought you'd need to call RowDefinitions.Add() and ColumnDefinitions.Add() in a loop to do so, though.

A: No, this is not possible because the only way this would work is if you could assign a completely new value to the RowDefinitions property, which you can't:
public RowDefinitionCollection RowDefinitions { get; }
                                                ^^^^

The syntax as shown in your question is just a handy way of calling .Add on the object in that property, so there is no way for you to inline in that syntax do this. Your code is just "short" for this:
var temp = new Grid();
temp.RowSpacing = 12;
temp.ColumnSpacing = 12;
temp.VerticalOptions = LayoutOptions.FillAndExpand;
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
... same for columns

Specifically, your code is not doing this:
temp.RowDefinitions = ...
                    ^

You would probably want code like this:
var grid = new Grid()
{
    RowSpacing = 12,
    ColumnSpacing = 12,
    VerticalOptions = LayoutOptions.FillAndExpand,
    RowDefinitions = Enumerable.Range(0, 100).Select(_ =>
        new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }),
    ColumnDefinitions = Enumerable.Range(.....

But you cannot do this as this would require that RowDefinitions and ColumnDefinitions was writable.
The closest thing is like this:
var temp = new Grid
{
    RowSpacing = 12,
    ColumnSpacing = 12,
    VerticalOptions = LayoutOptions.FillAndExpand,
};

for (int index = 0; index < rowCount; index++)
    temp.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
... same for columns
var grid = temp;

A: RowDefinitions is RowDefinitionCollection. RowDefinitionCollection is internal which you cannot create outside Grid.


Q: Difference between Tomcat's extraResourcePaths and aliases to access an external directory Simple question: In Tomcat7, what's the difference between using extraResourcePaths and aliases to access an directory outside the application?
I can use either of these two server.xml snippets and they both seem to work.  Both seem to load this URL successfully: http://localhost/app/images/box.jpg.  Is there an advantage to using one over the other?
<Context docBase="Eclipse_Project" path="/app"
        reloadable="true" source="org.eclipse.jst.j2ee.server:Eclipse_Project"
        aliases="/images=D:\path\to\images"/>

or
<Context docBase="Eclipse_Project" path="/app"
        reloadable="true" source="org.eclipse.jst.j2ee.server:Eclipse_Project">
        <Resources className="org.apache.naming.resources.VirtualDirContext"
                extraResourcePaths="/images=D:\path\to\images"/>
</Context>

A: This is the result of having multiple different ways of pulling in resources that aren't part of a WAR or exploded directory. Frankly it is a mess long overdue a clean-up. The 'overlay' (or whatever it ends up being called) feature proposed for Servlet 3.1  (i.e. Tomcat 8) has prompted a major clean-up. All the current implementations will be unified into a single implementation. It isn't pretty though, and it is going to take a while to complete.
Aliases are treated as external to the web application resources. The DirContext checks aliases before it checks its internal resources. Hence when you request the real path you get the original.
If you use extraResourcePaths they are treated as part of the web application resources. It looks like Eclipse has triggered a copy of application resources to the work directory. This is usually done to avoid file locking. Since the extraResourcePaths are treated as part of the webapp, they get copied too and getRealPath() reports the copied location since that is where Tomcat is serving the resources from.

A: After investigating further, I found this difference.
The results of this Java code is different.  I still don't know why.
String path = getServletContext().getRealPath("/images");

Using extraResourcePaths, path is below, which is a folder under where Eclipse explodes my web app and not a valid directory.
C:\Projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\Eclipse_Project\images

Using aliases, path is below and is what I actually need.
D:\path\to\images

Now if someone could actually explain this.  :-)


Q: Invalid results from SQL Server "NOT IN" clause I have run a query on our SQL Server 2012 which returned no results. I discovered that this was incorrect and I SHOULD have gotten 16 records. I changed the query and get the answer expected but I am at a loss to understand why my original query did not work as expected.
So my ORIGINAL query which returned no results was:
SELECT
    WPB.[ID number]
FROM
    [Fact].[REPORT].[WPB_LIST_OF_IDS] WPB
WHERE
    [ID number] NOT IN (SELECT DISTINCT IdNumber
                        FROM MasterData.Dimension.Customer DC)

The reworked query is this:
SELECT
    WPB.[ID number]
FROM
    [Fact].[REPORT].[WPB_LIST_OF_IDS] WPB
LEFT JOIN
    MasterData.Dimension.Customer DC ON WPB.[ID number] = DC.IdNumber
WHERE
    DC.IdNumber IS NULL

Can anyone tell me WHY the first query (which incidentally runs in fractions of a second vs the 2nd which takes a minute) does not work? I don't want to repeat this mistake in the future!

A: Don't use not in with a subquery.  It doesn't work the way you expect with NULL values.  If any value returned by the subquery is NULL, then no rows are returned at all.
Instead, use not exists.  This has the semantics that you expect:
select wpb.[ID number]
from [Fact].[REPORT].[WPB_LIST_OF_IDS] wpb
where not exists (select 1
                  from MasterData.Dimension.Customer dc
                  where wpb.[ID number] = dc.IdNumber
                 );

Of course, the left join method also works.


Q: Return two different sections in my UITableView I'm trying to return two seperate .counts in my UITableView. I kind of know the logic behind it but not using the syntax right. How can I do this? What I want it to do is fill my tableview up with the both .counts. I would also like to put in a label on top of the first section and second section. Anything would help!
Here is what I have so far but I'm only getting the first section of cells. Why isnt it displaying both .counts?
func tableView(tableView: UITableView, numberOfSectionsInTableView: Int) -> Int{
        return 2;
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if (section == 0){
           return featSubNames.count
        }
        else{
            return subCatNames.count
        }

    }
    func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
        if (section == 0){
            ????
        }
        if (section == 1){
            ????
        }
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell

        // Configure the cell
        switch (indexPath.section) {

        case 0:
            cell.textLabel?.text = featSubName[indexPath.row]
            cell.textLabel?.textColor = UIColor.whiteColor()
        case 1:
            cell.textLabel?.text = subCatNames[indexPath.row]
            cell.textLabel?.textColor = UIColor.whiteColor()
        default:
            cell.textLabel?.text = "Other"

        }

        return cell
    }

A: Your code seems to be right. To get the UIViews on the header of each section, you can return any object that inherits from a UIView(this doesn't mean that would be nice to). So, you can return a small container with a UIImageView and a UILabel, if you want this for example.
Your code for the viewHeader would be something like this:
func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
    // instantiate the view to be returned and placed correctly
    let commonLabel = UILabel(frame: CGRectMake(0, 0, tableWidth, 30))
    commonLabel.textColor = .blackColor()
    commonLabel.textAlignment = .Center
    // ... other settings in the properties

    if section == 0 {
        commonLabel.text = "section1"
        // other settings for the first section
    }
    if section == 1 {
        commonLabel.text = "section2"
        // other settings ...
    }
    return commonLabel
}

Notes:
Be sure to set the container view's frame,for sectionHeaders the top view in the hierarchy don't accept auto layout.
Implementing the viewForHeaderInSection method is more accessible to custom UI's, you can use the TitleForHeaderInSection if you wish, but it's limited for more complex stuffs.
EDIT:
If you're using storyboards, you still can use this code, although it's not so elegant in terms of apps that use IB for the UI. For this, you might take a look at this link: How to Implement Custom Table View Section Headers and Footers with Storyboard
. This implements only the view using storyboards, but the delegate part must to be wrote.


Q: Spring MVC - lookup validators automatically Suppose I have a sample entity class like this:
public class Address {
    ...
}

and a corresponding validator:
@Component
public AddressValidator implements Validator {

    @Override
    public boolean supports(Class<?> entityClass) {
        return entityClass.equals(Address.class);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        ...
    }
}

When I use a controller like the following, everything works:
@RestController
@RequestMapping("/addresses")
public class AddressController {

    @Autowired
    private AddressValidator validator;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(validator);
    }

    @RequestMapping(method=POST)
    public Long addNewAddress(@Valid @RequestBody Address address) {
        ...
    }
}

However, if I omit the validator registering part (i.e. the following), validation is not performed.
@Autowired
private AddressValidator validator;

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
}

Having to register validators manually seems pointless. Can I instruct Spring to look up validators automatically (similar to how controllers are looked up)?
It's a Spring Boot based application.

A: You can use my example from gist or below. The idea is to have a main CompositeValidator that will be a holder of all your Validator or SmartValidator instances.
It supports hints and can be also integrate with Hibernate Annotation Validator (LocalValidatorFactoryBean). And also it's possible to have more that one validator per specific Model.

CompositeValidator.java
@Component
public class CompositeValidator implements SmartValidator {
    @Autowired
    private List<Validator> validators = Collections.emptyList();

    @PostConstruct
    public void init() {
        Collections.sort(validators, AnnotationAwareOrderComparator.INSTANCE);
    }

    @Override
    public boolean supports(Class<?> clazz) {
         for (Validator validator : validators) {
            if (validator.supports(clazz)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void validate(Object target, Errors errors) {
        validate(target, errors, javax.validation.groups.Default.class);
    }

    @Override
    public void validate(Object target, Errors errors, Object... validationHints) {
        Class<?> clazz = target.getClass();

        for (Validator validator : validators) {
            if (validator.supports(clazz)) {
                if (validator instanceof SmartValidator) {
                    ((SmartValidator) validator).validate(target, errors, validationHints);
                } else {
                    validator.validate(target, errors);
                }
            }
        }
    }
}

SomeController.java
@Controller
@RequestMapping("/my/resources")
public class SomeController {

    @RequestMapping(method = RequestMethod.POST)
    public Object save(
            @Validated(javax.validation.groups.Default.class) // this interface descriptor (class) is used by default
            @RequestBody MyResource myResource
    ) { return null; }
}

Java Config
 @Configuration
    public class WebConfig {
        /** used for Annotation based validation, it can be created by spring automaticaly and you don't do it manualy */
        // @Bean
        // public Validator jsr303Validator() {
        //   LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        //   // validator.setValidationMessageSource(...);
        //   return validator;
        // }

        @Bean
        public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
            return new WebMvcConfigurerAdapter() {
                @Autowired
                private CompositeValidator validator;

                @Override
                public Validator getValidator() {
                    return validator;
                }
            }
        }

Or XML Config
<!-- used for Annotation based validation, it can be created by spring automaticaly and you don't do it manualy -->
<!--<bean id="jsr303Validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">-->
<!--  <property name="validationMessageSource" ref="messageSource"/>-->
<!--</bean>-->

<mvc:annotation-driven validator="compositeValidator">
  //...
</mvc:annotation-driven>

A: You can configure global Validator.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#validation-mvc
If you are using Java based spring configuration with WebMvcConfigurationSupport, you can override getValidator()
/**
 * Override this method to provide a custom {@link Validator}.
 */
protected Validator getValidator() {
    return null;
}

You may call setValidator(Validator) on the global WebBindingInitializer. This allows you to configure a Validator instance across all @Controller classes. This can be achieved easily by using the Spring MVC namespace:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven validator="globalValidator"/>

</beans>

A: I have not found a build in Spring solution for this, but here is what I do.
I declare my validator beans in the spring java configuration like so:
@Bean
public Validator studentValidator(){
    return new StudentValidator();
}

@Bean
public Validator carValidator(){
    return new CarValidator();
}

Then I have all controllers extends a base controller like so:
public abstract class BaseController <T> {
     public BaseController(List<Validator> validators) {
        super();
        this.validators = validators;
      }
  //Register all validators
  @InitBinder
  protected void initBinder(WebDataBinder binder) {
    validators.stream().forEach(v->binder.addValidators(v));
  }

}

The concrete class of this controller gets the List injected via dependency injection, like so:
@Controller
public class StudentController extends BaseController<Student>{

    @Inject
      public StudentController(List<Validator> validators) {
        super(validators);
      }

}

The base Controller uses the @InitBinder call-back method to register all Validators.
I am surprised that spring doesn't automatically register all objects in class path that implement the Validator interface.


Q: Runtime error while working with 2D arrays in a loop C I wrote this piece of code to find the GCD of any two numbers, and as I am working with multiple test cases,  I used a 2D array with each testcase as a row and the first two elements in each row to store the numbers. FOr example, a[0][0] stores the first number of the first test case.
It works well up to user input, but the part which calculates the gcd, I'm getting a runtime error. I checked to see if I was trying to access an undefined location in the array, but with no luck.
const int testCase;
scanf("%d", &testCase);
int a[testCase][3], i, j, k;

for(k = 0; k < testCase; k++){
    scanf("%d %d", &a[k][0], &a[k][1]);
}

// problem occurs after this

for(j = 0; j < testCase; j++){

    for(i = 0; i <= a[j][0] && i <= a[j][1]; i++){
        if(a[j][0] % i == 0 && a[j][1] % i == 0){
            a[j][2] = i;
        }
    }
    printf("%d\n", a[j][2]);


Q: PHP inheritance - methods and properties I'm obviously not understanding inheritance correctly. I'll let my code do the talking:
abstract class Calc {
private $x;
private $y;
public function AddNumbers() {
    echo $this->x. " + " .$this->y;
}
}

class myCalc extends Calc {
public function __construct ($x,$y) {
    $this->x = $x;
    $this->y = $y;
   }
}

$calc1 = new myCalc(3,4);
$calc1->AddNumbers();
echo 'done';
exit;

OK, so what's going on here: I'd like to have an abstract class, that would define two properties (x and y) and an abstract method, (nevermind the concatenation of numbers, implementation of the method is out of the scope of my question) which would access there properties.
Then, a concrete class extends that abstract one. As you can see, I can successfully access the properties and set them, but when I call add numbers, it appears as if the properties are not set.
What is going on, why is this not working and how can I fix it?
I could just define a method for adding numbers in concrete class, but I want to have a method in abstract class with a definition that can be reused.
Thanks!

A: The two properties in the abstract class are private, which means they are NOT present and known in any class that extends this one.
So MyCalc does not write to these properties, and you cannot read them in the AddNumbers function. The MyCalc constructor actually creates new, public properties instead.
Make the properties "protected", and it will work.

A: The private keyword defines that only the methods in Calc can modify those variables. If you want methods in Calc and methods in any of its subclasses to access those variables, use the protected keyword instead.
You can access $this->x because PHP will let you create a member variable on the object without declaring it. When you do this the resulting member variable is implicitly declared public but it doesn't relate to the private variable defined in Calc, which is not in scope in myCalc.


Q: How to show jquery confirmation dialogue with multiple forms and submit buttons mvc I have a mvc project and on one page there is a table of data with a submit button that is inside its own form tag.  I want to have a pop up modal dialogue when the user clicks the delete button to ask for confirmation of the delete.  How would you do this with jquery?

A: you can use the ajax.actionlink
@Ajax.ActionLink("Delete", "DeleteUser", new { id = user.user_id }, new AjaxOptions { Confirm = "Are You sure to delete?", UpdateTargetId = "article_1" })


Q: Kohana 3 ORM query using NOTIN() Is there a way to use a http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_not-in with Kohana's ORM? Something like:
$products = ORM::factory('products')->notin('contry_id', $csl)->find_all();

A: Use where statement:
$products = ORM::factory('products')->where('contry_id', 'NOT IN', $csl)->find_all();

$csl must be array


Q: How to focus on form input after appending it to dom? The snippet below adds a form to the page on click:
$(document).ready(function () {
  $(".reply").click(function () {
    var form = '<form id="rform" action="/sendme" method="POST"><input class="title" name="title" type="text" /><textarea rows="8" name="body"></textarea><input type="submit" value="Submit"></form>';
    $(".placeholder").append(form);
  });
});

to the html:
 Reply

The Reply link can appear anywhere on the page. The problem is that after appending the form, the browser jumps to the top of the page.
I'm wondering how to scroll/focus to the title input field after appending the form.
I've tried adding focus() or scroll() after .append(form) but none worked. I've also searched SO, but could not find useful answers to similar question.

A:

$(document).ready(function() {
  $(".reply").click(function(event) {
    event.preventDefault();
    $('.placeholder').html('');
    var form = '<form id="rform" action="/sendme" method="POST"><input class="title" name="title" type="text" /><textarea rows="8" name="body"></textarea><input type="submit" value="Submit"></form>';
    $(".placeholder").append(form);
    $("input.title").focus();
  });
});
input,
textarea {
  display: block;
  width: 100%;
  margin-top: 10px;
  box-sizing: border-box;
}

form {
  max-width: 400px;
}

Reply

First , if you donot want it to scroll to top.  Use the  event.preventDefault();
Second , use $('.placeholder').html(''); if you donot want repeated comment form on click.
third , $("input.title").focus(); works just fine. Already tested

A: Use this code it works
  $("[data-scroll-to]").click(function() {
   var form = '<form id="rform" action="/sendme" method="POST"><input class="title" id="id2" name="title" type="text" /><textarea rows="8" name="body"></textarea><input type="submit" value="Submit"></form>';
      $("#id1").append(form);

  var $this = $(this),
      $toElement      = $this.attr('data-scroll-to'),
      $focusElement   = $this.attr('data-scroll-focus'),
      $offset         = $this.attr('data-scroll-offset') * 1 || 0,
      $speed          = $this.attr('data-scroll-speed') * 1 || 500;

  $('html, body').animate({
    scrollTop: $($toElement).offset().top + $offset
  }, $speed);
  if ($focusElement) $($focusElement).focus();

});

https://codepen.io/Thaks123/pen/byWmGo?editors=1111
It works with scroll also.

A: The page is jumping to the top because you are navigating to an anchor. Remove href="#" from the reply link. You could replace it with href="javascript:void(0);"
You should then be able to use .focus() to position the page where you like.


Q: Cast different objects and call a method in same line? I have the code:
        foreach(var o in objects)
        {
            o.Update(time);

            if(o is Portal)
            {
                var a = (Portal)o;
                a.Interact(ref player, player.Interact);
            }
            else if(o is Enemy)
            {
                var e = (Enemy)o;
                e.Update(time, player);
            }
        }

I don't know if anything like this is possible?
I want to do it in one line.
This is what I have in mind:
(Enemy)o => Update(time, player);

I know it's stupid but I want something similar. The method that has player as a parameter is unique to the Enemy object. I have to parse to call it.

A: You can make your loop simpler (in case you use C# 6 or higher):
foreach(var o in objects)
{
    o.Update(time);

    (o as Portal)?.Interact(ref player, player.Interact);
    (o as Enemy)?.Update(time, player);
}

For C# 5 or lower you should use:
foreach(var o in objects)
{
    o.Update(time);

    if (o is Portal)
    {
        ((Portal)o).Interact(ref player, player.Interact);
    }
    else if(o is Enemy)
    {
        ((Enemy)o).Update(time, player);
    }
}

In this case you have less lines of code but you cast two times.
You can cast only one time:
foreach(var o in objects)
{
    o.Update(time);

    var e = o is Portal;
    if (e != null)
    {
        e.Interact(ref player, player.Interact);
    }
    else
    {
        ((Enemy)o).Update(time, player);
    }
}

A: Try this:
((Enemy)o).Update(time, player);

Remember about possible Null Reference Exception if you didn't check a type of this object. In your code everything is fine.

A: You can replace those two lines with a single line as follows:
else if(o is Enemy)
{
    ((Enemy)o).Update(time, player);
}

A: You call the function in that way:
var a = ((Portal)o).Interact(ref player, player.Interact);

so the type of a will be the returned type of Interact, but in context of your code it won't matter much.

A: To go further than other response, you could use the visitor pattern.
First create a IVisitorClient and a IVisitor interface.
interface IVisitorClient
{
    Accept(IVisitor visitor);
}

interface IVisitor
{
    Visit(SceneObject o); // here the types of your objects
    Visit(Enemy e);
    Visit(Portal p);
}

Make your different object implement IVisitorClient.
abstract class SceneObject : IVisitorClient
{
    public virtual void Accept(IVisitor visitor)
    {
         visitor.Visit(this);
    }
}

class Portal : SceneObject
{
...

    public override void Accept(IVisitor visitor)
    {
         visitor.Visit(this);
    }
...
}

class Enemy: SceneObject
{
...

    public override void Accept(IVisitor visitor)
    {
         visitor.Visit(this);
    }
...
}

Then build an updater that implement IVisitor :
class UpdaterVisitor : IVisitor
{
    readonly Player player;
    readonly Time time;

    public UpdaterVisitor(Player player, Time time)
    {
        this.player = player;
        this.time = time;
    }

    public void Visit(SceneObject o)
    {
        e.Update(time);
    }

    public void Visit(Enemy e)
    {
        e.Update(time, player);
    }

    public void Visit(Portal p)
    {
        p.Interact(ref player, player.Interact);
    }
}

Finally, to update the object, the code will look like this.
var updateVisitor = new UpdaterVisitor(player, time);
foreach(var o in objects)
{
    o.Accept(updateVisitor);
}

A: Or do it this way to avoid the double cast...
foreach(var o in objects)
{
    o.Update(time);

    Portal p = o as Portal;

    if(p != null)
    {
        p.Interact(ref player, player.Interact);
    }
    else
    {
        Enemy e = o as Enemy;
        if (e != null)
        {
            e.Update(time, player);
        }
    }
}


Q: Can a variadic template match a non-variadic template parameter? Consider the following snippet:
template<template<class> class T,class U>
struct apply
{
     typedef T<U> type;
};

typedef apply<std::tuple,int>::type tuple_of_one_int; //Should be std::tuple<int>

GCC 4.8.2. says:
type/value mismatch at argument 1 in template parameter list for [...] struct apply
expected a template of type ‘template<class> class T’, got ‘template<class ...> class std::tuple’

Which basically means that a variadic template like std::tuple is not a valid template argument for T in apply.
Is this a GCC bug or does the standard mandates this behaviour?

A: Someone correct me if I'm wrong but it seems like it's correct from this quote:

3 A template-argument matches a template template-parameter (call it P) when each of the template parameters in the template-parameter-list of the template-argument’s corresponding class template or [FI 11] template aliasalias template (call it A) matches the corresponding template parameter in the template-parameter-list of P

A (the given template) has to match each of it's templates parameters to P's the template template.
From the second part of the section we learn the restriction doesn't apply in the reverse, meaning a template template containing a parameter pack can match anything.

When P’s template-parameter-list contains a template parameter pack (14.5.3), the template parameter pack will match zero or more template parameters or template parameter packs in the template-parameter- list of A with the same type and form as the template parameter pack in P

As you probably already knew the way to make it work is
template<template<class> class T,class U>
struct apply
{
         typedef T<U> type;
};

template<class T> using tuple_type  = std::tuple<T>;
typedef apply<tuple_type,int>::type tuple_of_one_int;

The c++11 standard also has an equivalent example to yours.
template <class ... Types> class C { /∗ ... ∗/ };

template<template<class> class P> class X { /∗ ... ∗/ };

X<C> xc; //ill-formed: a template parameter pack does not match a template parameter

The last comment completely describes your situation, class C would be the equivalent of std::tuple in this case.

A: Your code is ill-formed, there is equivalent example in the standard (under 14.3.3/2):
...
template <class ... Types> class C { /∗ ... ∗/ };

template<template<class> class P> class X { /∗ ... ∗/ };
...
X<C> xc; // ill-formed: a template parameter pack does not match a template parameter
...

A: The fix:
template<template<class...> class T,class U>
struct apply
{
     typedef T<U> type;
};

typedef apply<std::tuple,int>::type tuple_of_one_int;
typedef apply<std::vector,int>::type vector_of_int;