def test_create_points(self): point1 = Point(**point_data_1) point1.clean() point2 = Point(**point_data_2) point1.clean() point3 = Point(**point_data_3) self.assertRaises(forms.ValidationError, point3.clean)
def submitPoint(request): userName = getUserName(request) if userName == None: return HttpResponseRedirect("/") pointDesc = "" maplerId = int(request.POST['maplerId']) if maplerId == -1: # new point newPoint = Point(owner=request.user) updatePointAccordingToForm(request.POST, newPoint) pointDesc = newPoint.description newPoint.save() else: point = Point.objects.get(pk=maplerId) if point.owner.username == userName: updatePointAccordingToForm(request.POST, point) pointDesc = point.description point.save() logRecord = UserLog() logRecord.ip = str(get_client_ip(request)) logRecord.user = request.user logRecord.comment="Pt submit: " + pointDesc logRecord.save() return HttpResponseRedirect("/map/manage-points/")
def river_name_input(request): # print get_ip(request) # print request.POST river_info = json.loads(request.POST['river_name']) river_name = river_info['river_name'] object_id = river_info['object_id'] # print river_name # print object_id # latitude = request.POST['latitude'] # longitude = request.POST['longitude'] # river_id = request.POST['river_id'] # print 'river name:', river_name # print 'latitude:', latitude # print 'longitude:', longitude # context = { # 'river_name': 'yr', # 'latitude': latitude, # 'longitude': longitude, # } P = Point(point_name=river_name, object_id=object_id) P.save() # print 'saved' # return render(request, 'crowdsource/river_name_response.html', context) return HttpResponse(status=200)
def import_photos(username, photoset_title, api_key, api_secret): flickr_api.set_keys(api_key=api_key, api_secret=api_secret) user = flickr_api.Person.findByUserName(username) photosets = user.getPhotosets() for photoset in iter(photosets): if photoset.title == photoset_title: photos = photoset.getPhotos() for photo in iter(photos): photo_id = int(photo.id) point = Point.query(Point.pointid == photo_id).get() if point is None: latitude = None longitude = None timestamp = None title = photo.title thumb_url = None photo_url = None photopage = None info = photo.getInfo() taken = info[u"taken"] timestamp = datetime.strptime(taken, "%Y-%m-%d %H:%M:%S") urls = info[u"urls"][u"url"] for url in urls: if url[u"type"] == "photopage": photopage = url[u"text"] break if u"location" in info: location = info[u"location"] # locality = location[u'locality'] # region = location[u'region'] # country = location[u'country'] latitude = float(location[u"latitude"]) longitude = float(location[u"longitude"]) # title = "%s, %s, %s" % (locality, region, country) sizes = photo.getSizes() thumb_url = sizes[u"Square"][u"source"] photo_url = sizes[u"Medium"][u"source"] try: point = Point( title=title, latitude=latitude, longitude=longitude, type="photo", timestamp=timestamp, pointid=photo_id, thumb=thumb_url, photo=photo_url, resource=photopage, ) point.put() except AttributeError: pass except Exception as e: logging.error(e.args[0]) return Response(json.dumps({"status": "ok"}), status=200, mimetype="application/json")
def import_media(access_token, client_secret): global api api = InstagramAPI(access_token=access_token.encode('ascii','ignore'), client_secret=client_secret.encode('ascii','ignore')) m = hashlib.md5() media = get_media() for item in media: pointid = int(m.hexdigest()[:8], 16) point = Point.query(Point.pointid == pointid).get() if point is None: m.update(item.id) title = None desc = None video = None if hasattr(item, 'caption'): if item.caption is not None: desc = item.caption.text if hasattr(item, 'location'): if item.location.name is not None: title = item.location.name if item.location.point is not None: latitude = item.location.point.latitude longitude = item.location.point.longitude timestamp = item.created_time thumb = item.images.get('thumbnail').url photo = item.images.get('standard_resolution').url if hasattr(item, 'videos'): video = item.videos.get('standard_resolution').url resource = item.link try: point = Point( title=title, latitude=latitude, longitude=longitude, type='photo', timestamp=timestamp, pointid=pointid, thumb=thumb, photo=photo, video=video, resource=resource, desc=desc ) point.put() except AttributeError: pass except Exception as e: logging.error(e.args[0]) return Response(json.dumps({ 'status': 'ok' }), status=200, mimetype='application/json');
def create(self, request): """ """ point = Point(**json.loads(request.form.cleaned_data['geo'])) point.save() request.form.cleaned_data['geo'] = point wifi = Wifi(**request.form.cleaned_data) wifi.save() return rc.CREATED
def test_point_deletion(self): result = Customer.get_points_for('sudhirurl') start_count = len(result) first_point = result[0] Point.delete_point(first_point['key'], self.sudhir_gmail) new_result = Customer.get_points_for('sudhirurl') self.assertEqual(len(new_result), start_count - 1) self.assertFalse(self.find(new_result, first_point))
def setPoint(request, flag, pid, oid, name, description, longitude, latitude, index): if request.user.is_authenticated(): try : newOid = int(oid) newName = replace(name, "_", " ") newDescription = replace(description, "_", " ") newIndex = int(index) p = Point(oid=Object.objects.get(oid=newOid), name=newName, description=newDescription, index=newIndex, longitude=longitude, latitude=latitude) p.save() return success() #return HttpResponse("insert_"+str(o.oid)) except : return HttpResponse("Erreur "+traceback.format_exc()) return failure()
def load_route(): try: data = json.loads(request.data) url = data['url'] except Exception as e: logging.error(e.args[0]) abort(400) obj = urllib2.urlopen(url) str = obj.read() kml_str = "" for line in iter(str.splitlines()): if not 'atom:link' in line: kml_str+=line kml_str+='\n' Point.delete_all('route') root = parser.fromstring(kml_str) pointid = 1000 for placemark in root.Document.Folder.Placemark: coordinates = placemark.MultiGeometry.Point.coordinates.text.split(',') try: point = Point( title = placemark.name.text, type = 'route', latitude = float(coordinates[1]), longitude = float(coordinates[0]), pointid = pointid, timestamp = datetime.now() ) except TypeError: abort(500) except Exception as e: logging.error(e.args[0]) abort(500) try: point.put() except CapabilityDisabledError: logging.error(u'App Engine Datastore is currently in read-only mode.') abort(500) except Exception as e: logging.error(e.args[0]) abort(500) pointid += 1 return list_point('route')
def list_point(type): points_dict = [] points = Point.query(Point.type == type).order(Point.timestamp, Point.pointid).fetch() for point in points: points_dict.append(point.to_dict()) return Response(json.dumps(points_dict), mimetype='application/json');
def post(self): args = self.reqparse.parse_args() Point.query.delete() points = [] for i in range(args['points']): unisinos = Building.query.filter(Building.name == 'Unisinos').first() random_point = unisinos.random_point() points.append(random_point) p = Point() p.geom = 'POINT({0} {1})'.format(random_point.x, random_point.y) db.session.add(p) db.session.commit() return jsonify(results=[p.coords for p in Point.query.all()])
def add_tags_and_points(chart,data,tags = []): for key in data: try: tag = Tag.objects.get(short=key) except ObjectDoesNotExist: tag = Tag(short=key) tag.save() value = data[key] if isinstance(value, int): point = Point(value=value) point.chart = chart point.save() point.tags.add(tag) for t in tags: point.tags.add(t) else: add_tags_and_points(chart,value,[tag]+tags)
def test_point_editing(self): result = Customer.get_points_for('sudhirurl') start_count = len(result) new_point_dict = dict(lat=7.0, lon=7.0, title="seven") new_point_key = Point.create_point(self.sudhir, new_point_dict).key().__str__() result = Customer.get_points_for('sudhirurl') self.assertEqual(len(result), start_count + 1) self.assertTrue(self.find(result, new_point_dict)) new_point_dict = dict(lon=7.0, lat=8.0, title='seveneight') Point.edit(new_point_key, new_point_dict, self.sudhir_gmail) new_results = Customer.get_points_for('sudhirurl') self.assertEqual(len(new_results), start_count + 1) self.assertTrue(self.find(new_results, new_point_dict)) self.assertRaises(db.BadValueError, Point.edit, new_point_key, dict(lon=2345, lat=3, title='invalid values'), self.sudhir_gmail)
def test_setting_points_for_user(self): mom = models.Customer(user=users.User('*****@*****.**'), url='momurl') mom.put() confirmation = Point.create_point(mom, dict(lat=34.678, lon= -44.3456)) self.assertTrue(confirmation) result = Customer.get_points_for('momurl') self.assertEqual(len(result), 1) self.assertEqual(result.count(dict(lat=34.678, lon= -44.3456, title='Untitled', key=str(confirmation.key()))), 1)
def test_user_creation_and_editing(self): test_user = users.User('*****@*****.**') new = Customer.create(url='test', user=test_user) self.assertTrue(new) self.assertEqual(Customer.get_points_for('test').__len__(), 0) self.assertTrue(Point.create_point(new, dict(lat=63.345, lon= -4.23))) self.assertEqual(Customer.get_points_for('test').__len__(), 1) self.assertRaises(Exception, Customer.create, url='test', user=users.User('*****@*****.**')) self.assertRaises(Exception, Customer.create, url='TeSt', user=users.User('*****@*****.**')) self.assertRaises(Exception, Customer.create, url='new_test', user=test_user) renew = Customer.create(url='newtest', user=test_user) self.assertTrue(renew) self.assertEqual(Customer.get_points_for('newtest').__len__(), 1) self.assertTrue(Point.create_point(renew, dict(lat=43.345, lon= -3.23))) self.assertEqual(Customer.get_points_for('newtest').__len__(), 2)
class TestPoint(unittest.TestCase): def setUp(self): self.point = Point(10, -100, 33) self.point.speed = 154 self.point.gas = 0.98 self.point.brake = 0.1 self.point.clutch = 0.4 def test_equal_coords(self): self.assertTrue(self.point.equal_coords(Point(10, -100, 33))) def test_dumps(self): result = self.point.dumps() self.assertEqual(result['x'], self.point.x) self.assertEqual(result['y'], self.point.y) self.assertEqual(result['z'], self.point.z) self.assertEqual(result['s'], self.point.speed) self.assertEqual(result['g'], self.point.gas) self.assertEqual(result['b'], self.point.brake) self.assertEqual(result['c'], self.point.clutch)
def list_point(type): points_dict = memcache.get('{}:points'.format(type)) if points_dict is None: points_dict = [] points = Point.query(Point.type == type).order(Point.timestamp, Point.pointid).fetch() for point in points: points_dict.append(point.to_dict()) if not memcache.add('{}:points'.format(type), points_dict, 43200): logging.error('Memcache set failed.') return Response(json.dumps(points_dict), mimetype='application/json');
def delete_point(type, id): point = Point.get_by_id(int(id)) try: point.key.delete() except CapabilityDisabledError: logging.error(u'App Engine Datastore is currently in read-only mode.') abort(500) except Exception as e: logging.error(e.args[0]) abort(500) return Response(json.dumps({ 'status': 'ok' }), mimetype='application/json');
def test_filter_points(self): point1 = Point(**point_data_1) point1.save() point2 = Point(**point_data_2) point2.save() assert [x for x in filter_points(100, 0, 100, 0)] == [point1] assert [x for x in filter_points(0, -20, 50, 0)] == [point2]
async def create(self, ctx: commands.context): session_ = sessionmaker(bind=engine.get_engine()) session = session_() point = session.query(Point).filter_by( owner=str(ctx.author.id) ).first() if point is not None: await ctx.reply( "**경고** 당신은 이미 포인트 지갑을 가지고 있습니다." ) else: point = Point() point.owner = str(ctx.author.id) point.point = 0 session.add(point) session.commit() await ctx.reply( "포인트 지갑 생성 완료" )
def test_closest_points(self): points_test = [ Point(3, 3), Point(6, 2), Point(5, 6), Point(7, 4), Point(2, 9) ] close_pair_true = (Point(6, 2), Point(7, 4)) self.assertTupleEqual(closest_points(points_test), close_pair_true)
def ungone(): point_id = request.form.get('point_id', False) user = request.cookies.get('username', False) if not user or not point_id: print('missing sth') return 'nothing done' else: try: p = Point.get(id=point_id) u = User.get(username=user) u = UserPoint.get(user=u, point=p) # type: UserPoint u.delete_instance() return 'success' except DoesNotExist: return 'not exist'
def add(request, team_id): # default point object point = Point() point.team = Team.objects.get(id=team_id) # handle form if request.method == 'POST': add_form = AddPointForm(request.POST, instance=point) if add_form.is_valid(): add_form.save() messages.success(request, "Point added.") return redirect('/game/score/' + str(team_id)) else: add_form = AddPointForm(instance=point) data = { 'team_id': team_id, 'forms': { 'add': add_form }, } return render_to_response('game/add.html', data, context_instance = RequestContext(request))
def gone(): point_id = request.form.get('point_id', False) user = request.cookies.get('username', False) if not user or not point_id: return 'nothing done' else: p = Point.get(id=point_id) u = User.get(username=user) try: u, _ = UserPoint.get_or_create(user=u, point=p) if not _: return 'nothing done' else: return 'success' except DoesNotExist: return 'nothing done'
def build_polygons(): polygons = [] with open("../static/states.json", "r") as json_data: for line in json_data: # result.append(json.loads(line)) data = json.loads(line) poly = Polygon(data["state"]) borders = data["border"] for border in borders: poly.add_point(Point(border[0], border[1])) polygons.append(poly) return polygons
def test_polygon_in(self): p1 = Point(1, 1) p2 = Point(1, -1) p3 = Point(-1, -1) p4 = Point(-1, 1) p = Polygon([p1, p2, p3, p4]) p0 = Point(0, 0) pn = Point(1.1, 1) self.assertEqual(p.contains_point(p0), True) self.assertNotEqual(p.contains_point(pn), True)
def test_triangle_area(self): p1 = Point(0, 1) p2 = Point(0, 0) p3 = Point(1, 0) t = Triangle(p1, p2, p3) self.assertAlmostEqual(t.area, 0.5) p1 = Point(-100, 0) p2 = Point(0, 100) p3 = Point(100, 0) t = Triangle(p1, p2, p3) self.assertAlmostEqual(t.area, 10000)
def update_point(type, id): point = Point.get_by_id(int(id)) try: data = json.loads(request.data) if 'title' in data: point.title = data['title'] if 'latitude' in data: point.latitude = float(data['latitude']) if 'longitude' in data: point.longitude = float(data['longitude']) if 'desc' in data: point.desc = data['desc'] if 'resource' in data: point.resource = data['resource'] if 'thumb' in data: point.thumb = data['thumb'] if 'photo' in data: point.photo = data['photo'] if 'video' in data: point.video = data['video'] if 'timestamp' in data: point.timestamp = datetime.strptime(data['timestamp'], "%Y-%m-%dT%H:%M:%S.%fZ") if 'hide' in data: point.hide = bool(data['hide']) point.put() except CapabilityDisabledError: logging.error(u'App Engine Datastore is currently in read-only mode.') abort(500) except Exception as e: logging.error(e.args[0]) abort(500) return Response(json.dumps(point.to_dict()), mimetype='application/json');
def load_tracker(): tracker_url = Config.query(Config.name == 'tracker_url').order(-Config.date_added).get() if tracker_url is None: return Response(json.dumps({ 'error': 'tracker_url configuration was not found.' }), status=500, mimetype='application/json'); tracker_type = Config.query(Config.name == 'tracker_type').order(-Config.date_added).get() if tracker_type is None: return Response(json.dumps({ 'error': 'tracker_type configuration was not found.' }), status=500, mimetype='application/json'); if tracker_type.value == 'delorme': last_date = None last_point = Point.query(Point.type == 'tracker').order(-Point.timestamp).get() if last_point is not None: last_date = last_point.to_dict().timestamp return delorme.load_data(tracker_url.value, last_date) elif tracker_type.value == 'spot': return Response(json.dumps({ 'error': 'tracker not supported.' }), status=400, mimetype='application/json'); else: return Response(json.dumps({ 'error': 'tracker not supported.' }), status=400, mimetype='application/json');
def sync_score(channel): with open(f'./storage/{channel.replace(",", "")}.csv', mode='r') as csvfile: reader = csv.DictReader(csvfile) for row in reader: team = s.query(Team).filter(Team.name.match(channel)).first() receiver = s.query(User).filter(User.username.match( row['User'])).first() giver = s.query(User).filter(User.username.match( row['Sender'])).first() points = Point(giver_id=giver.id, receiver_id=receiver.id, team_id=team.id, points=int(row['Points'])) s.add(points) s.commit() s.close() print(row)
def new(request): """ Funkcja zwraca stronę z formularzem do dodania nowego punktu lub dodaje punkt w zależności od typus żądania: GET (utwórz formularz) lub POST (zapisz formularz). .. include:: ../source/login_required.rst """ if request.method == 'POST': form = NewPointForm(request.POST) if form.is_valid(): point = Point() point.user = request.user point.desc = form.cleaned_data['desc'] point.latit = float(form.cleaned_data['latit']) point.longi = float(form.cleaned_data['longi']) messages.success(request, ADDED) point.save() return HttpResponseRedirect('/')
def hodl(ticker: str, start_date: date, end_date: date, user_config: dict = None): user_config = user_config or {} config = deepcopy( DEFAULT_CONFIG.get( ticker, { 'x_scale': settings.DEFAULT_X_SCALE, 'y_scale': settings.DEFAULT_Y_SCALE })) for k, v in user_config.items(): if v is not None: config[k] = v start_date_string = start_date.isoformat() if start_date else "" end_date_string = end_date.isoformat() if end_date else "" data = tiingo_client.get(start_date_string, end_date_string, ticker) start = data[0] start_date = parser.parse(start["date"]).date() end_date = parser.parse(data[-1]["date"]).date() x_scale = config["x_scale"] y_scale = config["y_scale"] track = Track( start_date, end_date, ticker, [ Point( x=idx + settings.STARTING_AREA_X * x_scale, y=day["close"] - start["close"] + settings.STARTING_AREA_Y * y_scale, date_recorded=day["date"].split('T')[0], price=day["close"], ) for idx, day in enumerate(data) ], config, ) return track_to_json(track)
def test_loci(self): l = Loci() p1 = Point(1, 1) p2 = Point(2, 1) p3 = Point(2, 3) p4 = Point(2, 2) l.append_points(p1, p2, p3, p4) q = l.query(Point(2.5, 0.5)) self.assertEqual(q, 0) res = l.get_points_in_rect(((1.5, 2.5), (0.5, 3.5))) res2 = l.get_points_in_rect(((0.5, 2.5), (0.5, 3.5))) self.assertEqual(res, 3) self.assertEqual(res2, 4) p1 = Point(2, 1) p2 = Point(1, 2) p3 = Point(0, 3) l = Loci() l.append_points(p1, p2, p3) res = l.get_points_in_rect(((0.5, 2.5), (0.5, 2.5))) self.assertEqual(res, 2)
def new_dot(value): ret = list(p_coords) ret[dimension] = value return Point(*ret)
# !/usr/bin/env python from google.appengine.ext import db import cgi from models import Point arguments = cgi.FieldStorage() p = Point(latitude=str(arguments['latitude']),longitude=str(arguments['longitude'])) p.put() ~
def get_point(type, id): point = Point.get_by_id(int(id)) return Response(json.dumps(point.to_dict()), mimetype='application/json');
def test_chain_method(self): graph = OrientedGraph() point = Point(4, 5) v1 = Vertex(Point(4, 2)) v2 = Vertex(Point(2, 4)) v3 = Vertex(Point(6, 5)) v4 = Vertex(Point(5, 7)) e1 = OrientedEdge(v1, v2, 1) e2 = OrientedEdge(v1, v3, 1) e3 = OrientedEdge(v2, v3, 1) e4 = OrientedEdge(v2, v4, 1) e5 = OrientedEdge(v3, v4, 1) graph.add_vertex(v1) graph.add_vertex(v2) graph.add_vertex(v3) graph.add_vertex(v4) graph.add_edge(v1, v2, 1) graph.add_edge(v1, v3, 1) graph.add_edge(v2, v3, 1) graph.add_edge(v2, v4, 1) graph.add_edge(v3, v4, 1) ordered = [v1, v2, v3, v4] weight_table = OrderedDict({ v1: { "vin": [], "vout": [e1, e2], "win": 0, "wout": 2 }, v2: { "vin": [e1], "vout": [e4, e3], "win": 1, "wout": 2 }, v3: { "vin": [e3, e2], "vout": [e5], "win": 2, "wout": 1 }, v4: { "vin": [e4, e5], "vout": [], "win": 2, "wout": 0 }, }) e1_balanced = copy.deepcopy(e1) e1_balanced.weight = 2 e5_balanced = copy.deepcopy(e5) e5_balanced.weight = 2 weight_table_balanced = { v1: { "vin": [], "vout": [e1_balanced, e2], "win": 0, "wout": 3 }, v2: { "vin": [e1_balanced], "vout": [e4, e3], "win": 2, "wout": 2 }, v3: { "vin": [e3, e2], "vout": [e5_balanced], "win": 2, "wout": 2 }, v4: { "vin": [e4, e5_balanced], "vout": [], "win": 3, "wout": 0 }, } e1_new = copy.deepcopy(e1) e1_new.weight = 0 e2_new = copy.deepcopy(e2) e2_new.weight = 0 e3_new = copy.deepcopy(e3) e3_new.weight = 0 e4_new = copy.deepcopy(e4) e4_new.weight = 0 e5_new = copy.deepcopy(e5) e5_new.weight = 0 chains = [[e1_new, e4_new], [e1_new, e3_new, e5_new], [e2_new, e5_new]] root = NodeWithParent(data=chains[1]) tree = ChainsBinTree(root) tree.root.left = NodeWithParent(data=chains[0], parent=root) tree.root.right = NodeWithParent(data=chains[2], parent=root) point_between = (chains[0], chains[1]) ans = chain_method(graph, point) self.assertEqual(ordered, next(ans)) self.assertEqual(weight_table, next(ans)) self.assertEqual(weight_table_balanced, next(ans)) self.assertEqual(chains, next(ans)) self.assertEqual(tree, next(ans)) self.assertEqual(point_between, next(ans))
def add_point(type): try: data = json.loads(request.data) title = None if 'title' in data: title = data['title'] if 'latitude' in data: latitude = float(data['latitude']) else: abort(400) if 'longitude' in data: longitude = float(data['longitude']) else: abort(400) desc = None if 'desc' in data: desc = data['desc'] resource = None if 'resource' in data: resource = data['resource'] thumb = None if 'thumb' in data: thumb = data['thumb'] photo = None if 'photo' in data: photo = data['photo'] timestamp = datetime.now() if 'timestamp' in data: timestamp = datetime.strptime(data['timestamp'], "%Y-%m-%dT%H:%M:%S.%fZ") point = Point( title=title, latitude=latitude, longitude=longitude, desc=desc, resource=resource, timestamp=timestamp, type=type ) point.put() except CapabilityDisabledError: logging.error(u'App Engine Datastore is currently in read-only mode.') abort(500) except BadValueError: abort(400) except TypeError: abort(400) except Exception as e: logging.error(e.args[0]) abort(500) return Response(json.dumps(point.to_dict()), mimetype='application/json');
from models import Track, Line, Point from dateutil import parser example_track = Track( start_date=parser.parse("2010-01-01"), end_date=parser.parse("2020-01-01") ) example_track.lines.append(Line(point_a=Point(x=-10, y=20), point_b=Point(x=50, y=25)))
def delete_point(key, user): return Point.delete_point(key, user)
def query_tag(tag): x = (Point.select().join(PointTag).join(Tag).where( Tag.tag == tag).order_by(Point.created_date.desc())) return render_template('index.html', points=x)
def nearest(lon, lat): x = list(Point.select().execute()) # type: list[Point] x.sort(key=lambda z: (float(z.longitude) - lon)**2 + (float(z.latitude) - lat)**2) return render_template('index.html', points=x)
def test_objective_function(): # generate dummy points points = [Point(0, 1, 1), Point(1, 1, 2), Point(2, 1, 4)] # dummy instance instance = PDPInstance(1, points) assert objective_function(points, instance.distances) == 1
def setUp(self): self.point = Point(10, -100, 33) self.point.speed = 154 self.point.gas = 0.98 self.point.brake = 0.1 self.point.clutch = 0.4
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--config", help="Configuration file") args = parser.parse_args() config_file = args.config config = configparser.ConfigParser() config.read(config_file) # TODO: add errors handling # TODO: move all to the new class start_point = Point( float(config['START POINT']['x']), float(config['START POINT']['y']), float(config['START POINT']['z']), ) dimensions = Vector( float(config['SCENE DIMENSIONS']['dx']), float(config['SCENE DIMENSIONS']['dy']), float(config['SCENE DIMENSIONS']['dz']), ) stl_file = config['OTHERS']['STL file path'] condition = float(config['OTHERS']['minimum volume']) result_file_path = config['OTHERS']['result file path'] stl = STL(stl_file)
def get_points_in_rect(self, rect): x, y = rect q = self.query return (q(Point(x[1], y[1])) - q(Point(x[0], y[1])) - q(Point(x[1], y[0])) + q(Point(x[0], y[0])))
def test_quickhull2(self): pts = [ Point(0, 6), Point(8, 11), Point(10, 4), Point(7, 13), Point(6, 3), Point(3, 0), Point(4, 2), Point(12, 1), Point(14, 10), Point(5, 9), Point(3, 11), Point(1, 4), ] tree = BinTree( Node([ pts[0], pts[10], pts[9], pts[3], pts[1], pts[8], pts[7], pts[2], pts[4], pts[6], pts[5], pts[11], ])) tree.root.left = Node( [pts[0], pts[10], pts[9], pts[3], pts[1], pts[8]]) tree.root.right = Node( [pts[8], pts[7], pts[2], pts[4], pts[6], pts[5], pts[11], pts[0]]) tree.root.left.left = Node([pts[0], pts[10], pts[3]]) tree.root.left.right = Node([pts[3], pts[8]]) tree.root.left.left.left = Node([pts[0], pts[10]]) tree.root.left.left.right = Node([pts[10], pts[3]]) tree.root.right.left = Node([pts[8], pts[7]]) tree.root.right.right = Node( [pts[7], pts[4], pts[6], pts[5], pts[11], pts[0]]) tree.root.right.right.left = Node([pts[7], pts[5]]) tree.root.right.right.right = Node([pts[5], pts[0]]) hull = [pts[0], pts[10], pts[3], pts[8], pts[7], pts[5]] ans = quickhull(pts) self.assertEqual(tree, next(ans)) self.assertEqual(hull, next(ans))
def direction_correct(points, i1, i2, i3): p1, p2, p3 = points[i1], points[i2], points[i3] d = Point.direction(p1, p2, p3) return (d > 0 or d == 0 and p1.dist_to_point(p2) > p1.dist_to_point(p3))
def test_point_centroid(self): p1 = Point(1, 2, 3) p2 = Point(1, 5, 6) p3 = Point(1, 2, 3) self.assertEqual(Point.centroid((p1, p2, p3)), Point(1, 3, 4)) p1 = Point(1, 2, 3) p2 = Point(1, 5, 6) p3 = Point(1, 2, 3) p4 = Point(1, 2, 3) self.assertEqual(Point.centroid((p1, p2, p3, p4)), Point(1, 2.75, 3.75))
def parse_font(font): path = 'datasets/fonts/' + font tools_font = TTFont(path) font_record = Font( name=font, family=tools_font['name'].names[1].string.decode("utf-8"), style=tools_font['name'].names[2].string.decode("utf-8"), ascent=tools_font['hhea'].ascent, descent=tools_font['hhea'].descent, units_per_em=tools_font['head'].unitsPerEm, xMin=tools_font['head'].xMin, yMin=tools_font['head'].yMin, xMax=tools_font['head'].xMax, yMax=tools_font['head'].yMax) duplicate_font = check_font_record_duplicate(font_record) if duplicate_font: print("Font family already present: " + font_record.family) return else: print("Parsing new font family: " + font_record.family) codepoints = [] #Extract valid unicode codepoints, and constituents of composite glyphs for cmap in tools_font['cmap'].tables: if cmap.isUnicode(): codepoints = codepoints + list(cmap.cmap.keys()) codepoints = list(set(codepoints)) #Ensure glyphs only parsed once unicode_names = [] name_dict = {} #Extract the glyph data using the character code for code in codepoints: for cmap in tools_font['cmap'].tables: if cmap.isUnicode(): if code in cmap.cmap.keys(): unicode_names.append(cmap.cmap[code]) name_dict[cmap.cmap[code]] = code print("Candidate unicode glyphs extracted by cmap naming: " + str(len(codepoints))) print("Total number of glyphs in font: " + str(len(tools_font['glyf']))) #Build a glyph dictionary of contour objects for simple glyphs, or a list of #constituent glyph names for composite glyphs #Importantly, our code assumes that composite glyphs have a one-deep hierarchy #i.e. only composed of simple glyphs. This appears to be standard, and a part #of validation workflows when fonts are being created by hand glyphs = {} for name in tools_font['glyf'].glyphOrder: glyph = tools_font['glyf'][name] horizontal_metrics = tools_font['hmtx'][name] unicode_g = -1 unicode_block = None offsets = [] contours = [] if name in unicode_names: unicode_g = name_dict[name] unicode_block = db.session.query(UnicodeBlock).filter( (UnicodeBlock.start <= unicode_g) & (unicode_g <= UnicodeBlock.end)).first() if glyph.numberOfContours < 1: #Check for composites if glyph.numberOfContours < 0: for x in glyph.components: offsets.append( Offset(x=x.x, y=x.y, glyph_name=x.glyphName) ) #Only store the name - the composite_glyph reference will be back-populated, and the component glyph will be referenced later glyphs[name] = Glyph(unicode=unicode_g, name=name, advance_width=horizontal_metrics[0], left_side_bearing=horizontal_metrics[1], xMin=glyph.xMin, xMax=glyph.xMax, yMin=glyph.yMin, yMax=glyph.yMax, simple=False, contours=contours, offsets=offsets, block=unicode_block, font=font_record) else: #Extract all simple glyphs in the font startPt = 0 endPt = -1 for c_ind in range(0, glyph.numberOfContours): startPt = endPt + 1 endPt = glyph.endPtsOfContours[c_ind] s_ind = 1 strokes = [] flag_val = 1 #Determine curve orientation: https://en.wikipedia.org/wiki/Curve_orientation clockwise = True hull_index = 0 hull_y = 0 hull_x = 0 #Demarcate a new contour, possibly a new glyph strokes.append( Stroke(type="G" if c_ind == 0 else "M", order=0, point=Point(x=glyph.coordinates[startPt][0], y=glyph.coordinates[startPt][1]))) for xy in range(startPt + 1, endPt + 1): #LAST POINT ON-CURVE if flag_val == 1: if glyph.flags[ xy] == 1: #THIS POINT ON-CURVE - Build a line 'L' #strokes.append(Stroke(type='L', order=s_ind, points=points)) strokes.append( Stroke(type='L', order=s_ind, point=Point( x=glyph.coordinates[xy][0], y=glyph.coordinates[xy][1]))) else: #THIS POINT OFF-CURVE - Build a control point 'C' strokes.append( Stroke(type='C', order=s_ind, point=Point( x=glyph.coordinates[xy][0], y=glyph.coordinates[xy][1]))) else: #LAST POINT OFF-CURVE if glyph.flags[ xy] == 1: #THIS POINT ON-CURVE - Build a quadratic 'Q' strokes.append( Stroke(type='Q', order=s_ind, point=Point( x=glyph.coordinates[xy][0], y=glyph.coordinates[xy][1]))) else: #THIS POINT OFF-CURVE - Infer a quadratic 'Q' from points and build a control point 'C' #We are dealing with a series of 'off-curve' points #Infer implicit 'on-curve' points as the midpoint between two control points p1 = [strokes[-1].point.x, strokes[-1].point.y] p2 = [ glyph.coordinates[xy][0], glyph.coordinates[xy][1] ] midpoint = Point(x=(p1[0] + p2[0]) / 2, y=(p1[1] + p2[1]) / 2) strokes.append( Stroke(type='Q', order=s_ind, point=midpoint)) s_ind += 1 strokes.append( Stroke(type='C', order=s_ind, point=Point(x=p2[0], y=p2[1]))) s_ind += 1 flag_val = glyph.flags[xy] new_p = strokes[-1].point hull_point = (hull_y == new_p.y and hull_x < new_p.x) or (hull_y < new_p.y) if hull_point: hull_index = s_ind - 1 hull_y = new_p.y hull_x = new_p.x #We'll just have to remember to add a return to start stroke when making training data #Having a line between the last and first point is implicit behavior in all kinds of drawing applications #We will handle this in our front-end visualization and Unity's font engine #points = [Point(x=strokes[-1].points[1].x, y=strokes[-1].points[1].y), # Point(x=strokes[1].points[1].x, y=strokes[1].points[1].x)] #strokes.append(Stroke(type='L', order=s_ind, points=points)) num_strokes = len(strokes) a = strokes[hull_index - 1].point b = strokes[hull_index].point c = strokes[(hull_index + 1) % num_strokes].point determinant = ((b.x - a.x) * (c.y - c.y)) - ((c.x - a.x) * (b.y - a.y)) clockwise = determinant < 0 s_ind += 1 #strokes.append(Stroke(type='M', order=s_ind)) #Purpose is to demarcate contours for training??? contours.append(Contour(orientation=clockwise, strokes=strokes)) glyphs[name] = Glyph( unicode=unicode_g, name=name, advance_width=horizontal_metrics[0], left_side_bearing=horizontal_metrics[1], xMin=glyph.xMin, xMax=glyph.xMax, yMin=glyph.yMin, yMax=glyph.yMax, simple=True, contours=contours, #offsets = offsets, block=unicode_block, font=font_record) #This adds absolutely everything because font is linked to everything else db.session.add(font_record) #MAKE ASSOCIATION TABLE AND MAKE GLYPHS/CONTOURS MANY-TO-MANY #Link composite glyphs to their constituent simpler contours #Only query composite glyphs from the current font using a join composite_glyphs = Glyph.query.filter_by(simple=False, font=font_record).all() for composite in composite_glyphs: contours = [] for i in range(0, len(composite.offsets)): component = composite.offsets[i] component_glyph = Glyph.query.filter_by(name=component.glyph_name, font=font_record).first() new_contour = Contour(strokes=[ Stroke(type="G" if i == 0 else "M", order=i, point=Point(x=component.x, y=component.y)) ], glyphs=[composite]) db.session.add(new_contour) contours.append(new_contour) contours.extend(component_glyph.contours) composite.contours = contours db.session.commit() return glyphs
def homepage(): x = Point.select().order_by(Point.created_date.desc()).execute() return render_template('index.html', points=x)
import json import os import tweepy from pymongo import MongoClient from tweepy import OAuthHandler, Status from config import Config from models import Point from util import get_status_text GEOBOX_WORLD = [Point(-180, -90), Point(180, 90)] # From http://boundingbox.klokantech.com/ GEOBOX_CHICAGO = [ Point( 41.573604, -87.965887, ), Point( 42.085967, -87.367663, ) ] class TwitterAuthentication(object): """Twitter authentication object. This is basically just a wrapper for Twitter API keys to prevent a bunch of variables being scattered everywhere. """ @staticmethod
def __init__(self): self.origin = ps.Point( gv.W / 4, gv.H / 4, -1) # canvas point where to translate_to (canvas center) self.templates = init_templates() # array storing all Template objects
def edit_point(key, new_point, user): return Point.edit(key, new_point, user)
def test_region_tree_method(self): pts = [ Point(1, 9), Point(7, 13), Point(3, 3), Point(1.5, 3), Point(5, 7), Point(9, 8), Point(6, 9), Point(7, 5), Point(7, 12), Point(4, 11), Point(1, 5) ] x_range, y_range = [2.2, 7.7], [6.6, 11.11] pre = (sorted(pts), sorted(sorted(pts), key=lambda u: u.y)) projections = [[Point(1, 5), Point(1, 9)], [Point(1.5, 3)], [Point(3, 3)], [Point(4, 11)], [Point(5, 7)], [Point(6, 9)], [Point(7, 5), Point(7, 12), Point(7, 13)], [Point(9, 8)]] tree = BinTree( Node([[1, 8], [ Point(1.5, 3), Point(3, 3), Point(1, 5), Point(7, 5), Point(5, 7), Point(9, 8), Point(1, 9), Point(6, 9), Point(4, 11), Point(7, 12), Point(7, 13) ]])) tree.root.left = Node([[1, 4], [ Point(1.5, 3), Point(3, 3), Point(1, 5), Point(1, 9), Point(4, 11) ]]) tree.root.left.left = Node([[1, 2], [Point(1.5, 3), Point(1, 5), Point(1, 9)]]) tree.root.left.right = Node( [[2, 4], [Point(1.5, 3), Point(3, 3), Point(4, 11)]]) tree.root.left.right.left = Node([[2, 3], [Point(1.5, 3), Point(3, 3)]]) tree.root.left.right.right = Node([[3, 4], [Point(3, 3), Point(4, 11)]]) tree.root.right = Node([[4, 8], [ Point(7, 5), Point(5, 7), Point(9, 8), Point(6, 9), Point(4, 11), Point(7, 12), Point(7, 13) ]]) tree.root.right.left = Node([[4, 6], [Point(5, 7), Point(6, 9), Point(4, 11)]]) tree.root.right.left.left = Node([[4, 5], [Point(5, 7), Point(4, 11)]]) tree.root.right.left.right = Node([[5, 6], [Point(5, 7), Point(6, 9)]]) tree.root.right.right = Node([[6, 8], [ Point(7, 5), Point(9, 8), Point(6, 9), Point(7, 12), Point(7, 13) ]]) tree.root.right.right.left = Node( [[6, 7], [Point(7, 5), Point(6, 9), Point(7, 12), Point(7, 13)]]) tree.root.right.right.right = Node( [[7, 8], [Point(7, 5), Point(9, 8), Point(7, 12), Point(7, 13)]]) ps = [ tree.root.left.right.right, tree.root.right.left, tree.root.right.right.left ] ss = [[Point(4, 11)], [Point(5, 7), Point(6, 9), Point(4, 11)], [Point(6, 9)]] ans = region_tree_method(pts, x_range, y_range) self.assertEqual(pre, next(ans)) self.assertEqual(projections, next(ans)) self.assertEqual(tree, next(ans)) self.assertEqual([3, 7], next(ans)) self.assertEqual(ps, next(ans)) self.assertEqual(ss, next(ans))
def set_point(customer, new_point): return Point.create_point(customer, new_point)
def test_point_creation(self): p1 = Point(1, 2) p2 = Point(1, 2, 3.6) self.assertEqual(p1.coords, (1, 2)) self.assertEqual(p2.coords, (1, 2, 3.6))
from models import Point, Line, LineType import settings starting_lines = [ Line( point_a=Point(x=-5, y=settings.STARTING_AREA_Y), point_b=Point(x=settings.STARTING_AREA_X, y=settings.STARTING_AREA_Y), type=LineType.ACCELERATION, ) ]
def test_hull_sum(self): p1 = Point(2, 2) p2 = Point(2, -2) p3 = Point(-2, -2) p4 = Point(-2, 2) r1 = Polygon((p1, p2, p3, p4)) p1 = Point(3, 0) p2 = Point(0, -3) p3 = Point(-3, 0) p4 = Point(0, 3) r2 = Polygon((p1, p2, p3, p4)) h = Hull(r1) + Hull(r2) self.assertEqual( h, [ Point(0.0, -3.0), Point(2.0, -2.0), Point(3.0, 0.0), Point(2.0, 2.0), Point(0.0, 3.0), Point(-2.0, 2.0), Point(-3.0, 0.0), Point(-2.0, -2.0), ], ) p1 = Point(2, 2) p2 = Point(2, 0) p3 = Point(0, 0) p4 = Point(0, 2) r1 = Polygon((p1, p2, p3, p4)) p1 = Point(-2, -2) p2 = Point(-2, 0) p3 = Point(0, -1) p4 = Point(0, -2) r2 = Polygon((p1, p2, p3, p4)) h = Hull(r1) + Hull(r2) self.assertEqual(h, [ Point(-2.0, -2.0), Point(0.0, -2.0), Point(2.0, 0.0), Point(2.0, 2.0), Point(0.0, 2.0), Point(-2.0, 0.0) ])