I have my server working perfectly with Parse-server and heroku.
One of the things I'm missing is that I want one of my cloud code functions to be called at 1:00 am each day. Is there any way I can automate this? Maybe with Parse or with another service? I just need to call that method 1 time per day.
So after some research on Github and on npm packages I have found this one.
First you install node-schedule A cron-like and not-cron-like job scheduler for Node.
You can install it through Putty in your server with this command npm install node-schedule
After you install it successfully you can open your main.js file that you have your Cloud Code and paste the following code
var schedule = require('node-schedule');
var j = schedule.scheduleJob(' * * * * *', function(){
console.log('This console log will run every 5 minutes');
});
The meaning of the stars
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ |
│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
│ │ │ │ └───── month (1 - 12)
│ │ │ └────────── day of month (1 - 31)
│ │ └─────────────── hour (0 - 23)
│ └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)
So you can have the complete code running like this if you want it to run 5 seconds (to see if its working by replacing your cloud code)
var schedule = require('node-schedule');
var j = schedule.scheduleJob('*/5 * * * *', function(){
Parse.Cloud.define("averageStars", function(request, response) {
var query = new Parse.Query("Review");
query.equalTo("movie", request.params.movie);
query.find({
success: function(results) {
var sum = 0;
for (var i = 0; i < results.length; ++i) {
sum += results[i].get("stars");
}
response.success(sum / results.length);
},
error: function() {
response.error("movie lookup failed");
}
});
});
});
Useful links:
node schedule
Try this one and I'm waiting for your results!
Related
I am trying to load JSON data from Kafka into Clickhouse where the JSON contains some escape sequences. E.g:
:) SELECT JSONExtractRaw('{"message": "Hello \"to\" you!"}', 'message')
SELECT JSONExtractRaw('{"message": "Hello "to" you!"}', 'message')
┌─JSONExtractRaw('{"message": "Hello "to" you!"}', 'message')─┐
│ "Hello " │
└─────────────────────────────────────────────────────────────┘
It appears that prior to calling JSONExtractRaw, the input strings are unescaped, which produces invalid JSON. The unescaping seems to be reproducible with this minimal example:
:) SELECT 'Hello \"there\"'
SELECT 'Hello "there"'
┌─'Hello "there"'─┐
│ Hello "there" │
└─────────────────┘
I am wondering if it's possible to retain the original (escaped) representation of the input.
Thank you!
SELECT '{"message": "Hello \\"to\\" you!"}'
┌─'{"message": "Hello \\"to\\" you!"}'─┐
│ {"message": "Hello \"to\" you!"} │
└──────────────────────────────────────┘
Let's test your case without CLI to emulate the table filled by data coming outside:
echo '{"message": "Hello \"to\" you!"}' | clickhouse-client \
--password 12345 \
--query="INSERT INTO test.json_001 SELECT json FROM input('json String') FORMAT CSV"
create database test;
create table test.json_001 (json String) Engine=Memory;
Get required data:
clickhouse-client \
--password 12345 \
--query="SELECT JSONExtractRaw(json, 'message'), JSONExtractString(json, 'message') FROM test.json_001"
# result:
# "Hello \\"to\\" you!" Hello "to" you!
SELECT
JSONExtractRaw(json, 'message'),
JSONExtractString(json, 'message')
FROM test.json_001
/* result
┌─JSONExtractRaw(json, 'message')─┬─JSONExtractString(json, 'message')─┐
│ "Hello \"to\" you!" │ Hello "to" you! │
└─────────────────────────────────┴────────────────────────────────────┘
*/
It works as it should. I don't see any problems.
Using a POST on my front-end (React.js, with react-beautiful-dnd), I'm trying to update the position of the items a user has stored.
My strategy is to send over an updated index of IDs that are ordered in the specified position.
My Data (example, simplified)
┌────┬────────┬───────┐
│ id │ title │ index │ <── my "position"
├────┼────────┼───────┤
│ 1 │ Apple │ 4 │
│ 2 │ Banana │ 1 │
│ 3 │ Mango │ 3 │
│ 4 │ Kiwi │ 2 │
│ 5 │ Orange │ 0 │
└────┴────────┴───────┘
New positions array (anatomy)
$value: sorted ids ------> [3, 2, 5, 1, 4]
: : : : :
$key: new index will be… 0, 1, 2, 3, 4
The Code
The controller ingests an array that derives the new positions from the keys of the array. It loops then through the collection of given IDs and reassigns them the updated index.
public function reorder(Request $request) {
$newIndex = $request->newIndex;
$items = Item::whereIn('id', $newIndex)->get();
foreach ($newIndex as $key => $value) {
// TODO: check if $item->index needs to be rewritten at all
$item = $items->find($value);
$item->index = $key;
$item->save();
}
return response('Success', 200);
}
dd() of $request->input
array:1 [
"newIndex" => array:5 [
0 => 4
1 => 1
2 => 2
3 => 5
4 => 3
]
]
The problem
It seems… the code only works once? Did I miss something? The POST fires every time and the set array is accurate, so the issue is not on the frontend side of things.
I have a Julia code which runs for quite sometime. I want to run the code for 3 hours and then terminate it. Does anyone know what is the most efficient way to do this. Would appreciate any advice. Thanks
#async and #sync are really useful for coroutine type process control in Julia. You can start an async process that calls exit at a later point so as to terminate the entire program:
function killafterseconds(s)
#async begin
sleep(s)
println("terminating after $s seconds")
exit(0)
end
end
function countdown(n)
for t in n:-1:0
println(t)
sleep(1)
end
end
killafterseconds(10)
countdown(10000)
Here's a solution using threads. I'm just begginging coding in Julia so it's not high quality code, but it works. You first need to wrap your function as a Task, by using the #task macro, and then call runTask():
function runTask(origtask:: Task, timeoutms:: Int)
startTime = Dates.datetime2epochms(now())
function internal_task(taskFinished)
try
schedule(origtask)
yield()
wait(origtask)
if istaskdone(origtask)
taskFinished[] = true
Base.task_result(origtask)
else
throw(ErrorException("Task is not done even after wait() for it to finish - something is wrong"))
end
catch e
#warn "Error while processing task: $e"
taskFinished[] = true
missing
end
end
taskFinished = Threads.Atomic{Bool}(false)
thread = Threads.#spawn internal_task(taskFinished)
while !taskFinished[] && (Dates.datetime2epochms(now()) - startTime) < timeoutms
sleep(0.1)
end
if taskFinished[]
return fetch(thread)
end
# Task timeouted
origtask.exception = InterruptException()
return missing
end # function
The worst part of this code is active waiting using sleep(0.1). I guess I could get rid of it by spawning one more thread, so there would be 3 in total: one would execute the actual work from the origtask and after doing it would notify a condition, one would wait on the mentioned condition and another one would sleep for the timeout number of seconds and then notify the condition.
I recommend using Distributed to spawn your function as a new process and control it's time (I believe I have been answering similar question but I cannot find the answer).
Here is the code:
using Distributed
function run_with_timeout(timeout::Int,f::Function, wid::Int)
result = RemoteChannel(()->Channel{Tuple}(1));
#spawnat wid put!(result, (f(),myid()))
res = (:timeout, wid)
time_elapsed = 0.0
while time_elapsed < timeout && !isready(result)
sleep(0.5)
time_elapsed += 0.5
end
if !isready(result)
println("Timeout! at $wid")
else
res = take!(result)
end
return res
end
You can use it like this (please note how external packages are imported):
wid = addprocs(1)[1]
#everywhere using DataFrames
#everywhere function ff()
sleep(2)
#code fir making heavy computations
#this is the place to write whatever you need
return DataFrame(x=[1,2],y=[1,3])
end
Now let us run it. Note that the second returned value is the workerid to run computations (you might want to remove it):
julia> run_with_timeout(10,() ->(try;ff();catch ee;dump(ee);end ),wid)
(2×2 DataFrame
│ Row │ x │ y │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 1 │
│ 2 │ 2 │ 3 │, 2)
If we give our code only 1 sec to execute it will fail:
julia> run_with_timeout(1,() ->(try;ff();catch ee;dump(ee);end ),wid)
Timeout! at 2
(:timeout, 2)
Finally, since the timeout occured the process should be killed (otherwise it would continue to execute):
rmprocs(wid)
I am in requirement for solution where I have one Admin posts application for an Android app. I have placed a delete button for post. The requirement is that delete button must be shown for 5 minutes from time of posting.
Here is the ngif condition which I have used..
*ngIf="((((post.CreatedDate | date:'dd/MM/yyyy') == (PresentDate | date:'dd/MM/yyyy')) && ((post.CreatedDate | date:'HH') == (post.CreatedDate | date:'HH')))&&((post.CreatedDate | date:'mm')< (time)))"
Code in TS page for present time + 5 minutes
const d: Date = new Date();
this.PresentDate = d;
var x = new Date();
d.getHours(); // => 9
d.getMinutes(); // => 30
this.time = d.getMinutes() +5;
this.hours = d.getHours();
Please help with the solution
Long expression in html is not good practice.
*ngIf="canDeletePost(post)"
canDeletePost(post) {
return Date.now() - post.CreatedDate.getTime() < 5 * 60 * 1000;
}
If CreatedDate is Js date. 5 * 60 * 1000 - 5 min in milliseconds. Actually, have a method in ngIf is not good practice also.
Anyway, you don't need date pipe. Pipes is used for changing view.
I'm new to Jekyll and Liquid, and I've been trying to utilize a site that has 100+ pages, separated into 15 modules. I need the navigation to reflect only to related pages, but I'm stuck on how to do this efficiently. For example, a directory like:
animal-species/
├── _docs/
│ ├── mammals/
│ │ ├── mam-page01.md
│ │ └── mam-page02.md
│ ├── reptiles/
│ │ ├── rep-page01.md
│ │ └── rep-page02.md
Set in pages:
title: Mammals Overview
module: mammals
---
docs.yml:
- module: mammals
title: Section Title
docs:
- mam-page01
- mam-page02
- module: reptiles
title: Section Title
docs:
- rep-page01
- rep-page02
In my nav.html file I've tried sorting with {% for section in site.data.docs | where page.module == page.module %} or page.module == section.module with no luck. I've also tried creating nested collections with 3.7.0 and collections_dir:, also failing. Every page is available to each other in all navs:
navigation of site
How can I set the nav to only show same-module pages? I have 15 modules and with like some sort of global sorting without having to code for all sub-directories.
Thank you for your help/patience! I'm very green to this.
I've bypassed a collections directory and _config.yml restructure but adding additional variables to by assign output:
{% assign docs = site.data.docs[page.module] | map: 'docs' | join: ',' | split: ',' %}
{% for document in docs %}
{% assign dir = page.module | prepend: "/" | append: "/" %}
{% assign document_url = document | prepend: {{dir}} | append:"/" %}
{% if document_url == page.url %}
"Previous"/"Next" buttons will only link to items with the same module. A simple solution that took me forever to divine.