text:
Q: LRU cache design Least Recently Used (LRU) Cache is to discard the least recently used items first
How do you design and implement such a cache class? The design requirements are as follows:
1) find the item as fast as we can
2) Once a cache misses and a cache is full, we need to replace the least recently used item as fast as possible.
How to analyze and implement this question in terms of design pattern and algorithm design?

A: I see here several unnecessary complicated implementations, so I decided to provide my implementation as well. The cache has only two methods, get and set. Hopefully it is better readable and understandable:
#include<unordered_map>
#include<list>

using namespace std;

template<typename K, typename V = K>
class LRUCache
{

private:
    list<K>items;
    unordered_map <K, pair<V, typename list<K>::iterator>> keyValuesMap;
    int csize;

public:
    LRUCache(int s) :csize(s) {
        if (csize < 1)
            csize = 10;
    }

    void set(const K key, const V value) {
        auto pos = keyValuesMap.find(key);
        if (pos == keyValuesMap.end()) {
            items.push_front(key);
            keyValuesMap[key] = { value, items.begin() };
            if (keyValuesMap.size() > csize) {
                keyValuesMap.erase(items.back());
                items.pop_back();
            }
        }
        else {
            items.erase(pos->second.second);
            items.push_front(key);
            keyValuesMap[key] = { value, items.begin() };
        }
    }

    bool get(const K key, V &value) {
        auto pos = keyValuesMap.find(key);
        if (pos == keyValuesMap.end())
            return false;
        items.erase(pos->second.second);
        items.push_front(key);
        keyValuesMap[key] = { pos->second.first, items.begin() };
        value = pos->second.first;
        return true;
    }
};

A: This is my simple sample c++ implementation for LRU cache, with the combination of hash(unordered_map), and list. Items on list have key to access map, and items on map have iterator of list to access list.
#include <list>
#include <unordered_map>
#include <assert.h>

using namespace std;

template <class KEY_T, class VAL_T> class LRUCache{
private:
        list< pair<KEY_T,VAL_T> > item_list;
        unordered_map<KEY_T, decltype(item_list.begin()) > item_map;
        size_t cache_size;
private:
        void clean(void){
                while(item_map.size()>cache_size){
                        auto last_it = item_list.end(); last_it --;
                        item_map.erase(last_it->first);
                        item_list.pop_back();
                }
        };
public:
        LRUCache(int cache_size_):cache_size(cache_size_){
                ;
        };

        void put(const KEY_T &key, const VAL_T &val){
                auto it = item_map.find(key);
                if(it != item_map.end()){
                        item_list.erase(it->second);
                        item_map.erase(it);
                }
                item_list.push_front(make_pair(key,val));
                item_map.insert(make_pair(key, item_list.begin()));
                clean();
        };
        bool exist(const KEY_T &key){
                return (item_map.count(key)>0);
        };
        VAL_T get(const KEY_T &key){
                assert(exist(key));
                auto it = item_map.find(key);
                item_list.splice(item_list.begin(), item_list, it->second);
                return it->second->second;
        };

};

A: Here is my implementation for a basic, simple LRU cache.
//LRU Cache
#include <cassert>
#include <list>

template <typename K,
          typename V
          >
class LRUCache
    {
    // Key access history, most recent at back
    typedef std::list<K> List;

    // Key to value and key history iterator
    typedef unordered_map< K,
                           std::pair<
                                     V,
                                     typename std::list<K>::iterator
                                    >
                         > Cache;

    typedef V (*Fn)(const K&);

public:
    LRUCache( size_t aCapacity, Fn aFn )
        : mFn( aFn )
        , mCapacity( aCapacity )
        {}

    //get value for key aKey
    V operator()( const K& aKey )
        {
        typename Cache::iterator it = mCache.find( aKey );
        if( it == mCache.end() ) //cache-miss: did not find the key
            {
            V v = mFn( aKey );
            insert( aKey, v );
            return v;
            }

        // cache-hit
        // Update access record by moving accessed key to back of the list
        mList.splice( mList.end(), mList, (it)->second.second );

        // return the retrieved value
        return (it)->second.first;
        }

private:
        // insert a new key-value pair in the cache
    void insert( const K& aKey, V aValue )
        {
        //method should be called only when cache-miss happens
        assert( mCache.find( aKey ) == mCache.end() );

        // make space if necessary
        if( mList.size() == mCapacity )
            {
            evict();
            }

        // record k as most-recently-used key
        typename std::list<K>::iterator it = mList.insert( mList.end(), aKey );

        // create key-value entry, linked to the usage record
        mCache.insert( std::make_pair( aKey, std::make_pair( aValue, it ) ) );
        }

        //Purge the least-recently used element in the cache
    void evict()
        {
        assert( !mList.empty() );

        // identify least-recently-used key
        const typename Cache::iterator it = mCache.find( mList.front() );

        //erase both elements to completely purge record
        mCache.erase( it );
        mList.pop_front();
        }

private:
    List mList;
    Cache mCache;
    Fn mFn;
    size_t mCapacity;
    };

A: I implemented a thread-safe LRU cache two years back.
LRU is typically implemented with a HashMap and LinkedList. You can google the implementation detail. There are a lot of resources about it(Wikipedia have a good explanation too).
In order to be thread-safe, you need put lock whenever you modify the state of the LRU.
I will paste my C++ code here for your reference.
Here is the implementation.
/***
    A template thread-safe LRU container.

    Typically LRU cache is implemented using a doubly linked list and a hash map.
    Doubly Linked List is used to store list of pages with most recently used page
    at the start of the list. So, as more pages are added to the list,
    least recently used pages are moved to the end of the list with page
    at tail being the least recently used page in the list.

    Additionally, this LRU provides time-to-live feature. Each entry has an expiration
    datetime.
***/
#ifndef LRU_CACHE_H
#define LRU_CACHE_H

#include <iostream>
#include <list>

#include <boost/unordered_map.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/mutex.hpp>

template <typename KeyType, typename ValueType>
  class LRUCache {
 private:
  typedef boost::posix_time::ptime DateTime;

  // Cache-entry
  struct ListItem {
  ListItem(const KeyType &key,
           const ValueType &value,
           const DateTime &expiration_datetime)
  : m_key(key), m_value(value), m_expiration_datetime(expiration_datetime){}
    KeyType m_key;
    ValueType m_value;
    DateTime m_expiration_datetime;
  };

  typedef boost::shared_ptr<ListItem> ListItemPtr;
  typedef std::list<ListItemPtr> LruList;
  typedef typename std::list<ListItemPtr>::iterator LruListPos;
  typedef boost::unordered_map<KeyType, LruListPos> LruMapper;

  // A mutext to ensuare thread-safety.
  boost::mutex m_cache_mutex;

  // Maximum number of entries.
  std::size_t m_capacity;

  // Stores cache-entries from latest to oldest.
  LruList m_list;

  // Mapper for key to list-position.
  LruMapper m_mapper;

  // Default time-to-live being add to entry every time we touch it.
  unsigned long m_ttl_in_seconds;

  /***
      Note : This is a helper function whose function call need to be wrapped
      within a lock. It returns true/false whether key exists and
      not expires. Delete the expired entry if necessary.
  ***/
  bool containsKeyHelper(const KeyType &key) {
    bool has_key(m_mapper.count(key) != 0);
    if (has_key) {
      LruListPos pos = m_mapper[key];
      ListItemPtr & cur_item_ptr = *pos;

      // Remove the entry if key expires
      if (isDateTimeExpired(cur_item_ptr->m_expiration_datetime)) {
        has_key = false;
        m_list.erase(pos);
        m_mapper.erase(key);
      }
    }
    return has_key;
  }

  /***
      Locate an item in list by key, and move it at the front of the list,
      which means make it the latest item.
      Note : This is a helper function whose function call need to be wrapped
      within a lock.
  ***/
  void makeEntryTheLatest(const KeyType &key) {
    if (m_mapper.count(key)) {
      // Add original item at the front of the list,
      // and update <Key, ListPosition> mapper.
      LruListPos original_list_position = m_mapper[key];
      const ListItemPtr & cur_item_ptr = *original_list_position;
      m_list.push_front(cur_item_ptr);
      m_mapper[key] = m_list.begin();

      // Don't forget to update its expiration datetime.
      m_list.front()->m_expiration_datetime = getExpirationDatetime(m_list.front()->m_expiration_datetime);

      // Erase the item at original position.
      m_list.erase(original_list_position);
    }
  }

 public:

  /***
      Cache should have capacity to limit its memory usage.
      We also add time-to-live for each cache entry to expire
      the stale information. By default, ttl is one hour.
  ***/
 LRUCache(std::size_t capacity, unsigned long ttl_in_seconds = 3600)
   : m_capacity(capacity), m_ttl_in_seconds(ttl_in_seconds) {}

  /***
      Return now + time-to-live
  ***/
  DateTime getExpirationDatetime(const DateTime &now) {
    static const boost::posix_time::seconds ttl(m_ttl_in_seconds);
    return now + ttl;
  }

  /***
      If input datetime is older than current datetime,
      then it is expired.
  ***/
  bool isDateTimeExpired(const DateTime &date_time) {
    return date_time < boost::posix_time::second_clock::local_time();
  }

  /***
      Return the number of entries in this cache.
   ***/
  std::size_t size() {
    boost::mutex::scoped_lock lock(m_cache_mutex);
    return m_mapper.size();
  }

  /***
      Get value by key.
      Return true/false whether key exists.
      If key exists, input paramter value will get updated.
  ***/
  bool get(const KeyType &key, ValueType &value) {
    boost::mutex::scoped_lock lock(m_cache_mutex);
    if (!containsKeyHelper(key)) {
      return false;
    } else {
      // Make the entry the latest and update its TTL.
      makeEntryTheLatest(key);

      // Then get its value.
      value = m_list.front()->m_value;
      return true;
    }
  }

  /***
      Add <key, value> pair if no such key exists.
      Otherwise, just update the value of old key.
  ***/
  void put(const KeyType &key, const ValueType &value) {
    boost::mutex::scoped_lock lock(m_cache_mutex);
    if (containsKeyHelper(key)) {
      // Make the entry the latest and update its TTL.
      makeEntryTheLatest(key);

      // Now we only need to update its value.
      m_list.front()->m_value = value;
    } else { // Key exists and is not expired.
      if (m_list.size() == m_capacity) {
        KeyType delete_key = m_list.back()->m_key;
        m_list.pop_back();
        m_mapper.erase(delete_key);
      }

      DateTime now = boost::posix_time::second_clock::local_time();
      m_list.push_front(boost::make_shared<ListItem>(key, value,
                                                     getExpirationDatetime(now)));
      m_mapper[key] = m_list.begin();
    }
  }
};
#endif

