ractivejs list sorting , ascending decending support? - ractivejs

Im trying to understand if there is a feature in ractivejs , for descending sorting , and ascending .
I couldnt find anyhting in the documentation .

No - Ractive purposely avoids being a 'kitchen sink' utility library. But it's very easy to add an ascending or descending helper:
var helpers = Ractive.defaults.data;
// assuming a and b are numbers...
helpers.ascending = function ( a, b ) {
return a - b;
};
helpers.descending = function ( a, b ) {
return b - a;
};
ractive = new Ractive({
el: 'body',
template: '' +
'<p>ascending: {{ numbers.slice().sort(ascending) }}</p>' +
'<p>descending: {{ numbers.slice().sort(descending) }}</p>'
},
data: {
numbers: [ 9, 4, 6, 2, 4, 1, 10, 2, 7, 8 ]
}
});
Note that you could also put the ascending and descending functions directly on the data object, if that's preferable.
Here's a JSFiddle to demonstrate: http://jsfiddle.net/rich_harris/nszt3150/

Related

(Godot Engine) How do I know which exported enum flags are enabled in script

By using the Godot engine and writing in the GDScript language,
let's say I have an enum declared as:
enum eTextMode {CHAR, NUMBER, SYMBOLS_TEXT, SYMBOLS_ALL}
And an export variable as:
export(eTextMode, FLAGS) var _id: int = 0
In the inspector panel I can see which flag is selected or not, but how can I know in code which specifically flag is selected?
By selecting in the inspector, for example: the NUMBER and SYMBOLS_TEXT flags, the _id variable will be set as 5
My approach is the following hard-coded dictionary:
var _selected_flags: Dictionary = {
CHAR = _id in [1, 3, 5, 7, 9, 11, 13, 15],
NUMBER = _id in [2, 3, 6, 7, 10, 11, 14, 15],
SYMBOLS_TEXT = _id in [4, 5, 6, 7, 12, 13, 14, 15],
SYMBOLS_ALL = _id in [8, 9, 10, 11, 12, 13, 14, 15]
}
Resulting in:
{CHAR:True, NUMBER:False, SYMBOLS_ALL:False, SYMBOLS_TEXT:True}
The above result is exactly what I'm expecting (a dictionary with string keys as they are defined in the enum with a boolean value representing the selection state).
How could I manage to do this dynamically for any enum regardless of size?
Thank you very much,
One tacky solution that I could manage is by not using an enum at all, but instead a dictionary like the following example:
const dTextMode: Dictionary = {CHAR = false, NUMBER = false, SYMBOLS_TEXT = false, SYMBOLS_ALL = false}
export(Dictionary) var m_dTextMode: Dictionary = dTextMode setget Set_TextMode, Get_TextMode
func Get_TextMode() -> Dictionary: return m_dTextMode
func Set_TextMode(_data: Dictionary = m_dTextMode) -> void: m_dTextMode = _data
An exported dictionary is not as good-looking as an exported enum with FLAGS, and by following this approach it kind of invalidates my initial problem.
By selecting CHAR and SYMBOLS_TEXT in the exported dictionary from the inspector, and then calling print(self.Get_TextMode()) the result is indeed what I expected:
{CHAR:True, NUMBER:False, SYMBOLS_ALL:False, SYMBOLS_TEXT:True}
I still can't figure out though how to achieve this result by using the export(*enum, FLAGS) aproach.
Edit: also, the setter function is not feasible to be used in script since the user must know to duplicate the dTextMode constant first, edit it and set is as an argument.
Thanks to the comments from #Thearot from my first answer, I have managed to figure out the following solution which meets all expectations, with one caveat: it seems like an overkill solution...
enum eTestFlags {FLAG_1, FLAG_2, FLAG_3, FLAG_5, FLAG_6}
export(eTestFlags, FLAGS) var m_iTestFlags: int = 0 setget Set_TestFlags
func Get_TestFlags() -> Dictionary: return self._get_enum_flags(m_iTestFlags, eTestFlags)
func Set_TestFlags(_id: int = m_iTestFlags) -> void: m_iTestFlags = _id
func _get_enum_flags(_val_selected: int, _enum: Dictionary, _bit_check_limit: int = 32) -> Dictionary:
var _enum_keys: Array = _enum.keys() ; _enum_keys.invert()
var _bin_string: String = ""
var _val_temp: int = 0
var _val_count: int = _bit_check_limit - int(_is_pow2(_bit_check_limit))
while(_val_count >= 0):
_val_temp = _val_selected >> _val_count
_bin_string += "1" if _val_temp & 1 else "0"
_val_count -= 1
var _bin_string_padded: String = "%0*d" % [_enum_keys.size(), int(_bin_string)]
var _result_dict: Dictionary = {}
for _str_id in range(_bin_string_padded.length(), 0, -1):
_result_dict[_enum_keys[_str_id - 1]] = bool(_bin_string_padded[_str_id - 1] == "1")
return _result_dict
func _is_pow2(_value: int) -> bool:
return _value && (not (_value & (_value - 1)))
Now, if I print(self.Get_TestFlags()) after selecting FLAG_2 and FLAG_6 the result is:
{FLAG_1:False, FLAG_2:True, FLAG_3:False, FLAG_5:False, FLAG_6:True}
You're on the right track but overcomplicating things. Without going too much into the math (see Wikipedia), here's what you'd do in Godot:
enum eTextMode {CHAR, NUMBER, SYMBOLS_TEXT, SYMBOLS_ALL}
export(eTextMode, FLAGS) var _id: int = 0
func _ready() -> void:
for modeName in eTextMode:
var bit_flag_value: int = int(pow(2, eTextMode[modeName]))
if _id & bit_flag_value:
printt("Flagged", modeName)
You can access the named fields of your enum like elements in an Array/Dictionary by default (iterate through the keys, get their 0-based index as values). The above math trick turns the 0-based index into the correct bit flag number, and if you (single) '&' it with the combined bit-flags value you can check whether or not that flag is set.

