sort different data obejcts in same row with react-table - react-table

I'm really not sure how to describe what I'm trying to do. I'm trying to create a react-table component where my data is organized in a certain way.
Let's say I have a list of objects like this:
{ id: '887SYEP',
client: 'CS',
side: 'S',
price: 85.8125,
qty: 9866000,
id: '8a59875bdaca5f886c5e7bdc42bb753b78cbe59d' }
Please see the image attached. If "side" prop is "B" then then the price and related data is bid data and if its "S" then its offer data. each object is a stock quote. however i want to order it in such a way that the table looks like this where the highest bids and offers are at the top:
image of ideal table
This data is in one row even though its two separate quote objects. the corresponding "client" and "price" are to the left if its "side" property is type "S" and to the right if its "B" (buy/sell side). is there a way to use one table to achieve this or do i need two? the Bid and Offer prices are only related in so much as its the same stock and a way for the user to see the top prices for each.

first you should filter Buyers and Sellers
let buyers = orders.filter(obj => obj.side === "B")
let sellers = orders.filter(obj => obj.side === "S")
then sort both by price
buyers.sort((a,b) => a.price < b.price)
sellers.sort((a,b) => a.price > b.price)
for simplicity let assume both arrays are of the same length. to combine them do:
let orders = []
for (let index in buyers) {
let {client: BClient, qty: BQty, price: Bid} = buyers[index]
let {client: SClient, qty: SQty, price: Offer} = sellers[index]
orders.push({
BClient,
BQty,
Bid,
Offer,
SQty,
SClient
})
}
then display orders

Related

How do I access a calculated field in Rails?

In my first attempt to develop something in Ruby on Rails :) ... I have a list of names stored in fields "first_name" and "last_name". In my Person model, I have defined something like this:
def sort_name
sort_name = last_name + ',' + first_name
end
Now I want to show all persons shown in a list, sorted by sort_name, but (in my controller) something like
#persons = Person.order(:sort_name)
doesn't work (Unknown column 'sort_name' in 'order clause'). How do reference to the calculated field sort_name in my controller?
I am sure this is a "oh my god I am so stupid moment" but happy for any advise!
If the model Person has the fields name, first_lastname and second_lastname, you can do the next:
Person.order(:name, :first_lastname, :second_lastname)
By default is ordering in ascending way. Also you can put if you want ascending or descending way for each field:
Person.order(name: :asc, first_lastname: :desc, second_lastname: :asc)
Additional if you want add a column with the complete name, you can use select, using postgresql the code would be:
people = Person.order(
name: :asc, first_lastname: :desc, second_lastname: :asc
).select(
"*, concat(name,' ', first_lastname, ' ',second_lastname) as sort_name"
)
people[0].sort_name
# the sort_name can be for example "Adán Saucedo Salas"

Multiple commits to neo4j from R

