FeathersJS query using two $or but and'ed together - feathersjs

I'm trying to figure out how to generate the following SQL condition using Feather's REST query:
(color = 'blue' OR color = 'green') AND (sport = 'hockey' or sport = 'football')
This is what I've tried (based on the documentation):
?$or[0][color][$eq]=blue&$or[1][color][$eq]=green&$or[2][sport][$eq]=hockey&$or[3][sport][$eq]=football
But this generates the following:
((color = 'blue') OR (color = 'green') OR (sport = 'hockey') or (sport = 'football'))
I've tried different combinations and even nested $or statements but I cannot seem to wrap my head around it. Is this even possible in FeathersJS? Any suggestions would be greatly appreciated.

You can restructure this using $in.
// Object
{
color: {
$in: ['blue', 'green']
},
sport: {
$in: ['hockey', 'football']
}
}
// String: ?color[$in][0]=blue&color[$in][1]=green&sport[$in][0]=hockey&sport[$in][1]=football
which generates:
WHERE color IN ('blue', 'green') AND sport IN ('hockey', 'football')

Related

TypeORM conditional querying many to many relations

Let's say I've a colors table and an items table, with a #ManyToMany relation between these 2 tables (an item can have many colors and a color can have many items).
Using TypeORM, I would like to get all items that match only one or more provided colors.
If an item has an additional color that is not specified in the query, it should not be retrieved.
const matchingColors = ['green', 'blue'];
const query = await this.itemRepository
.createQueryBuilder('item')
.innerJoin('item.colors', 'color', 'color.name IN (:...matchingColors)', { matchingColors })
.getMany();
In my example above I would like to get all items that match the matchingColors array, so all items that have green, or blue, or green and blue color(s). So if an item has the blue and red colors, or only red (or no color), it should be excluded from the results.
Currently, I didn't find a proper way to do it. The query in my example above doesn't work correctly. My dream is to make it work using only 1 SQL query. Thanks for your help!
Try this:
const matchingColors = ['green', 'blue'];
const items = await this.itemRepository
.createQueryBuilder('item')
.innerJoinAndSelect(
'item.colors',
'color',
'"color"."name" IN (:...matchingColors)',
{ matchingColors }
)
.getMany();

How to add legend for a bar chart with different colors in dc.js?

Below is the code snippet for a barchart with colored bars:
var Dim2 = ndx.dimension(function(d){return [d.SNo, d.something ]});
var Group2 = Dim2.group().reduceSum(function(d){ return d.someId; });
var someColors = d3.scale.ordinal().domain(["a1","a2","a3","a4","a5","a6","a7","a8"])
.range(["#2980B9","#00FFFF","#008000","#FFC300","#FF5733","#D1AEF1","#C0C0C0","#000000"]);
barChart2
.height(250)
.width(1000)
.brushOn(false)
.mouseZoomable(true)
.x(d3.scale.linear().domain([600,800]))
.elasticY(false)
.dimension(Dim2)
.group(Group2)
.keyAccessor(function(d){ return d.key[0]; })
.valueAccessor(function(d){return d.value; })
.colors(someColors)
.colorAccessor(function(d){return d.key[1]; });
How do I add a legend to this chart?
Using composite keys in crossfilter is really tricky, and I don't recommend it unless you really need it.
Crossfilter only understands scalars, so even though you can produce dimension and group keys which are arrays, and retrieve them correctly, crossfilter is going to coerce those arrays to strings, and that can cause trouble.
Here, what is happening is that Group2.all() iterates over your data in string order, so you get keys in the order
[1, "a1"], [10, "a3"], [11, "a4"], [12, "a5"], [2, "a3"], ...
Without changing the shape of your data, one way around this is to sort the data in your legendables function:
barChart2.legendables = function() {
return Group2.all().sort((a,b) => a.key[0] - b.key[0])
.map(function(kv) {
return {
chart: barChart2,
name: kv.key[1],
color: barChart2.colors()(kv.key[1]) }; }) };
An unrelated problem is that dc.js takes the X domain very literally, so even though [1,12] contains all the values, the last bar was not shown because the right side ends right at 12 and the bar is drawn between 12 and 13.
So:
.x(d3.scale.linear().domain([1,13]))
Now the legend matches the data!
Fork of your fiddle (also with dc.css).
EDIT: Of course, you want the legend items unique, too. You can define uniq like this:
function uniq(a, kf) {
var seen = [];
return a.filter(x => seen[kf(x)] ? false : (seen[kf(x)] = true));
}
Adding a step to legendables:
barChart2.legendables = function() {
var vals = uniq(Group2.all(), kv => kv.key[1]),
sorted = vals.sort((a,b) => a.key[1] > b.key[1] ? 1 : -1);
// or in X order: sorted = vals.sort((a,b) => a.key[0] - b.key[0]);
return sorted.map(function(kv) {
return {
chart: barChart2,
name: kv.key[1],
color: barChart2.colors()(kv.key[1]) }; }) };
Note that we're sorting by the string value of d.something which lands in key[1]. As shown in the comment, sorting by x order (d.SNo, key[0]) is possible too. I wouldn't recommend sorting by y since that's a reduceSum.
Result, sorted and uniq'd:
New fiddle.

