This is my first question and I might be doing something wrong.
I am trying to implement a Python application with a library already written in C.
I have created the shared library and I am using ctypes to use it in my Python script.
This is a small part of the script.
from ctypes import *
KYBER_SYMBITES = 32
CRYPTO_PUBLICKEYBITES = 800
CRYPTO_SECRETKEYBITES = 1664
def key_generation():
out_lib = CDLL("./PQCgenKAT_kem.so")
out_lib.crypto_kem_keypair.restype = c_int
out_lib.crypto_kem_keypair.argtypes(POINTER(c_char_p),
POINTER(c_char_p))
pk = [] * CRYPTO_PUBLICKEYBITES
sk = [] * CRYPTO_SECRETKEYBITES
ret_val = out_lib.crypto_kem_keypair(pk,sk)
couple = [] * 2
couple.insert(0,pk)
couple.insert(1,sk)
if ret_val != 0 :
print("ERROR")
return couple
But when I try to test a main file that calls this method I get this error
ale#ale-VirtualBox:~/Desktop/TEST$ /bin/python3
/home/ale/Desktop/TEST/main.py
Traceback (most recent call last):
File "/home/ale/Desktop/TEST/main.py", line 4, in <module>
lista = r.key_generation()
File "/home/ale/Desktop/TEST/RING.py", line 12, in key_generation
out.crypto_kem_keypair.argtypes = [(POINTER(c_char_p),
File "/usr/lib/python3.9/ctypes/__init__.py", line 387, in __getattr__
func = self.__getitem__(name)
File "/usr/lib/python3.9/ctypes/__init__.py", line 392, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: ./PQCgenKAT_kem.so: undefined symbol: crypto_kem_keypair
This is my first approach to shared libraries. Can anyone help me solve this problem and figure out where am I wrong?
Related
I'm trying to use OptaPy for inspector's schedule optimization.
I've tried to add a shadow variable, which must be updated along with another variable. Docs recommend to annotate one shadow variable with custom VariableListener and make others refer to it.
This is how I did it (part of actual code):
#planning_entity
class Task(Slot):
inspector: Inspector
prev_slot: Slot
from_time: datetime
def __init__(self, inspector: Inspector = None, from_time: datetime = None):
self.inspector = inspector
self.from_time = from_time
self.prev_slot = None
#custom_shadow_variable(Inspector,
variable_listener_class = TaskUpdatingVariableListener,
sources = [planning_variable_reference(variable_name = 'previous_slot')])
def get_inspector(self):
return self.inspector
#custom_shadow_variable(datetime,
variable_listener_ref = planning_variable_reference(variable_name = 'inspector'))
def get_from_time(self):
return self.from_time
#planning_variable(Slot,
value_range_provider_refs=['day_start_range', 'task_range'],
graph_type=PlanningVariableGraphType.CHAINED)
def get_previous_slot(self):
return self.prev_slot
def set_previous_slot(self, previous_slot: Slot):
self.prev_slot = previous_slot
Here, TaskUpdatingVariableListener is #variable_listener, and Slot is a #problem_fact.
The problem is when I run this code, it gives me Java type cast error:
Traceback (most recent call last):
File "model_v4.py", line 324, in <module>
class Task(Slot):
File ".../python3.9/site-packages/optapy/annotations.py", line 546, in planning_entity
return planning_entity_wrapper(entity_class)
File ".../python3.9/site-packages/optapy/annotations.py", line 540, in planning_entity_wrapper
out.__optapy_java_class = _generate_planning_entity_class(entity_class_argument, annotation_data)
File ".../python3.9/site-packages/optapy/optaplanner_java_interop.py", line 1030, in _generate_planning_entity_class
optaplanner_annotations = _get_optaplanner_annotations(python_class)
File ".../python3.9/site-packages/optapy/optaplanner_java_interop.py", line 955, in _get_optaplanner_annotations
_to_java_list(list(map(lambda annotation: getattr(getattr(python_class, method),
File ".../python3.9/site-packages/optapy/optaplanner_java_interop.py", line 936, in _to_java_list
out.add(_to_java_map(item))
File ".../python3.9/site-packages/optapy/optaplanner_java_interop.py", line 925, in _to_java_map
out.put(JObject(key, java.lang.Object), JObject(value, java.lang.Object))
File ".../python3.9/site-packages/jpype/_jobject.py", line 59, in __new__
return _JObjectFactory(*args, **kwargs)
File ".../python3.9/site-packages/jpype/_jobject.py", line 111, in _JObjectFactory
return tp._cast(v)
TypeError: Unable to cast 'dict' to java type 'java.lang.Object'
And if I remove second shadow variable (get_from_time), it compiles pretty well!
Changing variable type from datetime to anything else didn't help.
What could be the problem here?
This was a bug in optapy (see https://github.com/optapy/optapy/pull/99 for details), and will be fixed in the next release.
Trying to run a training script, after resolving a few error messages I've come accross this one, Anyone know what is happening here?
Batch size > 1 not implemented! Falling back to batch_size = 1 ...
Building multi-modal model...
Loading model parameters.
Traceback (most recent call last):
File "translate_mm.py", line 166, in <module>
main()
File "translate_mm.py", line 98, in main
use_filter_pred=False)
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/IO.py", line 198, in build_dataset
use_filter_pred=use_filter_pred)
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/TextDataset.py", line 75, in __init__
out_examples = list(out_examples)
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/TextDataset.py", line 69, in <genexpr>
out_examples = (self._construct_example_fromlist(
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/TextDataset.py", line 68, in <genexpr>
example_values = ([ex[k] for k in keys] for ex in examples_iter)
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/TextDataset.py", line 265, in _dynamic_dict
src_map = torch.LongTensor([src_vocab.stoi[w] for w in src])
File "/content/drive/My Drive/Thesis/thesis_code/onmt/io/TextDataset.py", line 265, in <listcomp>
src_map = torch.LongTensor([src_vocab.stoi[w] for w in src])
File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py", line 1178, in __getattr__
type(self).__name__, name))
AttributeError: 'Vocab' object has no attribute 'stoi'
which refers to
def _dynamic_dict(self, examples_iter):
for example in examples_iter:
src = example["src"]
src_vocab = torchtext.vocab.Vocab(Counter(src))
self.src_vocabs.append(src_vocab)
# Mapping source tokens to indices in the dynamic dict.
src_map = torch.LongTensor([src_vocab.stoi[w] for w in src])
example["src_map"] = src_map
if "tgt" in example:
tgt = example["tgt"]
mask = torch.LongTensor(
[0] + [src_vocab.stoi[w] for w in tgt] + [0])
example["alignment"] = mask
yield example
Note: the original model was made with a much older version of torchtext, I am guessing the error is related to that, but I am simply too inexperienced to know for sure.
Anyone has an idea? Googling this provided no significant results.
regards,
U.
You must use get_stoi()[w].This is for the newer version after removing the legacy. You also can use get_itos() which returns a list of elements.
I am getting an error when trying to run code and am unsure how to solve the issue. I am unsure what this datapath is and the error is coming straight from the matplotlib package. Any help is greatly appreciated. Here is the error I am getting:
running API pyqt5
using configuration at /home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/image_analyzer.conf
no Pyro installed. Use dummy event handler.
/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/mplwidget.py:123: MatplotlibDeprecationWarning:
The _init_toolbar method was deprecated in Matplotlib 3.3 and will be removed two minor releases later. Please fully initialize the toolbar in your subclass' __init__; a fully empty _init_toolbar implementation may be kept for compatibility with earlier versions of Matplotlib.
super(Toolbar, self).__init__(*args, **kwargs)
Traceback (most recent call last):
File "start.py", line 5, in <module>
dmw, app, reuseapp = main.run_app()
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/main.py", line 552, in run_app
dmw = DesignerMainWindow()
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/main.py", line 33, in __init__
self.setupUi(self)
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/gui.py", line 333, in setupUi
self.main_area = self.setup_main_area(self.main_widget)
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/gui.py", line 306, in setup_main_area
center_area = self.setup_center_area(main_area)
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/gui.py", line 196, in setup_center_area
self.main_image_plot = MplWidget(self.tabs[0])
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/mplwidget.py", line 109, in __init__
self.mpl_toolbar = Toolbar(self.figCanvas, self)
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/mplwidget.py", line 123, in __init__
super(Toolbar, self).__init__(*args, **kwargs)
File "/home/.local/lib/python3.8/site-packages/matplotlib/backends/backend_qt5.py", line 681, in __init__
NavigationToolbar2.__init__(self, canvas)
File "/home/.local/lib/python3.8/site-packages/matplotlib/backend_bases.py", line 2913, in __init__
init()
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/mplwidget.py", line 140, in _init_toolbar
self.basedir = os.path.join(mpl.rcParams["datapath"], "images")
File "/home/.local/lib/python3.8/site-packages/matplotlib/__init__.py", line 623, in __getitem__
return dict.__getitem__(self, key)
KeyError: 'datapath'
start.py file:
#!/bin/env python
from qimageanalyser import main
import sys
dmw, app, reuseapp = main.run_app()
if "app" in globals() and not reuseapp:
sys.exit(app.exec_())
image_analyzer.conf file (I have to write more text to post this so I am writing more text here):
[Analysis Functions]
fitter = gaussian
analyser = absorption2
clearonnewrun = False
[General]
atom = Li6
nPics = 2
default_ref_roi_xi = 0
default_ref_roi_yi = 0
default_ref_roi_xf = 40
default_ref_roi_yf = 100
[Gui]
colorscale = jet
[Guppy]
pixelarea = 329.28e-12
magnification = 0.33
[Manta]
pixelarea = 64e-12
magnification = 2.5
[None]
pixelarea = 100e-12
magnification = 1
[Li6]
crosssection = 2.14949894091e-13
clebsch = 0.5
mass = 6
[Li7]
crosssection = 2.14949894091e-13
clebsch = 0.5
mass = 7
[Na]
crosssection = 1.6564257603715025E-13
clebsch = 1
mass = 23
mpl.rcParams["datapath"] was deprecated: https://github.com/matplotlib/matplotlib/pull/16417
Solution is to use
mpl.get_data_path()
instead of
mpl.rcParams["datapath"]
I am trying to solve a very simple ODE using the dsolve sympy function:
from sympy import*
init_printing()
t = symbols('t', real = True)
A = symbols('A', complex = True)
f = Function('rho')(t)
dsolve(Derivative(f, t)+A*f, f)
But, then I get:
Traceback (most recent call last):
File "<ipython-input-9-3d1f21a5ef22>", line 1, in <module>
dsolve(Derivative(f, t)+A*f, f)
File "/home/ted/anaconda3/lib/python3.6/site-packages/sympy/solvers/ode.py", line 566, in dsolve
hints = _desolve(eq, func=func, hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics, x0=x0, n=n, **kwargs)
File "/home/ted/anaconda3/lib/python3.6/site-packages/sympy/solvers/deutils.py", line 205, in _desolve
n=terms, x0=x0, prep=prep)
File "/home/ted/anaconda3/lib/python3.6/site-packages/sympy/solvers/ode.py", line 1251, in classify_ode
r = _nth_linear_match(reduced_eq, func, order)
File "/home/ted/anaconda3/lib/python3.6/site-packages/sympy/solvers/ode.py", line 3723, in _nth_linear_match
terms[f.derivative_count] += c
AttributeError: 'Derivative' object has no attribute 'derivative_count'
The sympy version is 1.1.1, the python version is 3.6.4 and the ipython version is 6.2.1.
My bad! I tried to use one of the files (ode.py) from the current development version without updating the rest. Now I have it working. Thanks!
I have a problem with my python code specialy when I'm trying to define a function in a Class. Indeed, I want to call this function (which is in a file i called BC.py) in my main program which i called PBC.py
Class BC():
self.nmodes
self.L_ch
self.w
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
In my main programm i did:
from BC import *
A=BC()
C=func1(self,x)
Then I got this error:
The parameters file have been imported succesfully
Traceback (most recent call last):
File "PBC.py", line 35, in <module>
C =func1(A,eps)
NameError: name 'func1' is not defined
Please do you know where i am wrong?
The thing is, when i don't include the function in my class everything works well,
Class BC():
self.nmodes
self.L_ch
self.w
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x+15
return f
Exept that when i use only the function, all the parameters I defined before are not recognized???
For example:
r_0=scipy.optimize.fsolve(func1,0.003,args=(0.032))
I got this error:
The parameters file have been imported succesfully
Traceback (most recent call last):
File "PBC.py", line 75, in <module>
R_0=scipy.optimize.fsolve(func1,float(eps_real),args=(eps))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 127, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 183, in _root_hybr
_check_func('fsolve', 'func', func, x0, args, n, (n,))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 14, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
File "/home/cfd1/ndiaye/ATACAMAC/BCT_dev.py", line 75, in func1
self.k_ch=self.nmodes*self.pi/self.L_ch+eps/self.L_ch
AttributeError: 'numpy.ndarray' object has no attribute 'nmodes'
Someone can help?
Thank you very much.
Thank you for your answer but it isn't working, i still got this error:
Traceback (most recent call last):
File "PBC.py", line 36, in <module>
C =A.func1(x)
Now i'm trying with a very simplified script:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
And my main program is:
from dev import *
A=real()
C=A.func1(x)
Unfortunately it seems not working to caus' i have the same traceback error.
Thank you.
You should call it this way:
from BC import *
A=BC()
C=A.func1(x)
Edit for comment:
Please take care of the code format:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
Call the function this way (recommended):
A = BC()
C = A.func1(x)
or this other (less used and not recommended, just mentioned as information):
C = BC.func1(A, x)
Note: I would recommend you to rename your file with a name different than the class BC, because it confuses Python. Also, don't forget to declare x.