postgres data to dashing - sinatra

Is it possible to send data contained in postgres to dashing dashboard? I have found mysql example here and same question here.
I edited my job in jobs folder. I have also included pg gem.
require 'pg'
conn = PGconn.new(:host => "10.10.8.10", :port => "5432",:dbname => "db1",:login => "test",:password => "test")
results = conn.exec("select partner,sitetype from test")
# Sending to List widget, so map to :label and :value
acctitems = results.map do |row|
row = {
:label => row['partner'],
:value => row['sitetype']
}
end
# Update the List widget
send_event('account_count', { items: acctitems } )
end

Include in Gemfile :
gem 'pg'
In your jobs.rb file:
require 'pg'
SCHEDULER.every '3m', :first_in => 0 do |job|
conn = PGconn.new(:host => "localhost", :port => "5432",:dbname => "dbname",:user => "test",:password => "test")
results = conn.exec("select partner,sitetype from test")
# Sending to List widget, so map to :label and :value
acctitems = results.map do |row|
row = {
:label => row['partner'],
:value => row['sitetype']
}
end
# Update the List widget
send_event('account_count', { items: acctitems } )
end

Related

Stringify Struct in Perl

In my program, I have a section of code that updates a list box depending on the value of another list box.
The code that does this looks a little like this.
$listBox1->bind('<<ListboxSelect>>' => sub {
$listBox2->delete(0, 'end');
for(#{$hashOfArraysOfStruct{$listBox1->get($listBox1->curselection)}}) {
$listBox2->insert('end', $_->name);
}
});
This works fine. However, I have found it easier to simply use a list and manipulate the list on the <<ListboxSelect>>. I have bound this list to the list box using -listvariable.
The code to do this looks a bit like
$listBox1->bind('<<ListboxSelect>>' => sub {
#updateableList = #{$hashOfArraysOfStruct{$listBox1->get($listBox1->curselection)}};
});
The problem with this approach is, as hashOfArraysOfStruct, contains structures, the list box contains values such as MyStruct=HASH(0x31d7e3c).
Is there any way to display the name variable of the struct MyStruct without looping through the whole array and individually inserting each result into the list box?
MCVE
use strict;
use warnings;
use Tk;
use Class::Struct;
struct MyStruct => {
name => '$',
group => '$'
};
my %hashOfArraysOfStruct = (
A => [
MyStruct->new(name => 'Phil', group => 'A'),
MyStruct->new(name => 'Ian', group => 'A'),
MyStruct->new(name => 'George', group => 'A')
],
B => [
MyStruct->new(name => 'Mac', group => 'B'),
MyStruct->new(name => 'Will', group => 'B')
],
C => [
MyStruct->new(name => 'Cath', group => 'C'),
MyStruct->new(name => 'Thom', group => 'C'),
MyStruct->new(name => 'Richard', group => 'C'),
MyStruct->new(name => 'Paul', group => 'C'),
MyStruct->new(name => 'Nick', group => 'C')
]
);
my $mainWindow = MainWindow->new();
my #listOne = sort(keys %hashOfArraysOfStruct);
############################################
#Route One
#Less efficient as has to loop through all the values
#But it displays the name variable of MyStruct
my $listBox1 = $mainWindow->Scrolled("Listbox", -scrollbars => "osoe", -selectmode => "single", -listvariable => \#listOne)->pack;
my $listBox2 = $mainWindow->Scrolled("Listbox", -scrollbars => "osoe", -selectmode => "single")->pack;
$listBox1->bind('<<ListboxSelect>>' => sub {
$listBox2->delete(0, 'end');
for(#{$hashOfArraysOfStruct{$listBox1->get($listBox1->curselection)}}) {
$listBox2->insert('end', $_->name);
}
});
############################################
############################################
#Route Two
#Works but displays in the form of MyStruct=HASH(0x31d7e3c)
#my #updateableList;
#my $listBox1 = $mainWindow->Scrolled("Listbox", -scrollbars => "osoe", -selectmode => "single", -listvariable => \#listOne)->pack;
#my $listBox2 = $mainWindow->Scrolled("Listbox", -scrollbars => "osoe", -selectmode => "single", -listvariable => \#updateableList)->pack;
#$listBox1->bind('<<ListboxSelect>>' => sub {
# #updateableList = #{$hashOfArraysOfStruct{$listBox1->get($listBox1->curselection)}};
#});
############################################
############################################
#What I would like to happen
#I would like to use route two but when the struct is displayed
#in the list box, instead of being in Route Twos format, it should
#display the name variable of MyStruct.
############################################
MainLoop;
Massive Edit
Change
#updateableList = #{$hashOfArraysOfStruct{$listBox1->get($listBox1->curselection)}};
to
#updateableList = map { $_->name() } #{$hashOfArraysOfStruct{$listBox1->get($listBox1->curselection)}};
To extract the list of names from the list of structs;

Upload scorm packages in moodle course module using moodle rest api

I have already created a course using moodle RestAPI(function name : core_course_create_courses). then i want to upload a scorm package in moodle course module/activity.
i have write some code for that,this code will create a module in that course. i don't know how to upload scorm package in that course module.
here is my code
Add function core_course_create_modules in lib/db/services.php at line no : 327
'core_course_create_modules' => array(
'classname' => 'core_course_external',
'methodname' => 'create_modules',
'classpath' => 'course/externallib.php',
'description' => 'Creates modules in a course',
'type' => 'write',
'capabilities' => 'moodle/course:manageactivities',
)
Add 3 method in Courses/externallib.php file
2.1)create_modules_parameters
=> `public static function create_modules_parameters() {
$courseconfig = get_config('moodlecourse'); //needed for many default values
return new external_function_parameters(
array(
'courseid' => new external_value(PARAM_INT, 'ID of the course'),
'modules' => new external_multiple_structure(
new external_single_structure(
array(
'modulename' => new external_value(PARAM_TEXT, 'Name of the module'),
'section' => new external_value(PARAM_INT, 'Sectionnumber'),
'name' => new external_value(PARAM_TEXT, "Title of the module", VALUE_OPTIONAL),
'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
'description' => new external_value(PARAM_TEXT, 'the new module description', VALUE_OPTIONAL),
'descriptionformat' => new external_format_value(PARAM_INT, 'description', VALUE_DEFAULT),
'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_DEFAULT, $courseconfig->groupmode),
'groupmembersonly' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_DEFAULT, 0),
'groupingid' => new external_value(PARAM_INT, 'grouping id',VALUE_DEFAULT, 0)
)
)
)
)
);
}`
2.2) create_modules
`public static function create_modules($courseid, $modules) {
global $CFG, $DB;
require_once($CFG->dirroot . "/course/lib.php");
require_once($CFG->dirroot . "/course/modlib.php");
$moduleinfo = new stdClass();
$course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
// Clean the parameters.
$params = self::validate_parameters(self::create_modules_parameters(), array('courseid' => $courseid,'modules' => $modules));
$context = context_course::instance($course->id);
require_capability('moodle/course:manageactivities', $context);
foreach ($params['modules'] as $mod) {
$module = (object) $mod;
$moduleobject = $DB->get_record('modules', array('name'=>$module->modulename), '*', MUST_EXIST);
if(trim($module->modulename) == ''){
throw new invalid_parameter_exception('Invalid module name');
}
if (!course_allowed_module($course, $module->modulename)){
throw new invalid_parameter_exception('Module "'.$module->modulename.'" is disabled');
}
if(is_null($module->visible)){
$module->visible = 1;
}
if(is_null($module->description)){
$module->description = '';
}
if(!is_null($module->name) && trim($module->name) != ''){
$moduleinfo->name = $module->name;
}
$moduleinfo->modulename = $module->modulename;
$moduleinfo->visible = $module->visible;
$moduleinfo->course = $courseid;
$moduleinfo->section = $module->section;
$moduleinfo->introeditor = array('text' => $module->description, 'format' => $module->descriptionformat, 'itemid' => 0);
$moduleinfo->quizpassword = '';
$moduleinfo->groupmode = $module->groupmode;
$moduleinfo->groupmembersonly = $module->groupmembersonly;
$moduleinfo->groupingid = $module->groupingid;
$retVal = create_module($moduleinfo);
$result[] = array('id'=>$retVal->id);
}
return $result;
}`
2.3)create_modules_returns
`public static function create_modules_returns() {
return new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_INT, 'new module id')
)
)
);
}`
Parameters to call function
$module['courseid'] = 1; //course id
$module['modules'][] = array(
"section" => 2,//PARAM_INT, 'Sectionnumber'
"modulename" => "scorm",//PARAM_TEXT, 'Name of the module'
"name" => "Testing1",// OPTIONAL PARAM_TEXT, "Title of the module",
"visible" => 1,// OPTIONAL PARAM_INT, '1: available to student, 0:not available',
"description"=>"testing module using rest api", // OPTIONAL PARAM_TEXT, 'the new module description',
"descriptionformat"=>1,//PARAM_INT, 'description', VALUE_DEFAULT
//"groupmode" => "",//PARAM_INT, 'no group, separate, visible', VALUE_DEFAULT, $courseconfig->groupmode
//"groupmembersonly" => "",//PARAM_INT, '1: yes, 0: no', VALUE_DEFAULT, 0
//"groupingid" => "",//PARAM_INT, 'grouping id',VALUE_DEFAULT, 0
);
as per above code ,
its take name field as a scorm packages, in the admin side its display name as a scorm, when i was click on that its display errors:
screenshot for error
so, i don't know how to upload scorm package in course module using moodle Rest api, how can i do ?
Thank you.