Here is the unit tests.
#include "cxx_unit.h"
#include "lru_cache.h"

struct LruCacheTest
  : public FDS::CxxUnit::TestFixture<LruCacheTest>{
  CXXUNIT_TEST_SUITE();
  CXXUNIT_TEST(LruCacheTest, testContainsKey);
  CXXUNIT_TEST(LruCacheTest, testGet);
  CXXUNIT_TEST(LruCacheTest, testPut);
  CXXUNIT_TEST_SUITE_END();

  void testContainsKey();
  void testGet();
  void testPut();
};

void LruCacheTest::testContainsKey() {
  LRUCache<int,std::string> cache(3);
  cache.put(1,"1"); // 1
  cache.put(2,"2"); // 2,1
  cache.put(3,"3"); // 3,2,1
  cache.put(4,"4"); // 4,3,2

  std::string value_holder("");
  CXXUNIT_ASSERT(cache.get(1, value_holder) == false); // 4,3,2
  CXXUNIT_ASSERT(value_holder == "");

  CXXUNIT_ASSERT(cache.get(2, value_holder) == true); // 2,4,3
  CXXUNIT_ASSERT(value_holder == "2");

  cache.put(5,"5"); // 5, 2, 4

  CXXUNIT_ASSERT(cache.get(3, value_holder) == false); // 5, 2, 4
  CXXUNIT_ASSERT(value_holder == "2"); // value_holder is still "2"

  CXXUNIT_ASSERT(cache.get(4, value_holder) == true); // 4, 5, 2
  CXXUNIT_ASSERT(value_holder == "4");

  cache.put(2,"II"); // {2, "II"}, 4, 5

  CXXUNIT_ASSERT(cache.get(2, value_holder) == true); // 2, 4, 5
  CXXUNIT_ASSERT(value_holder == "II");

  // Cache-entries : {2, "II"}, {4, "4"}, {5, "5"}
  CXXUNIT_ASSERT(cache.size() == 3);
  CXXUNIT_ASSERT(cache.get(2, value_holder) == true);
  CXXUNIT_ASSERT(cache.get(4, value_holder) == true);
  CXXUNIT_ASSERT(cache.get(5, value_holder) == true);
}

void LruCacheTest::testGet() {
  LRUCache<int,std::string> cache(3);
  cache.put(1,"1"); // 1
  cache.put(2,"2"); // 2,1
  cache.put(3,"3"); // 3,2,1
  cache.put(4,"4"); // 4,3,2

  std::string value_holder("");
  CXXUNIT_ASSERT(cache.get(1, value_holder) == false); // 4,3,2
  CXXUNIT_ASSERT(value_holder == "");

  CXXUNIT_ASSERT(cache.get(2, value_holder) == true); // 2,4,3
  CXXUNIT_ASSERT(value_holder == "2");

  cache.put(5,"5"); // 5,2,4
  CXXUNIT_ASSERT(cache.get(5, value_holder) == true); // 5,2,4
  CXXUNIT_ASSERT(value_holder == "5");

  CXXUNIT_ASSERT(cache.get(4, value_holder) == true); // 4, 5, 2
  CXXUNIT_ASSERT(value_holder == "4");

  cache.put(2,"II");
  CXXUNIT_ASSERT(cache.get(2, value_holder) == true); // {2 : "II"}, 4, 5
  CXXUNIT_ASSERT(value_holder == "II");

  // Cache-entries : {2, "II"}, {4, "4"}, {5, "5"}
  CXXUNIT_ASSERT(cache.size() == 3);
  CXXUNIT_ASSERT(cache.get(2, value_holder) == true);
  CXXUNIT_ASSERT(cache.get(4, value_holder) == true);
  CXXUNIT_ASSERT(cache.get(5, value_holder) == true);
}

void LruCacheTest::testPut() {
  LRUCache<int,std::string> cache(3);
  cache.put(1,"1"); // 1
  cache.put(2,"2"); // 2,1
  cache.put(3,"3"); // 3,2,1
  cache.put(4,"4"); // 4,3,2
  cache.put(5,"5"); // 5,4,3

  std::string value_holder("");
  CXXUNIT_ASSERT(cache.get(2, value_holder) == false); // 5,4,3
  CXXUNIT_ASSERT(value_holder == "");

  CXXUNIT_ASSERT(cache.get(4, value_holder) == true); // 4,5,3
  CXXUNIT_ASSERT(value_holder == "4");

  cache.put(2,"II");
  CXXUNIT_ASSERT(cache.get(2, value_holder) == true); // II,4,5
  CXXUNIT_ASSERT(value_holder == "II");

  // Cache-entries : {2, "II"}, {4, "4"}, {5, "5"}
  CXXUNIT_ASSERT(cache.size() == 3);
  CXXUNIT_ASSERT(cache.get(2, value_holder) == true);
  CXXUNIT_ASSERT(cache.get(4, value_holder) == true);
  CXXUNIT_ASSERT(cache.get(5, value_holder) == true);
}

CXXUNIT_REGISTER_TEST(LruCacheTest);

A: A linked list + hashtable of pointers to the linked list nodes is the usual way to implement LRU caches. This gives O(1) operations (assuming a decent hash). Advantage of this (being O(1)): you can do a multithreaded version by just locking the whole structure. You don't have to worry about granular locking etc.
Briefly, the way it works:
On an access of a value, you move the corresponding node in the linked list to the head.
When you need to remove a value from the cache, you remove from the tail end.
When you add a value to cache, you just place it at the head of the linked list.
Thanks to doublep, here is site with a C++ implementation: Miscellaneous Container Templates.

A: I have a LRU implementation here. The interface follows std::map so it should not be that hard to use. Additionally you can provide a custom backup handler, that is used if data is invalidated in the cache.
sweet::Cache<std::string,std::vector<int>, 48> c1;
c1.insert("key1", std::vector<int>());
c1.insert("key2", std::vector<int>());
assert(c1.contains("key1"));

A:
We have to create a data structure that allows us to
optimize all three main operations at the same time.

Based on the above graph, we could infer that:

*

*Using tree would be best choice for general case.

*The hash table would be the best choice if we know the size of the cache is big enough (and the insertion of new elements infrequent
enough) to rarely require the removal of the oldest entry.

*The linked list could be a valid option if removing old entries were more important than storing entries or finding cache elements: but in
that case, the cache would basically be useless, and adding it would
provide no benefit.

*In all cases, the memory needed to store n entries is O(n).

Now my favorite question is, can we do any better?

A single data structure might not be enough to build the most
efficient solution to the problem. On the one hand, we have data
structures that are particularly good for quickly storing and
retrieving entries. Hash tables are pretty much impossible to beat if
that's the game. On the other hand, hash tables are terrible when it
comes to maintaining an ordering of things and they are not great when
it comes to retrieving the minimum (or maximum) element they contain,
but we have other structures that handle this very well. Depending on
the kind of order we would like to keep, we might need trees, or we
might be fine with lists.
We only have to keep an ordering on the cache entries, being able to
go from the least to the most recently used. Since the order is only
based on insertion time, new elements are not changing the order of
the older elements; therefore, we don't need anything fancy: we only
need a structure that supports FIFO. We could just use a list or a
queue. A linked list is usually the best choice when we don't know in
advance the number of elements we will have to store or the number can
change dynamically, while a queue is usually implemented using an
array (and so more static in dimension), but optimized for insertion
on the head and removal on the tail.
Linked lists can also support fast insertion/removal at their ends. We
need, however, a doubly-linked list, where we insert elements on the
front and remove them from the tail. By always keeping a pointer to
the tail and links from each node to its predecessor, we can implement
tail removal in O(1) time.

You can see the three data elements that are stored for the cache and
need to be updated after every operation:

(1) The hash table.

(2) The head of a doubly-linked list.

(3) A pointer to the last element in the list.

