how to get null space in unitywebrequest and base64type - base64

private IEnumerator GetData()
{
WWWForm form = new WWWForm();//php에 보낼 폼을 만듦
form.AddField("data", num);
UnityWebRequest request = new UnityWebRequest();
using (request =
UnityWebRequest.Post("http://localhost/LoadData.php", form))
{
yield return request.SendWebRequest();
if (request.isNetworkError)
{
Debug.Log(request.error);
}
else
{
Debug.Log(request.downloadHandler.text.Length);
Debug.Log(request.downloadHandler.text[request.downloadHandler.text.Length - 1]);
Debug.Log(request.downloadHandler.text[request.downloadHandler.text.Length - 2]);
Debug.Log(request.downloadHandler.text[request.downloadHandler.text.Length - 3]);
string str=request.downloadHandler.text;
str = str.Substring(0, str.Length - 2);
Debug.Log(str[str.Length - 1]);
results = request.downloadHandler.data;
byte[] by = Convert.FromBase64String(request.downloadHandler.text);
Debug.Log(by.Length);
Mesh mesh = MeshSerializer.ReadMesh(by);
transform.GetComponent<MeshFilter>().mesh = mesh;
}
}
I am sending a byte[] as a unity web request, but when sending and receiving, a space is added at the end. so at the beginning, I calculated this space, but it seems to be different for each character length.
The base64 type seems to end with == but I don't know if this is correct
If you use Unity Web Request, can you tell how many null are added?
Or is there a standard for how many null are there?
---added
After sending to Unity Web Request, Post-> Download, the length of the string increased by 2, so at the beginning, only 2 deleted.
As I keep using this method, I don't know what to do because each object has a different null length.
Is it correct to find and compare only the last blank column?

ZWSP: zero width space
https://en.wikipedia.org/wiki/Zero-width_space
ZWSP is created if it is not received in an unusual way.
but don't know that it was data end space add ZWSP

Related

Revit API SetPointElementReference(PointOnPlane) - wrong workplane

I try to create a family instance using CreateAdaptiveComponentInstance and try to host it on a reference point, that's also a control point of a CurveByPoints (spline).
The family links properly to the reference point, but the rotation of the reference point's workplane is totally ignored.
Try this standalone example. Move the reference point P2 -> The cross section at P1 will not rotate.
Now, rebuild and change the >> if(true) << to 'false'. Now you see what I want. But as soon as you move the point P2, the link between P2's coordinates and the family is broken.
CurveByPoints spl = null;
ReferencePointArray pts = null;
// create ref points
var p1 = doc.FamilyCreate.NewReferencePoint(new XYZ( 0, 0, 0)); p1.Name = "P1";
var p2 = doc.FamilyCreate.NewReferencePoint(new XYZ(10,10, 0)); p2.Name = "P2";
var p3 = doc.FamilyCreate.NewReferencePoint(new XYZ(30,20, 0)); p3.Name = "P3";
pts = new ReferencePointArray();
pts.Append(p1); pts.Append(p2); pts.Append(p3);
// create a spline
spl = doc.FamilyCreate.NewCurveByPoints(pts);
spl.Visible = true;
spl.IsReferenceLine = false; // MOdelliinie
// change points to adaptive points
foreach(ReferencePoint p in pts)
{
AdaptiveComponentFamilyUtils.MakeAdaptivePoint(doc, p.Id, AdaptivePointType.PlacementPoint);
p.CoordinatePlaneVisibility = CoordinatePlaneVisibility.Always;
p.ShowNormalReferencePlaneOnly = true;
}
// find an adaptive family to place at the points
FamilySymbol fam_sym = null;
var filter = new FilteredElementCollector(doc);
ICollection<Element> col = filter.OfClass(typeof(FamilySymbol)).ToElements();
if(col!=null)
{
foreach(FamilySymbol ele in col)
{
if(ele == null || !AdaptiveComponentInstanceUtils.IsAdaptiveFamilySymbol(ele) ) {continue;}
if(fam_sym == null)
{
fam_sym=ele;
}
if(ele.Name == "profil_adapt_offset_einfach2") // use a special one instead of the first matching
{
fam_sym = ele as FamilySymbol;
break;
}
}
}
// create family instances
if(fam_sym != null)
{
if(true) // this is waht I want. Try "false" to see what I expect
{
foreach (ReferencePoint p in pts)
{
var inst = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(doc, fam_sym);
var placements = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(inst);
ReferencePoint fam_pt = doc.GetElement(placements.FirstOrDefault()) as ReferencePoint;
var pl = Plane.CreateByNormalAndOrigin(new XYZ(1,0,0), p.Position);
// #### I THINK HERE IS MY PROBLEM ####
// "plane" just points to the reference POINT,
// and not the XZ-PLANE of the reference point.
Reference plane = p.GetCoordinatePlaneReferenceYZ();
PointOnPlane pop = doc.Application.Create.NewPointOnPlane(plane, UV.Zero, UV.BasisU, 0.0);
fam_pt.SetPointElementReference(pop);
}
}
else
{
// create family instances and place along the path
// -> looks good until you move a reference point
double ltot=0.0;
for(var i=0; i<pts.Size-1; ++i)
{
ltot += pts.get_Item(i).Position.DistanceTo(pts.get_Item(i+1).Position);
}
double lfromstart=0;
for(var i=0; i<pts.Size; ++i)
{
if(i>0)
{
lfromstart += pts.get_Item(i).Position.DistanceTo(pts.get_Item(i-1).Position);
}
var inst = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(doc, fam_sym);
var placements = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(inst);
var location = new PointLocationOnCurve(PointOnCurveMeasurementType.NormalizedCurveParameter, lfromstart / ltot, PointOnCurveMeasureFrom.Beginning);
PointOnEdge po = doc.Application.Create.NewPointOnEdge(spl.GeometryCurve.Reference, location);
// attach first adaptive point to ref point
var firstPoint = doc.GetElement(placements.FirstOrDefault()) as ReferencePoint;
firstPoint.SetPointElementReference(po);
}
}
}
I'm using Revit 2018.2, here.
People might also search for: GetCoordinatePlaneReferenceXZ, GetCoordinatePlaneReferenceXY.
[edit1]
NewReferencePoint() does not create SketchPlanes
When I manually move a generated reference point -> Now the SketchPlane for this ReferencePoint is generated. But how create that with the API?
[edi2]
- I found that e.g. manually changing the ReferencePoint.CoordinatePlaneVisibility=true will create the SketchPlane I need. But I can't do that in code:
var sel = new List<ElementId>();
foreach (ReferencePoint p in pts)
{
sel.Add(p.Id);
// make plane visible
p.CoordinatePlaneVisibility = CoordinatePlaneVisibility.Always;
// shake point
ElementTransformUtils.MoveElement(doc, p.Id, XYZ.BasisX);
ElementTransformUtils.MoveElement(doc, p.Id, XYZ.BasisX.Negate());
}
ui_doc.Selection.SetElementIds(sel);
doc.Regenerate();
ui_doc.RefreshActiveView();
Will it help if you use the NewReferencePoint overload taking a Transform argument, cf. NewReferencePoint Method (Transform)? That might define the required plane for you and associate it with the point.
The development team replied to your detailed description and test project provided in the attached ZIP file:
The developer seems to be in need of some API we haven’t exposed. PointElement’s API was written before RIDL, so the entire user interface is not exposed to the API. They need an API to get the reference plane that is normal to the the curve that it is driving. This plane is not the same as what is exposed by API PointElement.GetCoordinatePlaneReferenceYZ() (one among the three planes exposed to API).
As per SketchPlanes not being created (in the macro seen in the linked zip file), yes that is correct and matches the UI. SketchPlanes are elements and are different from Autodesk.Revit.DB.Reference. We don’t create them until we have to. And they get garbage collected too. At the end of description, I see some code that should work (assuming they wrapped it in a transaction). Normally selection of the point alone will trigger creation of the SketchPlane from the UI. That aside, I would still not recommend putting the point on SketchPlane for what they want to do.
While, what they want does not exist in API, it still does not quite mean there is no workaround for what they want to achieve. If the Selection or Reference API exposes selectable/visible references on an element, Autodesk.Revit.DB.Reference, then one can iterate over these and host the point. This is generic Element/Reference API.
I hope this clarifies.

Uncaught TypeError: Cannot read property 'copy' of undefined p5.js/node.js/socket.io

I'm having an error when the second client is connected. My code comparing the two clients current position by p5.Vector.dist() and there's an error, here it is.
And the line in p5.Vector.dist(p5.js:25914) is
p5.Vector.prototype.dist = function (v) {
var d = v.copy().sub(this); //This is the exact line where the error says from
return d.mag();
};
This is my code;
Client side;
//I use for loop to see all the contain of otherCircles
for(var x = 0; x < otherCircles.length; x++){
if(otherCircles[x].id != socket.id){ //To make sure i won't compare the client's data to its own because the data of all connected client's is here
console.log(otherCircles[x].radius); //To see if the data is not null
if(circle.eat(otherCircles[x])){
if(circle.radius * 0.95 >= otherCircles[x].radius){
otherCircles.splice(x,1);
console.log('ATE');
} else if(circle.radius <= otherCircles[x].radius * 0.95){
zxc = circle.radius;
asd = zxc;
circle.radius = null;
console.log('EATEN');
}
}
}
}
//Here's the eat function of the circle
function Circle(positionX,positionY,radius){
//The variables of Circle()
this.position = createVector(positionX, positionY);
this.radius = radius;
this.velocity = createVector(0, 0);
//Here's the eat function
this.eat = function(other) {
var distance = p5.Vector.dist(this.position, other.position); //Heres where the error
if (distance < this.radius + (other.radius * 0.25)) { //Compare there distance
return true;
} else {
return false;
}
}
}
The otherCircles[] contains;
And that is also the output of the line console.log(otherCircles[x].radius);.
I don't think the server side would be necessary because it only do is to receive the current position and size of the client and send the other clients position and size to. All there datas stored in otherCircles(). The line console.log(otherCircles[x].radius); result is not null, so I know there's data where being compared to the clients position, why I'm having an error like this.
It's going to be pretty hard to help you without an MCVE, but I'll try to walk you through debugging this.
You've printed otherCircles[x].radius, which is a good start. But if I were you, I'd want to know much more about otherCircles[x]. What variables and functions does it contain? I'd start by googling "JavaScript print function names of object" and try to figure out exactly what's in that object. What is the value of otherCircles[x].position?
From there, I'd also want to make sure that otherCircles[x].position is defined and an instance of p5.Vector. Does it have a copy() function?
I might also step through the code with a debugger- every browser has one, and you should become familiar with using it.
If you still can't get it work, then please post an MCVE that we can run by copy-pasting it. That means no server code, just hard-code your values so we can see the same error. I'd bet you find your problem while trying to narrow it down to a small example. But if not, we'll go from there. Good luck.

Swift UTF16 Substring

I'm receiving a string from the server in the following format:
118|...message...215|...message2...
Basically, it's the message length followed by a pipe and the message itself, repeated for multiple messages. The message is encoded UTF16.
I'm looking for a way to parse this in Swift. I know I could cast this as NSString and use standard indexes/ranges on that because UTF16 is what NSString uses, but I'm wondering what is the Swift way to handle this? I can't seem to find a way to pull a substring out of a String based on a UTF16 encoding.
Update
I'm not trying to initialize a String with raw UTF16 Data (there's plenty of ways to do that). I already have the string, so I'm trying to take a String in the above format and parse it. The issue I have is that the message length given to me by the server is based on UTF16. I can't simply extract the length and call String.advance(messageLength) on the Index because the length I've been given doesn't match the grapheme clusters that Swift advances on. My issue is that I can't extract from the string the message in Swift. I have to instead cast it over to NSString and then use "normal" NSRange on it. My question is how do I pull the substring out by extracting a range based on my search for the first pipe, and then use the length provided by the parser in UTF16.
This is all extremely simple to do with NSString. Not sure how it can be done in pure Swift (or if it can be done).
Here is my take on parsing the messages out of the string. I had to change your lengths to work with the string.
let message = "13|...message...14|...message2..."
let utf16 = message.utf16
var startingIndex = message.utf16.startIndex
var travellingIndex = message.utf16.startIndex
var messages = [String]()
var messageLength: Int
while travellingIndex != message.utf16.endIndex {
// Start walking through each character
if let char = String(utf16[travellingIndex..<travellingIndex.successor()]) {
// When we find the pipe symbol try to parse out the message length
if char == "|" {
if let stringNumber = Int(String(utf16[startingIndex..<travellingIndex])) {
messageLength = stringNumber
// We found the lenght, now skip the pipe character
startingIndex = travellingIndex.successor()
// move the travelingIndex to the end of the message
travellingIndex = travellingIndex.advancedBy(messageLength)
// get the message and put it into an array
if let message = String(utf16[startingIndex...travellingIndex]) {
messages.append(message)
startingIndex = travellingIndex.successor()
}
}
}
}
travellingIndex = travellingIndex.successor()
}
print(messages)
The output I get at the end is:
["...message...", "...message2..."]
The Foundation framework extends String to be initialisable from data:
import Foundation
let string = String(data: data, encoding: NSUTF16StringEncoding)
Getting rid of Foundation is not possible unless you implement the decoding yourself. Note that with Swift going open-source, Foundation is getting reimplemented without Objective-C dependency here.
EDIT: Thanks, Martin R, the link you provided is indeed working in pure Swift :D
EDIT:
There is the utf16 property of a String whose count property is the length in UTF16. Here is a simple parser for your purpose, efficiency isn't great, but it gets the job done:
func getMessages(var string: String) -> [String]? {
func getMessage(string: String) -> (message: String, rest: String)? {
guard let
index = string.characters.indexOf("|"),
length = Int(String(string.characters.prefixUpTo(index)))
else { return nil }
let msgRest = String(string.characters.suffixFrom(index.successor()))
return (String(msgRest.utf16.prefix(length)), String(msgRest.utf16.dropFirst(length)))
}
var messages : [String] = []
while let (message, rest) = getMessage(string) {
string = rest
messages.append(message)
}
return messages
}
func stringForMessages(messages: [String]) -> String {
return messages.map{ "\($0.utf16.count)|\($0)" }.joinWithSeparator("")
}
let messages = [
"123",
"💆🏽💆🏽💆🏽",
"🙉😇🎅🏿",
"6🕴⚽️"
]
let string = stringForMessages(messages)
let received = getMessages(string)
messages // ["123", "💆🏽💆🏽💆🏽", "🙉😇🎅🏿", "6🕴⚽️"]
I actually tried making it more efficient, but Swift's String mechanics pushed against it.. I challenge anyone to create a beautiful efficient crash-safe parser for this..

