my models:
class Mod(models.model)
name = models.CharField(max_length = 255)
co_x = models.DecimalField(max_digits = 11, decimal_places = 8)
co_y = models.DecimalField(max_digits = 11, decimal_places = 8)
my views:
def closedPoint(request):
location_name = str(request.POST.get("lo", default=""))
nokta_x = int(float(request.POST.get("x"))
nokta_y = int(float(request.POST.get("y"))
poi = Point(nokta_x, nokta_y, srid = 900913)
sk = Mod()
poi_s = Point(sk.co_x, co_y, srid = 900913)
resut_poi = Mod.objects.filter(poi_s__distance_lte = (poi, D(km = 7))).filter(name__in = location_name)
here i want to deduct closest point in 7 km but it gives "Invalid parameters given for Point initialization
Ok, so it's now clear your error message comes from initializing a Point class with None.
That is your first critical problem.
Judging by the error message, my guess is that poi_s is initialized with None, None as Mod() is an unsaved instance with no values and those are the invalid parameters.
sk = Mod() # unsaved Mod instance with no defaults
poi_s = Point(sk.co_x, co_y, srid = 900913)
# sk.co_x is None
Your second problem that will appear after fixing the above is querying a model with an invalid lookup type (specific to PointField, __distance) which accepts a tuple. How to solve that, I don't know.
You would have to look at how GeoDjango translates that tuple into a DB lookup.
Related
I am new to Python and I am trying to define a simple class with attributes and one method.
import scipy.optimize as optimize
class BondPricing:
def __init__(self, price = 95.0428,par = 100,T = 1.5,freq = 2,coup_perc = 5.75,dy = 0.01,guess = 0.05):
self.price = price
self.par = par
self.T = T
self.freq = freq
self.coup_perc = coup_perc
self.dy = dy
self.guess = guess
def ytm(self):
freq = float(self.freq) #cast frequency as float data type
periods = self.T*freq #calculate number of cash flow periods
coupon = self.coup_perc/100.*self.par/freq #calculate actual periodic coupon level
dt = [(i+1)/freq for i in range(int(periods))] #calculate time steps in bond maturity
#write down ytm function from bond pricing formula
ytm_func = lambda y:sum([coupon/(1+y/self.freq)**(self.freq*t) for t in dt])+self.par/(1+y/self.freq)**(self.freq*self.T)-self.price
return optimize.newton(ytm_func, self.guess) #find root of ytm function via Newton-Raphson
bond1 = BondPricing()
When I try to call the method of the class with bond1.ytm(price = 95.0428, par = 100, T = 1.5, coup_perc = 5.75, freq = 2), I get the following error:
TypeError: ytm() got an unexpected keyword argument 'price'
or when I try:
bond1.ymt()
I get this error:
AttributeError: 'BondPricing' object has no attribute 'ymt'
Can anyone kindly explain me what am I doing wrong?
Many thanks in advance!
When I try to call the method of the class with bond1.ytm(price = 95.0428, par = 100, T = 1.5, coup_perc = 5.75, freq = 2), I get the following error:
TypeError: ytm() got an unexpected keyword argument 'price'
The error is because the ytm method does not accept any arguments.
You should be passing the arguments when you intialize the class.
Example:
bond1 = BondPricing(price = 95.0428, par = 100, T = 1.5, coup_perc = 5.75, freq = 2)
# now call ytm method on the object
bond1.ytm()
or when I try: bond1.ymt()
I get this error:
AttributeError: 'BondPricing' object has no attribute 'ymt'
You have defined the method name as ytm.
You should be calling it as
bond1.ytm() # not bond1.ymt()
I've been trying to set up a script to automatically assign connector displacement boundary conditions. When I run the script it all looks fine in the GUI (wires are created, BCs are created and assigned the right value), but when I submit I get the following error: "Element connectivity is missing for element x of type "CONN3D2" and the element connectivity is in fact missing in the input file. I assign the edges by using the midpoints between the wire start and ends, but for some reason it doesn't assign them to the elements. This is my connector assignment function:
def assignConnectors(self):
p = self.m.parts[self.partName]
a = self.m.rootAssembly
a.Instance(name=self.instanceName, part=p, dependent=ON)
e = a.edges
n = a.instances[self.instanceName].nodes
#allelements = p.Set(name='allElements', elements=self.listObjElem)
elset = a.instances[self.instanceName].elements
elsetAssembly = a.Set('assemblyElements', elements=elset)
a.regenerate()
v1 = a.instances[self.instanceName].vertices
rows = len(self.listConstraints)
columns = len(self.listConstraints[0])
total = rows*columns
listObjNode=[];
self.listObjElem=[];
self.listObjConnector=[];
for j,pairElem in enumerate(self.listElem):
p1 = a.getCoordinates(self.listNodes[pairElem[0]-1])
p2 = a.getCoordinates(self.listNodes[pairElem[1]-1])
#print(p1,p2)
wires = a.WirePolyLine(points=((p1,p2),), mergeType=IMPRINT, meshable=OFF)
a.regenerate()
pt1 = a.getCoordinates(self.listNodes[pairElem[0]-1])
pt2 = a.getCoordinates(self.listNodes[pairElem[1]-1])
print(pt1,pt2)
pt11 = np.asarray(pt1[0])
pt12 = np.asarray(pt1[1])
pt13 = np.asarray(pt1[2])
pt21 = np.asarray(pt2[0])
pt22 = np.asarray(pt2[1])
pt23 = np.asarray(pt2[2])
new_p1 = (pt11+pt21)/2
new_p2 = (pt12+pt22)/2
new_p3 = (pt13+pt23)/2
new_p = tuple([new_p1,new_p2,new_p3])
print(new_p)
a = self.m.rootAssembly
e = a.edges
edges1 = e.findAt((new_p, ))
print(edges1)
region = a.Set(edges = edges1, name='Set'+str(j))
self.m.ConnectorSection(name='ConnSect-1'+str(j),translationalType=AXIAL)
csa = a.SectionAssignment(sectionName='ConnSect-1'+str(j), region=region)
self.m.ConnDisplacementBC(name='BC-'+str(j+total), createStepName=self.stepName, fastenerSetName='Set'+str(j), u1=float(self.listElongations[j]), u2=UNSET, u3=UNSET, ur1=UNSET, ur2=UNSET, ur3=UNSET, amplitude=UNSET, fixed=OFF, distributionType=UNIFORM)
a.regenerate()
Am I assigning the elements wrong somehow?
Thanks a lot for any help!
I wanted to try out some raycasting with Python in Maya using OpenMaya.MFnMesh.anyIntersection().
I just want to cast a ray from on object downwards and hit a plane, not go any further so I get only one raycasthit and get the translation values from the raycasthit.
I got the code from a video and made it a bit clearer to understand.
For the code to run properly in Maya you need an object that is higher in the Y-axis than a different one, preferably a polyPlane(for example: having a polySphere at position [0, 3, 0] and a polyPlane at position [0, 0, 0], select the polySphere and run the code)
import maya.OpenMaya as OpenMaya
import maya.cmds as cmds
def RayReposition(*args):
direction = (0.0, -1, 0)
sel = cmds.ls(sl = True)
fromPositionRay = cmds.xform(sel[0], query = True, translation = True)
selShape = cmds.listRelatives(shapes = True)
meshes = cmds.ls(geometry = True)
cmds.select(clear = True)
for x in meshes:
if x == selShape[0]:
continue
else:
OpenMaya.MGlobal.selectByName(x)
sList = OpenMaya.MSelectionList()
OpenMaya.MGlobal.getActiveSelectionList(sList)
item = OpenMaya.MDagPath()
sList.getDagPath(0, item)
item.extendToShape()
fnMesh = OpenMaya.MFnMesh(item)
raySource = OpenMaya.MFloatPoint(fromPositionRay[0], fromPositionRay[1], fromPositionRay[2], 1.0)
rayDir = OpenMaya.MFloatVector(direction[0], direction[1], direction[2])
faceIds = None
triIds = None
idsSorted = False
testBothDirections = False
worldSpace = OpenMaya.MSpace.kWorld
maxParam = 999999
accelParams = None
sortHits = True
hitPoints = OpenMaya.MFloatPointArray()
hitRayParams = OpenMaya.MFloatArray()
hitFaces = OpenMaya.MIntArray()
hitTris = None
hitBarys1 = None
hitBarys2 = None
tolerance = 0.0001
hit = fnMesh.anyIntersection(raySource, rayDir, worldSpace, maxParam, testBothDirections, faceIds, triIds, idsSorted, accelParams, tolerance, hitPoints, hitRayParams, hitFaces, hitTris, hitBarys1, hitBarys2)
OpenMaya.MGlobal.clearSelectionList()
firstHit = (hitPoints[0].x, hitPoints[0].y, hitPoints[0].z)
print firstHit
RayReposition()
I expected to get the translation values from the raycasthit but I get the following error:
TypeError: in method 'MFnMesh_anyIntersection', argument 4 of type 'MIntArray const *'
Using the OpenMaya.MFnMesh.allIntersections() function instead works perfectly fine but I get every single hit from the raycast, but I only want the first hit.
Links to the OpenMaya.MFnMesh API:
link: https://help.autodesk.com/view/MAYAUL/2016/ENU/?guid=__py_ref_class_open_maya_1_1_m_fn_mesh_html
The main thing is that anyIntersection is looking for a single intersection it hits first, not multiple. So your out parameters are of the wrong types because they're arrays.
I would also avoid clearing or making new selections in your loop as it would just slow down performance by having to redraw the viewports every time.
Here's a working example that will create a locator on the first mesh it hits:
import maya.OpenMaya as OpenMaya
import maya.cmds as cmds
def RayReposition(*args):
direction = (0.0, -1, 0)
sel = cmds.ls(sl=True)
fromPositionRay = cmds.xform(sel[0], query=True, translation=True)
selShape = cmds.listRelatives(shapes=True)
meshes = cmds.ls(geometry=True)
for x in meshes:
if x == selShape[0]:
continue
else:
sList = OpenMaya.MSelectionList()
sList.add(x)
item = OpenMaya.MDagPath()
sList.getDagPath(0, item)
item.extendToShape()
fnMesh = OpenMaya.MFnMesh(item)
raySource = OpenMaya.MFloatPoint(fromPositionRay[0], fromPositionRay[1], fromPositionRay[2], 1.0)
rayDir = OpenMaya.MFloatVector(direction[0], direction[1], direction[2])
worldSpace = OpenMaya.MSpace.kWorld
maxParam = 999999
testBothDirections = False
faceIds = None
triIds = None
idsSorted = False
accelParams = None
sortHits = True
hitPoints = OpenMaya.MFloatPoint()
hitRayParams = None
hitFaces = None
hitTris = None
hitBarys1 = None
hitBarys2 = None
tolerance = 0.0001
hit = fnMesh.anyIntersection(
raySource, rayDir, faceIds, triIds, idsSorted, worldSpace, maxParam, testBothDirections, accelParams,
hitPoints, hitRayParams, hitFaces, hitTris, hitBarys1, hitBarys2, tolerance)
if hit:
firstHit = (hitPoints.x, hitPoints.y, hitPoints.z)
loc = cmds.spaceLocator()[0]
cmds.xform(loc, ws=True, t=firstHit)
print "Hit on {} at {}".format(x, firstHit)
break
RayReposition()
I find the c++ documentation a bit more clearer of what the method expects for parameters.
I have a function that is supposed to update Django objects, which each have two date fields, named "production" and "development". The function reads from a python object, containing a list of Django objects along with their new dates, as well as a single label indicating for the entire list whether the fields to be updated are "production" or "development".
For testing, I have two python objects, containing two different lists of django objects and dates, one for "production" and one for "development". When I call the function on one of these objects, no matter what, it's the list and dates in the "production" object that get updated, though whether the info goes to the "development" or "production" fields in those django objects still depends on the label of the initial python object being called on. I have no idea why this is happening.
Python class and initialization of two python objects:
import pytz
import datetime
class timess():
#Reflects update statuses for the two servers
lists = {
"none" : [],
"uploaded" : [],
}
servername = ""
def __init__(self, nonay, uplay, servertype):
self.lists["none"] = nonay
self.lists["uploaded"] = uplay
self.servername = servertype
timezone = pytz.timezone("America/Chicago")
d1 = datetime.datetime(1999, 8, 12, 12, 32, 41)
d2 = datetime.datetime(1996, 8, 12, 12, 32, 41)
d3 = datetime.datetime(2004, 8, 12, 12, 32, 41)
d1a = timezone.localize(d1)
d2a = timezone.localize(d2)
d3a = timezone.localize(d3)
p1 = datetime.datetime(1997, 8, 12, 12, 32, 41)
p2 = datetime.datetime(2002, 8, 12, 12, 32, 41)
p3 = datetime.datetime(2006, 8, 12, 12, 32, 41)
p4 = datetime.datetime(1992, 8, 12, 12, 32, 41)
p1a = timezone.localize(p1)
p2a = timezone.localize(p2)
p3a = timezone.localize(p3)
p4a = timezone.localize(p4)
dnonay = [
("mvol/0004/1905/0404", None),
("mvol/0004/1920/1111", None),
("mvol/0004/1930/0812", None),
("mvol/0004/1905/0214", None),
("mvol/0004/1930/1001", None),
("mvol/0004/1905/0917", None),
("mvol/0004/1930/0712", None),
("mvol/0004/1920/1202", None),
]
duplay = [
("mvol/0004/1905/0130", d1a),
("mvol/0004/1920/0624", d2a),
("mvol/0004/1930/0311", d3a),
]
dtimess = timess(dnonay, duplay, "development")
pnonay = [
("mvol/0004/1905/0130", None),
("mvol/0004/1920/1111", None),
("mvol/0004/1905/0214", None),
("mvol/0004/1930/0311", None),
("mvol/0004/1905/0917", None),
("mvol/0004/1930/0712", None),
("mvol/0004/1920/0624", None)
]
puplay = [
("mvol/0004/1905/0404", p1a),
("mvol/0004/1920/1202", p2a),
("mvol/0004/1930/0812", p3a),
("mvol/0004/1930/1001", p4a),
]
ptimess = timess(pnonay, puplay, "production")
Function definitions:
from listpage.timess import *
from listpage.models import *
def integratetimess(timess):
'''
Takes information in server update list and applies it
to mvolFolder objects in site. Does not work properly.
'''
if timess.servername == "development":
for line in timess.lists["uploaded"]:
target = mvolFolder.objects.get(name = line[0])
target.dev = line[1]
target.save()
if timess.servername == "production":
for line in timess.lists["uploaded"]:
target = mvolFolder.objects.get(name = line[0])
target.pro = line[1]
target.save()
def integrateot(namey, date, servertype):
'''
This function works when called on
a django mvolFolder object outside of the
timess object
'''
target = mvolFolder.objects.get(name = namey)
if(servertype == "development"):
print(namey)
print("development, initially:")
print(target.dev)
print(target.pro)
target.dev = date
print("development, after changing")
print(target.dev)
print(target.pro)
target.save()
if(servertype == "production"):
print(namey)
print("production, initially:")
print(target.dev)
print(target.pro)
target.pro = date
print("production, after changing")
print(target.dev)
print(target.pro)
target.save()
def integratetimesx(timess):
'''
However, when integrateot is called to loop on the
list in the python object, there's the same issue
as the first function
'''
for line in timess.lists["uploaded"]:
integrateot(line[0], line[1], timess.servername)
Django object model:
from django.db import models
# Create your models here.
class Folder(models.Model):
name = models.CharField(max_length = 19)
def __str__(self):
return self.name
class mvolFolder(Folder):
date = models.DateTimeField(null = True)
valid = models.NullBooleanField(null = True)
dev = models.DateTimeField(null = True)
pro = models.DateTimeField(null = True)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null = True, related_name = 'children')
Django shell input:
from listpage.models import mvolFolder
from listpage.timess import *
from listpage.convtimess import *
integratetimesx(ptimess)
integratetimesx(dtimess)
Python 3.7.0
Django 2.0.8
Windows 10 Enterprise Version 1803
I could be wrong, the question is a little vague and you never give an exact description of the problem, but it looks to me to be a python problem not a django one. The timess class has a class attribute called lists which you are treating as an instance attribute. Here's a concise description of the difference in a similar case. For a timess instance, self.list is a local reference to the class dictionary. Calling timess(...) changes the value in the class dictionary, so it's changed for all instances. I won't comment on the rest of the code, but to make this class work as (I think) you expect, try this instead:
class timess():
def __init__(self, nonay, uplay, servertype):
self.lists = {
"none" : [nonay],
"uploaded" : [uplay],
}
self.servername = servertype
I use mongoengine and when I call a class mongoengine give me error
for example when I use : Site.objects()
I get this
TypeError: id must be an instance of (str, unicode, ObjectId), not <type 'dict'>
and it's my class definition :
class Site(db.Document):
siteURL = db.URLField('''required = True''')
name = db.StringField(required = True)
pages = db.ListField(ReferenceField(Page))
siteId = db.IntField(required = True , unique = True )
views = db.IntField(required = True , default = 0)
visitors = db.IntField(required = True , default = 0)
stat_by_hour = LimitedListField(EmbeddedDocumentField(HourStat))
weekday_stat = db.ListField(EmbeddedDocumentField(WeekdayStat))
os = db.ListField(ReferenceField(OS))
countries = db.ListField(ReferenceField(Country))
cities = db.ListField(ReferenceField(City))
browsers = db.ListField(ReferenceField(Browser))
resolutions = db.ListField(ReferenceField(Resolution))
mostVisitedDays = db.SortedListField(EmbeddedDocumentField(MostVisitedDay) , ordering="visitors")