I have collected some tweets using the twitteR package and thereafter exported them to a neo4j database using Nicole White's various tutorials. I extract the tweets to a dataframe called kdf and thereafter use functions from stringr for basic cleaning up as demonstrated by Nicole. I am then sending this to neo4j from R. The essential part of my code is:
library(RNeo4j)
graph = startGraph("http://localhost:7474/db/data/", username="xxxx", password="xxxx")
clear(graph)
addConstraint(graph, "Tweet", "id")
addConstraint(graph, "User", "username")
addConstraint(graph, "Hashtag", "hashtag")
addConstraint(graph, "Tags", "ent_tag")
query = "
CREATE (tweet:Tweet {id: {tweetID}})
SET tweet.text = {text}
CREATE (user:User {name: {Username}})
CREATE (user)-[:TWEETED]->(tweet)
FOREACH(reply_to_sn IN CASE {reply_to_sn} WHEN NULL then [] else [{reply_to_sn}] END |
MERGE (replytouser:User {username:{reply_to_sn}})
CREATE (tweet)-[:IN_REPLY_TO]->(replytouser)
)
FOREACH(retweet_sn IN CASE {retweet_sn} WHEN NULL THEN [] ELSE [{retweet_sn}] END |
MERGE(retweet_user:User {username: {retweet_sn}})
CREATE (tweet)-[:RETWEET_OF]->(retweet_user)
)
FOREACH(hastag_nodes IN CASE {hashtag_nodes} WHEN NULL then [] else [{hashtag_nodes}] END |
MERGE (h:Hashtag {hashtag :{hashtag_nodes}})
CREATE (tweet)-[:HASHTAG]->(h)
)
FOREACH(mentioned_users IN CASE {mentioned_users} WHEN NULL then [] else [{mentioned_users}] END |
MERGE (m:User {username :{mentioned_users}})
CREATE (tweet)-[:MENTIONED]->(m)
)
"
tx = newTransaction(graph)
for(i in 1:nrow(kdf)){
row = kdf[i, ]
appendCypher(tx, query,
tweetID=row$id,
text=row$text,
Username=row$screenName,
reply_to_sn=row$replyToSN,
retweet_sn=getRetweetSN(row$text),
hashtag_nodes=getHashtags(row$text),
mentioned_users=getMentions(row$text))
}
commit(tx)
What I have done thereafter is extracted named entities for all the text using Watson's Alchemy API. This is stored in a dataframe called ent_tbl. This contains three variables, tweetid, etext and etype. Now I am trying to export this data too to the same neo4j databse and join on the id of the tweets. This is the other part of the code:
query="
MATCH(t:ent_tag {id : $twid, type :$etype, text :$etext})
MATCH(tw:tweet {tweetID : $twid })
CREATE (tw)-[:HAS_ENT]->(t)
"
tx=newTransaction(graph)
for (i in 1:nrow(ent_tbl)){
row = ent_tbl[i,]
appendCypher(tx, query,
twid=row2$tweetid,
etype=row2$etype,
etext=row2$etext)
}
commit(tx)
While I do not get any errors on committing this, summary(graph) does not show me the relationship between the tags (t) and the tweets (tw) that I expected to see.
> summary(graph)
This To That
1 User TWEETED Tweet
2 Tweet RETWEET_OF User
3 Tweet HASHTAG Hashtag
4 Tweet MENTIONED User
5 Tweet IN_REPLY_TO User
Why would this happen?
This is my db.schema in neo4j:
That is because the MATCH does not find any tag or tweet so it breaks. If you want to add data to existing nodes, you should match them by ID and then set their properties. And you got to be consistent with labels and upper/lower cases. I think this is what you are looking for.
query="
MATCH(t:Tags {ent_tag : $twid})
MATCH(tw:Tweet {tweetID : $twid })
SET t.type=$etype, t.text=$etext
CREATE (tw)-[:HAS_ENT]->(t)
"
tx=newTransaction(graph)
for (i in 1:nrow(ent_tbl)){
row = ent_tbl[i,]
appendCypher(tx, query,
twid=row2$tweetid,
etype=row2$etype,
etext=row2$etext)
}
commit(tx)

How to get 3 data that have the highest value of a column in the table

I am using knex and bookshelf, and my table consists of author, title, content, count, and each data looks like this:
author: 'John Doe',
title: 'aaaaa',
content: 'aaaaaaaa'
count: 54,
I want to retrieve data based on the value of count, and I want to get 4 data that has the highest count value.
If I want to retrieve all data, I am doing like this:
router.get('/', (req, res) => {
Article.forge().fetchAll().then(article => {
res.json(article);
})
})
Is there any way that I can do like forge({ count: 3 data that has the highest count value }) or
What should I add the code so that I can achieve this?
Combine orderBy with fetchPage
Article
.orderBy('-count')
.fetchPage({
pageSize: 3
})
.forge()
This highlights a reason why my team is removing bookshelf and just using basic knex. Unless you are wanting to fetch related models it's simpler to deal without the ORM layer. The knex equivalent knex code is:
knex('articles')
.orderBy('count', 'desc')
.limit(3)
Which is slightly simpler and the resulting rows' properties can be accessed directly, ie rows[0].id rather than rows[0].get('id')

If Else in R, if product ID is X then change Product Name