NodeJS for-loop unsuccessful at trimming urls that end in with numbers

I'm trying to take a group of Facebook Page urls and extract only the entity title of the page. Ie for 'https://www.facebook.com/BalanceSpaBoca' I'm looking only for 'BalanceSpaBoca.' This script works great for most of the sample data I'm using (the testFBurls array), printing only the trimmed string. For others, though, it prints both the trimmed string and the original string. It seems like all of the urls that get printed twice end with a string of numbers, but I'm not sure why that should make any difference in how the program runs.
var testFBurls = [
'http://www.facebook.com/pages/A-Yoga-Way/361702000576231',
'http://www.facebook.com/aztigurbansalon',
'https://www.facebook.com/pages/Azzurri-Salon-Spa/542579982495983',
'https://www.facebook.com/BalanceSpaBoca',
'https://www.facebook.com/BocaAmericanNailsandSpa',
'http://www.facebook.com/beachyogagirl',
'https://www.facebook.com/pages/Beauty-of-Wax/156355679240',
'http://www.facebook.com/beehivefitness.boca',
'https://www.facebook.com/pages/Believe-Day-Spa-Boutique/197615685896',
'https://www.facebook.com/photo.php?fbid=10151725966640897&set=a.10151725965355897.1073741828.197615685896&type=1&theater',
'http://facebook.com/pages/bigfoot-spa/1486364798260300',
'http://www.facebook.com/bloheartsyou',
'http://www.facebook.com/pages/The-Wellness-Center-Of-Boca-Raton/170371382995576',
'https://www.facebook.com/TherapyBodyBalanced',
'https://www.facebook.com/pages/BodyVital-Massage/177664492277158',
'https://www.facebook.com/bodyworkmall',
'https://www.facebook.com/pages/The-Bombay-Room-Yoga-Studio/148731658497764',
];
var possibleFBurlStarts = [
"https://www.facebook.com/",
"http://www.facebook.com/",
"https://www.facebook.com/pages/",
"http://www.facebook.com/pages/",
];
for (var count=0; count<testFBurls.length; count++){
var currentURL = testFBurls[count];
if (currentURL.indexOf(".com/photo") > -1) {
testFBurls.splice(i, 1);
i--;
}
for (var i=0; i < possibleFBurlStarts.length; i++){
var indexOfSubstring = currentURL.indexOf(possibleFBurlStarts[i]);
if (indexOfSubstring > -1) {
var res = currentURL.replace(possibleFBurlStarts[i], "");
}
}
if (count == testFBurls.length-1){
console.log(testFBurls);
}
}
Here's my console output
pages/A-Yoga-Way/361702000576231
A-Yoga-Way/361702000576231
aztigurbansalon
pages/Azzurri-Salon-Spa/542579982495983
Azzurri-Salon-Spa/542579982495983
BalanceSpaBoca
BocaAmericanNailsandSpa
beachyogagirl
pages/Beauty-of-Wax/156355679240
Beauty-of-Wax/156355679240
beehivefitness.boca
pages/Believe-Day-Spa-Boutique/197615685896
Believe-Day-Spa-Boutique/197615685896
bloheartsyou
pages/The-Wellness-Center-Of-Boca-Raton/170371382995576
The-Wellness-Center-Of-Boca-Raton/170371382995576
TherapyBodyBalanced
pages/BodyVital-Massage/177664492277158
BodyVital-Massage/177664492277158
bodyworkmall
pages/The-Bombay-Room-Yoga-Studio/148731658497764
The-Bombay-Room-Yoga-Studio/148731658497764
Notice that the first url is listed twice (first in its original form, and secondly in its truncated form), but then the second url (the third line in the output) is listed in truncated form alone. Any ideas what is causing this disparity? Only the truncated url should be printed.
You're modifying the array you're iterating through while you're iterating through it: testFBurls.splice(i, 1); which is typically a not-great thing to do. In any case, I think you should be able to accomplish your goal a lot easier with a simple regular expression:
for (var count=0; count<testFBurls.length; count++){
var matches = testFBurls[count].match(/^https?\:\/\/www\.facebook\.com\/(?:pages\/)?([^\/]+)/);
if (matches) {
console.log('found it:', matches[1]);
}
}