How can i get the values in eloquent relation array result of laravel 8

I have a result array from laravel8 relations. like below
$val = {
"q_id": 1,
"q_text": "1111",
"q_mandatory": 1,
"q_status": "unpublished",
"que_logic_relation": [
{
"ql_id": 1,
"ql_quest_id": 1,
"ql_answer_choice_id": null,
"ql_succeeding_q_order": 3,
},
{
"ql_id": 4,
"ql_quest_id": 1,
"ql_answer_choice_id": null,
"ql_succeeding_q_order": 3,
}
]
}
When I print $val['q_text'] // output 1111
when I print $val['que_logic_relation'] //no result or empty
I want to print the data in que_logic_relation seperately. How can I do that?
Issued fixed by adding toArray() to the query result and everything works fine now.

Updating map value for a specific key in Kotlin

I am new at Kotlin and trying to catch up the language.
I have a function that returns DayofWeek as a key and an Int as a value.
The issue that I am facing is that I need to take a list of object that has another list of object inside that has an Int value which I need to save and increment for every time I see the same value.
Here is my function -
class OrdersAnalyzer {
data class Order(val orderId: Int, val creationDate: LocalDateTime, val orderLines: List<OrderLine>)
data class OrderLine(val productId: Int, val name: String, val quantity: Int, val unitPrice: BigDecimal)
fun totalDailySales(orders: List<Order>) : Map<DayOfWeek, Int> {
val map: MutableMap<DayOfWeek, Int>? = mutableMapOf(
Pair(DayOfWeek.SUNDAY, 0),
Pair(DayOfWeek.MONDAY, 0),
Pair(DayOfWeek.TUESDAY, 0),
Pair(DayOfWeek.WEDNESDAY, 0),
Pair(DayOfWeek.THURSDAY, 0),
Pair(DayOfWeek.FRIDAY, 0),
Pair(DayOfWeek.SATURDAY, 0)
)
for (order in orders) {
val dayOfWeek = order.creationDate.dayOfWeek
var quantity = 0
map?.put(dayOfWeek, quantity)
}
return map!!
}
}
So the issues I am facing right now are 2 -
1) How can I increment the value of each pair when it is the corrent DayOfWeek? I don't want to replace, I want to add it to the last value.
2) When returning the Map, I do not want to return the DayOfWeeks that have the value of 0. How can I do that?
Here is a modified version of the elegant answer provided by Arjan, with some test code.
Updated the answer after the comment from Alon Shlider -- now counting all order item quantities grouped by day of the week:
fun totalDailySales(orders: List<Order>): Map<DayOfWeek, Int> =
orders.groupBy { it.creationDate.dayOfWeek }
.mapValues { sumItemQuantities(it.value) }
fun sumItemQuantities(orders: List<Order>) =
orders.flatMap { it.orderLines.map { line -> line.quantity } }.sum()
fun main() {
val orders = listOf(
Order(
1,
LocalDateTime.now().minusDays(2),
listOf(
OrderLine(6, "laptop", 28, 1200.toBigDecimal())
)
),
Order(
2,
LocalDateTime.now().minusDays(1),
listOf(
OrderLine(496, "VR headset", 6, 400.toBigDecimal())
)
)
)
println(totalDailySales(orders))
}
Output:
{FRIDAY=28, SATURDAY=6}
With this approach, Kotlin functions do the grouping and counting for you. The groupBy function creates a map from DayOfWeek to a list of orders (grouping all orders with the same day of week in a list). The mapValues function transforms that map by replacing the lists with the result of the sumItemQuantities function (for each list).
In the for loop in your code, you can retrieve the current quantity for a specific day (or use zero if it isn't set yet), increase it by the right amount and then store it. To return only the map entries with non zero values, you could filter (return totalsPerDay.filter { it.value > 0 }) or start with an empty map. This is your function with some changes:
fun totalDailySales(orders: List<Order>): Map<DayOfWeek, Int> {
val totalsPerDay = mutableMapOf<DayOfWeek, Int>()
for (order in orders) {
val dayOfWeek = order.creationDate.dayOfWeek
val currentQuantity = totalsPerDay[dayOfWeek] ?: 0
// This is not the best way to increment by the sum of the order
// item quantities...
val orderItemQuantities = sumItemQuantities(listOf(order))
totalsPerDay[dayOfWeek] = currentQuantity + orderItemQuantities
}
return totalsPerDay
}
Output after calling it:
println(OrdersAnalyzer().totalDailySales(orders))
{FRIDAY=28, SATURDAY=6}
Updated answer (also thanks to Freek de Bruijn), with some test code.
I think it would be something like this:
fun totalDailySales(orders: List<Order>) : Map<DayOfWeek, Int> =
orders.groupBy { it.creationDate.dayOfWeek }
.mapValues { it.value.flatMap { it.orderLines } }
.mapValues { it.value.map { it.quantity } }
.mapValues { it.value.sum() }
groupBy creates a Map where the values are of type List<Order>, so you need to call a few steps to convert these values to Int. First we use flatMap to convert List<Order> to List<OrderLine> (map would convert to List<List<OrderLine>>). Then we use map to get the quantities out of List<OrderLine>, and finally sum() to add up all those quantities.
val orders = listOf(
Order(
2,
LocalDateTime.now().minusDays(2),
listOf(
OrderLine(5, "monitor", 10, 200.toBigDecimal()),
OrderLine(4, "keyboard", 5, 50.toBigDecimal())
)
)
)
println(totalDailySales(orders))
This results in the output:
{FRIDAY=15}

Idiomatic `obj.value = f(obj)` in Ramda?

R.evolve lets us replace object properties with the result of a function applied to that property's current value:
R.evolve({ count: R.inc }, { count: 1 })
== { count: 2 }
But I frequently find I want to add a property calculated from multiple properties of input object:
assocFruitTotal({ appleCount: 5, orangeCount: 3 })
== { appleCount: 5, orangeCount: 3, fruitCount: 8 }
I came up with my own simple utility function:
const assocDerived = R.curry(
(name, f, obj) => ({
...obj,
[name]: f(obj)
});
... and I use it a lot:
const sumFruit = R.pipe(
R.props(['appleCount', 'orangeCount']),
R.sum);
const assocFruitTotal = assocDerived('fruitCount', sumFruit);
But the sheer frequency with which I use this makes me wonder why it's not
native to Ramda, as so many other convenient functions are. And that makes
me wonder whether I'm missing a better idiom that achieves the outcome -- that is, building up detail in an object by adding properties based upon combinations of other properties.
Is there an idiomatic functional programming construct I should be using instead?
Personally I would do it this way:
const fruitCount = applySpec({fruitCount: compose(sum, values)})
fruitCount({apple: 5, orange: 3})
//=> {"fruitCount": 8}
const withFruitCount = converge(mergeRight, [identity, fruitCount]);
withFruitCount({apple: 5, orange: 3});
//=> {"apple": 5, "fruitCount": 8, "orange": 3}
If there are non-count properties to exclude from the sum, you can use pickBy:
const pickCount = pickBy(flip(includes('Count')));
pickCount({appleCount: 5, orangeCount: 3, foo: 'bar'});
//=> {"appleCount": 5, "orangeCount": 3}
Let's start by recognizing that obj.value = f(obj) is a mutable assignment and therefore not a functional idiom to begin with. This is imperative-style thinking at work.
Storing a computed value as a property on your object is a misstep, in most cases. If either appleCount or orangeCount changes, there's nothing there to enforce the integrity of fruitCount.
fruitCount should be a function, not a property.
const fruitCount =
pipe
( props ([ 'appleCount', 'orangeCount' ])
, sum
)
fruitCount ({ appleCount: 1, orangeCount: 3 }) // 4
fruitCount ({ appleCount: 5, orangeCount: 3 }) // 8
If I had to guess, this is fake data and an example problem. In some scenarios, a computed value does make sense (memoisation is the first technique that comes to mind) but those cases make up the exception, not the rule. You say "the sheer frequency with which I use this ...", so I'd wager you do it in more areas than you should.
And as you pointed out, Ramda doesn't have a built-in for this, so this should further indicate that there are more conventional ways of solving this kind of problem.
An object-oriented programmer would assign this as a computed property -
const FruitData = function (apples = 0, oranges = 0)
{ this.apples = apples
this.oranges = oranges
}
Object.defineProperty
( FruitData.prototype
, 'fruitCount'
, { get () { return this.apples + this.oranges } }
)
const f =
new FruitData (3, 4)
console .log (f.fruitCount) // 7
When writing functional style, we leave OOP concepts at the door. Start thinking in terms of functions and your problems go away -
const FruitData = (apples = 0, oranges = 0) =>
({ apples, oranges })
const appleCount = fd =>
fd.apples
const orangeCount = fd =>
fd.oranges
const fruitCount = fd =>
appleCount (fd) + orangeCount (fd)
console .log (fruitCount (FruitData (10, 3))) // 13

Angular-Chart property to labels and value to data

I am trying to map a result to an angular-chart but am confused on how to map my labels and map my data. My service returns an object that looks like this:
Object {0: 5, 4: 1, 9: 1, 14: 2}
Question
How do I map my labels to the 0, 4, 9, 14 so that I can use it to put into a bar graph and data like below:
angular.module("app", ["chart.js"]).controller("BarCtrl", function ($scope) {
$scope.labels = ['0', '4', '9', '14'];
$scope.data = [
[5, 1, 1, 2]
];
});
Question 2 -- instead of using the numbers can I type in names for the labels?
I resolved this by mapping the value to an array.
var array = $.map($scope.count, function (value, index) {
return [value];
});
console.log(array);
Then using array on my chart.

Resources