pg_search_scope: chaining scopes seems impossible

I have a search form for searching "documents", that have a small dozen of search criterions, including "entire_text", "keywords" and "description".
I'm using pg_search_scope, but I have 2 different scopes.
This is in my document.rb:
pg_search_scope :search_entire_text,
:against => :entire_text,
:using => {
:tsearch => {
:prefix => true,
:dictionary => "french"
}
}
pg_search_scope :search_keywords,
:associated_against => {
:keywords => [:keyword]
},
:using => {
:tsearch => {
:any_word => true
}
}
Each separately works fine. But I can't do this:
#resultats = Document.search_keywords(params[:ch_document][:keywords]).search_entire_text(params[:ch_document][:entire_text])
Is there any way to work around this?
Thanks
I've never used pg_search_scope but it looks like you indeed can't combine two pg_search_scope's.
What you could do is use :search_entire_text with a pg_search_scope and use the resulting id's in a Document.where([1,2,3]) that way you can use standard rails scope's for the remaining keyword searches.
Example:
# If pluck doesn't work you can also use map(&:id)
txt_res_ids = Document.search_entire_text(params[:ch_document][:entire_text]).pluck(:id)
final_results = Document.where(id: txt_res_ids).some_keyword_scope.all
It works. Here's the entire code ... if ever this could help someone :
Acte.rb (I didn't translate to english, the explanations are commented to correspond to the question above)
pg_search_scope :cherche_texte_complet, #i.e. find entire text
:against => :texte_complet,
:using => {
:tsearch => {
:prefix => true,
:dictionary => "french"
}
}
pg_search_scope :cherche_mots_clefs, #find keywords
:associated_against => {
:motclefs => [:motcle]
},
:using => {
:tsearch => {
:any_word => true
}
}
def self.cherche_date(debut, fin) #find date between
where("acte_date BETWEEN :date_debut AND :date_fin", {date_debut: debut, date_fin: fin})
end
def self.cherche_mots(mots)
if mots.present? #the if ... else is necessary, see controller.rb
cherche_mots_clefs(mots)
else
order("id DESC")
end
end
def self.ids_texte_compl(ids)
if ids.any?
where("id = any (array #{ids})")
else
where("id IS NOT NULL")
end
end
and actes_controller.rb
ids = Acte.cherche_texte_complet(params[:ch_acte][:texte_complet]).pluck(:id)
#resultats = Acte.cherche_date(params[:ch_acte][:date_debut],params[:ch_acte][:date_fin])
.ids_texte_compl(ids)
.cherche_mots(params[:ch_acte][:mots])
Thanks !
chaining works in pg_search 2.3.2 at least
SomeModel.pg_search_based_scope("abc").pg_search_based_scope("xyz")

How do I set the HTTP User-Agent when using Search::Elasticsearch?

I'm using Search::Elasticsearch to query MetaCPAN.
my $es = Search::Elasticsearch->new(
cxn_pool => 'Static::NoPing',
nodes => 'api.metacpan.org:80',
);
my $scroller = $es->scroll_helper(
index => 'v0',
type => 'release',
search_type => 'scan',
scroll => '2m',
size => $size,
body => {
fields => [qw(author archive date)],
query => { range => { date => { gte => $date } } },
},
);
This works ok, but I'd like to set the HTTP User-Agent header to a custom value so my requests can be identified if there's a problem. How do I do that with Search::Elasticsearch?
You can pass arguments to the handle constructor using handle_args. So for the default HTTP::Tiny you would use agent:
my $es = Search::Elasticsearch->new(
cxn_pool => 'Static::NoPing',
nodes => 'api.metacpan.org:80',
handle_args => { agent => "youragent/0.1" },
);

OR operator in Mongo 'update' $criteria

I want to check for an existing record by matching either title or url fields. If either one matches, update that record. Otherwise, insert.
How do write the following properly (using Mongoid in Ruby):
articles.update(
{ **:title => story.title OR :url => story.url** },
{ :title => story.title, :url => story.url, :source => story.source, :last_updated => Time.now },
{ :upsert => true } )
Thanks!
You need do the request and update it like :
'''
articles.any_of({:title => xxx}, {:url => yyyy}).update( :foo => 'bar')
'''