python color entire pandas dataframe rows based on column values

I have a script that downloads a .csv and does some manipulation and then emails panda dataframes in a nice html format by using df.to_html.
I would like to enhance these tables by highlighting, or coloring, different rows based on their text value in a specific column.
I tried using pandas styler which appears to work however I can not convert that to html using to_html. I get a "AttributeError: 'str' object has no attribute 'to_html"
Is there a another way to do this?
As an example lets say my DF looks like the following and I want to highlight all rows for each manufacturer. i.e Use three different colors for Ford, Chevy, and Dodge:
Year Color Manufacturer
2011 Red Ford
2010 Yellow Ford
2000 Blue Chevy
1983 Orange Dodge
I noticed I can pass formatters into to_html but it appears that it cannot do what I am trying to accomplish by coloring? I would like to be able to do something like:
def colorred():
return ['background-color: red']
def color_row(value):
if value is "Ford":
result = colorred()
return result
df1.to_html("test.html", escape=False, formatters={"Manufacturer": color_row})
Surprised this has never been answered as looking back at it I do not believe this is even possible with to_html formatters. After revisiting this several times I have found a very nice solution I am happy with. I have not seen anything close to this online so I hope this helps someone else.
d = {'Year' : [2011, 2010, 2000, 1983],
'Color' : ['Red', 'Yellow', 'Blue', 'Orange'],
'Manufacturer' : ['Ford', 'Ford', 'Chevy', 'Dodge']}
df =pd.DataFrame(d)
print (df)
def color_rows(s):
df = s.copy()
#Key:Value dictionary of Column Name:Color
color_map = {}
#Unqiue Column values
manufacturers = df['Manufacturer'].unique()
colors_to_use = ['background-color: #ABB2B9', 'background-color: #EDBB99', 'background-color: #ABEBC6',
'background-color: #AED6F1']
#Loop over our column values and associate one color to each
for manufacturer in manufacturers:
color_map[manufacturer] = colors_to_use[0]
colors_to_use.pop(0)
for index, row in df.iterrows():
if row['Manufacturer'] in manufacturers:
manufacturer = row['Manufacturer']
#Get the color to use based on this rows Manufacturers value
my_color = color_map[manufacturer]
#Update the row using loc
df.loc[index,:] = my_color
else:
df.loc[index,:] = 'background-color: '
return df
df.style.apply(color_rows, axis=None)
Output:
Pandas row coloring
Since I do not have the cred to embed images here is how I email it. I convert it to html with the following.
styled = df.style.apply(color_rows, axis=None).set_table_styles(
[{'selector': '.row_heading',
'props': [('display', 'none')]},
{'selector': '.blank.level0',
'props': [('display', 'none')]}])
html = (styled.render())

changing bar fill colours in ssrs chart

