end=" " ^ SyntaxError: invalid cors requestsyntax

温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
渔童使棒钓收纶,芦中鼓枻,樵青使苏兰薪桂,竹里煎茶
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
&看看就明白了……原来(教材跟不上啊。。):
python v3.0以后的版本中将v2.x版本的print 改为了print().
&所以此处调用print("Hello world!")则可成功。
阅读(612)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
loftPermalink:'',
id:'fks_',
blogTitle:'Python刚刚尝试就遇:SyntaxError: invalid syntax',
blogAbstract:'
突然想起个笑话:
一个具有多年编程功力的程序员一天突发兴致要学习书法了,于是就准备了笔墨纸砚,并身着素衣,一副大师模样,手握狼毫深思良久,终于在洁白如玉的宣纸写下:Hello World
&看看就明白了……原来(教材跟不上啊。。):
python v3.0以后的版本中将v2.x版本的print 改为了print().
&所以此处调用print(\"Hello world!\")则可成功。
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}python循环时报 SyntaxError: invalid syntax 错_百度知道
python循环时报 SyntaxError: invalid syntax 错
i = 0;i&10 while i:
driver.execute_script(&window.scrollBy(0,300)&,&&)
i++;运行时报这个错误:SyntaxError: invalid syntax如何处理
我有更好的答案
题主给的错误信息不全,请截图说明。目测有一个错误:if i%2==0 : # if的结尾有冒号
关键是运行时给的错误信息,编辑器的提示不可靠。另外目测有一个小错误:while i:是要表达什么?应该是while i & 10:吧?
采纳率:77%
来自团队:
python对格式要求比较严格,你应该是格式有问题
要如何缩进呢?我没有加任何空格,除了if、、i++前面按了一个tab键 ,driver..前面按了两个tab键
if后边条件我记得都有冒号啊
为您推荐:
其他类似问题
python的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。Python 2.7 SyntaxError invalid syntax
Related questions
Python 2.7 SyntaxError invalid syntax
imported from
Keep getting this error below, Im assuming the quoted code below is causing it:
ANY HELP appreciated thank you :)
SyntaxError: invalid syntax
Traceback (most recent call last):
File "b.py", line 8, in &module&
ssl = ctypes.cdll.LoadLibrary (ctypes.util.find_library ('ssl') or 'libeay32 ')
File "c:\Python27\lib\ctypes\__init__.py", line 443, in LoadLibrary
return self._dlltype(name)
File "c:\Python27\lib\ctypes\__init__.py", line 365, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 126] The specified module could not be found
New error now:
c:\Python25>python b.py Traceback (most recent call last):
"b.py", line 15, in
ssl.EC_KEY_new_by_curve_name.restype = ctypes.c_void_p NameError: name 'ssl' is not defined
UPDATE: JUST added the whole code below so you guys can see, appreciated if someone can take a look below.
import hashlib
import ctypes
import ctypes.util
import urllib2
import sys
import codecs
ctypes.util.find_library('ssl') or ctypes.util.find_library('libeay32')
def check_result (val, func, args):
if val == 0: raise ValueError
else: return ctypes.c_void_p (val)
ssl.EC_KEY_new_by_curve_name.restype = ctypes.c_void_p
ssl.EC_KEY_new_by_curve_name.errcheck = check_result
class KEY:
def __init__(self):
NID_secp256k1 = 714
self.k = ssl.EC_KEY_new_by_curve_name(NID_secp256k1)
self.compressed = False
self.POINT_CONVERSION_COMPRESSED = 2
self.POINT_CONVERSION_UNCOMPRESSED = 4
def __del__(self):
ssl.EC_KEY_free(self.k)
self.k = None
def generate(self, secret=None):
if secret:
priv_key = ssl.BN_bin2bn(secret, 32, ssl.BN_new())
group = ssl.EC_KEY_get0_group(self.k)
pub_key = ssl.EC_POINT_new(group)
ctx = ssl.BN_CTX_new()
ssl.EC_POINT_mul(group, pub_key, priv_key, None, None, ctx)
ssl.EC_KEY_set_private_key(self.k, priv_key)
ssl.EC_KEY_set_public_key(self.k, pub_key)
ssl.EC_POINT_free(pub_key)
ssl.BN_CTX_free(ctx)
return self.k
return ssl.EC_KEY_generate_key(self.k)
def set_privkey(self, key):
self.mb = ctypes.create_string_buffer(key)
ssl.d2i_ECPrivateKey(ctypes.byref(self.k), ctypes.byref(ctypes.pointer(self.mb)), len(key))
def set_pubkey(self, key):
self.mb = ctypes.create_string_buffer(key)
ssl.o2i_ECPublicKey(ctypes.byref(self.k), ctypes.byref(ctypes.pointer(self.mb)), len(key))
def get_privkey(self):
size = ssl.i2d_ECPrivateKey(self.k, 0)
mb_pri = ctypes.create_string_buffer(size)
ssl.i2d_ECPrivateKey(self.k, ctypes.byref(ctypes.pointer(mb_pri)))
return mb_pri.raw
def get_pubkey(self):
size = ssl.i2o_ECPublicKey(self.k, 0)
mb = ctypes.create_string_buffer(size)
ssl.i2o_ECPublicKey(self.k, ctypes.byref(ctypes.pointer(mb)))
return mb.raw
def get_secret(self):
bn = ssl.EC_KEY_get0_private_key(self.k);
bytes = (ssl.BN_num_bits(bn) + 7) / 8
mb = ctypes.create_string_buffer(bytes)
n = ssl.BN_bn2bin(bn, mb);
return mb.raw.rjust(32, chr(0))
def set_compressed(self, compressed):
self.compressed = compressed
if compressed:
form = self.POINT_CONVERSION_COMPRESSED
form = self.POINT_CONVERSION_UNCOMPRESSED
ssl.EC_KEY_set_conv_form(self.k, form)
def dhash(s):
return hashlib.sha256(hashlib.sha256(s).digest()).digest()
def rhash(s):
h1 = hashlib.new('ripemd160')
h1.update(hashlib.sha256(s).digest())
return h1.digest()
b58_digits = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def base58_encode(n):
while n & 0:
n, r = divmod(n, 58)
l.insert(0,(b58_digits[r]))
return ''.join(l)
def base58_decode(s):
for ch in s:
digit = b58_digits.index(ch)
n += digit
def base58_encode_padded(s):
res = base58_encode(int('0x' + s.encode('hex'), 16))
for c in s:
if c == chr(0):
return b58_digits[0] * pad + res
def base58_decode_padded(s):
for c in s:
if c == b58_digits[0]:
h = '%x' % base58_decode(s)
if len(h) % 2:
h = '0' + h
res = h.decode('hex')
return chr(0) * pad + res
def base58_check_encode(s, version=0):
vs = chr(version) + s
check = dhash(vs)[:4]
return base58_encode_padded(vs + check)
def base58_check_decode(s, version=0):
k = base58_decode_padded(s)
v0, data, check0 = k[0], k[1:-4], k[-4:]
check1 = dhash(v0 + data)[:4]
if check0 != check1:
raise BaseException('checksum error')
if version != ord(v0):
raise BaseException('version mismatch')
return data
def gen_eckey(passphrase=None, secret=None, pkey=None, compressed=False, rounds=1):
if passphrase:
secret = passphrase.encode('utf8')
for i in xrange(rounds):
secret = hashlib.sha256(secret).digest()
secret = base58_check_decode(pkey, 128)
compressed = len(secret) == 33
secret = secret[0:32]
k.generate(secret)
k.set_compressed(compressed)
def get_addr(k):
pubkey = k.get_pubkey()
secret = k.get_secret()
hash160 = rhash(pubkey)
addr = base58_check_encode(hash160)
payload = secret
if k.compressed:
payload = secret + chr(1)
pkey = base58_check_encode(payload, 128)
return addr, pkey
def test():
# random uncompressed
print get_addr(gen_eckey())
# random compressed
print get_addr(gen_eckey(compressed=True))
# by secret
print get_addr(gen_eckey(secret=('%064x' % 0xdeadbabe).decode('hex')))
# by passphrase
print get_addr(gen_eckey(passphrase='Satoshi Nakamoto'))
# by private key, uncompressed
print get_addr(gen_eckey(pkey='5K1HkbYffstTZDuV4riUWMbAMkQh57b8798uoy9pXYUDYeUHe7F'))
# by private key, compressed
print get_addr(gen_eckey(pkey='L3ATL5R9Exe1ubuAnHVgNgTKZEUKkDvWYAWkLUCyyvzzxRjtgyFe'))
if __name__ == '__main__':
dict_file = "dictionary.txt"
found_file = "found_addresses.txt"
abe_server = "localhost"
abe_port = "2750"
abe_chain = "Bitcoin"
print "Starting search for used brainwallet addresses using dictionary '%s'" % dict_file
num_lines = sum(1 for line in open(dict_file))
line_count = 0
found = codecs.open(found_file,'a','utf8')
dictionary = codecs.open(dict_file,'r','utf8')
for raw_line in dictionary:
line_count += 1
line = raw_line.rstrip()
a = get_addr(gen_eckey(passphrase=line))
address = a[0]
private_address = a[1]
url = "http://%s:%s/chain/%s/q/getreceivedbyaddress/%s" % (abe_server, abe_port, abe_chain, address)
received_bitcoins = urllib2.urlopen(url).read()
except urllib2.URLError:
print "Request failed for word '%s' to URL '%s'" % (line, url)
if(received_bitcoins != "0"):
msg = "Found address %s using dictionary word %s which has received %s bitcoins. Private key: %s\n" % (address, line.rstrip(), received_bitcoins, private_address)
found.write(msg)
if( (line_count % 1000) == 0 ):
print "Progress: %s of %s words checked so far" % (line_count, num_lines)
found.close()
dictionary.close()
I suspect that the find_libary is failing and then it can not load 'libeay32 ' - Possibly because it is missing or the space at the end may not help.
If the code is as posted the syntax error is that you are not assigning anything to ssl.
I would suggest changing:
ctypes.util.find_library('ssl') or ctypes.util.find_library('libeay32')
libname = ctypes.util.find_library('ssl') or ctypes.util.find_library('libeay32')
print ('Library found as', libname)
if libname:
ssl = ctypes.LibraryLoader.LoadLibrary(libname)
sys.exit()
See also questions close to this topic
i have a dataset named as oDetail.txt ....like this
Transaction id
Product id
i am trying to implement the following code for Apriori...in order to find frequent patterns
from itertools import combinations
import pandas as pd
import numpy as np
trans=pd.read_table('C:/Users/malik/Desktop/oDetail.txt', header=None,index_col=0)
def apriori(trans, support=1, minlen=1):
collen, rowlen
tssum=ts.sum(axis=1)
maxlen=tssum.loc[tssum.idxmax()]
items=list(ts.columns)
results=[]
#loop through items
range(1, maxlen):
#generate patterns
pattern=[]
len(pattern):
#calculate support
pattern=['support']=pattern.sum/rowlen
#filter by support level
Condit=pattern['support']& support
pattern=pattern[Condit]
results.append(pattern)
return results
results =apriori(trans)
print (results)
But this code is showing me following error:
SyntaxError: can't assign to literal
I'm building a news website.In news detail page,I want to fetch out(gather) the relative news depend on the news title.
I only want to gather all the news that
have 3 or 4 same words in the title,and it doesn't matter what words are they.
For example,if some of the news title have the 3 same words"python AI future",and these news will be relative news to each other.
Any friend could help?
Here is my Model:
class News(models.Model):
title = models.CharField(max_length=100, verbose_name='标题')
Here is my newsDetail view:
def newsDetailView(request, news_pk):
news = get_object_or_404(News, id=news_pk)
return render(request, "news_detail.html", {
'news': news,
I'm using SSOCircle IDP to test the integration of a Django application with SAML2 (using django-saml2-auth).
The application is not accessible via the public internet, only my local intranet. I'm being routed to the idp.ssocircle.com page just fine, but I'm then seeing an error message: "Unable to do Single Sign On or Federation."
Does my SAMLRequest payload look correct? Is it an issue that the URLs I'm passing in the payload are not web accessible?
&?xml version='1.0' encoding='UTF-8'?&
&ns0:AuthnRequest xmlns:ns0="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:ns1="urn:oasis:names:tc:SAML:2.0:assertion" AssertionConsumerServiceURL="https://172.18.76.140:8280/my_app/user/sso/acs/" Destination="https://idp.ssocircle.com:443/sso/SSORedirect/metaAlias/publicidp" ID="id-vwAPqXFdIM8qwAzyF" IssueInstant="T18:35:57Z" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Version="2.0"&
&ns1:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity"&https://172.18.76.140:8280/my_app/user/sso/acs/&/ns1:Issuer&
&ns0:NameIDPolicy AllowCreate="false" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient" /&
&/ns0:AuthnRequest&
I am trying to create a python list in C++, but I cannot seem to get the class from the __builtin__-module.
PyObject* o_builtin = PyImport_ImportModule("__builtin__");
PyObject* o_list = PyDict_GetItemString(o_builtin, "list");
if (o_list == nullptr) {
cout && "could not find list in __builtin__" &&
How would I go about this?
I do not know how go detect all of rock. i can detect some rock. Some rock is black i cant detect.
import numpy as np
import cv2
def nothing(x):
H_Max= 169
while True:
name_pic='153.jpg'
img = cv2.imread(name_pic)
frame = cv2.imread(name_pic)
img = cv2.resize(img, ())
frame = cv2.resize(frame, ())
blurred = cv2.GaussianBlur(frame, (5, 5), 0)
hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (H_Min, S_Min, V_Min), (H_Max, S_Max, V_Max))
kernel = np.ones((5,5), np.uint8)
frame_out, contours, hierarchy = cv2.findContours(
mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
M = cv2.moments(cnt)
if M['m00'] == 0 :
M['m00'] = 0.1
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])
area = cv2.contourArea(cnt)
if area & 2.5 :
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.imshow('frame1',frame)
cv2.imshow('fimg', img)
key = cv2.waitKey(1) & 0xFF
if key == 27:
cv2.destroyAllWindows()
I do not know how to improve my detection.
This is picture before and after processing.
Before detection:
After detection:
I have a small python script to extract bitmap data for OS X file/folder icons. It's written to run under Python 2.7.10 and requires pyObjC and wxPython-phoenix.
from AppKit import NSWorkspace, NSGraphicsContext, NSMakeRect
import Quartz
size = 128
workspace = NSWorkspace.sharedWorkspace()
icon_image = workspace.iconForFile_('/'.decode('utf-8'))
image_rect = NSMakeRect(0, 0, size, size)
# Create a context to hold the image data
color_space = Quartz.CGColorSpaceCreateWithName(Quartz.kCGColorSpaceGenericRGB)
context = Quartz.CGBitmapContextCreate(None, size, size, 8, 0, color_space, Quartz.kCGImageAlphaPremultipliedLast)
# Wrap graphics context
gctx = NSGraphicsContext.graphicsContextWithCGContext_flipped_(context, False)
# Make our bitmap context current and render the NSImage into it
NSGraphicsContext.setCurrentContext_(gctx)
icon_image.drawInRect_(image_rect)
width = Quartz.CGBitmapContextGetWidth(context)
height = Quartz.CGBitmapContextGetHeight(context)
bits_per_pixel = Quartz.CGBitmapContextGetBitsPerPixel(context)
varlist_data = Quartz.CGBitmapContextGetData(context)
values = bytearray()
for byte in varlist_data.as_tuple(width*height*(bits_per_pixel/8)):
values.append(byte)
wx_img = wx.Bitmap.FromBufferRGBA(width, height, values)
print "icon image data is ok" if wx_img.IsOk() else "failed"
# Clean up and release memory
NSGraphicsContext.setCurrentContext_(None)
Quartz.CGContextRelease(context) # &-- !!!this causes a crash!!!
Quartz.CGColorSpaceRelease(color_space)
It works fine, except for the cleanup call to Quartz.CGContextRelease(context) at the very end.
The script is basically a pyObjC version of the Objective C implementation .
How can I change the code to successfully perform the memory cleanup?
I am creating a Python wrapper for a C DLL using Python ctypes.
In the Python code below I am creating a array connectionString of c_ubyte that I need to fill int the individual. For example 1,2,3,4,5,6... This connection string is passed to the DLL's DoCallBack function and printed. A buffer is created for the callback function to fill in and everything is passed to the python call back function.
I am looking for a way to update the connectionString bytes before passing them to the DLL's DoCallBack.
Then how to extract the bytes from the connectionString in the python callbackFnk function.
I am looking for a way to update the bytes in outBuffer from the callbackFnk python function
A continuation of this question
C DLL Code
typedef void(*FPCallback)(unsigned char * outBuffer, unsigned short MaxOutBufferLength, unsigned char * connectionString);
FPCallback g_C
extern "C" __declspec( dllexport ) void RegisterCallback(void(*p_Callback)( unsigned char * outBuffer, unsigned short MaxOutBufferLength, unsigned char * connectionString)) {
g_Callback = p_C
extern "C" __declspec( dllexport ) void DoCallBack( unsigned char connectionString) {
printf( "connectionString=[%02x %02x %02x %02x %02x %02x...]\n", connectionString[0], connectionString[1], connectionString[2], connectionString[3], connectionString[4], connectionString[5] );
const unsigned short MAX_BUFFER_SIZE = 6 ;
unsigned char outBuffer[MAX_BUFFER_SIZE];
g_Callback( outBuffer, MAX_BUFFER_SIZE, connectionString, 6 );
// Print the results.
printf( "buffer=[%02x %02x %02x %02x %02x %02x...]\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5] );
Python code
def callbackFnk( outBuffer, outBufferMaxSize, connectionString )
# (Q2) How do I extract individual bytes of the connectionString?
# (Q3) How do I update individual bytes of the out buffer?
customDLL = cdll.LoadLibrary ("customeDLL.dll")
# RegisterCallback
CustomDLLCallbackFUNC = CFUNCTYPE(None, POINTER( c_ubyte), c_ushort, POINTER( c_ubyte) )
CustomDLLCallback_func = CustomDLLCallbackFUNC( callbackFnk )
RegisterCallback = customDLL.RegisterCallback
RegisterCallback.argtypes = [ CustomDLLCallbackFUNC ]
RegisterCallback( CustomDLLCallback_func )
# DoCallBack
DoCallBack = customDLL.DoCallBack
DoCallBack.argtypes = [ POINTER( c_ubyte) ]
connectionString = c_ubyte(6)
# (Q1) How do I update this array of bytes?
# Call the callback
DoCallBack(connectionString)
I am accessing an API and can't get the data returned. The two float pointers will point to an array of data. I must assume the API is working properly. A different function call provides a the length of the data I am retrieving. This values is length down below when attempted.
C Header for Function
int function(int, float * data1, float * data2)
ctypes setup
dll.function.argtypes = (c_int, POINTER(c_float), POINTER(c_float))
dll.function.restypes = c_int
Failed Attempt 1:
x = c_float()
y = c_float()
status = dll.function(1, byref(x), byref(y))
Program crashes OR Access violation writing.
Failed Attempt 2:
x = POINTER(c_float)()
y = POINTER(c_float)()
status = dll.function(1, x, y)
Null Pointer Error
Failed Attempt 3:
dll.function.argtypes = (c_int, c_void_p, c_void_p)
x = c_void_p()
y = c_void_p()
status = dll.function(1, x, y)
Null Pointer Error
Failed Attempt 4:
array = c_float * length
x = array()
y = array()
status = dll.function(1, byref(x), byref(y))
Program crashes
Failed Attempt 5:
array = c_float * length
x = POINTER(array)()
y = POINTER(array)()
status = dll.function(1, x, y)
Null Pointer Error OR ArgumentError: expected LP_c_float instance instead of LP_c_float_Array_[length]
Failed Attempt 6:
x = (c_float*length)()
y = (c_float*length)()
a = cast(x, POINTER(c_float))
b = cast(y, POINTER(c_float))
status = dll.function(1, a, b)
Program crashes
What am I missing and why?
I believe the argtypes are correct. I am attempting to meet them properly, but there continues to be an issues. Do I need to "malloc" the memory somehow? (I'm sure I need to free after I get the data).
This is on Windows 7 with Python 2.7 32-bit.
I have looked through other similar issues and am not finding a solution. I am wondering if, at this point, I can blame the API for this issue.
In Python:
//DeviceData contains char[1024] and int attributes
pRes = PDeviceData() //Pointer(DeviceData)
size = c_int(0)
// initializes pRes into DeviceData[5] with data "IAmTesting" and 123 + i
sdk.lib.Set(byref(pRes), byref(size))
//print attributes char[1024] and int attributes from pRes element
sdk.lib.Read(byref(pRes[1]), size))
Data: ing,
instead of "IAmTesting", 124. With index 0, it displays correctly (IAmTesting, 123).
It seems that the indexing might be incorrect as the set and read functions work without issue in C using the following code:
DeviceData *pResultArray = NULL;
int plSize = 5;
Set(&pResultArray, &plSize));
Read(&pResultArray[1], plSize);
where C declaration of functions are:
int SECRET_C_API Set(DeviceData **device, int *result);
int SECRET_C_API Read(DeviceData *device, int result);
Is my way of accessing the index of the double pointer correct in Python?

我要回帖

更多关于 invalid 的文章

 

随机推荐