clustering.. error with function "fviz_nbclust()" - cluster-analysis

I'm trying to determine the number of cluters (elbow method and silhouette and gap statistic method) with function fviz_nbclust
knowing that at this point I'm only reproducing an example I found on Rpubs.com
thanks in advance for your help
I tried for all three methods ,
this
fviz_nbclust(df, kmeans, method = "wss") + geom_vline(xintercept = 4, linetype = 2)+ labs(subtitle = "Elbow method")
and this
elbow_method <- fviz_nbclust(cust_data, FUNcluster = kmeans, method = "wss") elbow_method
I keep getting this error message:
Error in call_with_cleanup(map_impl, environment(), .type, .progress, :
object 'cleancall_call' not found

Related

Correct parameters for rotation using $BitmapDecoder.GetSoftwareBitmapAsync

I have this PowerShell code:
$AsyncTask = $BitmapDecoder.GetSoftwareBitmapAsync()
But discovered that some of the images coming in are rotated, so experimenting I came up with this:
$BmTf = [BitmapTransform]::new()
$BmTf.Rotation = [BitmapRotation]::None
# $BmTf.Rotation = [BitmapRotation]::Clockwise90Degrees
# $BmTf.Rotation = [BitmapRotation]::Clockwise180Degrees
# $BmTf.Rotation = [BitmapRotation]::Clockwise270Degrees
$AsyncTask = $BitmapDecoder.GetSoftwareBitmapAsync(
[BitmapPixelFormat]::Bgra8,
[BitmapAlphaMode]::Ignore,
$BmTf,
[ExifOrientationMode]::IgnoreExifOrientation,
[ColorManagementMode]::DoNotColorManage
)
While it does work, I'm not familiar BitmapPixelFormat, or the other parameters. The documentation for GetSoftwareBitmapAsync() doesn't appear to give any hints on what the default value it is using for BitmapPixelFormat.
Does anyone know the best values to pass to the version of GetSoftwareBitmapAsync() that takes 5 parameters to mimic the version of GetSoftwareBitmapAsync() that takes 0 parameters?
EDIT:
Just found out that trying [BitmapPixelFormat]::Unknown causes this error:
Exception calling "GetSoftwareBitmapAsync" with "5" argument(s): "The
parameter is incorrect. Windows.Graphics.Imaging: The bitmap pixel
format is unsupported."
But no errors with [BitmapPixelFormat]::Bgra8.
I don't know why GetSoftwareBitmapAsync doesn't like [BitmapPixelFormat]::Unknown, but here is the solution I found.
I need to first load the image to see if it needs rotating. That is done with the original command:
$AsyncTask = $BitmapDecoder.GetSoftwareBitmapAsync()
$SoftwareBitmap = GetAsync( $AsyncTask, ([SoftwareBitmap]) )
Then extract its BitmapPixelFormat:
$BitmapPixelFormat = $SoftwareBitmap.BitmapPixelFormat
And then use $BitmapPixelFormat for all calls to the 5 parameter version of GetSoftwareBitmapAsync().

Getting error 'Insight.Database.FastExpando' does not contain a definition for 'Set1'

The following code is giving the above error, and I cannot figure out why:
var x = _sqlConn.Connection().QueryResults<Results>("MyDb.dbo.get_records", new { id = theId });
int retVal = x.Outputs.Return_Value;
if (retVal == 0) // ...meaning result set was also returned...fine to this point.
{
var list = x.Outputs.Set1; // exception thrown here with above error
var temp = list.FirstOrDefault();
I have been using other features of Insight.Database for a number of years, but have not had to retrieve a SQL RETURN value at the same time as a recordset. The SQL itself works correctly in SSMS, returning a result set and the RETURN value of 0, as expected. This is happening in VS2019, .NET 4 and .NET 4.5.2; Insight.Database 5.2.7 and 5.2.8.
I got this code from the following page:
https://github.com/jonwagner/Insight.Database/wiki/Specifying-Result-Structures
where it shows this:
var results = connection.QueryResults<Beer, Glass>("GetAllBeersAndAllGlasses");
IList<Beer> beers = results.Set1;
which I combined with the following code from here:
https://github.com/jonwagner/Insight.Database/wiki/Output-Parameters
var results = connection.QueryResults<Results>("MyProc", inputParameters);
var p = results.Outputs.p;
That part works. It's accessing .Set1 that is failing, and I am not sure how to track down why.
I do not have experience with the FastExpando class, but Jon promised magic, and I want to believe. Thanks for any help.
I haven’t tried results+dynamic objects in a while…
I think it is because you are doing:
QueryResults<Results> and Results is an Insight type
You probably want:
QueryResults<MyType>
And then you get back a Results<MyType>
Which contains the return val and Set1
If not, post a ticket over on github and we will help you out.

Gatling - how to achieve feeders to pick a new value in loop

In Gatling, I am using feeders to pass the values of the coordinates in a request, below is the code. I want on each repeat a new value from the feeder to be picked up. I am get the following error --
/mapping/v2/: Failed to build request: No attribute named 'map 30 (100.0%) x' is defined
Could someone please advice how this can be achieved. thanks.
val mapfeeder = csv(fileName = "data/cordinates.csv").circular
object PDP {
val pdp = group("ABC_01_DetailsPage") {
exec(http("PropertyDetailsPage")
.get("/abc/property/detail.html?propertyId=12345&index=0&q=${address_json6}&qt=address&_qt=address&offset=1&sort=address&limit=20&view=property&mode=&radius=1.0Km&landuse=All")
.check(substring("Change in Median Price")))
}
.pause(duration = 1)
.feed(mapfeeder) //this works but only take the fist value and repeats it 30 times
.group("ABC_02_DetailsPage_MAP") {
repeat(30) {
feed(mapfeeder) // this one fails with the error mentioned in the post
exec(http("/mapping")
.get(uri22 + "?mapTypeId=1006&x=${mapx}&y=${mapy}&z=19&access_token=${maptoken}"))
}
val scn = scenario("RecordedSimulation")
.feed(SearchFeeder)
.exec(Homepage.homepage, Login.login, SearchLink.search, SearchEntry.searchentry, PDP.pdp, Logout.logout)
setUp(scn.inject(atOnceUsers(1))).protocols(httpProtocol)
You're missing a dot to attach your feed and the following exec, so only the result of the last instruction (the exec) is passed to the repeat method.
It should be:
repeat(30) {
feed(mapfeeder)
.exec(
http("/mapping") // <== HERE, DOT WAS MISSING
.get(uri22 + "?mapTypeId=1006&x=${mapx}&y=${mapy}&z=19&access_token=${maptoken}")
)
}

cgi.parse_multipart function throws TypeError in Python 3

I'm trying to make an exercise from Udacity's Full Stack Foundations course. I have the do_POST method inside my subclass from BaseHTTPRequestHandler, basically I want to get a post value named message submitted with a multipart form, this is the code for the method:
def do_POST(self):
try:
if self.path.endswith("/Hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers
ctype, pdict = cgi.parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
messagecontent = fields.get('message')
output = ""
output += "<html><body>"
output += "<h2>Ok, how about this?</h2>"
output += "<h1>{}</h1>".format(messagecontent)
output += "<form method='POST' enctype='multipart/form-data' action='/Hello'>"
output += "<h2>What would you like to say?</h2>"
output += "<input name='message' type='text'/><br/><input type='submit' value='Submit'/>"
output += "</form></body></html>"
self.wfile.write(output.encode('utf-8'))
print(output)
return
except:
self.send_error(404, "{}".format(sys.exc_info()[0]))
print(sys.exc_info() )
The problem is that the cgi.parse_multipart(self.rfile, pdict) is throwing an exception: TypeError: can't concat bytes to str, the implementation was provided in the videos for the course, but they're using Python 2.7 and I'm using python 3, I've looked for a solution all afternoon but I could not find anything useful, what would be the correct way to read data passed from a multipart form in python 3?
I've came across here to solve the same problem like you have.
I found a silly solution for that.
I just convert 'boundary' item in the dictionary from string to bytes with an encoding option.
ctype, pdict = cgi.parse_header(self.headers['content-type'])
pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
In my case, It seems work properly.
To change the tutor's code to work for Python 3 there are three error messages you'll have to combat:
If you get these error messages
c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
AttributeError: 'HTTPMessage' object has no attribute 'getheader'
or
boundary = pdict['boundary'].decode('ascii')
AttributeError: 'str' object has no attribute 'decode'
or
headers['Content-Length'] = pdict['CONTENT-LENGTH']
KeyError: 'CONTENT-LENGTH'
when running
c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
if c_type == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, p_dict)
message_content = fields.get('message')
this applies to you.
Solution
First of all change the first line to accommodate Python 3:
- c_type, p_dict = cgi.parse_header(self.headers.getheader('Content-Type'))
+ c_type, p_dict = cgi.parse_header(self.headers.get('Content-Type'))
Secondly, to fix the error of 'str' object not having any attribute 'decode', it's because of the change of strings being turned into unicode strings as of Python 3, instead of being equivalent to byte strings as in Python 3, so add this line just under the above one:
p_dict['boundary'] = bytes(p_dict['boundary'], "utf-8")
Thirdly, to fix the error of not having 'CONTENT-LENGTH' in pdict just add these lines before the if statement:
content_len = int(self.headers.get('Content-length'))
p_dict['CONTENT-LENGTH'] = content_len
Full solution on my Github:
https://github.com/rSkogeby/web-server
I am doing the same course and was running into the same problem. Instead of getting it to work with cgi I am now using the parse library. This was shown in the same course just a few lessons earlier.
from urllib.parse import parse_qs
length = int(self.headers.get('Content-length', 0))
body = self.rfile.read(length).decode()
params = parse_qs(body)
messagecontent = params["message"][0]
And you have to get rid of the enctype='multipart/form-data' in your form.
In my case I used cgi.FieldStorage to extract file and name instead of cgi.parse_multipart
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
print('File', form['file'].file.read())
print('Name', form['name'].value)
Another hack solution is to edit the source of the cgi module.
At the very beginning of the parse_multipart (around the 226th line):
Change the usage of the boundary to str(boundary)
...
boundary = b""
if 'boundary' in pdict:
boundary = pdict['boundary']
if not valid_boundary(boundary):
raise ValueError('Invalid boundary in multipart form: %r'
% (boundary,))
nextpart = b"--" + str(boundary)
lastpart = b"--" + str(boundary) + b"--"
...

What am I doing wrong with this Python class? AttributeError: 'NoneType' object has no attribute 'usernames'

Hey there I am trying to make my first class my code is as follows:
class Twitt:
def __init__(self):
self.usernames = []
self.names = []
self.tweet = []
self.imageurl = []
def twitter_lookup(self, coordinents, radius):
twitter = Twitter(auth=auth)
coordinents = coordinents + "," + radius
print coordinents
query = twitter.search.tweets(q="", geocode='33.520661,-86.80249,50mi', rpp=10)
print query
for result in query["statuses"]:
self.usernames.append(result["user"]["screen_name"])
self.names.append(result['user']["name"])
self.tweet.append(h.unescape(result["text"]))
self.imageurl.append(result['user']["profile_image_url_https"])
What I am trying to be able to do is then use my class like so:
test = Twitt()
hello = test.twitter_lookup("38.5815720,-121.4944000","1m")
print hello.usernames
This does not work and I keep getting: "AttributeError: 'NoneType' object has no attribute 'usernames'"
Maybe I just misunderstood the tutorial or am trying to use this wrong. Any help would be appreciated thanks.
I see the error is test.twitter_lookup("38.5815720,-121.4944000","1m") return nothing. If you want the usernames, you need to do
test = Twitt()
test.twitter_lookup("38.5815720,-121.4944000","1m")
test.usernames
Your function twitter_lookup is modifying the Twitt object in-place. You didn't make it return any kind of value, so when you call hello = test.twitter_lookup(), there's no return value to assign to hello, and it ends up as None. Try test.usernames instead.
Alternatively, have the twitter_lookup function put its results in some new object (perhaps a dictionary?) and return it. This is probably the more sensible solution.
Also, the function accepts a coordinents (it's 'coordinates') argument, but then throws it away and uses a hard-coded value instead.