I am trying to figure out what is working and why the other way is not working for me.
At the moment I have a list of shops I use and I need to change the naming every time; so I have decided to go by the product_id which never changes, but my code is not working.
product_id <- vector()
This one is not working:
product_name[product_id == '40600000003'] <- 'my cool store']
but this one does work:
product_name[product_name == 'my#cool#Store'] <- 'my cool store'
Now, I am not sure what am I doing wrong, I tried to do:
if (product_id == '40600000003') {
product_name = 'my cool shop'
}
I have a list of 15 shops that I need to change the naming as they arrive in the wrong format from the api connection.
Try 40600000003 instead of '40600000003' it's more than likely reading your vector slots as int if it doesn't contain any characters

Filter a product collection by two categories in Magento

I'm trying to find products that are in two categories.
I've found an example to get products that are in category1 OR category2.
http://www.alphadigital.cl/blog/lang/en-us/magento-filter-by-multiple-categories.html
I need products that are in category1 AND category2.
The example in the blog is:
class ModuleName_Catalog_Model_Resource_Eav_Mysql4_Product_Collection
extends Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection{
public function addCategoriesFilter($categories){
$alias = 'cat_index';
$categoryCondition = $this->getConnection()->quoteInto(
$alias.'.product_id=e.entity_id AND '.$alias.'.store_id=? AND ',
$this->getStoreId()
);
$categoryCondition.= $alias.'.category_id IN ('.$categories.')';
$this->getSelect()->joinInner(
array($alias => $this->getTable('catalog/category_product_index')),
$categoryCondition,
array('position'=>'position')
);
$this->_categoryIndexJoined = true;
$this->_joinFields['position'] = array('table'=>$alias, 'field'=>'position' );
return $this;
}
}
When I'm using this filter alone it perform OR query on several categories.
When I combine this filter with prepareProductCollection of Mage_Catalog_Model_Layer
it somehow remove the filter effect.
How can I change the filter to AND and combine it with prepareProductCollection?
Thanks
Thanks
This code will allow you to filter by multiple categories but avoid completely killing performance if you had to perform multiple collection loads:
$iNumberFeaturedItems = 4;
$oCurrentCategory = Mage::registry('current_category');
$oFeaturedCategory = Mage::getModel('catalog/category')->getCollection()
->addAttributeToFilter('name','Featured')
->getFirstItem();
$aFeaturedCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect(array('name', 'price', 'small_image', 'url_key'), 'inner')
->addStoreFilter()
->addCategoryFilter($oFeaturedCategory)
->addCategoryIds();
The first step is to get a collection of products for one category (in this case, a Featured category). Next step is to get the IDs of the products, notice that this does NOT perform a load (ref Mage_Core_Model_Mysql4_Collection_Abstract::getAllIds())
$aFeaturedProdIds = $aFeaturedCollection->getAllIds();
shuffle($aFeaturedProdIds); //randomize the order of the featured products
Then get the IDs for a second category:
$aCurrentCatProdIds = $oCurrentCategory->getProductCollection()->getAllIds();
And intersect the arrays to find product IDs that exist in both categories:
$aMergedProdIds = array_intersect($aFeaturedProdIds,$aCurrentCatProdIds);
For this particular use case, we loop until we have sufficient intersecting products, traversing up the category tree until we find a large enough match (but stopping at root category!):
while(count($aMergedProdIds) < $iNumberFeaturedItems && $oCurrentCategory->getId() != Mage::app()->getStore()->getRootCategoryId()):
$oCurrentCategory = $oCurrentCategory->getParentCategory();
$aParentCatProdIds = $oCurrentCategory->getProductCollection()->getAllIds();
$aMergedProdIds = array_intersect($aFeaturedProdIds,$aParentCatProdIds);
endwhile;
Finally, filter our initial collection by the IDs of the intersecting products, and return.
$aFeaturedItems = $aFeaturedCollection->addIdFilter(array_slice($aMergedProdIds,0,$iNumberFeaturedItems))->getItems();
return $aFeaturedItems;
I am also working on this to no avail, it was available in magento 1.3 using the attribute filter with finset on the category_ids column, however this was moved into the index table from the entity table and now no longer works.
There is one possible solution, but requries an override function which I found here
But this solution is far from ideal.
I think that it will be enough to call addCategoryFilter() twice on your product collection - once for each category. I have not tested it though, so might be wrong.

Resources