how to short my list time wise ascending/ descending order
i have array like this:
this.array= [
{name: A, time: 10:00am},
{name: b, time: 10:05am},
{name: c, time: 10:02am},
{name: e, time: 09:00am}
]
i want to show this array time wise acceding order like:
this.array= [
{name: e, time: 09:00am},
{name: A, time: 10:00am},
{name: c, time: 10:02am},
{name: b, time: 10:05am},
]
The best way would be to use MomentJS:
array= [
{'name': 'A', 'time': '10:00am'},
{'name': 'b', 'time': '10:05am'},
{'name': 'c', 'time': '10:02am'},
{'name': 'e', 'time': '09:00am'}
]
sorted = array.sort(function(a, b) {
aT = new moment(a.time, 'HH:mm:ss a');
bT = new moment(b.time, 'HH:mm:ss a');
return aT.isBefore(bT) ? -1 : bT.isBefore(aT) ? 1 : 0;
});
To get MomentJS do:
npm install --save moment
then use it:
import * as moment from 'moment';
See https://momentjs.com/docs/#/use-it/typescript/.
Related
I have v2.0 of Memgraph, seems like temporal types like duration can't be part of the wShortest aggregate function.
Here is my code:
MATCH (n) DETACH DELETE n;
CREATE
(storage {name: "storage", current_time: localtime("T11:00")}),
(tape {name: "tape"}),
(lto {name: "lto"}),
(archive1 {name: "archive1", opens: localtime("T10:00"), closes: localtime("T11:00")}),
(archive2 {name: "archive2", opens: localtime("T08:00"), closes: localtime("T10:00")}),
(archive3 {name: "archive3", opens: localtime("T13:00"), closes: localtime("T16:00")}),
(archive4 {name: "archive4", opens: localtime("T15:00"), closes: localtime("T19:00")}),
(storage)-[:Fetch {duration: duration("3H")}]->(tape),
(storage)-[:Fetch {duration: duration("1H")}]->(lto),
(tape)-[:Drive {duration: duration("2H")}]->(archive1),
(tape)-[:Drive {duration: duration("4H")}]->(archive2),
(lto)-[:Ride {duration: duration("5H")}]->(archive3),
(lto)-[:Ride {duration: duration("4H")}]->(archive)
;
Here is wShortest query:
MATCH (a {name: "storage"})-[edge_list *wShortest 10 (e, n | e.duration) fetch_time]->(b)
RETURN *;
The error that I get is Error: Query failed: Calculated weight must be numeric, got duration.
This was a bug that was fixed with Memgraph 2.1.0 release. In the changelog it says: Allow duration values to be used as weights in the Weighted Shortest Path query.
If I have an array of events that include a utc timestamp and event data like as follows:
[{utcts: , data: , ... ];
how would you use RxJS to "replay" those events with the correct time differentials between each item in the array? Assume the array is ordered by the utcts field so the first item has the lowest value.
here is a very basic set of data to get started:
var testdata = [
{utcts: 1, data: 'a'},
{utcts: 4, data: 'b'},
{utcts: 6, data: 'c'},
{utcts: 10, data: 'd'}
];
Assume the utcts is just the number of seconds from the start of replaying the event which starts at 0 seconds.
Use delayWhen to give you timed replay.
Since utcts given is relative (not absolute) time, don't need to refresh the timestamp inside the data object.
I have added a timestamp to the console log so we can see the elapsed output time.
Note the extra few milliseconds is typical of rxjs process time.
console.clear()
const testdata = [
{utcts: 1, data: 'a'},
{utcts: 4, data: 'b'},
{utcts: 6, data: 'c'},
{utcts: 10, data: 'd'}
];
const replayData = (data) => Rx.Observable.from(data)
.delayWhen(event => Rx.Observable.of(event).delay(event.utcts * 1000))
// Show replay items with output time (in milliseconds)
const start = new Date()
replayData(testdata)
.timestamp()
.subscribe(x => console.log(x.value, 'at', x.timestamp - start, 'ms'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>
Ref delayWhen, timestamp
This also works, arguably simpler, not sure which is best.
mergeMap() flattens the inner observable, which is necessary to apply the delay.
const replayData = (data) => Rx.Observable.from(data)
.mergeMap(event => Rx.Observable.of(event).delay(event.utcts * 1000))
Rough pseudo (comes out of my head directly without running to verify) might be something similar to
Observable.scan((acc, value) => ({
delay: delay === NaN ? value.utcts - delay,
value
}), { delay: NaN, value: null })
.mergeMap(({delay, value}) => Observable.from(value).delay(delay))
scan operator is similar to reduce, but emits intermediate values. Using that compute diff between times to get delay those values, then emit values per given delayed time. There are couple of other approaches could work in same way.
This should work in https://rxviz.com (copy-paste there):
const { delay, mergeMap } = RxOperators;
const { from, Observable, of } = Rx;
const testdata = [
{utcts: 0.2, data: 'a'},
{utcts: 2.0, data: 'b'},
{utcts: 2.8, data: 'c'},
{utcts: 4.0, data: 'd'}
];
from(testdata).pipe(
mergeMap(event => of(event).pipe(
delay(event.utcts * 1000)
))
)
I'm successfully getting data back through StreamBuilder and need to sort it. How can I sort a Map of my snapshot data by keys? Also, If you give an example of doing this my value that would help also. I think I want to do a SplayTreeMap, but if there is a better way please provide. Here is my dictionary...
{Vid2: {imageString: https://i.ytimg.com/vi/Amq-qlqbjYA/mqdefault.jpg, title: BLACKPINK - '마지막처럼 (AS IF IT'S YOUR LAST)' M/V, rank: 2, videoID: Amq-qlqbjYA}, Vid10: {imageString: https://i.ytimg.com/vi/KSH-FVVtTf0/mqdefault.jpg, title: EXO 엑소 'Monster' MV, rank: 10, videoID: KSH-FVVtTf0}, Vid6: {imageString: https://i.ytimg.com/vi/BVwAVbKYYeM/mqdefault.jpg, title: [MV] BTS(방탄소년단) _ DOPE(쩔어), rank: 6, videoID: BVwAVbKYYeM}, Vid3: {imageString: https://i.ytimg.com/vi/m8MfJg68oCs/mqdefault.jpg, title: [MV] BTS(방탄소년단) _ Boy In Luv(상남자), rank: 3, videoID: m8MfJg68oCs}, Vid4: {imageString: https://i.ytimg.com/vi/9pdj4iJD08s/mqdefault.jpg, title: BLACKPINK - '불장난 (PLAYING WITH FIRE)' M/V, rank: 4, videoID: 9pdj4iJD08s}, Vid1: {imageString: https://i.ytimg.com/vi/3s1jaFDrp5M/mqdefault.jpg, title: EPIK HIGH - 'BORN HATER' M/V, rank: 1, videoID: 3s1jaFDrp5M}, Vid8: {imageString: https://i.ytimg.com/vi/3QAcvc4Ysl0/mqdefault.jpg, title: LONNI - LA KPOP 2, rank: 8, videoID: 3QAcvc4Ysl0}, Vid5: {imageString: https://i.ytimg.com/vi/2ips2mM7Zqw/default.jpg, title: BIGBANG - 뱅뱅뱅 (BANG BANG BANG) M/V, rank: 5, videoID: 2ips2mM7Zqw}}
I would like to display it either by keys...
Vid1, Vid2, Vid3...
or by values like rank ie...
Vid1:rank "1", Vid2: rank "2", Vid3: rank "3"...
If the source is a map, this should do what you want:
final sorted = new SplayTreeMap<String,dynamic>.from(map, (a, b) => a.compareTo(b));
DartPad example
I have a large data set of rental listings that I want to generate the average price for each city based on the number of bedrooms. I have the following types of rows:
{( city: 'New York', num_bedrooms: 1, price: 1000.00 ),
( city: 'New York', num_bedrooms: 2, price: 2000.00 ),
( city: 'New York', num_bedrooms: 1, price: 2000.00 ),
( city: 'Chicago', num_bedrooms: 1, price: 4000.00 ),
( city: 'Chicago', num_bedrooms: 1, price: 1500.00 )}
Using Pig, I want to get results in the following format:
{( city: 'New York', 1: 1500.00, 2: 2000.00),
( city: 'Chicago', 1: 2750.00 )}
Alternatively, I could deal with this too:
{( city: 'New York', num_bedrooms: 1, price: 1500.00),
( city: 'New York', num_bedrooms: 2, price: 2000.00),
( city: 'Chicago', num_bedrooms: 1, price: 2750.00 )}
My plan is to create bar charts using this data with the number of bedrooms along the X axis, and the price on the Y axis for a given city. I have been able to group by city and number of bedrooms and then average that, but I don't know how to put the data in the format I want. So far this is what I have:
D = GROUP blah BY (city, num_bedrooms);
C = FOREACH D GENERATE blah.city, blah.num_bedrooms, AVG(blah.price);
However this causes the city and num_bedrooms to be repeated for each time they appear!
Input :
New York,1,1000.00
New York,2,2000.00
New York,1,2000.00
Chicago,1,4000.00
Chicago,1,1500.00
Approach 1 :
Pig Script :
rental_data = LOAD 'rental_data.csv' USING PigStorage(',') AS (city:chararray, num_bedrooms: long, price:double);
rental_data_grp_city = GROUP rental_data BY (city);
rental_kpi = FOREACH rental_data_grp_city {
one_bed_room = FILTER rental_data BY num_bedrooms==1;
two_bed_room = FILTER rental_data BY num_bedrooms==2;
GENERATE group AS city, AVG(one_bed_room.price) AS one_bed_price, AVG(two_bed_room.price) AS tow_bed_price;
};
Output : DUMP rental_kpi :
(Chicago,2750.0,)
(New York,1500.0,2000.0)
Approach 2 :
Pig Script :
rental_data = LOAD 'rental_data.csv' USING PigStorage(',') AS (city:chararray, num_bedrooms: long, price:double);
rental_data_grp_city = GROUP rental_data BY (city,num_bedrooms);
rental_kpi = FOREACH rental_data_grp_city {
prices_bag = rental_data.price;
GENERATE group.city AS city, group.num_bedrooms AS num_bedrooms, AVG(prices_bag) AS price;
}
Output : DUMP rental_kpi :
(Chicago,1,2750.0)
(New York,2,2000.0)
(New York,1,1500.0)
i have a list of file in this form:
base/images/graphs/one.png
base/images/tikz/two.png
base/refs/images/three.png
base/one.txt
base/chapters/two.txt
i would like to convert them to a nested dictionary of this sort:
{ "name": "base" , "contents":
[{"name": "images" , "contents":
[{"name": "graphs", "contents":[{"name":"one.png"}] },
{"name":"tikz", "contents":[{"name":"two.png"}]}
]
},
{"name": "refs", "contents":
[{"name":"images", "contents": [{"name":"three.png"}]}]
},
{"name":"one.txt", },
{"name": "chapters", "contents":[{"name":"two.txt"}]
]
}
trouble is, my attempted solution, given some input like images/datasetone/grapha.png" ,"images/datasetone/graphb.png" each one of them will end up in a different dictionary named "datasetone" however i'd like both to be in the same parent dictionary as they are in the same directory, how do i create this nested structure without duplicating parent dictionaries when there's more than one file in a common path?
here is what i had come up with and failed:
def path_to_tree(params):
start = {}
for item in params:
parts = item.split('/')
depth = len(parts)
if depth > 1:
if "contents" in start.keys():
start["contents"].append(create_base_dir(parts[0],parts[1:]))
else:
start ["contents"] = [create_base_dir(parts[0],parts[1:]) ]
else:
if "contents" in start.keys():
start["contents"].append(create_leaf(parts[0]))
else:
start["contents"] =[ create_leaf(parts[0]) ]
return start
def create_base_dir(base, parts):
l={}
if len(parts) >=1:
l["name"] = base
l["contents"] = [ create_base_dir(parts[0],parts[1:]) ]
elif len(parts)==0:
l = create_leaf(base)
return l
def create_leaf(base):
l={}
l["name"] = base
return l
b=["base/images/graphs/one.png","base/images/graphs/oneb.png","base/images/tikz/two.png","base/refs/images/three.png","base/one.txt","base/chapters/two.txt"]
d =path_to_tree(b)
from pprint import pprint
pprint(d)
In this example you can see we end up with as many dictionaries named "base" as there are files in the list, but only one is necessary, the subdirectories should be listed in the "contents" array.
This does not assume that all paths start with the same thing, so we need a list for it:
from pprint import pprint
def addBits2Tree( bits, tree ):
if len(bits) == 1:
tree.append( {'name':bits[0]} )
else:
for t in tree:
if t['name']==bits[0]:
addBits2Tree( bits[1:], t['contents'] )
return
newTree = []
addBits2Tree( bits[1:], newTree )
t = {'name':bits[0], 'contents':newTree}
tree.append( t )
def addPath2Tree( path, tree ):
bits = path.split("/")
addBits2Tree( bits, tree )
tree = []
for p in b:
print p
addPath2Tree( p, tree )
pprint(tree)
Which produces the following for your example path list:
[{'contents': [{'contents': [{'contents': [{'name': 'one.png'},
{'name': 'oneb.png'}],
'name': 'graphs'},
{'contents': [{'name': 'two.png'}],
'name': 'tikz'}],
'name': 'images'},
{'contents': [{'contents': [{'name': 'three.png'}],
'name': 'images'}],
'name': 'refs'},
{'name': 'one.txt'},
{'contents': [{'name': 'two.txt'}], 'name': 'chapters'}],
'name': 'base'}]
Omitting the redundant name tags, you can go on with :
import json
result = {}
records = ["base/images/graphs/one.png", "base/images/tikz/two.png",
"base/refs/images/three.png", "base/one.txt", "base/chapters/two.txt"]
recordsSplit = map(lambda x: x.split("/"), records)
for record in recordsSplit:
here = result
for item in record[:-1]:
if not item in here:
here[item] = {}
here = here[item]
if "###content###" not in here:
here["###content###"] = []
here["###content###"].append(record[-1])
print json.dumps(result, indent=4)
The # characters are used for uniqueness (there could be a folder which name was content in the hierarchy). Just run it and see the result.
EDIT : Fixed a few typos, added the output.