Actionscript deserialize Strings into objects

is there a way to deserialize strings to objects in actionscript:
i.e.
var str:String = "{ id: 1, value: ['a', 500] }";
should be made into an appropriate actionscript object.
this is not json, since the keys are not wrapped in quotes.
Ok, for that type of data pattern, there's not a nice way that I know of to do this. going off the assumption you can't affect the data to make it more JSON-like ... here's off the top of my head what I would conceptually try:
var str:String = "{ id:1, value:['a', 500] }";
// strip off the { and } characters since we've nothing nice to do that for us...
var mynewString:String = str.slice(1, str.length - 1);
var stringItems:Array = mynewString.split(",");
var obj:Object = new Object();
for (var i in stringItems)
{
var objProps:Array = stringItems[i].split(":");
// kill off the quotes here
obj[props[0]] = objProps[1].slice(1, objProps[1].length - 1);
if ( obj[props[0]].indexOf('[') == 0 ) {
// remove [ and ] if there
var maybeStrArray:String = obj[props[0]].slice(1, str.length - 1);
// right now assume we're an array based on our inbound data
var strArr:Array = maybeStrArray.split(",");
obj[props[0]] = strArr;
}
}
Something like that or similar to it anyway. Yes, it's crude, and absolutely it could be fashioned in a way that is more flexible (such as move the string to array convert to its own function so I could use it elsewhere). It's just the first thing that conceptually came to mind as an answer.
Try that, tweak around with it and see if it helps.
You can use as3corelib library for JSON deserialization. It's really not worth spending your time on writing own implementation (except you wish so).

Resources