SO Post
Current I've got 5 bars in my RS chart - in the future there might be 7 bars or 17 bars or 27 bars!
With a couple of bars I can have an expression like this:
=iif(Fields!Market.Value = "Spain"
,"Gold"
,iif (Fields!Market.Value = "Denmark"
, "Gray"
, iif(Fields!Market.Value = "Italy"
, "Blue"
, "Purple"
)
)
)
If I can't predict how many countries will be included + I'd rather not have to hard code in "Green", "Red" etc how do I change the expression?
I've tried this but it is erroring:
=Switch(Mod(Fields!Rank.Value/CDbl(2))=CDbl(0), "Gold",
Mod(Fields!Rank.Value/CDbl(3))=CDbl(0), "Gray",
Mod(Fields!Rank.Value/CDbl(2))>CDbl(0) "Blue")
Above is the totally incorrect syntax: This works:
=Switch(CDbl(Fields!Rank.Value Mod 2)=CDbl(0), "Gold",
CDbl(Fields!Rank.Value Mod 3)=CDbl(0), "Gray",
CDbl(Fields!Rank.Value Mod 2)>CDbl(0), "Blue")
Ok - the above runs (not sure how!) but the below is based on help from Dominic Goulet and is really easy to follow and nice and expandable to more colours; this is the solution for 5 colours:
=Switch(CDbl(Fields!Rank.Value Mod 5)=CDbl(0), "Gold",
CDbl(Fields!Rank.Value Mod 5)=CDbl(1), "Gray",
CDbl(Fields!Rank.Value Mod 5)=CDbl(2), "Green",
CDbl(Fields!Rank.Value Mod 5)=CDbl(3), "Red",
CDbl(Fields!Rank.Value Mod 5)=CDbl(4), "Pink")
First of all, instead of using many "IIF"s, you should use "Switch", it's leaner that way.
Switch(Fields!Market.Value = "Spain", "Gold",
Fields!Market.Value = "Denmark", "Gray",
Fields!Market.Value = "Italy", "Blue")
Now if you want a color per coutry, you should defenitely store that in your database and pull it out when you need it. That way, a country will always have the same color on every report you have.
It would be better to create a function. For that, go to Report Properties, choose code and type this example :
Public Function Color(ByVal Index as Integer) as String
Select Case Index
Case = 1
return "#a6cee3"
Case = 2
return "#1f78b4"
Case = 3
return "#b2df8a"
Case = 4
return "#33a02c"
Case = 5
return "#fb9a99"
Case = 6
return "#e31a1c"
Case = 7
return "#fdbf6f"
Case = 8
return "#ff7f00"
Case = 9
return "#cab2d6"
Case = 10
return "#6a3d9a"
End Select
End Function
On the Fill option from "Series Properties->Pick color-> Color choose fx
put this code
=Code.Color(rownumber(nothing))
Each bar will have a color.
For the HEX colors I took from the website : http://colorbrewer2.org/#type=qualitative&scheme=Paired&n=10
It shows the best colors that match with each other, so you don't need to think of that. And you can add as many colors as you want

IsNull inside Sum statement in Linq to Sql

I'm trying to change some SQL into Linq-to-Sql, however I have the following line in SQL that I'm not sure how to convert:
SUM(Quantity * IsNull(ExchangeRate,1) * Factor )
So I've so far written the grouping Linq as follows:
var items = from item in _dataContext.GetTable<Trade>()
group item by new {item.Curve}
into grp
select new Model.Position
{
Curve = grp.Key.Curve,
Value = ... "That line here"
};
return item
I've thought of using the let keyword, and tried using grp.Sum have struggled as there's the IsNull in the query.
Any help converting this query would be greatly appreciated!
Richard
Typing blind (without intellisense :D) but the following should work:
var items = from item in _dataContext.GetTable<Trade>()
group item by new { item.Curve } into grp
select new Model.Position
{
Curve = grp.Key.Curve,
Value = grp.Sum(i => i.Quantity * (i.ExchangeRate.HasValue ? i.ExchangeRate.Value : 1) * i.Factor)
};