Sikuli IDE can't import other script JRuby - jruby

I'm working with SikuliIDE 1.1.0
Script1:
#script 1
require 'java'
popup("hello, I am script1")
import 'script2'
reload(script2)
from script2 import *
myPop() # call function myPop in script2
script 2
# content of script2.sikuli
from sikuli import *
popup("hello I'm script2")
When I run script 1 I get the next error:
[error] NameError ( (NameError) cannot load Java class script2 )
[error] --- Traceback --- error source first line: class ( method ) file 1286: org.jruby.javasupport.JavaClass ( for_name ) org/jruby/javasupport/JavaClass.java 34: org.jruby.javasupport.JavaUtilities ( get_proxy_class ) org/jruby/javasupport/JavaUtilities.java 27: RUBY ( java_import ) file:/D:/Sikuli/sikulix.jar!/jruby/java/core_ext/object.rb 2412: org.jruby.RubyArray ( map ) org/jruby/RubyArray.java 22: RUBY ( java_import ) file:/D:/Sikuli/sikulix.jar!/jruby/java/core_ext/object.rb 5: RUBY ( (root) ) D:/sikuli scripts.sikuli [error] --- Traceback --- end --------------
Both scripts are stored in the same folder.
Can anyone help me with this?
Thanks.

okay, got it working with the change using "require 'd:\script2.sikuli\script2.rb'" i.s.o. the import.
But, it should also be working with an import somehow...

Related

How to create a mysql database in Django on the first run?

I'd like my application to be "plug-and-play", so I need to automatically create the database on the first run. I use docker with docker-compose
My attempt is to connect without specifying the database name and run a custom command before running the server:
command:
sh -c "python manage.py create_db &&
python manage.py runserver 0.0.0.0:8000"
And the command itself:
class Command(BaseCommand):
"""Django command to create DB"""
def handle(self, *args, **options):
con = connections['default']
db_name = os.environ.get('DB_NAME')
db_up = False
while not db_up:
try:
cursor = con.cursor()
cursor.execute(f'CREATE DATABASE IF NOT EXISTS {db_name}')
cursor.execute(f'USE {db_name}')
db_up = True
except Exception as err:
self.stdout.write('Database unavailable, waiting 1 second...')
self.stdout.write(str(err))
time.sleep(1)
self.stdout.write(self.style.SUCCESS('Database available!'))
If this is the right way, then now I just need to update the connection to use the newly created database, but I don't know how. The line cursor.execute(f'USE {db_name}') of course doesn't work.
Is it the right way to create the database?
If so, how to update the connection?
If not, how to do it?
Thanks!
EDIT
After hints from Nealium, I created an independent script (not a Django command) which I run before running the server.
import os
import time
from MySQLdb import _mysql
import os
db_host=os.environ.get('DB_HOST')
db_user=os.environ.get('DB_USER')
db_password=os.environ.get('DB_PASS')
db_name = os.environ.get('DB_NAME')
db_up = False
while not db_up:
try:
db = _mysql.connect(
host=db_host,
user=db_user,
password=db_password
)
db_up = True
db.query(f'CREATE DATABASE IF NOT EXISTS {db_name}')
db.close()
except Exception as err:
print('Database unavailable, waiting 1 second...')
time.sleep(1)
print('Database available!')
This what my management command generally looks like
call_command() basically does python manage.py {command}
Updated dothing command
from django.core.management.base import BaseCommand
from django.core.management import call_command
def create_db():
import mysql.connector
try:
mydb = mysql.connector.connect(
host=os.environ.get('DB_HOST'),
user=os.environ.get('DB_USER'),
password=os.environ.get('DB_PASS')
)
mycursor = mydb.cursor()
mycursor.execute('CREATE DATABASE IF NOT EXISTS {0}'.format(os.environ.get('DB_NAME')))
return True
except mysql.connector.Error as err:
print('Something went wrong: {}'.format(err))
except Exception as ex:
message("Exception: {}".format(ex))
return False
class Command(BaseCommand):
help = 'does thing'
def add_arguments(self, parser):
# Named (optional) arguments
parser.add_argument(
'--import',
action='store_true',
help='Skips Import',
)
def handle(self, *args, **kwargs):
print("Doing Thing")
# connect to db + create if it doesn't exist
status = create_db()
if status:
# create migrations
call_command('makemigrations') # (Django Command)
# can also pass arguemnts like a specific app
# call_command('makemigrations', 'app1')
# This create db **if** it doesn't exist
# + checks that migrations are up to date
call_command('migrate') # (Django Command)
if kwargs['import']:
# another management command to handle importing
# I've just a csv reader and a loop
call_command('importDb') # (Custom Command)
# Collect Static (+ don't ask for confirmation)
call_command('collectstatic', interactive=False) # (Django Command)
print('Thing has been Done')
else:
print('Thing not Done')
So with that, I just run:
python manage.py dothing (python manage.py dothing --import if I want db to be imported)
and then:
python manage.py runserver and it's good to go!
Edit
Just do something like this and pull the options from the settings:
https://www.w3schools.com/python/python_mysql_create_db.asp
Edit 2
It should work; From my testing Django doesn't actually connect to the db until its told to run a query (filter/get/create/delete)
You can generally test this with a basic management command and bad db settings:
Set db name in settings to 'invalid_db'
Test command below
from django.core.management.base import BaseCommand
from django.core.management import call_command
import os
class Command(BaseCommand):
help = 'testing '
def handle(self, *args, **kwargs):
print('Command is Running!')
print('doing the things')
print('about to migrate / use db / crash')
print('*'*100)
call_command('migrate')
So in theory, as long as you aren't using Django commands you should be able to do whatever you want