Notice how each element in the hash table points to a node in
the list where all the data is stored. To get from a list entry to the
corresponding hash entry, we have to hash the name of the company
stored in the node, which is the key for the table.
We considered the hash table and the linked list separately, but we
need to make them work together in synchrony. We might store very
large objects in the cache, and we definitely don't want to duplicate
them in both data structures. One way to avoid duplication is storing
the entries only in one of the structures and referencing them from
the other one. We could either add the entries to the hash table and
store in the other DS the key to the a hash table, or vice versa.
Now, we need to decide which data structure should hold the values and
which one should be left with the reference. The best choice is having
hash table entries store pointers to linked list nodes, and have the
latter store the actual values. (If we do the opposite, then the way
we link from a linked list node to the hash table entry will be tied
to the implementation of the hash table. It could be an index for open
addressing or a pointer if we use chaining. This coupling to
implementation is neither good design nor, often, possible, as you
usually can't access standard library internals).
This cache is called least recently used. It's not least recently
added. This means the ordering is not just based on the time we first
add an element to cache, but on the last time, it was accessed.

*

*When we add a new entry to the cache, when we have a cache miss, trying to access an element that is not on the cache, we just add a
new entry to the front of our linked list.

*But when we run into a cache hit, accessing an element that is indeed stored on the cache, we need to move an existing list element
to the front of the list, and we can only do that efficiently if we
can both retrieve in constant (we still need to include the time for
computing each hash value for the entry we look up.) time a pointer to
the linked list node for the existing entry (which could be anywhere
in the list, for what we know), and remove an element from the list in
constant time (again, we need a doubly-linked list for this; with an
array-based implementation of a queue, removal in the middle of the
queue takes linear time).

*If the cache is full, we need to remove the least-recently-used entry before we can add a new one. In this case, the method to remove
the oldest entry can access the tail of the linked list in constant
time, from which we recover the entry to delete. To locate it on the
hash table and delete it from it, we will need to hash the entry (or
its ID) at an extra cost (potentially non-constant: for strings, it
will depend on the length of the string).

reference

A: Is cache a data structure that supports retrieval value by key like hash table? LRU means the cache has certain size limitation that we need drop least used entries periodically.
If you implement with linked-list + hashtable of pointers how can you do O(1) retrieval of value by key?
I would implement LRU cache with a hash table that the value of each entry is value + pointers to prev/next entry.
Regarding the multi-threading access, I would prefer reader-writer lock (ideally implemented by spin lock since contention is usually fast) to monitor.

A: LRU Page Replacement Technique:
When a page is referenced, the required page may be in the cache.
If in the cache: we need to bring it to the front of the cache queue.
If NOT in the cache: we bring that in cache. In simple words, we add a new page to the front of the cache queue. If the cache is full, i.e. all the frames are full, we remove a page from the rear of cache queue, and add the new page to the front of cache queue.
# Cache Size
csize = int(input())

# Sequence of pages
pages = list(map(int,input().split()))

# Take a cache list
cache=[]

# Keep track of number of elements in cache
n=0

# Count Page Fault
fault=0

for page in pages:
    # If page exists in cache
    if page in cache:
        # Move the page to front as it is most recent page
        # First remove from cache and then append at front
        cache.remove(page)
        cache.append(page)
    else:
        # Cache is full
        if(n==csize):
            # Remove the least recent page
            cache.pop(0)
        else:
            # Increment element count in cache
            n=n+1

        # Page not exist in cache => Page Fault
        fault += 1
        cache.append(page)

print("Page Fault:",fault)

Input/Output
Input:
3
1 2 3 4 1 2 5 1 2 3 4 5

Output:
Page Fault: 10

A: This is my simple Java programmer with complexity O(1).
//
package com.chase.digital.mystack;

import java.util.HashMap;
import java.util.Map;

public class LRUCache {

  private int size;
  private Map<String, Map<String, Integer>> cache = new HashMap<>();

  public LRUCache(int size) {
    this.size = size;
  }

  public void addToCache(String key, String value) {
    if (cache.size() < size) {
      Map<String, Integer> valueMap = new HashMap<>();
      valueMap.put(value, 0);
      cache.put(key, valueMap);
    } else {
      findLRUAndAdd(key, value);
    }
  }

  public String getFromCache(String key) {
    String returnValue = null;
    if (cache.get(key) == null) {
      return null;
    } else {
      Map<String, Integer> value = cache.get(key);
      for (String s : value.keySet()) {
        value.put(s, value.get(s) + 1);
        returnValue = s;
      }
    }
    return returnValue;
  }

  private void findLRUAndAdd(String key, String value) {
    String leastRecentUsedKey = null;
    int lastUsedValue = 500000;
    for (String s : cache.keySet()) {
      final Map<String, Integer> stringIntegerMap = cache.get(s);
      for (String s1 : stringIntegerMap.keySet()) {
        final Integer integer = stringIntegerMap.get(s1);
        if (integer < lastUsedValue) {
          lastUsedValue = integer;
          leastRecentUsedKey = s;
        }
      }
    }
    cache.remove(leastRecentUsedKey);
    Map<String, Integer> valueMap = new HashMap<>();
    valueMap.put(value, 0);
    cache.put(key, valueMap);
  }

}

A: Detailed explanation here in my blogpost.

class LRUCache {
  constructor(capacity) {

        this.head = null;
        this.tail = null;
        this.capacity = capacity;
        this.count = 0;
    this.hashMap  = new Map();
  }

  get(key) {
    var node = this.hashMap.get(key);
    if(node) {
      if(node == this.head) {
        // node is already at the head, just return the value
        return node.val;
      }
      if(this.tail == node && this.tail.prev) {
        // if the node is at the tail,
        // set tail to the previous node if it exists.
        this.tail = this.tail.prev;
        this.tail.next = null;
      }
      // link neibouring nodes together
      if(node.prev)
        node.prev.next = node.next;
      if(node.next)
        node.next.prev = node.prev;
      // add the new head node
      node.prev = null;
      node.next = this.head;
      this.head.prev = node;
      this.head = node;
      return node.val;
    }
    return -1;
  }
  put(key, val) {
    this.count ++;
    var newNode = { key, val, prev: null, next: null };
    if(this.head == null) {
      // this.hashMap is empty creating new node
      this.head =  newNode;
      this.tail = newNode;
    }
    else {
      var oldNode = this.hashMap.get(key);
      if(oldNode) {
        // if node with the same key exists,
        // clear prev and next pointers before deleting the node.
        if(oldNode.next) {
          if(oldNode.prev)
            oldNode.next.prev = oldNode.prev;
          else
            this.head = oldNode.next;
        }
        if(oldNode.prev) {
          oldNode.prev.next = oldNode.next;
          if(oldNode == this.tail)
            this.tail = oldNode.prev;
        }
        // removing the node
        this.hashMap.delete(key);
        this.count --;
      }
      // adding the new node and set up the pointers to it's neibouring nodes
      var currentHead = this.head;
      currentHead.prev = newNode;
      newNode.next = currentHead;
      this.head = newNode;
      if(this.tail == null)
        this.tail = currentHead;
      if(this.count == this.capacity + 1) {
        // remove last nove if over capacity
        var lastNode = this.tail;
        this.tail = lastNode.prev;
        if(!this.tail) {
          //debugger;
        }
        this.tail.next = null;
        this.hashMap.delete(lastNode.key);
        this.count --;
      }
    }
    this.hashMap.set(key, newNode);
    return null;
  }
}

var cache = new LRUCache(3);
cache.put(1,1); // 1
cache.put(2,2); // 2,1
cache.put(3,3); // 3,2,1

console.log( cache.get(2) ); // 2,3,1
console.log( cache.get(1) ); // 1,2,3
cache.put(4,4);              // 4,1,2 evicts 3
console.log( cache.get(3) ); // 3 is no longer in cache

A: Java Code :
package DataStructures;

import java.util.HashMap;

class Node2 {

    int key;
    int value;
    Node2 pre;
    Node2 next;

    Node2(int key ,int value)
    {
        this.key=key;
        this.value=value;
    }
}
class LRUCache {

    private HashMap<Integer,Node2> lrumap;
    private int capacity;
    private Node2 head,tail;

    LRUCache(int capacity)
    {
        this.capacity=capacity;
        lrumap=new HashMap<Integer,Node2>();
        head=null;
        tail=null;
        }

    public void deleteNode(Node2 node)
    {

        if(node==head)
        {
            head.next.pre=null;
            head=head.next;
            node=null;
        }
        else if(node==tail)
        {
            tail.pre.next=null;
            tail=tail.pre;
            node=null;
        }
        else
        {
            node.pre.next=node.next;
            node.next.pre=node.pre;
            node=null;
        }
    }

    public void addToHead(Node2 node)
    {
        if(head==null && tail==null)
        {
            head=node;
            tail=node;
        }
        else
        {
        node.next=head;
        head.pre=node;
        head=node;
        }

    }

    public int get(int key)
    {
        if(lrumap.containsKey(key))
        {
            Node2 gnode=lrumap.get(key);
            int result=gnode.value;
            deleteNode(gnode);
            addToHead(gnode);

            return result;
        }

        return -1;
    }

    public void set(int key,int value)
    {
        if(lrumap.containsKey(key))
        {
            Node2 snode=lrumap.get(key);
            snode.value=value;
            deleteNode(snode);
            addToHead(snode);
        }
        else
        {
            Node2 node=new Node2(key,value);
            //System.out.println("mapsize="+lrumap.size()+"   capacity="+capacity);
            if(lrumap.size()>=capacity)
            {
            System.out.println("remove="+tail.key);
                lrumap.remove(tail.key);
                deleteNode(tail);

            }
            lrumap.put(key, node);
            addToHead(node);

        }
    }

    public void show()
    {
        Node2 node = head;

        while(node.next!=null)
        {
        System.out.print("["+node.key+","+node.value+"]--");
        node=node.next;
        }
        System.out.print("["+node.key+","+node.value+"]--");
        System.out.println();
    }

}

public class LRUCacheDS{

    public static void main(String[] args) {

        LRUCache lr= new LRUCache(4);
        lr.set(4,8);
        lr.set(2,28);
        lr.set(6,38);
        lr.show();
        lr.set(14,48);
        lr.show();
        lr.set(84,58);
        lr.show();
        lr.set(84,34);
        lr.show();
        lr.get(6);
        System.out.println("---------------------------------------------------------");
        lr.show();

    }
}

A: Is LRU approximation allowed? Here is one that does 20 million get/set operations per second for some image smoothing algorithm. I don't know if its not the worst but its certainly a lot faster than Javascript equivalent which does only 1.5 million get/set per second.
Unordered_map to keep track of items on circular buffers. Circular buffer doesn't add/remove nodes as other linked-list versions. So it should be at least friendly on the CPU's L1/L2/L3 caches unless cache size is much bigger than those caches. Algorithm is simple. There is a hand of clock that evicts victim slots while the other hand does save some of them from eviction as a "second chance" but lags the eviction by 50% phase so that if cache is big then cache items have a good amount of time to get their second chance / be saved from eviction.
Since this is an approximation, you shouldn't expect it to evict the least recent one always. But it does give a speedup on some network I/O, disk read/write, etc that are slower than RAM. I used this in a VRAM virtual buffer class that uses 100% of system video-ram (from multiple graphics cards). VRAM is slower than RAM so caching in RAM makes 6GB VRAM look like as fast as RAM for some cache-friendly access patterns.
Here is implementation:
#ifndef LRUCLOCKCACHE_H_
#define LRUCLOCKCACHE_H_

#include<vector>
#include<algorithm>
#include<unordered_map>
#include<functional>
#include<mutex>
#include<unordered_map>
/* LRU-CLOCK-second-chance implementation */
template<   typename LruKey, typename LruValue>
class LruClockCache
{
public:
    // allocates circular buffers for numElements number of cache slots
    // readMiss:    cache-miss for read operations. User needs to give this function
    //              to let the cache automatically get data from backing-store
    //              example: [&](MyClass key){ return redis.get(key); }
    //              takes a LruKey as key, returns LruValue as value
    // writeMiss:   cache-miss for write operations. User needs to give this function
    //              to let the cache automatically set data to backing-store
    //              example: [&](MyClass key, MyAnotherClass value){ redis.set(key,value); }
    //              takes a LruKey as key and LruValue as value
    LruClockCache(size_t numElements,
                const std::function<LruValue(LruKey)> & readMiss,
                const std::function<void(LruKey,LruValue)> & writeMiss):size(numElements)
    {
        ctr = 0;
        // 50% phase difference between eviction and second-chance hands of the "second-chance" CLOCK algorithm
        ctrEvict = numElements/2;

        loadData=readMiss;
        saveData=writeMiss;

        // initialize circular buffers
        for(size_t i=0;i<numElements;i++)
        {
            valueBuffer.push_back(LruValue());
            chanceToSurviveBuffer.push_back(0);
            isEditedBuffer.push_back(0);
            keyBuffer.push_back(LruKey());
        }
    }

    // get element from cache
    // if cache doesn't find it in circular buffers,
    // then cache gets data from backing-store
    // then returns the result to user
    // then cache is available from RAM on next get/set access with same key
    inline
    const LruValue get(const LruKey & key)  noexcept
    {
        return accessClock2Hand(key,nullptr);
    }

    // thread-safe but slower version of get()
    inline
    const LruValue getThreadSafe(const LruKey & key)  noexcept
    {
        std::lock_guard<std::mutex> lg(mut);
        return accessClock2Hand(key,nullptr);
    }

    // set element to cache
    // if cache doesn't find it in circular buffers,
    // then cache sets data on just cache
    // writing to backing-store only happens when
    //                  another access evicts the cache slot containing this key/value
    //                  or when cache is flushed by flush() method
    // then returns the given value back
    // then cache is available from RAM on next get/set access with same key
    inline
    void set(const LruKey & key, const LruValue & val) noexcept
    {
        accessClock2Hand(key,&val,1);
    }

    // thread-safe but slower version of set()
    inline
    void setThreadSafe(const LruKey & key, const LruValue & val)  noexcept
    {
        std::lock_guard<std::mutex> lg(mut);
        accessClock2Hand(key,&val,1);
    }

    void flush()
    {
        for (auto mp = mapping.cbegin(); mp != mapping.cend() /* not hoisted */; /* no increment */)
        {
          if (isEditedBuffer[mp->second] == 1)
          {
                isEditedBuffer[mp->second]=0;
                auto oldKey = keyBuffer[mp->second];
                auto oldValue = valueBuffer[mp->second];
                saveData(oldKey,oldValue);
                mapping.erase(mp++);    // or "it = m.erase(it)" since C++11
          }
          else
          {
                ++mp;
          }
        }
    }

    // CLOCK algorithm with 2 hand counters (1 for second chance for a cache slot to survive, 1 for eviction of cache slot)
    // opType=0: get
    // opType=1: set
    LruValue const accessClock2Hand(const LruKey & key,const LruValue * value, const bool opType = 0)
    {

        typename std::unordered_map<LruKey,size_t>::iterator it = mapping.find(key);
        if(it!=mapping.end())
        {

            chanceToSurviveBuffer[it->second]=1;
            if(opType == 1)
            {
                isEditedBuffer[it->second]=1;
                valueBuffer[it->second]=*value;
            }
            return valueBuffer[it->second];
        }
        else
        {
            long long ctrFound = -1;
            LruValue oldValue;
            LruKey oldKey;
            while(ctrFound==-1)
            {
                if(chanceToSurviveBuffer[ctr]>0)
                {
                    chanceToSurviveBuffer[ctr]=0;
                }

                ctr++;
                if(ctr>=size)
                {
                    ctr=0;
                }

                if(chanceToSurviveBuffer[ctrEvict]==0)
                {
                    ctrFound=ctrEvict;
                    oldValue = valueBuffer[ctrFound];
                    oldKey = keyBuffer[ctrFound];
                }

                ctrEvict++;
                if(ctrEvict>=size)
                {
                    ctrEvict=0;
                }
            }

            if(isEditedBuffer[ctrFound] == 1)
            {
                // if it is "get"
                if(opType==0)
                {
                    isEditedBuffer[ctrFound]=0;
                }

                saveData(oldKey,oldValue);

                // "get"
                if(opType==0)
                {
                    LruValue loadedData = loadData(key);
                    mapping.erase(keyBuffer[ctrFound]);
                    valueBuffer[ctrFound]=loadedData;
                    chanceToSurviveBuffer[ctrFound]=0;

                    mapping[key]=ctrFound;
                    keyBuffer[ctrFound]=key;

                    return loadedData;
                }
                else /* "set" */
                {
                    mapping.erase(keyBuffer[ctrFound]);

                    valueBuffer[ctrFound]=*value;
                    chanceToSurviveBuffer[ctrFound]=0;

                    mapping[key]=ctrFound;
                    keyBuffer[ctrFound]=key;
                    return *value;
                }
            }
            else // not edited
            {
                // "set"
                if(opType == 1)
                {
                    isEditedBuffer[ctrFound]=1;
                }

                // "get"
                if(opType == 0)
                {
                    LruValue loadedData = loadData(key);
                    mapping.erase(keyBuffer[ctrFound]);
                    valueBuffer[ctrFound]=loadedData;
                    chanceToSurviveBuffer[ctrFound]=0;

                    mapping[key]=ctrFound;
                    keyBuffer[ctrFound]=key;

                    return loadedData;
                }
                else // "set"
                {
                    mapping.erase(keyBuffer[ctrFound]);

                    valueBuffer[ctrFound]=*value;
                    chanceToSurviveBuffer[ctrFound]=0;

                    mapping[key]=ctrFound;
                    keyBuffer[ctrFound]=key;
                    return *value;
                }
            }

        }
    }

private:
    size_t size;
    std::mutex mut;
    std::unordered_map<LruKey,size_t> mapping;
    std::vector<LruValue> valueBuffer;
    std::vector<unsigned char> chanceToSurviveBuffer;
    std::vector<unsigned char> isEditedBuffer;
    std::vector<LruKey> keyBuffer;
    std::function<LruValue(LruKey)> loadData;
    std::function<void(LruKey,LruValue)> saveData;
    size_t ctr;
    size_t ctrEvict;
};

#endif /* LRUCLOCKCACHE_H_ */

Here is usage:
using MyKeyType = std::string;
using MyValueType = MinecraftChunk;

LruClockCache<MyKeyType,MyValueType> cache(1024*5,[&](MyKeyType key){
  // cache miss (read)
  // access data-store (network, hdd, graphics card, anything that is slower than RAM or higher-latency than RAM-latency x2)
  return readChunkFromHDD(key);
  },[&](MyKeyType key,MyValueType value){

  // cache miss (write)
  // access data-store
  writeChunkToHDD(key,value);
});

// cache handles all cace-miss functions automatically
MinecraftChunk chunk = cache.get("world coordinates 1500 35 2000");

// cache handles all cace-miss functions automatically
cache.set("world coordinates 1502 35 1999",chunk);

cache.flush(); // clears all pending-writes in the cache and writes to backing-store

A: Working of LRU Cache
Discards the least recently used items first. This algorithm requires keeping track of what was used when which is expensive if one wants to make sure the algorithm always discards the least recently used item. General implementations of this technique require keeping "age bits" for cache-lines and track the "Least Recently Used" cache-line based on age-bits. In such an implementation, every time a cache-line is used, the age of all other cache-lines changes.
The access sequence for the below example is A B C D E C D B.

class Node:
    def init(self, k, v):
        self.key = k
        self.value = v
        self.next = None
        self.prev = None
class LRU_cache:
    def init(self, capacity):
        self.capacity = capacity
        self.dic = dict()
        self.head = Node(0, 0)
        self.tail = Node(0, 0)
        self.head.next = self.tail
        self.tail.prev = self.head
    def _add(self, node):
        p = self.tail.prev
        p.next = node
        self.tail.prev = node
        node.next = self.tail
        node.prev = p
    def _remove(self, node):
        p = node.prev
        n = node.next
        p.next = n
        n.prev = p
    def get(self, key):
        if key in self.dic:
            n = self.dic[key]
            self._remove(n)
            self._add(n)
            return n.value
        return -1
    def set(self, key, value):
        n = Node(key, value)
        self._add(n)
        self.dic[key] = n
        if len(self.dic) > self.capacity:
            n = self.head.next
            self._remove(n)
            del self.dic[n.key]
cache = LRU_cache(3)
cache.set('a', 'apple')
cache.set('b', 'ball')
cache.set('c', 'cat')
cache.set('d', 'dog')
print(cache.get('a'))
print(cache.get('c'))


text:
Q: Inverse of a complex number (in Hamilton's pair representation) I've just started looking at ring theory and I am having trouble working with invertible elements.
In my notes we have been told that $R^\times$ is the set of all the invertible elements of $R$, and it is called the group of units of $R$. The set $R^\times$ of invertible elements of $R$ is a multiplicative group for the multiplication operation of $R$.
I have to work with the cartesian product $S:= R\times R$ with $R$ a commutative ring. Where $(a,b)(c,d) = (ac-db, ad+bc)$ and I am trying to show $(a,b)∈ S^\times$  iff $(a,-b)∈ S^\times$.
I'm guessing we define $S^\times$ the same way as we define $R^\times$? We also know that $S$ has unit $(1,0)$.
Should I proceed by showing $(a,b)(a,-b)=(1,0)=(a,-b)(a,b)$? I had seen online that for invertible elements $uv=1=vu$.
Thank you!

A: Hint $ $ It's simple viewed as $\,S \cong R[x]/(x^2\!+1) = R[i]\,$  where $\,i := [x] = x + (x^2\!+\!1)R[x]$
$$\begin{align}{\rm where}\ \ \ \   (a,\ b)*(c,\ d) &\,=\, (ac\!-\!bd,\ \ \ \, ad\!+\!bc)\\[.2em]
\to\ \  (a\!+\!bi)(c\!+\!di) &\,=\, \ \, ac\!-\!bd\! +\! (ad\!+\!bc)\,i \end{align}\qquad\qquad$$
generalizing the familiar case: $\,\Bbb R[x]/(x^2\!+1) = \Bbb R[i]\cong \Bbb C\ $ when $\ R = \Bbb R$
Then, as in any algebraic extension, existence of inverses in $R$ lifts to $R[i]$ by rationalizing ("real-izing") the denominator, which is a prototypical instance of the method of simpler multiples, i.e. we multiply $\,\alpha\in R[i]\,$ by its conjugate(s) to obtain its (simpler multiple) norm $\,r\in R,\,$ which has the simplification effect of reducing $\color{#c00}{\rm division\ by\ \alpha}\in R[i]$ to  simpler $\color{#0a0}{\rm division\ by\ } r\in R,\,$ i.e.
$\displaystyle  0\ne\alpha\in R[i]\ \ \Rightarrow\ \ 0\ne\alpha\bar\alpha = r\in  R\ \ \Rightarrow\!\!\! \underbrace{\color{#c00}{\frac{1}\alpha}\, =\, \frac{1\ \bar\alpha}{\alpha\:\bar\alpha}\, =\, \color{#0a0}{\frac{\bar\alpha}r}\in R[i]}_{\textstyle{\color{c00}{\textit{real-ize}}\ {\rm to}\ R \rm\ the\ denominator}}$
In this quadratic case the "simpler multiple" of $\alpha\in R[i]\,$ is simply its norm $\,N(\alpha) = {\alpha\bar\alpha}\in R$
$$\begin{align}\alpha &= a+bi\\ \Rightarrow\ \bar\alpha &= a-bi\end{align} \Rightarrow\  \alpha\bar\alpha = a^2+b^2 = r\in R\qquad$$

A: It's not true in general that $(a,b)(a,-b)=1$.
Note that for $R=\mathbb R$, the multiplication on $S$ is the multiplication on $\mathbb C$, so if you're familiar with $\mathbb C$, you can use your intuitions for that to guide you. In $\mathbb C$, the inverse of the conjugate is the conjugate of the inverse.
The same is true here: If $(a,b)$ is invertible, then there is $(c,d)$ such that $(ac-db,ad+bc)=(1,0)$; and then $(a,-b),(c,-d)=(ac-(-d)(-b),a(-d)+(-b)c)=(ac-db,ad+bc)=(1,0).$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gerrit Code review multiple submisions Im New to Gerrit,
trying to understand the correct way to submit multiple reviews:
i have files: a.py , b.py , c.py
i was asked to submit each file for a separate review,
all files are on same branch but each file has its own commit
Branch feature:
[CommitA: a.py] -> [CommitB:b.py] -> [CommitC:c.py]

*

*how do i submit to Gerrit for review files b.py and c.py without Gerrit including previous files in commit chain ?

*does Gerrit know to remove already submitted files ?

A: You can just execute the following:
git push origin COMMIT-C:refs/for/BRANCH

Gerrit will create 3 changes (reviews), one for each commit. Change 1 will have just a.py changed, change 2 will have just b.py and change 3 will have just c.py.This is exactly what you want: each file in a separate review.
Note:
In your case, COMMIT-C depends on COMMIT-B which depends on COMMIT-A, like the following:
BASE --- A --- B --- C

If you, for example, need to fix the COMMIT-A (amend the COMMIT-A, generating COMMIT-A' and another patchset on Gerrit) you'll need to rebase COMMIT-B (generating COMMIT-B') and COMMIT-C (generating COMMIT-C'). This can be done using the "Rebase" button on the Gerrit UI.
With Gerrit the most of times is better to work the independent changes "in parallel", like the following:
BASE --- A
    \
     \--- B
      \
       \---C

This way, you can amend any change you want without the need to change the other changes too.


text:
Q: XML Include elements from another xml So we have a xml file :
EnglandCities.xml
<Cities>
    <City Name="London">
        other children
    </City>
    <City Name="Southampton">
        other children
    </City>
</Cities>

Now we need a second file say :
UKCities.xml
<Cities>
    <City Name="London">
        other children
    </City>
    <City Name="Southampton">
        other children
    </City>
    <City Name="Belfast">
        other children
    </City>
    <City Name="Edinburgh">
        other children
    </City>
</Cities>

This UKCities.xml has new  entries "Belfast" & "Edinburgh".
Can we do a xml:include (or something similar) in UKCities.xml to get "London" & "Southampton" elements from EnglandCities.xml instead of typing them in?
Something of the sorts as below:
<Cities>
    <xml:include file="EnglandCities.xml"/>
    <City Name="Belfast">
        other children
    </City>
    <City Name="Edinburgh">
        other children
    </City>
</Cities>

A: You've tagged this as "xslt" which suggests you may be interested in an XSLT solution. (If this is not the case, please remove the tag, and I will delete this answer).
But assuming you can use XSLT, you could make use of the document() function to reference the "EnglandCities.xml" within the XSLT
<xsl:copy-of select="document('EnglandCities.xml')/*/*" />

Or maybe (if you were using the Identity Transform....)
<xsl:apply-templates select="document('EnglandCities.xml')/*/*" />

Try this XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:param name="include" select="'EnglandCities.xml'" />

  <xsl:template match="/*">
    <xsl:copy>
      <xsl:apply-templates select="document($include)/*/*" />
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

When applied to your original XML, the following is output
<Cities>
  <City Name="London">
        other children
    </City>
  <City Name="Southampton">
        other children
    </City>
    <City Name="Belfast">
        other children
    </City>
    <City Name="Edinburgh">
        other children
    </City>
</Cities>


text:
Q: How can I add a git pre-commit hook for the default rails 7 test suite? I'm trying to add a pre-commit hook that utilized the default rails 7 testing suite. I cannot seem to find any example that doesn't assume that I've replace the default test suite with Rspec.
How can I add a precommit hook that checks the default Rails 7 test suite that is run using rails test in the terminal?


text:
Q: Create windows shortcut and download it in ASP.NET I want to create a custom windows shortcut and download it in asp.mvc.
Specifically I want to be able to download a remote desktop shortcut with dynamic server as argument.
I came accross this example on the internet but in was clearly not meant for web application.
    public ActionResult Download()
    {
            WshShell wsh = new WshShell();
            IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut("/shorcut.lnk") as IWshRuntimeLibrary.IWshShortcut;
            shortcut.Arguments = "";
            shortcut.TargetPath = "c:\\app\\myftp.exe";
            // not sure about what this is fro
            shortcut.WindowStyle = 1;
            shortcut.Description = "my shortcut description";
            shortcut.WorkingDirectory = "c:\\app";
            //shortcut.IconLocation = "specify icon location";
            shortcut.Save();

        return File("/shorcut.lnk", "application/octet-stream", "shorcut.lnk");
    }

I got a plain access is denied. Is there another way to do it ?

A: I took the problem to the wrong direction, i did not need to do a shortcut to mstsc.exe but i needed to create my own rdp file that contains very simple text as a parameter.
public ActionResult Download()
        {
            StringBuilder sb = new StringBuilder();
            string srv = "mysrv.myurl.com";
            sb.AppendFormat("full address:s:{0}", srv);
            return File(Encoding.UTF8.GetBytes(sb.ToString()),
             "text/plain",
              string.Format("{0}.rdp", srv));
        }

This is working


text:
Q: Help needed in using Lexmark Pro705 with Ubuntu 13.10 From Lexmark: Drivers & Downloads I have downloaded 32 bit printer description and print utility for Lexmark Pro705 Ubuntu 12.04. These appear to install ok after overriding warnings of bad quality. On creation of printer using print utility, test job is stopped with message cups-insecure-filter-warning.
I've found and followed various advice on this:
sudo chmod 777 -R /usr/lib/cups/backend
sudo chown -hR root:root /usr/lib/cups/filter/*
sudo chown -hR root:root /usr/lib/cups/backend/*

Along with multiple restarts and recreation of print queues. I've tried both usb and wireless connections. Test print jobs continue to stop with message cups-insecure-filter-warning.
Has anyone managed to get the Lexmark Prevail Pro705 working on Ubuntu 13.10? Any advice greatly appreciated.

A: I solved the same problem some months ago:

*

*installed lexmark-inkjet-legacy-1.0-1.amd64.deb from your lexmark support link

*fixed some file permissions to
$ ls -la /usr/local/lexmark/v3/bin/
total 1004
drwxr-xr-x 3 root root   4096 .
drwxr-xr-x 8 root root   4096 ..
-rwxr-xr-x 1 root root 755469 lxhcp
-rwxr-xr-x 1 root root 110411 lxusb
-rwxr-xr-x 1 root root 146921 printfilter
drwxr-xr-x 2 root root   4096 .scripts

This is tested for Ubuntu 13.10 and 14.04


text:
Q: OpenAPI Generator - Java Client generating different model than Spring Server I'm trying to create the server and a client from the same api spec (v3.0.2) by using the openapi-generator-maven-plugin (v6.2.1).
For the server i'm using
<generatorName>spring</generatorName>
<library>spring-boot</library>

and for the client
<generatorName>java</generatorName>
<library>webclient</library>

In the api spec I'm having an object with a list of items.
The items can be one of two types.
   Section:
      type: object
      properties:
        items:
          type: array
          items:
            oneOf:
            - $ref: '#/components/schemas/SectionItemInput'
            - $ref: '#/components/schemas/SectionItemOutput'

For the two types I added a base class with a discriminator property set to 'type'
    SectionItemBase:
      required:
      - type
      type: object
      properties:
        type:
          type: string
        name:
          type: string
      discriminator:
        propertyName: type

Finally the two types look like this
    SectionItemInput:
      type: object
      allOf:
      - $ref: '#/components/schemas/SectionItemBase'
      - type: object
        properties:
          input:
            type: string

    SectionItemOutput:
      type: object
      allOf:
      - $ref: '#/components/schemas/SectionItemBase'
      - type: object
        properties:
          output:
            type: string

After building the server, I get these models
Section.java
public class Section {
  @JsonProperty("items")
  @Valid
  private List<SectionItemsInner> items = null;
  ...

SectionItemsInner.java
@JsonIgnoreProperties(
  value = "type", // ignore manually set type, it will be automatically generated by Jackson during serialization
  allowSetters = true // allows the type to be set during deserialization
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = SectionItemInput.class, name = "SectionItemInput"),
  @JsonSubTypes.Type(value = SectionItemOutput.class, name = "SectionItemOutput")
})

public interface SectionItemsInner {
    public String getType();
}

SectionItemBase.java
@JsonIgnoreProperties(
  value = "type", // ignore manually set type, it will be automatically generated by Jackson during serialization
  allowSetters = true // allows the type to be set during deserialization
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = SectionItemInput.class, name = "SectionItemInput"),
  @JsonSubTypes.Type(value = SectionItemOutput.class, name = "SectionItemOutput")
})

public class SectionItemBase { ...

SectionItemInput.java
public class SectionItemInput extends SectionItemBase implements SectionItemsInner { ...

SectionItemOutput.java
public class SectionItemOutput extends SectionItemBase implements SectionItemsInner { ...

This seems fine.
But when I build the client I get
Section.java
public class Section {
  public static final String JSON_PROPERTY_ITEMS = "items";
  private List<SectionItemsInner> items = null;
  ...

Up until here, it also seems fine. But starting with the SectionItemsInner it differs.
SectionItemsInner.java
@JsonTypeName("Section_items_inner")
@JsonIgnoreProperties(
  value = "type", // ignore manually set type, it will be automatically generated by Jackson during serialization
  allowSetters = true // allows the type to be set during deserialization
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = SectionItemInput.class, name = "SectionItemInput"),
  @JsonSubTypes.Type(value = SectionItemOutput.class, name = "SectionItemOutput"),
})

public class SectionItemsInner { ...

The generator creates a class instead of an interface like with the server generator.
Also it has all the properties of the type whichever comes last in the spec for the Section schema.
SectionItemBase.java
@JsonIgnoreProperties(
  value = "type", // ignore manually set type, it will be automatically generated by Jackson during serialization
  allowSetters = true // allows the type to be set during deserialization
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = SectionItemInput.class, name = "SectionItemInput"),
  @JsonSubTypes.Type(value = SectionItemOutput.class, name = "SectionItemOutput"),
})

public class SectionItemBase { ...

SectionItemBase has just the base properties, but there is no relationship between the SectionItemsInner and the SectionItemBase.
SectionItemInput.java
@JsonIgnoreProperties(
  value = "type", // ignore manually set type, it will be automatically generated by Jackson during serialization
  allowSetters = true // allows the type to be set during deserialization
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)

public class SectionItemInput extends SectionItemBase { ...

SectionItemInput extends SectionItemBase but also has no relation to SectionItemsInner.
After creating the server I wrote a body for a sample request
{
  "items": [
    {
      "type": "SectionItemOutput",
      "name": "output",
      "output": "TestOutput"
    },
    {
      "type": "SectionItemInput",
      "name": "input",
      "output": "TestInput"
    }
  ]
}

When I post this to the server, it gets parsed correctly and I can do something with it.
But when I try to parse this on the client
InputStream json = ...
ObjectMapper mapper = new ObjectMapper();
Section s = mapper.readValue(json, Section .class);

I get an error
com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'SectionItemOutput'
as a subtype of `org.openapitools.client.model.SectionItemsInner`:
Class `org.openapitools.client.model.SectionItemOutput` not subtype of
`org.openapitools.client.model.SectionItemsInner`
   at [Source: (BufferedInputStream); line: 4, column: 16] (through reference chain:
      org.openapitools.client.model.Section["items"]->java.util.ArrayList[0])

I'm very sorry for this long post, but it seems that I'm stucked.
I tried a few different other libraries (okhttp-gson, resttemplate, webclient) but none of them generates code which is compatible.
Thanks for any help or hint, bernd

A: As of right now, the java client generator (and its libraries) doesn't currently support polymorphism, but the Spring generator does.

Spring
Java

There are several options to work around this:

*

*You can force the webclient to implement the interface generated by the Spring generator by using the x-implements vendor extension.  However, this would require you to use two copies of the same schema, one with and one without the vendor extension.

*you can disable the model generation for your webclient and have it use all of the models generated by the spring generator.

Here's an example of your schema with the x-implements extension.  I took the liberty of cleaning it up a bit as well (I hate those inner classes).
components:
  schemas:
    Section:
      type: object
      properties:
        items:
          type: array
          items:
            $ref: "#/components/schemas/SectionItem"
    SectionItem:
      oneOf:
        - $ref: '#/components/schemas/SectionItemInput'
        - $ref: '#/components/schemas/SectionItemOutput'
      discriminator:
        propertyName: type
    SectionItemBase:
      required:
        - type
      type: object
      properties:
        type:
          type: string
        name:
          type: string
      discriminator:
        propertyName: type
    SectionItemInput:
      type: object
      allOf:
        - $ref: '#/components/schemas/SectionItemBase'
        - type: object
          title: SectionItemInputDetails
          properties:
            input:
              type: string
      x-implements:
        - 'generated.model.spring.SectionItem'
    SectionItemOutput:
      type: object
      allOf:
        - $ref: '#/components/schemas/SectionItemBase'
        - type: object
          title: SectionItemOutputDetails
          properties:
            output:
              type: string
      x-implements:
        - 'generated.model.spring.SectionItem'


text:
Q: How to write code for delete file from external memory I use this code for delete file from external memory.But it can not delete("Not Deleted").How can I do?
Main class
public void deleteButtonClicked(View v) {
    deleteExternalStoragePrivateFile();
}

private void deleteExternalStoragePrivateFile() {
    File path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    if (path != null) {

        if(getApplicationContext().deleteFile("OneRepublic_-_Something_I_Need.mp3"))
        {
            Toast.makeText(getApplicationContext(),"File Deleted",Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(getApplicationContext(),"Not Deleted",Toast.LENGTH_SHORT).show();
        }
    }
}

}

A: Context.deleteFile("")  deletes the given file associated with this Context's application package.
If you wanna delete a file you can use this code. Here is the link for the actual source.
public void deleteFile(String[] args)
    {
        try{

            File file = new File("c:\\logfile20100131.log");

            if(file.delete()){
                System.out.println(file.getName() + " is deleted!");
            }else{
                System.out.println("Delete operation is failed.");
            }

        }catch(Exception e){

            e.printStackTrace();

        }

    }

A: try this code for delete
    private void deleteExternalStoragePrivateFile() {
    File path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    if (path != null) {

        if (path.isDirectory()) {
            for (File child : path.listFiles()) {
                String child1 = child.toString();
                if (child1.contains("OneRepublic_-_Something_I_Need.mp3")) {
                    child.delete();
                }
                if (child.isDirectory()) {
                    Toast.makeText(getApplicationContext(), "Not Deleted", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(getApplicationContext(), "File Deleted", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}

A: Are you providing the necessary permissions?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

If you are indeed having the permissions, you can use file.delete() as suggested in other answers.
Edit:
private void deleteExternalStoragePrivateFile() {
File path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
if (path != null) {

    for(File f:path.listFiles()){
        String name = f.getName();
        if(name.contains("OneRepublic_-_Something_I_Need.mp3")){
            if(f.delete())
            {
                Toast.makeText(getApplicationContext(),"File Deleted",Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(getApplicationContext(),"Not Deleted",Toast.LENGTH_SHORT).show();
            }
        }
    }
}

}

A: //Find base directory - file
File file = getApplicationContext()
        .getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
if (!file.exists()) {
    file.mkdirs();
}

//Find your file path
File filePath = new File(file, YOUR_FILE_NAME);

//Delete your file
if(! filePath.exists())
    return;
else
    filePath.delete();

Make sure you have added following permissions in the manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


text:
Q: C# converts T-SQL date datatype to DateTime datatype by default When transfering a table from a database to a datagrid (WPF), the DATE datatype from T-SQL is converted to DateTime, but I don't want that. I want only the .Date part to show up in my datagrid.
Here's the piece of code in c#:
cmd = new SqlCommand("SELECT * FROM bibliotvguia.get_progtv();", con);

adap = new SqlDataAdapter(cmd);

dt = new DataTable();
adap.Fill(dt);
programs_datagrid.ItemsSource = dt.DefaultView;

And the XAML piece of code:
<DataGrid SelectionMode="Single" Name="programs_datagrid" Height="340"
                      AutoGenerateColumns="False" RowHeaderWidth="0" IsReadOnly="True" CanUserResizeColumns="True"
                      CanUserReorderColumns="False">
                    <DataGrid.Columns >
                        <DataGridTextColumn Header="Canal de TV" Binding="{Binding canal_media}"></DataGridTextColumn>
                        <DataGridTextColumn Header="Dia" Binding="{Binding dia_media}"></DataGridTextColumn>
                        <DataGridTextColumn Header="Hora" Binding="{Binding hora_media}"></DataGridTextColumn>
                        <DataGridTextColumn Header="Produção Audiovisual" Binding="{Binding titulo}"></DataGridTextColumn>
                    </DataGrid.Columns>
                </DataGrid>

The dia_media column is the one that has a DateTime type.
Thanks for your help.
The best for you.

A: There is only the DateTime type in NET, so you can't really have a variable with only the Date part. This kind of problem should not be resolved changing the storage of your datetime values or inserting complicate SQL function to extract the value as string or to remove the time part.
It is only just a matter on how do you format your data for presentation.
I suppose that you need something like this in your XAML
  <DataGridTextColumn Header="Dia" Binding="{Binding dia_media,
                                 StringFormat=dd MM yyyy}"/>

A: You can use a converter in your binding
XAML
       <Window.Resources>
         <locl:DateTimeConverter x:Key="converter"/>
       </Window.Resources>
     ...
        <DataGrid ItemsSource="{Binding Dates}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Date"
                                    Binding="{ Binding DateProperty,
                                               Converter={ StaticResource converter}}"/>
            </DataGrid.Columns>
        </DataGrid>

The converter class:
 public class DateTimeConverter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            DateTime dateValue = (DateTime)value;

            return dateValue.ToString("yyyy/MM/dd/");
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

and the result :

I hope it helps


text:
Q: Python object list weird behaviour I just started learning Python and come from a Java/C++ background and find the following behavior a little confusing. After calling s.add_trick("Woof") and d.add_trick("Woof"), s.tricks and d.tricks both contain ["Woof", "Bark"]. However, calling party() doesn't have the same behavior. Can someone explain?
class PartyAnimal:
    x = 0
    name = ''
    tricks = []

    def __init__(self, name):
        self.name = name

    def party(self):
        self.x += 1

    def add_trick(self, trick):
        self.tricks.append(trick)

s = PartyAnimal("Sally")
d = PartyAnimal("Danny")

s.party()
d.party()
s.add_trick("Woof")
d.add_trick("Bark")

print 's', s.name, s.x, s.tricks
print 'd', d.name, d.x, d.tricks

Output is this:
s Sally 1 ['Woof', 'Bark']
d Danny 1 ['Woof', 'Bark']

A: You're creating one tricks list that is shared by all instances of class. Create a new list in the __init__ instead:
def __init__(self, name):
    self.name = name
    self.tricks = []


text:
Q: OSX -- Output WAV independently to 12 speakers connected via USB soundcards I wish to simultaneously play sounds through up to 12 mono speakers.
I could connect these to my MacBook using 6 USB soundcards, and use the left and right channel of each.
But how can I get the MacBook to play sound out of speaker #5, for example?
PS If anyone can see a smarter way to wire up 12 speakers to a MacBook, please do say!

A: You can setup an Aggregate Device (Audio Midi Setup > Create Aggregate Device), which allows the ability to combine multiple devices of the same model, or to combine multiple inputs and outputs for apps that don't support separate input and output devices. This Apple guide shows how it works and is surprisingly quite easy to setup.
Another way to route audio to multiple channels and outputs (up to 64) is with the free app/plug-in Soundflower. You can download a compiled version, or compile the source code if you want/need to specifically do something that the current compiled version might not.


text:
Q: Set up Phemex API trading I try to set up a crypto-trading-bot, which can go short- and long-positions. So I created a phemex account and tried to implement a bot in jupyter notebook using python.
I created API key and secret on phemex.
I wrote the following code:
from phemex.client import Client
from phemex.exceptions import PhemexAPIException
import websocket, json, pprint, talib, numpy, requests

API_ID = "..."
API_SECRET = "..."
SOCKET = "wss://testnet.phemex.com/ws"

client = Client("API_ID", "API_SECRET", True)

def on_open(ws):
    print("opened connection")

def on_close(ws):
    print("closed connection")

def on_message(ws, message):
    print("received message")
    json_message = json.loads(message)
    pprint.pprint(json_message)

ws = websocket.WebSocketApp(SOCKET, on_open =on_open, on_close =on_close, on_message = on_message)
ws.run_forever()

With this code, I want to get the actual data for Bitcoin from phemex. If I do it for Binance it works just fine. Can some help me with this issue?
Thank you
Best regards
Daniel

A: You can get data from Phemex like this.
from phemex_python_api.phemex.client import Client
client.query_24h_ticker("BTCUSD")

To place an order:
client.place_order({"symbol":"DOGEUSD","clOrdID":"cryptomarauder1","side":Client.SIDE_BUY,"orderQty":1000,"ordType":Client.ORDER_TYPE_MARKET,"priceEp":0.2250,"takeProfitEp":0.25,"stopLossEp":0.20})

There is an issue with the API because setting the stop loss and take profit does not work for me. I already opened an issue here.
Feel free to use the documentation as a guide.
You can set Leverage like this:
# Set leverage
try:
    # Set 0 to change back to cross margin
    # Set to 10x
    r = client.change_leverage(Client.SYMBOL_BTCUSD, 10)
    print("response:" + str(r))
except PhemexAPIException as e:
    print(e)


text:
Q: Pygame object class comparision with a tuple So i am trying to create a game in pygame. Everything is going well, but I have a problem where I am trying to set the winning condition. For this I made some for loops to go through the rows and columns and without too many details, the point is if the white piece is in the first or the 5th row, the game is won.
def winner(self):
    for row in range(ROWS):
        for col in range(COLS):
            piece = self.get_piece(row, col)
            if piece == WHITE:
                print("hello")
                if row == 0:
                    return YELLOW
                if row == 4:
                    return BLUE

Both WHITE and piece return (250, 250, 250), but WHITE is a tuple, and piece is a '<class 'mygame.piece.Piece'>' class object, so I guess they are not comparable. I changed my code in the 5th row like this:
if piece == Piece(row, col, WHITE):

This returns a '<class 'mygame.piece.Piece'>' object as well, but for some reason it still doesn't print hello, meaning it doesn't compare the two object.
My question would be how can I compare two pygame objects? Or can I convert a pygame object to a tuple? I have the same problem with another function. I haven't found anything on this.

A: Piece(row, col, WHITE) creates an new object, so Piece(row, col, WHITE) is not equal to piece. Objects are not compared attribute-wise unless you implement the comparison method (__eq__).
You need to compare the object's color attribute to WHITE:
if piece and piece.color == WHITE:

If the object doesn't have an attribute color, then add one.


text:
Q: How to get UIImageView size after autolayout is applied? My storyboard has UIImageView which is automatically positioned and scaled by autolayout constraints.
When application runs, this UIImageView is properly resized and positioned according to device screen size and autolayout constraints.
How I can get UIImageView frame after it is displayed on the screen?
Common UIImageView.bounds and UIImageView.frame values return original values which were used in storyboard and does not reflect new UIImageView size.

A: Check these methods:
- (void)viewWillAppear:(BOOL)animated {
// view is about to be added to hieararchy
}

- (void)viewDidAppear:(BOOL)animated {
// view was added
}

- (void)viewDidLayoutSubviews {
// VC just laid off its views
}

A: In order to get the right frame/bounds of your UIImageView after resizing, you need first ask auto-layout to update that layout using [yourImageView layoutIfNeeded]. that will solve your constraints and update your yourImage.bounds.
[myImageView layoutIfNeeded];
NSLog(@"w: %f, h: %f", myImageView.bounds.size.width, myImageView.bounds.size.height);


text:
Q: Using TableView instead of ScrollView For creating a login page or something like that, in autolayout case I use tableView instead of using a scrollView in viewController. For IndexPath majority cases I reuse the customCell. For entirely different items only I use another customCell. Since the Cell Class are increasing in my project. I dont know is it a good practice. Please share your opinion to increase the overall performance and least memory usage for my application.

A: Putting UITableView in all views is not a good practice every time.
I recommend using scrollviews and content views inside them in pages like login.
Use Tableviews only in those screens which show repeated contents.
I have seen codes generated through tableview controllers in every page.
I dont do in that way.
Better you go for Scrollviews.. Its a good method as far as I have seen.


text:
Q: How to disable security for Certain APIs in Spring Boot I am writing an application in Spring Boot. I am using the Spring boot default security mechanism. But I want to disable security for certain endpoints like monitoring, healthcheck etc.

A: You can add following configuration in Spring Boot application.properties
security.ignored= # Comma-separated list of paths to exclude from the default secured paths

A: Use security.ignored=Url Paths to be ignored property in application.properties


text:
Q: Why doesn't the classical model of electrical conduction work with iron, cadmium and bismuth? My textbook says this:

In most metals, the charge carriers are electrons and the charge - carrier density determined from Hall - effect measurements is in good agreement with calculated values for such metals as lithium (Li), sodium (Na), copper (Cu), and silver (Ag), whose atoms each give up one electron to act as a current carrier. In this case $n_v$ is approximately equal to the number of conducting electrons per volume. This classical model however is not valid for metals like iron (Fe), bismuth (Bi) and Cadmium (Cd) or for semiconductors. These discrepancies can only be explained by using a model based on the quantum nature of solids.

(The context of $n_v$ here is that used in the measurement of Hall voltage): $$\Delta V_H = \frac{IBd}{n_vqA}$$
In an example where the Hall voltage was determined for a copper strip, the author mentioned that a semiconductor's Hall voltage would be much larger than that for metals because $n_v$ is much smaller than it is in metals that contribute one electron per atom.

My first question is how exactly does a semiconductor have a value of $n_v$ lower than one per atom? I read that the charge carriers increase in density with temperature in semi-conductors. Could this property be related to it?

(I found out that semiconductors follow electrical conduction based on band-theory and this explains how semiconductors have a lower $n_v$ than one per atom. The second question still puzzles me.)
I don't see why metals like iron and bismuth don't behave in the same way as copper and silver. How are they any different from the other metals and why does a discrepancy occur? They share similar properties with metals like magnesium (Mg) and zinc (Zn), so I really can't find any reason for their unusual behaviour. Could someone please suggest a possible reason?
Any help would be appreciated!


text:
Q: Type a function with a callable I have a lot of functions that have the same signature, let's say (int, int) -> int.
Is there a way to type these functions with a Callable (or something else) to avoid specifying the types of the parameters and the return type for each of these functions? I would like to do something like that (but it obviously fails):
from typing import Callable

f: Callable[[int, int], int]
def f(x, y):  #  with the previous line, this is equivalent to 'def f(x: int, y: int) -> int:'
    ...

Running mypy results in:
file.py:4: error: Name "f" already defined on line 3
Found 1 error in 1 file (checked 1 source file)

A: Maybe there's a more elegant solution. Not recommended but you can set the <function>.__annotations__. More info about it here.
from typing import get_type_hints

callable_int_annotations = {"x": int, "y": int, "return": int}

def f_with_hint(x: int, y: int) -> int:
    return x + y

def f_without_hint(x, y):
    return x + y

print(f"Before {get_type_hints(f_with_hint)=}")
print(f"Before {get_type_hints(f_without_hint)=}")

f_without_hint.__annotations__ = callable_int_annotations

print(f"After {get_type_hints(f_with_hint)=}")
print(f"After {get_type_hints(f_without_hint)=}")

Before get_type_hints(f_with_hint)={'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
Before get_type_hints(f_without_hint)={}
After get_type_hints(f_with_hint)={'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}
After get_type_hints(f_without_hint)={'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}


text:
Q: DO INSTEAD in postresql Rules I have a simple table like this :
CREATE TABLE gateway_text (
  id         BIGSERIAL                                  NOT NULL PRIMARY KEY,
  text       TEXT                                       NOT NULL,
  hash       char(40)                                   UNIQUE,
  created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT now()  NOT NULL
);

CREATE RULE "gateway_text_on_duplicate_ignore" AS ON INSERT TO "gateway_text"
  WHERE EXISTS(SELECT 1 FROM gateway_text WHERE hash=NEW.hash)
  DO INSTEAD SELECT * FROM gateway_text WHERE hash=NEW.hash;

SQL Fiddle
As you can see, the rule is for when the first select is passed (the hash is already in database) so the first insert, is not the one DO INSTEAD supposed to run for.
But the problem is, every time I run insert, I get the select result, even for the first insert of a hash.
In my case this is OK, very OK actually, but I don't know if this is correct or this is a bug? can I simply accept this as normal and relay on this?

A: Yes, the SELECT executing in addition to the INSERT is the behavior that should be expected.
Based on the qualification (the where exists()... clause) and the DO INSTEAD clause,
the RULE produces a sequence of queries looking like this, in pseudo-code:
IF NOT EXISTS (SELECT 1 FROM gateway_text WHERE hash=NEW.hash)
 THEN INSERT...

IF EXISTS (SELECT 1 FROM gateway_text WHERE hash=NEW.hash)
 THEN SELECT * FROM gateway_text WHERE hash=NEW.hash;

In the first step, NEW.hash is not in the table yet so the INSERT is executed (or if it's in the table already, then it's not executed, but that's not the case you're asking about).
In the second step, NEW.hash is now in the table so the SELECT is executed too.
See  Rules on INSERT, UPDATE, and DELETE in PostgreSQL documentation for more details.
The (wrong) idea that the SELECT should not be executed when the INSERT gets executed is a common misinterpretation of how RULEs work, because intuition is misleading here.
When looking at the rule, we're tempted to think that it does this:
    IF EXISTS (SELECT 1 FROM gateway_text WHERE hash=NEW.hash)
     THEN
       SELECT * FROM gateway_text WHERE hash=NEW.hash
     ELSE
       INSERT...

But it doesn't. To achieve this, a procedural language like plpgsql should be used.


text:
Q: Compare list of child to list of parent by specific value I have 2 lists, first on parent objects second child objects. Child object has extra property which i want to compare with a property of the parent class.
here is the example
  public class Parent
{
    public int X { get; set; }
}

public class Child : Parent
{
    public int Y { get; set; }
}

public class ClassXCompare : IEqualityComparer<Parent>
{
    public bool Equals(Parent x, Parent y)
    {
        var child = (Child)y;
        return x.X == child.Y;
    }

    public int GetHashCode(Parent parent)
    {
        int parentXhash = parent.X.GetHashCode();
        // Calculate the hash code for the product.
        return parentXhash ;
    }
}

and now if i test the following, it always fail
var parentList= new List<Parent>
        {
            new Parent {X = 5},
            new Parent {X = 6}
        };
        var childList= new List<Child>
        {
            new Child {Y = 5},
            new Child {Y = 6}
        };
        var compare = new ClassXCompare();
        var diff = parentList.Except(childList, compare);
        Assert.IsTrue(!diff.Any()); // Fail ???

i think my issue is located in the GetHashCode function
Any idea how to solve this?

(Please ignore the design of the application this is simplified
  version of the issue)

A: This is truly horrible design. The need to cast to specific types in the comparer will cause you no end of trouble.
However, the code below passes. Note the different method of casting, the null checks and the order of the lists on the except line.
The problem was that the Child instances do not set X and the order that the Except method passes values into Equals meant that "x" was the Child not "y".
This may "work" but you should serious reconsider your design.
public class Parent
{
    public int X { get; set; }
}

public class Child : Parent
{
    public int Y { get; set; }
}

public class ClassXCompare : IEqualityComparer<Parent>
{
    public bool Equals(Parent x, Parent y)
    {
        var child = y as Child;

        return child != null && x.X == child.Y;
    }

    public int GetHashCode(Parent parent)
    {
        var c = parent as Child;
        if (c == null)
            return parent.X.GetHashCode();
        else
            return c.Y.GetHashCode();
    }
}

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var parentList = new List<Parent>
            {
                    new Parent {X = 5},
                    new Parent {X = 6}
            };
        var childList = new List<Child>
            {
                    new Child {Y = 5},
                    new Child {Y = 6}
            };
        var compare = new ClassXCompare();
        var diff = childList.Except(parentList, compare);
        Assert.IsTrue(!diff.Any()); // Fail ???
    }
}

A: Equals in Set/Dictionary will only be called only if GetHashCode returns the same value for both items - see General advice and guidelines on how to properly override object.GetHashCode(). The simplest way to fix it is to use something like this, where child value is used to calculate HashCode if available:
public class ClassXCompare : IEqualityComparer<Parent>
{
    public bool Equals(Parent x, Parent y)
    {
        var child = (Child)y;
        return x.X == child.Y;
    }

    public int GetHashCode(Parent parent)
    {
        var child = parent as Child;
        return child == null ?
            parent.X : child.Y.
    }
}

Though it is not very extendable if you have to handle multiple child classes.
Not sure that there is an easy way to handle multiple child classes, other than with some custom generic IEqualityComparer and even that will just shorten it a bit.
P.S. Also I am not sure that the second parameter will always be a Child (doubt that standard covers it, though current implementation in this particular usage seems to work in an appropriate way), so you may have to make that IEqualityComparer more lenient to the order of parameters.


text:
Q: CSOM: Creating a ClientContext with an invalid Site Collection URL "rolls up" to Root Site Collection Over the past few days, I've been working on an issue where I was using CSOM to inspect a particular site collection for some expected values. However, instead of finding those expected values, I was actually finding values that only existed on the root Site Collection.
After a lot of hubbub, I finally figured out that all of my problems were because I had a typo in the URL I was using to create my ClientContext object. While I was happy to have moved past the issue at hand, it got me to wondering: Why did ClientContext seemingly "roll up" to the root URL instead of throwing an exception?
I created a function that inspects the Managed Metadata Term Stores for the provided ClientContext and returns only those that are specific to that Site Collection.
I'd then consume the above with something like the below.
$context = New-Object Microsoft.SharePoint.Client.ClientContext("https://mycompanys.sharepoint.com/site/INVALID_URL")
$context.credentials = $AValidCredentialsObject

#Get-SiteCollectionTerms is my 'custom function' that returns
#any Site Collection Taxonomy Groups for provided context.

$siteTerms = Get-SiteCollectionTerms -ClientContext $context

My expectation was that the function call wouldn't find anything (because I had not setup any site collection specific Taxonomy Groups on the site "VALID_URL") but, because I had the URL wrong, the results were coming back with a Taxonomy Group that only existed on the root site "https://mycompanys.sharepoint.com/"
So, that's the rub. I figured that there was probably a "Best Practice" when dealing with validating a ClientContext, but I've come up short in finding it.
Hoping someone in the community has a solid approach.

A: I use the approach of testing if the URL is valid by using a WebClient call. This code is C# and also creates the site collection so its a bit heavy for what you're asking, but its a project I had open in VS so it was easy to get to and should give you some idea of how I have handled it in the past.
string siteUrl = comp.SharePointSettings.WebApp + comp.SharePointSettings.SiteCollectionUrl;

using (WebClient client = new WebClient())
{
  try
  {
    client.UseDefaultCredentials = true;
    string check = client.DownloadString(siteUrl);
  }
  catch (Exception webEx)
  {
    if (webEx.GetType() == typeof(System.Net.WebException))
    {
        WebException exW = (WebException)webEx;

        if (comp.SharePointSettings.CreateSiteCollection)
        {
            ConsoleHelper.WriteWarning(ResStrings.SiteCollection_HTTPExceptionHandled, ((HttpWebResponse)exW.Response).StatusCode);
            var admService = new adminService.AdminSoapClient();
            Uri caUri = new Uri(comp.SharePointSettings.CAUrl + "/_vti_adm/admin.asmx");
            admService.Endpoint.Address = new System.ServiceModel.EndpointAddress(caUri, admService.Endpoint.Address.Headers.ToArray());
            admService.ClientCredentials.Windows.ClientCredential = (NetworkCredential)System.Net.CredentialCache.DefaultCredentials;
            admService.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
            admService.Open();

            admService.CreateSite(siteUrl,
                comp.SharePointSettings.SiteCollectionTitle,
                comp.SharePointSettings.SiteCollectionDescription,
                comp.SharePointSettings.SiteCollectionLocale,
                comp.SharePointSettings.SiteCollectionTemplate,
                comp.SharePointSettings.SiteCollectionAdmin,
                null,
                null,
                null,
                null);

            ConsoleHelper.WriteInfo(ResStrings.SiteCollection_SiteCreated);
        }
        else
        {
            ConsoleHelper.WriteError(ResStrings.SiteCollection_UnhandledErrorCreating, webEx.Message);
        }
    }
  }
}

//Now initialize the ClientContext


text:
Q: How to get chrome to use more CPU power I made a NeroEvolution based AI that plays snake in p5.js, and in order to try and speed up the training I am trying to get many game cycles per frame, but chrome can't keep up. Is there any way I can allow chrome to use more CPU horsepower? Or is there any way to run p5.js without a browser? Chrome is currently only using 14% of my CPU.

A: You might want to look up Electron if you want to make Javascript based Desktop apps. But be aware that it's still running chromium behind the scenes


text:
Q: R - Plotting a ROC curve for a Naive Bayes classifier using ROCR. Not sure if I'm plotting it correctly I have a Naive Bayes classifiers that I'm using to try to predict whether a game is going to win or lose based on historical data. The model has 25 variables in total, all of which are categorical factors. The class node is the games "Status" which is binary with outcomes: won and lost.
I'm using the bnlearn package to build the classifiers, and plotting the ROC curves with the ROCR package. My question problem essential comes from not understanding what I should be plotting. I know that ROC curves plot the TPR against the FPR. But should I be plotting the predicted probabilities vs the actual games outcomes? Or should I be plotting the predicted labels vs the actual games outcomes?
Here is a sample of my code, to hopefully help you understand what I mean.
#BUILD THE NAIVE MODEL
naive = naive.bayes(trainingdata, "Status")
fitted = bn.fit(naive, trainingdata, method="bayes", iss=1)

##RUN PREDICTION AND GET PROBABILITIES
pred = predict(fitted, testdata, prob=TRUE)
results_prob = data.frame(t(attributes(pred)$prob))

Now, after doing this I have the predictions for each row in the testdata, as well as the associated probabilities with each prediction. It looks something like this:
x <- cbind(pred, results_prob)
head(x)

  pred         Lost          Won
1 Lost 0.9926455284 7.354472e-03
2  Won 0.3744111013 6.255889e-01
3 Lost 0.9978362577 2.163742e-03
4  Won 0.0001894814 9.998105e-01
5 Lost 0.9999974266 2.573381e-06
6 Lost 0.6750732745 3.249267e-01

Right, so now I'm going to try and plot a ROC curve. I already have the actual outcomes of the sales saved in realResults, which looks like this
head(data.frame(realResults))

     realResults
1        Lost
2        Lost
3        Lost
4         Won
5        Lost
6        Lost

So here's what happens when I try to plot a ROC curve. I can try it 3 ways, one of which works, but I'm not sure if it's the correct way, which is why I've come here in the hopes that someone can explain if it is, or is not correct.
If I try to plot it with the prediction labels against the actual outcomes, like
library(ROCR)
pr <- prediction(pred, realResults)
prf <- performance(pr, "tpr", "fpr")
plot(prf)

I will get an error saying Error in prediction(pred, realResults) :
  Format of predictions is invalid.
If I try it by plotting the probabilities against the actual outcomes, like
pr <- prediction(results_prob, realResults)

I will get an error saying Error in prediction(results_prob, realResults) :
  Number of cross-validation runs must be equal for predictions and labels.
Finally, it will plot a ROC curve if I only do it for the probabilities of a win
pr <- prediction(results_prob$Won, realResults)
prf <- performance(pr, "tpr", "fpr")
plot(prf)

This gets an AUC of 0.94.
So my question is, have I done this correctly? I can't understand why the first method of plotting a ROC doesn't work, as the predictions and the results have the same format. They both have 2 labels: won and lost. I don't understand the error I'm getting for that one.
Can anyone offer some insight into this? The model's accuracy is about 88%, so there's no real problem there. It's just with plotting the ROCs. I want to ensure I'm going about it correctly. Apologies for the long post! Thanks
EDIT: I've been reading up on ROC curves, but still haven't be able to clarify if I am going about this approach correctly?

A: The problem may lies here
pr <- prediction(pred, realResults)
You may transform "pred" and "realResults" to 0-1 vector by :
predvec <- ifelse(pred=="Lost", 1, 0)
realvec <- ifelse(realResults=="Lost", 1, 0)

and using:
pr <- prediction(predvec, realvec)

the problem may be solved.
Bonus part:
you can plot roc curve with more information by:
plot(ROCRperf, colorize=TRUE, print.cutoffs.at=seq(0,1,by=0.1), text.adj=c(-0.2,1.7))

And a simple way to get auc:
as.numeric(performance(ROCRpred, "auc")@y.values)