I am a newbie for Django. Although I don't use the pdb for debugging but I used before and I removed all pdb methods, I get the Bdbquit error with following explanation:
/home/mastersnack/dpt2/app/views.py in start
version = request.session['version']
My related code is:
def start(request):
global Big_Matrix
if 'version' in request.session:
version = request.session['version']
else:
try:
version = Version.objects.order_by('-id')[0]
except IndexError:
return redirect('/')
if not request.user.id:
user = User(guest=True, date_joined=datetime.datetime.now(),
last_login=datetime.datetime.now())
user.save()
request.session["USER_ID"] = user.id
return redirect('/start')
rnd = Round(version=version, user=request.user, date=datetime.datetime.now())
rnd.save()
products = Product.objects.filter(version=version, selectable=True)
(a, b, c) = random.sample(products, 3)
poll = Poll(round=rnd, product_a= a, product_b= b, product_c= c,
date=datetime.datetime.now())
# (a,b,c)=get_meals(Big_Matrix, [])
# poll = Poll(round=rnd, product_a=Product.objects.get(stimuliNum = a, version =
version), product_b=Product.objects.get(stimuliNum = b, version = version),
product_c=Product.objects.get(stimuliNum = c, version = version),
date=datetime.datetime.now())
poll.save()
# (a,b,c)=get_meals(BigMatrix.objects.get(version = version).matrix, [])#bad_ functions)
# poll = Poll(round=rnd, product_a=Product.objects.get(oid = a, version = version), product_b=Product.objects.get(oid = b, version = version), product_c=Product.objects.get(oid = c, version = version), date=datetime.datetime.now())
# poll.save()
return redirect('/preferences')
Should I check my code again for the method maybe I forget to remove?
Make sure that you have removed all pdb methods and that you save your code.
After that if you are running the Django server, restart it.
That should do the trick
Related
I am running a Vertex AI batch prediction using the python API.
The function I am using is from the google cloud docs:
def create_batch_prediction_job_dedicated_resources_sample(
key_path,
project: str,
location: str,
model_display_name: str,
job_display_name: str,
gcs_source: Union[str, Sequence[str]],
gcs_destination: str,
machine_type: str = "n1-standard-2",
sync: bool = True,
):
credentials = service_account.Credentials.from_service_account_file(
key_path)
# Initilaize an aiplatfrom object
aiplatform.init(project=project, location=location, credentials=credentials)
# Get a list of Models by Model name
models = aiplatform.Model.list(filter=f'display_name="{model_display_name}"')
model_resource_name = models[0].resource_name
# Get the model
my_model = aiplatform.Model(model_resource_name)
batch_prediction_job = my_model.batch_predict(
job_display_name=job_display_name,
gcs_source=gcs_source,
gcs_destination_prefix=gcs_destination,
machine_type=machine_type,
sync=sync,
)
#batch_prediction_job.wait_for_resource_creation()
batch_prediction_job.wait()
print(batch_prediction_job.display_name)
print(batch_prediction_job.resource_name)
print(batch_prediction_job.state)
return batch_prediction_job
datetime_today = datetime.datetime.now()
model_display_name = 'test_model'
key_path = 'vertex_key.json'
project = 'my_project'
location = 'asia-south1'
job_display_name = 'batch_prediction_' + str(datetime_today)
model_name = '1234'
gcs_source = 'gs://my_bucket/Cleaned_Data/user_item_pairs.jsonl'
gcs_destination = 'gs://my_bucket/prediction'
create_batch_prediction_job_dedicated_resources_sample(key_path,project,location,model_display_name,job_display_name,
gcs_source,gcs_destination)
OUTPUT:
92 current state:
JobState.JOB_STATE_RUNNING
INFO:google.cloud.aiplatform.jobs:BatchPredictionJob projects/my_project/locations/asia-south1/batchPredictionJobs/37737350127597649
The above output is being printed on the terminal over and over after every few seconds.
The issue that I have is that the python program calling this function keeps on running until it is force stopped. I have tried both batch_prediction_job.wait() & batch_prediction_job.wait_for_resource_creation() with the same results.
How do I start a batch_prediction_job without waiting for it to complete and terminating the program just after the job has be created?
I gave you the wrong instruction on the comments, change the parameter sync=False and the function should return just after be executed.
Whether this function call should be synchronous (wait for pipeline run to finish before terminating) or asynchronous (return immediately)
sync=False
def create_batch_prediction_job_dedicated_resources_sample(
# ...
sync: bool = False,
):
UPDATE - Adding more details:
Check here my notebook code where I tested it and its working:
You have to change the sync=False AND remove/comment the following print lines:
#batch_prediction_job.wait()
#print(batch_prediction_job.display_name)
#print(batch_prediction_job.resource_name)
#print(batch_prediction_job.state)
Your code edited:
def create_batch_prediction_job_dedicated_resources_sample(
key_path,
project: str,
location: str,
model_display_name: str,
job_display_name: str,
gcs_source: Union[str, Sequence[str]],
gcs_destination: str,
machine_type: str = "n1-standard-2",
sync: bool = False,
):
credentials = service_account.Credentials.from_service_account_file(key_path)
# Initilaize an aiplatfrom object
aiplatform.init(project=project, location=location, credentials=credentials)
# Get a list of Models by Model name
models = aiplatform.Model.list(filter=f'display_name="{model_display_name}"')
model_resource_name = models[0].resource_name
# Get the model
my_model = aiplatform.Model(model_resource_name)
batch_prediction_job = my_model.batch_predict(
job_display_name=job_display_name,
gcs_source=gcs_source,
gcs_destination_prefix=gcs_destination,
machine_type=machine_type,
sync=sync,
)
return batch_prediction_job
datetime_today = datetime.datetime.now()
model_display_name = 'test_model'
key_path = 'vertex_key.json'
project = '<my_project_name>'
location = 'asia-south1'
job_display_name = 'batch_prediction_' + str(datetime_today)
model_name = '1234'
gcs_source = 'gs://<my_bucket_name>/Cleaned_Data/user_item_pairs.jsonl'
gcs_destination = 'gs://<my_bucket_name>/prediction'
create_batch_prediction_job_dedicated_resources_sample(key_path,
project,location,
model_display_name,
job_display_name,
gcs_source,
gcs_destination,
sync=False,)
Results sync=False:
Results sync=True:
I have a function that opens up a webdriver session and then calls for external functions based on the input url.
from externalfunctions import *
def itemiser(url):
regex = re.compile(r'www.(.+).com')
name = regex.search(url).group(1)
options = {
'a': a,
'b': b,
'c': c
}
if name in options:
ff = webdriver.Firefox()
ff.get(url)
result = options[name]()
ff.quit()
print(result)
return result
functions a,b,c are in externalfuntions.py
def a():
x = ff.find_element_by_css_selector('body')
return x
def b():
x = ff.find_element_by_css_selector('span')
return x
def c():
x = ff.find_element_by_css_selector('html')
return x
When I run this, it says that ff is not defined, obviously because the a,b,c functions can't access the webdriver.
How do I do this without having to start a webdriver session every time the a,b,c functions are run.
This is basic Python (indeed, basic programming). If a function needs access to something, you need to pass it:
result = options[name](ff)
and
def a(ff):
x = ff.find_element_by_css_selector('body')
return x
etc.
You need to import the webdriver library (selenium) and declare the webdriver:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
options.add_argument("window-size=1,1")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Users\XXX\chromedriver')
and then you can use:
driver.get(url)
driver.find_element_by_css_selector('html')
I'm using OpenSSL in my C++ program, and I need to link crypto and ssl with it. If it were for example gcc, I would just pass:
-lcrypto -lssl
I am adding this dependency in Network-Simulator 3.
But I don't know how to do this in WAF. How should I add them as a dependency?
First you need to check in configure if the library is available, then you can build it.
def configure(cnf):
# other parameters omitted for brevity
cnf.check(lib=["crypto", "ssl"])
def build(bld):
# other parameters omitted for brevity
bld(use=["crypto", "ssl"])
You could also use the uselib_store parameter if you don't want to repeat the libraries:
cnf.check(lib=["crypto", "ssl"], uselib_store=["libs"])
bld(use=["libs"])
I tried adding CRYPTOPP instead of Crypto because I could do the same work with CRYPTOPP.
This is how it worked for me.
The below code needs to be added/edited in wscript found in ns-3.xx directory.
def configure(conf):
#other parameters removed
env = conf.env
conf.env['cryptopp'] = conf.check(mandatory=True, lib='cryptopp', uselib_store='CRYPTOPP')
conf.env['sph'] = conf.check(mandatory=True, lib='sph', uselib_store='SPH')
conf.env.append_value('CXXDEFINES', 'ENABLE_CRYPTOPP')
conf.env.append_value('CCDEFINES', 'ENABLE_CRYPTOPP')
conf.env['lssl'] = conf.check(mandatory=True, lib='ssl', uselib_store='OPENSSL')
conf.env.append_value('CXXDEFINES', 'ENABLE_SSL')
conf.env.append_value('CCDEFINES', 'ENABLE_SSL')
.....
def create_ns3_program(bld, name, dependencies=('core',)):
program = bld(features='cxx cxxprogram')
#other parameters removed
program.use = program.ns3_module_dependencies
if program.env['ENABLE_STATIC_NS3']:
if sys.platform == 'darwin':
program.env.STLIB_MARKER = '-Wl,-all_load,-lcryptopp,-lsph'
else:
program.env.STLIB_MARKER = '-Wl,-Bstatic,--whole-archive,-lcryptopp,-lsph'
program.env.SHLIB_MARKER = '-Wl,-Bdynamic,--no-whole-archive,-lcryptopp,-lsph'
else:
if program.env.DEST_BINFMT == 'elf':
# All ELF platforms are impacted but only the gcc compiler has a flag to fix it.
if 'gcc' in (program.env.CXX_NAME, program.env.CC_NAME):
program.env.append_value ('SHLIB_MARKER', '-Wl,--no-as-needed,-lcryptopp,-lsph')
return program
.......
def add_scratch_programs(bld):
all_modules = [mod[len("ns3-"):] for mod in bld.env['NS3_ENABLED_MODULES']]
try:
for filename in os.listdir("scratch"):
if filename.startswith('.') or filename == 'CVS':
continue
if os.path.isdir(os.path.join("scratch", filename)):
obj = bld.create_ns3_program(filename, all_modules)
obj.path = obj.path.find_dir('scratch').find_dir(filename)
obj.source = obj.path.ant_glob('*.cc')
obj.target = filename
obj.name = obj.target
obj.install_path = None
#Add the below paramters
obj.uselib = 'CRYPTOPP'
obj.uselib = 'SPH'
obj.uselib = 'OPENSSL'
elif filename.endswith(".cc"):
name = filename[:-len(".cc")]
obj = bld.create_ns3_program(name, all_modules)
obj.path = obj.path.find_dir('scratch')
obj.source = filename
obj.target = name
obj.name = obj.target
obj.install_path = None
#Add the below paramters
obj.uselib = 'CRYPTOPP'
obj.uselib = 'SPH'
obj.uselib = 'OPENSSL'
except OSError:
return
This basically adds all paramters at runtime to the simulator you are running from scratch.
PS: This script is specific to ns-3.
I just ran into some strange behavior that has me stumped. I'm writing a simple little GUI for some in-house data processing. I want to allow a user to switch between a few different data-processing modes and input some parameters which define how the data is processed for each mode. The problem is that when the user inputs new parameters, the app ignores requests to switch modes.
The code below replicates the issue. I apologize for the size, this was the shortest code that replicates the problem.
import Tkinter as Tk
class foo(Tk.Frame):
def __init__(self):
self.master = master =Tk.Tk()
Tk.Frame.__init__(self,self.master) #Bootstrap
#Here mode and parameters as key, value pairs
self.data = {'a':'Yay',
'b':'Boo'
}
self.tex = Tk.Text(master=master)
self.tex.grid(row=0,column=0,rowspan=3,columnspan=4)
self.e = Tk.Entry(master=master)
self.e.grid(row=3,column=0,columnspan=4)
self.sv =Tk.StringVar()
self.sv.set('a')
self.b1 = Tk.Radiobutton(master=master,
text = 'a',
indicatoron = 0,
variable = self.sv,
value = 'a')
self.b2 = Tk.Radiobutton(master=master,
text = 'b',
indicatoron = 0,
variable = self.sv,
value = 'b')
self.b3 = Tk.Button(master = master,
text='Apply',command=self.Apply_Func)
self.b4 = Tk.Button(master = master,
text='Print',command=self.Print_Func)
self.b1.grid(row=4,column=0)
self.b2.grid(row=4,column=1)
self.b3.grid(row=4,column=2)
self.b4.grid(row=4,column=3)
def Apply_Func(self):
self.innerdata = self.e.get()
def Print_Func(self):
self.tex.insert(Tk.END,str(self.innerdata)+'\n')
#This is how I'm retrieving the user selected parameters
#property
def innerdata(self):
return self.data[self.sv.get()]
#And how I'm setting the user defined parameters
#innerdata.setter
def innerdata(self,value):
self.data[self.sv.get()] = value
if __name__ == "__main__":
app = foo()
app.mainloop()
Expected behavior:
1) Press button 'a' then 'print' prints:
Yay
2) Press button 'b' then 'print' prints:
Boo
3) Type 'Zep Rocks' into the entry field and press apply
4) Pressing 'print' now yields
Zep Rocks
5) Pressing 'a' then 'print' should yield
Yay
But instead yields
Zep Rocks
Which might be true, but not desired right now. What is going on here?
Edit: I have some new information. Tk.Frame in python 2.7 is not a new-style class. It isn't friendly with descriptors, so rather than interpreting the '=' as a request to use the foo.innerdata's __set__ method, it just assigns the result of self.e.get() to innerdata.
ARGLEBARGLE!!!
Still an open question: how do I get this to do what I want in a clean manner?
So the core problem is that Tk.Frame doesn't subclass from object, so it is not a new-style python class. Which means it doesn't get down with descriptors like I was trying to use. One solution that I found is to subclass my app from object instead.
Code that solves my problem is below:
import Tkinter as Tk
class foo(object):
def __init__(self,master):
self.master = master #Bootstrap
self.mainloop = master.mainloop
self.data = {'a':{'value':7,'metavalue':False},
'b':{'value':'Beeswax','metavalue':True}
}
self.tex = Tk.Text(master=master)
self.tex.grid(row=0,column=0,rowspan=3,columnspan=4)
self.e = Tk.Entry(master=master)
self.e.grid(row=3,column=0,columnspan=4)
self.sv =Tk.StringVar()
self.sv.set('a')
self.b1 = Tk.Radiobutton(master=master,
text = 'a',
indicatoron = 0,
variable = self.sv,
value = 'a')
self.b2 = Tk.Radiobutton(master=master,
text = 'b',
indicatoron = 0,
variable = self.sv,
value = 'b')
self.b3 = Tk.Button(master = master,text='Apply',command=self.Apply_Func)
self.b4 = Tk.Button(master = master,text='Print',command=self.Print_Func)
self.b1.grid(row=4,column=0)
self.b2.grid(row=4,column=1)
self.b3.grid(row=4,column=2)
self.b4.grid(row=4,column=3)
def Apply_Func(self):
self.innerdata = self.e.get()
def Print_Func(self):
self.tex.insert(Tk.END,str(self.innerdata)+'\n')
#property
def innerdata(self):
return self.data[self.sv.get()]
#innerdata.setter
def innerdata(self,value):
self.data[self.sv.get()] = value
if __name__ == "__main__":
master = Tk.Tk()
app = foo(master)
app.mainloop()
In my views.py I have a method:
#......
def get_filter_result(self, customer_type, tag_selected):
list_customer_filter=[]
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
for customer_filter in customers_filter:
customer_filter.list_authorize_sale_type = sale_type_selected(customer_filter.authorize_sale_type)
list_customer_filter.append(customer_filter)
return list_customer_filter
**My case tag_selected is the checkbox values that user checked
I have a problems with tag_selected(is the list=1,2,3,...) that pass from my url
/?customer_type=TDO&tag=2 ===>filter okay
/?customer_type=TDO&tag=3 ===>filter okay
?customer_type=TDO&tag=2,3 ===>How Can I add And condition in filter?
for example
if len(tag_selected)==1:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
else:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected[0])
Q(tag__id=tag_selected[1])
Q(tag__id=tag_selected[2])
...
)
This works for both single and multiple conditions:
idseq = request.POST['tag'].split(',')
tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq))
Customers.objects.filter(..., tag_qs)