COLMAP running error in remote server while running Non-Rigid NeRF

I was checking the github code of LLFF : https://github.com/Fyusion/LLFF, Non-Rigid NeRF : https://github.com/facebookresearch/nonrigid_nerf and followed the suggested steps to install requirements. While running a preprocess file which return poses from images by SfM using COLMAP. I was getting the following error while executing the preprocessing in a remote server. Can anyone please help me with solving this?
python preprocess.py --input data/example_sequence1/
Need to run COLMAP
qt.qpa.xcb: could not connect to display
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.
Available platform plugins are: eglfs, minimal, minimalegl, offscreen, vnc, webgl, xcb.
*** Aborted at 1660905461 (unix time) try "date -d #1660905461" if you are using GNU date ***
PC: # 0x0 (unknown)
*** SIGABRT (#0x3e900138a9f) received by PID 1280671 (TID 0x7f5740d49000) from PID 1280671; stack trace: ***
# 0x7f57463a2197 google::(anonymous namespace)::FailureSignalHandler()
# 0x7f574421f420 (unknown)
# 0x7f5743bf300b gsignal
# 0x7f5743bd2859 abort
# 0x7f57442be35b QMessageLogger::fatal()
# 0x7f574477c799 QGuiApplicationPrivate::createPlatformIntegration()
# 0x7f574477cb6f QGuiApplicationPrivate::createEventDispatcher()
# 0x7f57443dbb62 QCoreApplicationPrivate::init()
# 0x7f574477d1e1 QGuiApplicationPrivate::init()
# 0x7f5744c03bc5 QApplicationPrivate::init()
# 0x562bbb634975 colmap::RunFeatureExtractor()
# 0x562bbb61d1a0 main
# 0x7f5743bd4083 __libc_start_main
# 0x562bbb620e39 (unknown)
Traceback (most recent call last):
File "imgs2poses.py", line 18, in <module>
gen_poses(args.scenedir, args.match_type)
File "/data1/user_data/ashish/NeRF/LLFF/llff/poses/pose_utils.py", line 268, in gen_poses
run_colmap(basedir, match_type)
File "/data1/user_data/ashish/NeRF/LLFF/llff/poses/colmap_wrapper.py", line 35, in run_colmap
feat_output = ( subprocess.check_output(feature_extractor_args, universal_newlines=True) )
File "/home/ashish/anaconda3/envs/nrnerf/lib/python3.6/subprocess.py", line 356, in check_output
**kwargs).stdout
File "/home/ashish/anaconda3/envs/nrnerf/lib/python3.6/subprocess.py", line 438, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['colmap', 'feature_extractor', '--database_path', 'scenedir/database.db', '--image_path', 'scenedir/images', '--ImageReader.single_camera', '1']' died with <Signals.SIGABRT: 6>.
'''

Import globally installed module

I am trying to execute my python script which imports globally installed modules through pip. (Module like nltk)
Below is my code.
interpreter.execfile("/home/roy/eclipse-workspace/geospatial-analysis/src/main/resources/wordnet_util.py");
PyObject someFunc = interpreter.get("get_similarity");
PyObject result = someFunc.__call__(new PyString("Apple pie."), new PyString("Banana pie."));
Double realResult = (Double) result.__tojava__(Double.class);
I have added the path for python modules like,
import sys
sys.path.append("/usr/local/lib/python2.7/dist-packages")
But I get the following error,
*sys-package-mgr*: can't create package cache dir, '/usr/local/lib/python2.7/dist-packages/cachedir/packages'
Exception in thread "main" Traceback (most recent call last):
File "/home/roy/eclipse-workspace/geospatial-analysis/src/main/resources/wordnet_util.py", line 6, in <module>
from nltk import word_tokenize, pos_tag
File "/usr/local/lib/python2.7/dist-packages/nltk/__init__.py", line 18, in <module>
from __future__ import print_function, absolute_import
ImportError: No module named __future__
Update:
I added sys.path.append("/usr/lib/python2.7") to the python file. It solved the above error. Now it can't find select module.
ImportError: No module named signal

No blog table in my first Mezzanine project on shared host

I'm trying to use Mezzanine cms (3.1.4) in a shared hosting at Dreamhost. I successfully created my first blog entry but strangely enough, I don't find the table associated with this entry. Phpadmin page at Dreamhost does show my mezzanine database (named hamlet) but there are only 10 tables in it :
auth_group, auth_group_permissions,auth_permission, auth_user, auth_user_groups, auth_user_user_permissions
django_admin_log, django_content_type, django_migrations, django_session
No blog table. Does someone have an explanation for this?
EDIT: Steps I did:
-Entered in my virtual environment env.mez
-Created the passenger_wsgi.py file:
import sys, os
INTERP = "/home/geantbrun/opt/python-2.7.7/bin/python"
#INTERP is present twice so that the new python interpreter knows the actual executable path
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
cwd = os.getcwd()
sys.path.append(cwd)
sys.path.append(cwd + '/mez') #You must add your project here
sys.path.insert(0,cwd+'/env.mez/bin')
sys.path.insert(0,cwd+'/env.mez/lib/python2.7/site-packages/mezzanine')
sys.path.insert(0,cwd+'/env.mez/lib/python2.7/site-packages')
os.environ['DJANGO_SETTINGS_MODULE'] = "mez.settings"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
-Created on Dreamhost panel the database hamlet
-Created my mezzanine-project (mez)
-Parameters set in settings.py:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": "hamlet",
"USER": "(myusername)",
"PASSWORD": "(mypass)",
"HOST": "mysql.geantbrun.com",
"PORT": "3306",
}
}
-Static files collected
-Command syncdb :
python manage.py syncdb
Syncing...
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_redirect
Creating table django_session
Creating table django_site
Creating table south_migrationhistory
Creating table django_admin_log
Creating table django_comments
Creating table django_comment_flags
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'geantbrun'):
Email address:
Password:
Password (again):
Superuser created successfully.
A site record is required.
Please enter the domain and optional port in the format 'domain:port'.
For example 'localhost:8000' or 'www.example.com'.
Hit enter to use the default (127.0.0.1:8000): (mysite.com)
Creating default site record: mysite.com ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Synced:
> mezzanine.boot
> moderna
> django.contrib.auth
> django.contrib.contenttypes
> django.contrib.redirects
> django.contrib.sessions
> django.contrib.sites
> django.contrib.sitemaps
> django.contrib.staticfiles
> compressor
> filebrowser_safe
> south
> django.contrib.admin
> django.contrib.comments
Not synced (use migrations):
- mezzanine.conf
- mezzanine.core
- mezzanine.generic
- mezzanine.blog
- mezzanine.forms
- mezzanine.pages
- mezzanine.galleries
- mezzanine.twitter
(use ./manage.py migrate to migrate these)
-At this point, on Dreamhost panel, I see that 14 tables are now created in hamlet database (auth_, django_ and south_migrationhistory tables).
-Migrate command: python manage.py migrate
Running migrations for conf:
- Migrating forwards to 0004_ssl_account_settings_rename.
> conf:0001_initial
> conf:0002_auto__add_field_setting_site
> conf:0003_update_site_setting
- Migration 'conf:0003_update_site_setting' is marked for no-dry-run.
> conf:0004_ssl_account_settings_rename
- Migration 'conf:0004_ssl_account_settings_rename' is marked for no-dry-run.
- Loading initial data for conf.
Installed 0 object(s) from 0 fixture(s)
Running migrations for core:
- Migrating forwards to 0006_initial.
> core:0001_initial
(...other migrations)
> core:0006_initial
FATAL ERROR - The following SQL query failed: CREATE TABLE "core_sitepermission" ("id" integer NOT NULL PRIMARY KEY, "user_id" integer NOT NULL)
The error was: table "core_sitepermission" already exists
! Error found during real run of migration! Aborting.
Error in migration: core:0006_initial
Traceback (most recent call last):
File "manage.py", line 29, in <module>
execute_from_command_line(sys.argv)
(...other traces)
File "/home/geantbrun/mysite.com/env.mez/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 452, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: table "core_sitepermission" already exists
Note that file referred to at last line is .../backends/sqlite3/base.py. I realize that DATABASES parameter is maybe overridden by local_settings file. I removed the DATABASES parameter from local_settings and rerun the migrate command. Result:
Error in migration: core:0006_initial
Traceback (most recent call last):
File "manage.py", line 29, in <module>
execute_from_command_line(sys.argv)
File "/home/geantbrun/mysite.com/env.mez/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 124, in execute
return self.cursor.execute(query, args)
File "/home/geantbrun/mysite.com/env.mez/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/home/geantbrun/mysite.com/env.mez/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
django.db.utils.OperationalError: (1050, "Table 'core_sitepermission' already exists")
No more mention to sqlite3 but same kind of error at the end ('core_sitepermission already exists'). Does the migrate command should be run with --fake parameter because the database is already created?

Gradle loads mysql-connector jar but no dbunit jar as external dependencies, why?

Please give me some lights about what I'm doing wrong here. First of all I'm newbie with Gradle and Groovy and for learning purposes I'm playing with them and DBUnit.
I tried the code listed below, my goal is to generate a dataset getting the data from a mysql db.
import groovy.sql.Sql
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
repositories {
mavenCentral()
}
configurations {
dbunit
}
dependencies {
dbunit 'dbunit:dbunit:2.2',
'junit:junit:4.11',
'mysql:mysql-connector-java:5.1.25'
}
URLClassLoader loader = GroovyObject.class.classLoader
configurations.dbunit.each { File file -> loader.addURL(file.toURL()) }
task listJars << {
configurations.dbunit.each { File file -> println file.name }
}
task listTables << {
getConnection("mydb").eachRow('show tables') { row -> println row[0] }
}
task generateDataSet << {
def IDatabaseConnection conn = new DatabaseConnection(getConnection("mydb").connection)
def IDataSet fullDataSet = conn.createDataSet()
FlatXmlDataSet.write(fullDataSet, new FileOutputStream("full.xml"))
}
static Sql getConnection(db) {
def props = [user: 'dbuser', password: 'userpass', allowMultiQueries: 'true'] as Properties
def url = (db) ? 'jdbc:mysql://host:3306/'.plus(db) : 'jdbc:mysql://host:3306/'
def driver = 'com.mysql.jdbc.Driver'
Sql.newInstance(url, props, driver)
}
What is weird to me is that all MySQL methods work well, I can get the list of tables and for instance the connection was done well so the mysql-connector-java.jar is being loaded (I think), but when I add the DBUnit stuff (import libs and the generateDataSet method) it seems the dbunit jar is not available for the script, I got the following errors:
FAILURE: Build failed with an exception.
* Where:
Build file '/home/me/tmp/dbunit/build.gradle' line: 5
* What went wrong:
Could not compile build file '/home/me/tmp/dbunit/build.gradle'.
> startup failed:
build file '/home/me/tmp/dbunit/build.gradle': 5: unable to resolve class org.dbunit.dataset.xml.FlatXmlDataSet
# line 5, column 1.
import org.dbunit.dataset.xml.FlatXmlDataSet;
^
build file '/home/me/tmp/dbunit/build.gradle': 2: unable to resolve class org.dbunit.database.DatabaseConnection
# line 2, column 1.
import org.dbunit.database.DatabaseConnection;
^
build file '/home/me/tmp/dbunit/build.gradle': 3: unable to resolve class org.dbunit.database.IDatabaseConnection
# line 3, column 1.
import org.dbunit.database.IDatabaseConnection;
^
build file '/home/me/tmp/dbunit/build.gradle': 4: unable to resolve class org.dbunit.dataset.IDataSet
# line 4, column 1.
import org.dbunit.dataset.IDataSet;
^
4 errors
But if I call the listJars task, I got this:
:listJars
junit-4.11.jar
mysql-connector-java-5.1.25.jar
hamcrest-core-1.3.jar
xercesImpl-2.6.2.jar
xmlParserAPIs-2.6.2.jar
junit-addons-1.4.jar
poi-2.5.1-final-20040804.jar
commons-collections-3.1.jar
commons-lang-2.1.jar
commons-logging-1.0.4.jar
dbunit-2.2.jar
BUILD SUCCESSFUL
Which in my understanding means all those jars were loaded and are available for the script, am I right? or am I doing something wrong with the class loader stuff?
Thanks very much.
The GroovyObject.class.classLoader.addURL hack is not the right way to add a dependency to the build script class path. It's just sometimes necessary to get JDBC drivers to work with Groovy (long story). Here is how you add a dependency to the build script class path:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "some:library:1.0"
}
}
// library can be used in the rest of the build script
You can learn more about this in the Gradle User Guide.