Why am I getting a compiler error indicating the boolean OR function "|" cannot be used with in the following manner:
localEvent = self.window.nextEventMatchingMask(NSEventMask.LeftMouseUpMask | NSEventMask.LeftMouseDraggedMask)
EDIT:
Here is what I eventually found to work
localEvent = self.window!.nextEventMatchingMask(Int(NSEventMask.LeftMouseUpMask.rawValue | NSEventMask.LeftMouseDraggedMask.rawValue))!
Try like this:
localEvent = window.nextEventMatchingMask(Int(NSEventMask.LeftMouseUpMask.rawValue))
or
localEvent = window.nextEventMatchingMask(
Int(NSEventMask.LeftMouseUpMask.union(.LeftMouseDraggedMask).rawValue))
Related
I have made the following attampt at a derive macro in Rust:
extern crate proc_macro;
use crate::proc_macro::TokenStream;
use quote::quote;
use syn;
#[proc_macro_derive(DeserializeConfigurable)]
pub fn deserialize_configurable_derive(input: TokenStream) -> TokenStream {
let ast: syn::DeriveInput = syn::parse(input).unwrap();
let name = &ast.ident;
let gen = quote! {
impl<'de> Deserialize<'de> for #name {
fn deserialize<D>(deserializer: D) -> Result<#name, D::Error>
where
D: Deserializer<'de>,
{
let config = <#name as Configurable>::Config::deserialize(deserializer)?;
Ok(#name::from_config(config))
}
}
};
gen.into()
}
The goal is to provide a specific blanket implementation for deserialize based on another trait, Configurable.
However, the compiler has the following complaint regarding my quote statement:
recursion limit reached while expanding the macro stringify
I don't see the recursion here. I am not even using stringify! What is calling what in infinity here?
Trying to compile this locally gives this full error message:
error: recursion limit reached while expanding the macro `stringify`
--> src/lib.rs:13:15
|
13 | let gen = quote! {
| _______________^
14 | | impl<'de> Deserialize<'de> for #name {
15 | | fn deserialize<D>(deserializer: D) -> Result<#name, D::Error>
16 | | where
... |
22 | | }
23 | | };
| |_____^
|
= help: consider adding a `#![recursion_limit="128"]` attribute to your crate
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
error: aborting due to previous error
Putting the following as the first line of the crate makes the error go away. My guess is that the default recursion_limit is simply too low for a macro this complex (which IMO isn't that complex). I'm sure there's a good reason, and I'm glad the error message contained the solution:
#![recursion_limit="128"]
I am trying to a call a function using the following code:
{
fileName = strsplit(file,'.');
Process = strcat(fileName(1),'_config()')
}
The code works if I hard code: Process = EDA_config() but when I use the above to concatenate the string where fileName(1) = 'EDA', it results in an error. Any help would be appreciated.
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"--"
...
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.
I have a requirement for a test to make a call to one REST endpoint that generates a security token then make a second to the actual system under test. In order to do this I am using smartrics.rest.fitnesse.fixture.RestFixture and setting the baseurl in instantiation to the first base. I am trying to make this call and then set the new baseurl to the new location but am having trouble doing so.
It appears from perusing the code that there is a method setBaseUrl(Url url) but I cannot find an example of using this and am failing trying to figure it out myself.
Has anyone had any luck with this or is there another, better/easier way to achieve this?
The problem lies in RestFixture:processRow - since it uses Java reflection, it attempts to call method without parameters. This will fail since setBaseUrl accepts one argument (Url). I have tried one modification, though not the best way to achieve it - current code RestFixture v3.0 (RestFixture.processRow()):
method1 = getClass().getMethod(methodName);
method1.invoke(this);
Modified code in RestFixture.processRow():
Method[] methods = getClass().getMethods();
int i = 0;
for(i = 0; i < methods.length; i++){
if(methodName.equals(methods[i].getName())){
method1 = methods[i];
break;
}
}
Class[] paramTypes = method1.getParameterTypes();
List<Object> params = new ArrayList<Object>();
for(i = 0; i < paramTypes.length; i++){
String cellText = row.getCell(i+1).text();
Object param = paramTypes[i].getConstructor(String.class).newInstance(cellText);
params.add(param);
}
method1.invoke(this, params.toArray());
Once this modification is done (you might need to add required imports - java.lang.InstantiationException, java.lang.Object, java.util.ArrayList; and an exception handler for InstantiationException), re-build the RestFixture and that should work.
We had what sounds like a similar requirement - we needed to use RestFixture(POST) to retrieve a URL for use in a subsequent RestFixture call(GET).
(Note that we're using an ancient RestFixture 1.1)
I modified the processArguments() method in RestFixture.java thus:
// baseUrl = new Url(args[0]); // original line
baseUrl = new Url(resolve(args[0])); // modified
With this modification in place, my Fitnesse test looks like this:
`!| RestFixture | http:///fds |
| setBody |{"param1":"blah","param2":"blather"} |
| POST | /GetThatUrl | 200 | | |
| let | $urlresult | body | |
!| RestFixture | $urlresult |
| GET| | 200 | Content-Length:[\d]+ | ||`
Without the code change, $urlresult was not resolved and I could not pass in the URL as a variable.