text
stringlengths
226
34.5k
Python: Transform a unicode variable into a string variable Question: I used a web crawler to get some data. I stored the data in a variable `price`. The type of `price` is: <class 'bs4.element.NavigableString'> The type of each element of `price` is: <type 'unicode'> Basically the `price` contains some white space and line feeds followed by: `$520`. I want to eliminate all the extra symbols and recover only the number `520`. I already did a naive solution: def reducePrice(price): key=0 string="" for i in price: if (key==1): string=string+i if (i== '$'): key=1 key=0 return string But I want to implement a more elegant solution, transforming the type of `price` into `str` and then using `str` methods to manipulate it. I already searched a lot in the web and other posts in the forum. The best I could get was that using: p = "".join(price) I can generate a big unicode variable. If you can give me a hint I would be grateful (I'm using python 2.7 in Ubuntu). **edit** I add my spider just in case you need it: def spider(max_pages): page = 1 while page <= max_pages: url = "http://www.lider.cl/walmart/catalog/product/productDetails.jsp?cId=CF_Nivel2_000021&productId=PROD_5913&skuId=5913&pId=CF_Nivel1_000004&navAction=jump&navCount=12" source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text) title = "" price = "" for link in soup.findAll('span', {'itemprop': 'name'}): title = link.string for link in soup.find('em', {'class': 'oferLowPrice fixPriceOferUp '}): price = link.string print(title + '='+ str(reducePrice(price))) page += 1 spider(1) **edit 2** Thanks to Martin and mASOUD I could generate the solution using `str` methods: def reducePrice(price): return int((("".join(("".join(price)).split())).replace("$","")).encode()) This method return an `int`. This was not my original question but it was the next step in my project. I added it because we can't cast unicode into `int` but using encode() to generate a `str` first, we can. Answer: Use a RegEx to extract the price from your Unicode string: import re def reducePrice(price): match = re.search(r'\d+', u' $500 ') price = match.group() # returns u"500" price = str(price) # convert "500" in unicode to single-byte characters. return price Even though this function converts Unicode to a "regular" string as you asked, is there any reason you want this? Unicode strings can be worked with the same way as a regular string. That is `u"500"` is almost the same as `"500"`
Find Pandas dataframe column based on values, in Python Question: I have 2 Pandas Dataframes in Python. Here they are: import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(10,3),columns=list('ABC')) df2 = pd.DataFrame(np.random.rand(10,3),columns=list('ABC')) df['A'] = 1 print df print df2 A B C 0 1 0.333141 0.803991 1 1 0.043958 0.582038 2 1 0.833433 0.782856 3 1 0.722592 0.237912 4 1 0.634979 0.664208 5 1 0.809748 0.889524 6 1 0.110342 0.650617 7 1 0.035417 0.251089 8 1 0.481492 0.128792 9 1 0.190135 0.213608 A B C 0 0.897373 0.599721 0.361668 1 0.495024 0.471351 0.090395 2 0.651174 0.621328 0.721208 3 0.253459 0.567619 0.104370 4 0.357627 0.616717 0.775327 5 0.164323 0.716166 0.740565 6 0.841509 0.464837 0.398952 7 0.398680 0.186555 0.293076 8 0.298785 0.784237 0.704184 9 0.124763 0.384852 0.307361 As you can see in `df`, there is one column with **only** 1's. I need to do the following: 1. Find the name of the column in a Dataframe (`df`) that contains **only** 1's in all rows. 2. Drop that column from `df` 3. Drop that **SAME** column from `df2` I would like to get this: B C 0 0.333141 0.803991 1 0.043958 0.582038 2 0.833433 0.782856 3 0.722592 0.237912 4 0.634979 0.664208 5 0.809748 0.889524 6 0.110342 0.650617 7 0.035417 0.251089 8 0.481492 0.128792 9 0.190135 0.213608 B C 0 0.599721 0.361668 1 0.471351 0.090395 2 0.621328 0.721208 3 0.567619 0.104370 4 0.616717 0.775327 5 0.716166 0.740565 6 0.464837 0.398952 7 0.186555 0.293076 8 0.784237 0.704184 9 0.384852 0.307361 Is there a way to do this? Answer: You can use `DataFrame.apply` with `axis=0` to apply a function to every column of a dataframe. In your case you want to check whether `all(col==1)` for each column. Then you can pick out the columns using a list comprehension, and finally use `DataFrame.drop` do drop the columns: allonecols = df.apply(lambda col: all(col==1), axis = 0) allonecols A True B False C False dtype: bool dropcols = [k for k,v in allonecols.to_dict().items() if v] dropcols ['A'] df2.drop(dropcols, axis = 1)
Python: generating a "curve fit score" Question: I am working on a project in which I am trying to model the movement of an object in a [kymograph](http://en.wikipedia.org/wiki/Kymograph). In order to do so, I fit a curve to each line of pixels in an image, and append the location of the vertex to approximately model the location of the object in the image. Below is a sample image. ![Image to be analyzed](http://i.stack.imgur.com/D1CyB.png) As you can see, early in the time series (at the top of the image) the position of the object is nicely focused and easily modeled with a Gaussian curve. However, closer to the end of the time series (at the bottom of the image), the peak is much more diffuse. I suspect that the data at the bottom of the image will be fit much more closely by a curve modeling a Poisson distribution (image below, right) while the data at the top/middle of the image will be fit much more closely by a Gaussian or polynomial curve (image below, left). ![good and bad examples](http://i.stack.imgur.com/SKu1a.png) Is there any way to, for each line of pixels, fit more than one curve to the same data and then score each for a least-squares fit? This way, I could (hopefully) switch models midway through an image to accommodate changing behaviors of the object that I am trying to track. My current code is below: from PIL import Image def populateData(picture) : """Open an image and populate a list of lists with the grayscale value""" im = Image.open(picture) size = im.size width = size[0] height = size[1] allPixels = list(im.getdata()) pixelList = [allPixels[width*i : width * (i+1)] for i in range(height)] return(pixelList) rawData = populateData("testTop.tif") import numpy as np from scipy.optimize import curve_fit def findVertex(listOfRows) : xList = [] for row in listOfRows : x = np.arange(len(row)) ffunc = lambda x, a, x0, s: a*np.exp(-0.5*(x-x0)**2/s**2) p, _ = curve_fit(ffunc, x, row, p0=[100,5,2]) x0 = p[1] xList.append(x0) xArray = np.array(xList) return(xArray) xValues = findVertex(rawData) def buildRows(listOfRows) : yArray = np.arange(len(listOfRows)) return(yArray) yValues = buildRows(rawData) from matplotlib import pyplot as plt from scipy import ndimage image = ndimage.imread("testTop.tif",flatten=True) fig = plt.figure() axes = fig.add_subplot(111) axes.imshow(image) axes.plot(xValues, yValues, 'k-') axes.set_title('testLine') axes.grid() axes.set_xlabel('x') axes.set_ylabel('time') plt.show() ![program output](http://i.stack.imgur.com/La2sc.png) EDIT: This is the file I used as an input (testTop.tif) ![input image](http://i.stack.imgur.com/Gh5dB.png) Answer: You will need to work out some form of [goodness of fit](http://en.wikipedia.org/wiki/Goodness_of_fit) between the fit and your data. Taking the sum of the squared differences between your current fit (a Gaussian) and your data divided by the variance. sumerrsq = 0. for i in range(yValues.shape[0]): sumerrsq += np.power(yValues[i] - xValues[i],2) goodfit = np.sqrt(sumerrsq/var) I think you can use use the second output from curve fit (the covariance) to get the variance, p, pcov = curve_fit(ffunc, x, row, p0=[100,5,2]) var = np.diag(pcov) You can then check the value of goodfit and if it is not sufficient, switch to a different distribution. In using a different distribution, you may need to use a different estimation of error (this assumes the errors are normally distributed). Note, without the data (and not being sure what array was which) I couldn't test any of this code...
Numba : 'Module' object has no attribute 'global_variables' Question: This is a basic example of numba import numpy as np from numba import double from numba.decorators import jit, autojit X = np.random.random((1000, 3)) def pairwise_python(X): M = X.shape[0] N = X.shape[1] D = np.empty((M, M), dtype=np.float) for i in range(M): for j in range(M): d = 0.0 for k in range(N): tmp = X[i, k] - X[j, k] d += tmp*tmp D[i, j] = np.sqrt(d) return D pairwise_numba = autojit(pairwise_python) pairwise_numba(X) But it generate the error message AttributeError: Failed at object (object mode frontend) Failed at object (object mode backend) 'Module' object has no attribute 'global_variables' My conda version is numba 0.18.2 np19py27_1 numbapro 0.18.0 np19py27_p2 llvmlite 0.4.0 py27_0 Do you have a same problem? Help me.. Answer: It's complicated. This is my solution. $ sudo apt-get install llvm-3.5-dev $ sudo apt-get install libedit-dev $ pip install enum34 $ git clone https://github.com/numba/llvmlite $ cd llvmlite $ LLVM_CONFIG=/usr/bin/llvm-config-3.5 python setup.py install $ conda install numba Fetching package metadata: .... Solving package specifications: . Package plan for installation in environment /home/khkim/anaconda/envs/test: The following packages will be UPDATED: numba: 0.17.0-np19py27_0 --> 0.18.2-np19py27_1 The following packages will be DOWNGRADED: llvmlite: 0.5.0-py27_0 --> 0.4.0-py27_0 And the code work well.
Replace a particular text from a CSV file without knowing the text Question: I need to replace a particular value from a text file, without knowing the value of the string to be replaced. All I know is the line number, and the location of the value in that line which has to be replaced. This has to be done using Python 2.7 for example, the file is like this: a,b,c,s,d,f s,d,f,g,d,f a,d,s,f,g,r a,s,d,f,e,c My code goes like this: point_file = open(pointfile,'r+') read_lines = point_file.readlines() arr1 = [] for i in range(len(read_lines)): arr1.append(read_lines[i]) Now I need to replace arr1[3].split(',')[3] How to do that? **Edit** I do not wish to achieve this using a temporary copy file and then overwrite the existing file. I need to edit the value **in place** the **existing** file. Answer: OK, so I'm assuming fields can have any value (or the following can be shortened considerably by clever substitution tricks). from __future__ import print_function target = (3, 3) # Coordinates of the replaced value new_val = 'X' # New value for the replaced cells with open('src.txt') as f_src: data = f_src.read().strip() table = [line.split(',') for line in data.split('\n')] old_val = table[target[0]][target[1]] new_data = '\n'.join( ','.join( new_val if cell == old_val else cell for cell in row) for row in table) with open('tgt.txt', 'w') as f_tgt: print(new_data, file=f_tgt) My test `src.txt`: a,b,c,s,d,f s,d,f,g,d,f a,d,s,f,g,r a,s,d,f,e,c My output `tgt.txt`: a,b,c,s,d,X s,d,X,g,d,X a,d,s,X,g,r a,s,d,X,e,c
Parsing XML with undeclared prefixes in Python Question: I am trying to parse XML data with Python that uses prefixes, but not every file has the declaration of the prefix. Example XML: <?xml version="1.0" encoding="UTF-8"?> <item subtype="bla"> <thing>Word</thing> <abc:thing2>Another Word</abc:thing2> </item> I have been using xml.etree.ElementTree to parse these files, but whenever the prefix is not properly declared, ElementTree throws a parse error. (`unbound prefix`, right at the start of `<abc:thing2>`) Searching for this error leads me to solutions that suggest I fix the namespace declaration. However, I do not control the XML that I need to work with, so modifying the input files is not a viable option. Searching for namespace parsing in general leads me to many questions about searching in namespace-agnostic way, which is not what I need. I am looking for some way to automatically parse these files, even if the namespace declaration is broken. I have thought about doing the following: * tell ElementTree what namespaces to expect beforehand, because I do know which ones can occur. I found `register_namespace`, but that does not seem to work. * have the full DTD read in before parsing, and see if that solves it. I could not find a way to do this with ElementTree. * tell ElementTree to not bother about namespaces at all. It should not cause issues with my data, but I found no way to do this * use some other parsing library that _can_ handle this issue - though I prefer not to need installation of extra libraries. I have difficulty seeing from the documentation if any others would be able to solve my issue. * some other route that I am currently not seeing? UPDATE: After Har07 put me on the path of `lxml`, I tried to see if this would let me perform the different solutions I had thought of, and what the result would be: * telling the parser what namespaces to expect beforehand: I still could not find any 'official' way to do this, but in my searches before I had found the suggestion to simply add the requisite declaration to the data programmatically. (for a different programming situation - unfortunately I can't find the link anymore) It seemed terribly hacky to me, but I tried it anyway. It involves loading the data as a string, changing the enclosing element to have the right `xmlns` declarations, and then handing it off to `lxml.etree`'s `fromstring` method. Unfortunately, that also requires removing all reference to encoding declaration from the string. It works, though. * Read in the DTD before parsing: it is possible with `lxml` (through `attribute_defaults`, `dtd_validation`, or `load_dtd`), but unfortunately does not solve the namespace issue. * Telling `lxml` not to bother about namespaces: possible through the `recover` option. Unfortunately, that also ignores other ways in which the XML may be broken (see Har07's answer for details) Answer: One possible way is using `ElementTree` compatible library, [`lxml`](http://lxml.de/compatibility.html). For example : from lxml import etree as ElementTree xml = """<?xml version="1.0" encoding="UTF-8"?> <item subtype="bla"> <thing>Word</thing> <abc:thing2>Another Word</abc:thing2> </item>""" parser = ElementTree.XMLParser(recover=True) tree = ElementTree.fromstring(xml, parser) thing = tree.xpath("//thing")[0] print(ElementTree.tostring(thing)) All you need to do for parsing a non well-formed XML using `lxml` is passing parameter `recover=True` to constructor of `XMLParser`. `lxml` also has full support for xpath 1.0 which is very useful when you need to get part of XML document using more complex criteria. **UPDATE :** I don't know all the types of XML error that `recover=True` option can tolerate. But here is another type of error that I know besides unbound namespace prefix: unclosed tag. `lxml` will fix -rather than ignore- unclosed tag by adding corresponding closing tag automatically. For example, given the following broken XML : xml = """<item subtype="bla"> <thing>Word</thing> <bad> <abc:thing2>Another Word</abc:thing2> </item>""" parser = ElementTree.XMLParser(recover=True) tree = ElementTree.fromstring(xml, parser) print(ElementTree.tostring(tree)) The final output XML after parsed by `lxml` is as follow : <item subtype="bla"> <thing>Word</thing> <bad> <abc:thing2>Another Word</abc:thing2> </bad></item>
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 7240: character maps to <undefined> Question: I am student doing my master thesis. As part of my thesis, I am working with **python**. I am reading a log file of `.csv` format and writing the extracted data to another `.csv` file in a well formatted way. However, when the file is read, I am getting this error: > Traceback (most recent call last): File > "C:\Users\SGADI\workspace\DAB_Trace\my_code\trace_parcer.py", line 19, in > for row in reader: > > * File > "C:\Users\SGADI\Desktop\Python-32bit-3.4.3.2\python-3.4.3\lib\encodings\cp1252.py", > line 23, in decode return > `codecs.charmap_decode(input,self.errors,decoding_table)[0]` > * UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position > 7240: character maps to `<undefined>` > import csv import re #import matplotlib #import matplotlib.pyplot as plt import datetime #import pandas #from dateutil.parser import parse #def parse_csv_file(): timestamp = datetime.datetime.strptime('00:00:00.000', '%H:%M:%S.%f') timestamp_list = [] snr_list = [] freq_list = [] rssi_list = [] dab_present_list = [] counter = 0 f = open("output.txt","w") with open('test_log_20150325_gps.csv') as csvfile: reader = csv.reader(csvfile, delimiter=';') for row in reader: #timestamp = datetime.datetime.strptime(row[0], '%M:%S.%f') #timestamp.split(" ",1) timestamp = row[0] timestamp_list.append(timestamp) #timestamp = row[0] details = row[-1] counter += 1 print (counter) #if(counter > 25000): # break #timestamp = datetime.datetime.strptime(row[0], '%M:%S.%f') #timestamp_list.append(float(timestamp)) #search for SNRLevel=\d+ snr = re.findall('SNRLevel=(\d+)', details) if snr == []: snr = 0 else: snr = snr[0] snr_list.append(int(snr)) #search for Frequency=09ABC freq = re.findall('Frequency=([0-9a-fA-F]+)', details) if freq == []: freq = 0 else: freq = int(freq[0], 16) freq_list.append(int(freq)) #search for RSSI=\d+ rssi = re.findall('RSSI=(\d+)', details) if rssi == []: rssi = 0 else: rssi = rssi[0] rssi_list.append(int(rssi)) #search for DABSignalPresent=\d+ dab_present = re.findall('DABSignalPresent=(\d+)', details) if dab_present== []: dab_present = 0 else: dab_present = dab_present[0] dab_present_list.append(int(dab_present)) f.write(str(timestamp) + "\t") f.write(str(freq) + "\t") f.write(str(snr) + "\t") f.write(str(rssi) + "\t") f.write(str(dab_present) + "\n") print (timestamp, freq, snr, rssi, dab_present) #print (index+1) #print(timestamp,freq,snr) #print (counter) #print(timestamp_list,freq_list,snr_list,rssi_list) '''if snr != []: if freq != []: timestamp_list.append(timestamp) snr_list.append(snr) freq_list.append(freq) f.write(str(timestamp_list) + "\t") f.write(str(freq_list) + "\t") f.write(str(snr_list) + "\n") print(timestamp_list,freq_list,snr_list)''' f.close() I searched for the special character and I did not find any. I searched the Internet which suggested to change the format: I tried ut8, latin1 and few other formats, but i am still getting this error. Can you please help me how to solve with `pandas` as well. I also tried with `pandas` but I am still getting the error. I even removed a line in the log file, but the error occurs in the next line. Please help me finding a solution, thank you. Answer: i have solved this issue. we can use this code import codecs types_of_encoding = ["utf8", "cp1252"] for encoding_type in types_of_encoding: with codecs.open(filename, encoding = encoding_type, errors ='replace') as csvfile: your code .... ....
Building libxml with gradle Question: Could you please share your wisdom on cross-compilation of a library like `libxml2`, `libpng`, `libfreetype` that has a configure script and a Makefile for android and other hosts like linux, windows and Mac Os X using **gradle**? At the moment I do not have a complete working example for either libraries but would like to have a solution similar to the following: <https://github.com/couchbase/couchbase-lite-java- native/blob/master/crosscompile-build.gradle> // // To cross compile to ARM replace the default build.gradle with this file. // Before running the build install these additional linux packages // // gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf // apply plugin: 'c' apply plugin: 'java' apply plugin: 'maven' version = System.getenv("MAVEN_UPLOAD_VERSION") model { platforms { osx_x86 { architecture "x86" operatingSystem "osx" } osx_x86_64 { architecture "x86_64" operatingSystem "osx" } linux_x86 { architecture "x86" operatingSystem "linux" } linux_x86_64 { architecture "x86_64" operatingSystem "linux" } linux_amd64 { architecture "amd64" operatingSystem "linux" } linux_arm { architecture "arm" operatingSystem "linux" } windows_x86 { architecture "x86" operatingSystem "windows" } windows_x86_64 { architecture "x86_64" operatingSystem "windows" } windows_amd64 { architecture "amd64" operatingSystem "windows" } } toolChains { visualCpp(VisualCpp) gcc(Gcc) gccArm(Gcc) { getCppCompiler().setExecutable 'arm-linux-gnueabihf-g++' getCCompiler().setExecutable 'arm-linux-gnueabihf-gcc' getAssembler().setExecutable 'arm-linux-gnueabihf-as' getLinker().setExecutable 'arm-linux-gnueabihf-gcc' getStaticLibArchiver().setExecutable 'arm-linux-gnueabihf-ar' addPlatformConfiguration(new ArmSupport()) } clang(Clang) } } class ArmSupport implements TargetPlatformConfiguration { boolean supportsPlatform(Platform element) { return element.getArchitecture().name == "arm" } List<String> getCppCompilerArgs() { [] } List<String> getObjectiveCppCompilerArgs() { [] } List<String> getObjectiveCCompilerArgs() { [] } List<String> getCCompilerArgs() { [] } List<String> getAssemblerArgs() { [] } List<String> getLinkerArgs() { [] } List<String> getStaticLibraryArchiverArgs() { [] } } sources { native_library { c { source { srcDir "src/main/c" } exportedHeaders { srcDir "src/main/include" } } } } libraries { native_library { baseName "CouchbaseLiteJavaNative" } all { binaries.withType(SharedLibraryBinary) { binary -> if (targetPlatform.operatingSystem.macOsX) { cCompiler.args '-I', "/System/Library/Frameworks/JavaVM.framework/Headers" linker.args '-framework', "JavaVM" } else if (targetPlatform.operatingSystem.linux) { cCompiler.args '-I', "${org.gradle.internal.jvm.Jvm.current().javaHome}/include" cCompiler.args '-I', "${org.gradle.internal.jvm.Jvm.current().javaHome}/include/linux" } else if (targetPlatform.operatingSystem.windows) { cCompiler.args "-I${org.gradle.internal.jvm.Jvm.current().javaHome}/include" cCompiler.args "-I${org.gradle.internal.jvm.Jvm.current().javaHome}/include/win32" linker.args "--add-stdcall-alias" } } } } binaries.withType(SharedLibraryBinary) { binary -> if (!buildable) { return } def builderTask = binary.tasks.builder jar.into("native/${targetPlatform.operatingSystem.name}/${targetPlatform.architecture.name}") { from builderTask.outputFile } jar.dependsOn builderTask } task createMavenDirectory(type: Exec) { ext { uploadUser = System.getenv("MAVEN_UPLOAD_USERNAME") + ":" + System.getenv("MAVEN_UPLOAD_PASSWORD") mkcolPath = System.getenv("MAVEN_UPLOAD_REPO_URL") + "com/couchbase/lite/java-native/" + version + "/" } commandLine "curl", "--user", uploadUser, "-X", "MKCOL", mkcolPath } // this hack is only needed for apache mod_dav based Maven repo's like file.couchbase.com. otherwise, skip it createMavenDirectory.onlyIf { System.getenv("MAVEN_UPLOAD_REPO_URL").contains("files") } // first create the directory, then do the upload task uploadArchivesWrapper(dependsOn: createMavenDirectory) << { uploadArchives.execute() } // this will upload, but will not first create a directory (which is needed on some servers) uploadArchives { repositories { mavenDeployer { repository(url: System.getenv("MAVEN_UPLOAD_REPO_URL")) { authentication(userName: System.getenv("MAVEN_UPLOAD_USERNAME"), password: System.getenv("MAVEN_UPLOAD_PASSWORD")) } pom.version = version pom.groupId = 'com.couchbase.lite' pom.artifactId = 'java-native' pom.project { licenses { license { name 'Couchbase Community Edition License Agreement' url 'http://www.couchbase.com/agreement/community' distribution 'repo' } } } } } } task sourcesJar(type: Jar, dependsOn: classes) { classifier = 'sources' from sourceSets.main.java.srcDirs } artifacts { archives sourcesJar } It would be ideal to use the toolchain provided by **Android NDK** and not specify **gnueabi** and link everything statically. ## Edit I have extended the build file quite a bit, however I am getting `UP-TO DATE` for all of the tasks: The setup is: `libxml2-2.9.2` `build.gradle` apply plugin: 'c' import com.ulabs.gradle.AutoConfigureTask import com.ulabs.gradle.MakefileTask import com.ulabs.gradle.ConfigureTask gradle.allprojects { ext.getLibXmlLibsPath = { def distDir = new File(project(":libxml2").projectDir, "buildLibxml2") return distDir.toString() } ext.getLibXmlHeaderPath = { def hDir = new File(project(":libxml2").projectDir, "include") return hDir.toString() } } project(':libxml2') { model { toolChains { visualCpp(VisualCpp) gcc(Gcc) clang(Clang) } platforms { x86 { architecture "x86" } x64 { architecture "x86_64" } itanium { architecture "ia-64" } } components { xml2(NativeLibrarySpec) { sources { c { exportedHeaders { srcDir "include" include "libxml/*.h" } exportedHeaders { srcDir "include" include "win32config.h", "wsockcompat.h" } exportedHeaders { srcDir "." include "libxml.h" } } } } } repositories { libs(PrebuiltLibraries) { libxml2 { headers.srcDir getLibXmlHeaderPath() binaries.withType(StaticLibraryBinary) { def baseDir = getLibXmlLibsPath() staticLibraryFile = file("${baseDir}/libxml2.a") } binaries.withType(SharedLibraryBinary) { def os = targetPlatform.operatingSystem def baseDir = getLibXmlLibsPath() if (os.windows) { sharedLibraryFile = file("${baseDir}/libxml2.dll") if (file("${baseDir}/util.lib").exists()) { sharedLibraryLinkFile = file("${baseDir}/libxml2.lib") } } else if (os.macOsX) { sharedLibraryFile = file("${baseDir}/libxml2.dylib") } else { sharedLibraryFile = file("${baseDir}/libxml2.so") } } } } } } task autoConfigTask(type: AutoConfigureTask) << { extraArgs "" } task configureTask(type: ConfigureTask, dependsOn: autoConfigTask) << { extraArgs "--without-python", "--without-zlib" } task makeFileTask(type: MakefileTask, dependsOn: configureTask) << { println "Running makefile Task ${project}" } task make(dependsOn : makeFileTask) << { def distDir = new File(getLibXmlLibsPath()) delete distDir.toString() distDir.mkdirs() def binDir = projectDir.toString() + "/.libs" FileTree tree = fileTree(binDir.toString()) { include 'libxml2*' exclude '*.la*' } tree.each {File file -> copy { from file.toString() into distDir.toString() } } } } build.dependsOn(make) assemble.dependsOn(make) `buildSrc/src/main/groovy/com/ulabs/gradle/*.groovy` contains: package com.ulabs.gradle import org.gradle.api.DefaultTask import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.Input import org.gradle.api.tasks.Optional import org.gradle.api.Project import org.gradle.api.tasks.incremental.IncrementalTaskInputs class AutoConfigureTask extends DefaultTask { @Input @Optional def extraArgs @TaskAction def execConfigure(IncrementalTaskInputs inputs) { println "Launching AutoConfigureTask from: " + project.projectDir if(!new File(project.projectDir, 'configure.ac').exists() && !new File(project.projectDir, 'configure.in').exists()) { throw new FileNotFoundException( 'autoconfigure task should have either configure.in or configure.ac ') } boolean outDated = false inputs.outOfDate { change -> outDated = true } if(outDated) { project.exec { executable "autoreconf" args "-ivf", hasProperty("extraArgs") ? extraArgs : "" } } } } package com.ulabs.gradle import org.gradle.api.DefaultTask import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.Input import org.gradle.api.tasks.Optional import org.gradle.api.Project import org.gradle.api.tasks.incremental.IncrementalTaskInputs class ConfigureTask extends DefaultTask { @Input @Optional def extraArgs @TaskAction def execConfigure(IncrementalTaskInputs inputs) { if(!new File(project.projectDir, 'configure').exists()) { throw new FileNotFoundException( 'configure task should have a configure script') } boolean outDated = false inputs.outOfDate { change -> outDated = true } if(outDated) { project.exec { executable "./configure" args hasProperty("extraArgs") ? extraArgs : "" } } } } package com.ulabs.gradle import org.gradle.api.DefaultTask import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.Input import org.gradle.api.tasks.Optional import org.gradle.api.Project import org.gradle.api.tasks.incremental.IncrementalTaskInputs class MakefileTask extends DefaultTask { @Input @Optional def extraArgs @Input @Optional def env @TaskAction def execConfigure(IncrementalTaskInputs inputs) { if(!new File(project.projectDir, 'configure').exists()) { throw new FileNotFoundException( 'makefile task should have a Makefile script') } boolean outDated = false inputs.outOfDate { change -> outDated = true } if(outDated) { project.exec { executable "make" args hasProperty("extraArgs") ? extraArgs : "-f Makefile" } } } } This most probably has something to do with inputs to tasks or messed up condiguration/runtime stages of the tasks however I tried many options and none seem to work. So in the end I would like to have: * `./configure`, `autotools` or `make` are not run unless their arguments change (`extraArgs` or `env`) * when the arguments change, I'd like them all to run in a chain as specified by dependencies * I would like `libxml2` to act like a project that can be linked with others and be able to match platform/architecture of the dependant, with linkage api, shared or static Answer: So it seems its better to just call the build system that is shipped with the library itself. Here is the script that does it: task autoReconfigure(type : Exec) { executable "autoreconf" args "-vif" workingDir "." } task configureTask(type : Exec, dependsOn : autoReconfigure) { executable "./configure" args "--without-zlib" workingDir "." } task makeFileTask(type : Exec, dependsOn : configureTask) { executable "make" args "-f", "Makefile" workingDir "." } build.dependsOn(makeFileTask) assemble.dependsOn(makeFileTask) I will try to add support for different toolchains/platforms as I go along
making multi-index in pandas dataframes in Python? Question: I have a data set where there is a matrix of numeric values indexed by a time variable. Each matrix is a numpy array (that can be converted into a dataframe with columns corresponding to columns of the matrix). if i have these matrices how can i make them into a single dataframe where each matrix has a time index? specifically: # time t1 d1 = pandas.DataFrame({"a": [1,2,3,4], "b":[10,20,30,40]}) # time t2 d2 = pandas.DataFrame({"a": [10,20,30,40], "b": [1,2,5,6]}) # time t3 d3 = ... i want to make an index called "time" to index these dataframes, and then aggregate values from columns "a" and "b" across the time index. how can you do this in pandas? my attempt: d=pandas.DataFrame([d1,d2],index=(0, 1),columns=["time"]) _update_ : unutbu's solution for adding two hierarchical columns is: ` c = pd.concat([d1, d2], keys=[('t1', 'p1'), ('t2', 'p2')], names=['time', 'position']) ` my final question is how do you access this resulting structure? for example how do you do vectorized operations across `time`, or across `position`? eg take the average of the rows for each value of `time`. also, how does this compare to encoding `time` and `position` into each dataframe and using `groupby`? in other words when to use levels versus flat columns that are grouped? here's an alternative solution using flat dataframe with groupby: d1["time"] = 1 d1["position"] = "x" d2["time"] = 2 d2["position"] = "y" c = pandas.concat([d1, d2]) # take mean for all time values c.groupby("time").apply(lambda x: np.mean(x, axis=1)) Answer: Given import pandas as pd d1 = pd.DataFrame({"a": [1,2,3,4], "b":[10,20,30,40]}) d2 = pd.DataFrame({"a": [10,20,30,40], "b": [1,2,5,6]}) then [`pd.concat([d1, d2], keys=['t1', 't2'])`](http://pandas.pydata.org/pandas- docs/stable/generated/pandas.concat.html) returns: In [177]: pd.concat([d1, d2], keys=['t1', 't2']) Out[177]: a b t1 0 1 10 1 2 20 2 3 30 3 4 40 t2 0 10 1 1 20 2 2 30 5 3 40 6 * * * If you wish to add more than one level to the new MultiIndex, you can instead pass a _list of tuples_ to the `keys` parameter: In [237]: pd.concat([d1, d2], keys=[('t1', 'p1'), ('t2', 'p2')], names=['time', 'position']) Out[237]: a b time position t1 p1 0 1 10 1 2 20 2 3 30 3 4 40 t2 p2 0 10 1 1 20 2 2 30 5 3 40 6 Note, it is important here that `keys` receives a list of **tuples** , rather than a list of lists.
Animating quiver in matplotlib Question: I followed some suggested code in response to this question, [Plotting animated quivers in Python](http://stackoverflow.com/questions/19329039/plotting-animated-quivers- in-python), but I'm finding I have a problem that one did not address. consider the following code: from matplotlib import pyplot as plt import numpy as np import matplotlib.animation as animation def ufield(x,y,t): return np.cos(x+y)*np.sin(t) def vfield(x,y,t): return np.sin(x+y)*np.cos(t) x = np.linspace(0,10, num=11) y = np.linspace(0,10, num=11) X,Y = np.meshgrid(x,y) t = np.linspace(0,1) def update_quiver(j, ax, fig): u = ufield(X,Y,t[j]) v = vfield(X,Y,t[j]) Q.set_UVC(u, v) ax.set_title('$t$ = '+ str(t[j])) return Q, fig =plt.figure() ax = fig.gca() u = ufield(X,Y,t[0]) v = vfield(X,Y,t[0]) Q = ax.quiver(X, Y, u, v) ax.set_title('$t$ = '+ str(t[0])) ax.set_xlabel('$x$') ax.set_ylabel('$y$') ani = animation.FuncAnimation(fig, update_quiver, frames = range(0,t.size), interval=1,fargs=(ax, fig)) plt.show() This code runs fine, without a problem. But, if I want to use an init_func, and I do, because I want to do more with my animation, I tried: def init_quiver(): u = ufield(X,Y,t[0]) v = vfield(X,Y,t[0]) Q = ax.quiver(X, Y, u, v) ax.set_title('$t$ = '+ str(t[0])) ax.set_xlabel('$x$') ax.set_ylabel('$y$') return Q, remove these lines from the main body of the script u = ufield(X,Y,t[0]) v = vfield(X,Y,t[0]) Q = ax.quiver(X, Y, u, v) and update the animation lines as follows: ani = animation.FuncAnimation(fig, update_quiver, frames = range(0,t.size), init_func=init_quiver, interval=1,fargs=(ax, fig)) plt.show() But when I run this, I see the first frame, and nothing ever updates. Answer: When I run your script, I see the behaviour you describe, and in the terminal where I run it, I get an error with a Traceback ending: > > File "quiv.py", line 21, in update_quiver > Q.set_UVC(u, v) > NameError: global name 'Q' is not defined > You can rectify this by adding the line global Q as the first line of your `init_quiver` function. The complete code now reads: from matplotlib import pyplot as plt import numpy as np import matplotlib.animation as animation def ufield(x,y,t): return np.cos(x+y)*np.sin(t) def vfield(x,y,t): return np.sin(x+y)*np.cos(t) x = np.linspace(0,10, num=11) y = np.linspace(0,10, num=11) X,Y = np.meshgrid(x,y) t = np.linspace(0,1) def update_quiver(j, ax, fig): u = ufield(X,Y,t[j]) v = vfield(X,Y,t[j]) Q.set_UVC(u, v) ax.set_title('$t$ = '+ str(t[j])) return Q, def init_quiver(): global Q u = ufield(X,Y,t[0]) v = vfield(X,Y,t[0]) Q = ax.quiver(X, Y, u, v) ax.set_title('$t$ = '+ str(t[0])) ax.set_xlabel('$x$') ax.set_ylabel('$y$') return Q, fig =plt.figure() ax = fig.gca() ax.set_title('$t$ = '+ str(t[0])) ax.set_xlabel('$x$') ax.set_ylabel('$y$') ani = animation.FuncAnimation(fig, update_quiver, frames = range(0,t.size), init_func=init_quiver, interval=1,fargs=(ax, fig)) plt.show()
Python: difficulty converting ascii to unicode Question: My goal: get the page source from a url and count all instances of a keyword within that page source How I am doing it: getting the pagesource via urllib2, looping through each char of the page source and comparing it to the keyword My problem: my keyword is encoded in utf-8 while the page source is in ascii... I am running into errors whenever I try conversions. getting the page source: import urllib2 response = urllib2.urlopen(myUrl) return response.read() comparing page source and keyword: pageSource[i] == keyWord[j] I need to convert one of these strings to the other's encoding. Intuitively I felt that ascii (the page source) to utf-8 (the key word) would be the best and easiest, so: pageSource = unicode(pageSource) UnicodeDecodeError: 'ascii' codec can't decode byte __ in position __: ordinal not in range(128) Answer: When trying to work with text, don't leave your data as byte strings. Decode to Unicode early, encode back to bytes as late as possible. Decode your downloaded network data: import urllib2 response = urllib2.urlopen(myUrl) # Latin-1 is the default for HTTP text/ responses, adjust as needed codec = response.info().getparam('charset', 'latin1') return response.read().decode(codec) and do the same for your `keyWord` data. If it is encoded as UTF-8, decode it as such, or use Unicode string literals. You may want to read up on Python and Unicode: * [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://joelonsoftware.com/articles/Unicode.html) by Joel Spolsky * [Pragmatic Unicode](http://nedbatchelder.com/text/unipain.html) by Ned Batchelder * The [Python Unicode HOWTO](http://docs.python.org/2/howto/unicode.html)
Web Scraper for dynamic forms in python Question: I am trying to fill the form of this website <http://www.marutisuzuki.com/Maruti-Price.aspx>. It consists of three drop down lists. One is Model of the car, Second is the state and third is city. The first two are static and the third, city is generated dynamically depending upon the value of state, there is an onclick java script event running which gets the values of corresponding cities in a state. I am familiar with mechanize module in python. I came across several links telling me that I cannot handle **dynamic content** in mechanize. But this link <http://toddhayton.com/2014/12/08/form-handling-with-mechanize-and- beautifulsoup/> in the section "**Adding item dynamically** " states that I can use mechanize to handle dynamic content but I did not understand this line of code in it `item = Item(br.form.find_control(name='searchAuxCountryID'),{'contents': '3', 'value': '3', 'label': 3})` What is "Item" in this line of code corresponding to the city field in the form. I came across selenium module which might help me handling dynamic drop down list. But I was not able to find anything in its documentation or any good blog on how to use it. Can some one suggest me how to submit this form for different models, states and cities? Any links on how to solve this problem will be appreciated. A sample code in python on how to submit the form will be helpful. Thanks in advance. Answer: If you look at the request being sent to that site in developer tools, you'll see that a POST is sent as soon as you select a state. The response that is sent back has the form with the values in the city dropdown populated. So, to replicate this in your script you want something like the following: * Open the page * Select the form * Select values for model and state * Submit the form * Select the form from the response sent back * Select value for city (it should be populated now) * Submit the form * Parse the response for the table of results That will look something like: #!/usr/bin/env python import re import mechanize from bs4 import BeautifulSoup def select_form(form): return form.attrs.get('id', None) == 'form1' def get_state_items(browser): browser.select_form(predicate=select_form) ctl = browser.form.find_control('ctl00$ContentPlaceHolder1$ddlState') state_items = ctl.get_items() return state_items[1:] def get_city_items(browser): browser.select_form(predicate=select_form) ctl = browser.form.find_control('ctl00$ContentPlaceHolder1$ddlCity') city_items = ctl.get_items() return city_items[1:] br = mechanize.Browser() br.open('http://www.marutisuzuki.com/Maruti-Price.aspx') br.select_form(predicate=select_form) br.form['ctl00$ContentPlaceHolder1$ddlmodel'] = ['AK'] # model = Maruti Suzuki Alto K10 for state in get_state_items(br): # 1 - Submit form for state.name to get cities for this state br.select_form(predicate=select_form) br.form['ctl00$ContentPlaceHolder1$ddlState'] = [ state.name ] br.submit() # 2 - Now the city dropdown is filled for state.name for city in get_city_items(br): br.select_form(predicate=select_form) br.form['ctl00$ContentPlaceHolder1$ddlCity'] = [ city.name ] br.submit() s = BeautifulSoup(br.response().read()) t = s.find('table', id='ContentPlaceHolder1_dtDealer') r = re.compile(r'^ContentPlaceHolder1_dtDealer_lblName_\d+$') header_printed = False for p in t.findAll('span', id=r): tr = p.findParent('tr') td = tr.findAll('td') if header_printed is False: str = '%s, %s' % (city.attrs['label'], state.attrs['label']) print str print '-' * len(str) header_printed = True print ' '.join(['%s' % x.text.strip() for x in td])
Changing tick labels without affecting the plot Question: I am plotting a 2-D array in python using matplotlib and am having trouble formatting the tick marks. So first, my data is currently organized as a 2-D array with (elevation, latitude). I am plotting values of electron density as a function of height and latitude (basically a longitudinal slice at a specific time). I want to label the x axis going from -90 to 90 degrees in 30 degree intervals and the y values with another array of elevations (each model run has different elevation values so I can't manually assign an arbitrary elevation). I have arrays with latitude values in it and another with elevation values both 1-D arrays. Here is my code: from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt #load the netcdf file into a variable mar120="C:/Users/WillEvo/Desktop/sec_giptie_cpl_mar_120.nc" #grab the data into a new variable fh=Dataset(mar120,mode="r") #assign model variable contents to python variables lons=fh.variables['lon'][:] lats=fh.variables['lat'][:] var1=fh.variables['UN'][:] #specifying which time and elevation to map ionst=var1[0,:,:,21] ionst=ionst[0:len(ionst)-1] #close the netCDF file fh.close() #Set the figure, size, and resolution plt.figure(figsize=(8,6), dpi=100, facecolor='white') plt.subplot(1,1,1) plt.imshow(ionst, origin='lower', interpolation='spline16') plt.xticks([-90, -60, -30, 0, 30, 60, 90]) plt.show() If I don't include the plt.xticks argument I get the following good image but bad tick labels: ![Good Image but bad tick labeling](http://i.stack.imgur.com/ZbkK4.png) If I include the plt.xticks argument I get the following: ![Bad figure, data remains static](http://i.stack.imgur.com/0cckx.png) How can I fix this? I want the data to follow the change in axis (but be accurate). I also need to do this for the y axis but without manually entering values and instead feeding an array of values. Thanks Answer: Use the `extent` argument of `imshow` to set the x and y ranges of the image, and use `aspect='auto'` to allow the aspect ratio of the image to be adjusted to fit the figure. For example, the following code In [68]: from scipy.ndimage.filters import gaussian_filter In [69]: np.random.seed(12345) In [70]: a = np.random.randn(27, 36) In [71]: b = gaussian_filter(a, 4) In [72]: ymin = 0 In [73]: ymax = 1 In [74]: plt.imshow(b, origin='lower', extent=[-90, 90, ymin, ymax], aspect='auto') Out[74]: <matplotlib.image.AxesImage at 0x1115f02d0> In [75]: plt.xticks([-90, -60, -30, 0, 30, 60, 90]) Out[75]: ([<matplotlib.axis.XTick at 0x108307cd0>, <matplotlib.axis.XTick at 0x1101c1c50>, <matplotlib.axis.XTick at 0x1115d4610>, <matplotlib.axis.XTick at 0x1115f0d90>, <matplotlib.axis.XTick at 0x1115ff510>, <matplotlib.axis.XTick at 0x11161db10>, <matplotlib.axis.XTick at 0x111623090>], <a list of 7 Text xticklabel objects>) generates this plot: ![image](http://i.stack.imgur.com/minvJ.png)
How do I start an SSH session locally using Python? Question: What I mean to ask is, if I am on System "A" (Linux) and I want to ssh into System "B" (Windows): On System "A", I can do ssh [email protected] which will prompt me to a password and when that gets authenticated, I will get to the "$" of System "B" (on System "A"). 1. how do I send username and password together as a single line (since I want to use a script) 2. How to achieve the scenario that I have above. Answer: I generally do it with Paramiko, its easier import paramiko # ssh print 'enter ssh' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # this will automatically add the keys ssh.connect(machineHostName, username=user, password=password) # Run your commands # example 1 : ls command print 'do a ls command' stdin, stdout, stderr = ssh.exec_command('ls') print stdout.readlines() time.sleep(2) # example 2 : change ip address print 'changing ip address' stdin, stdout, stderr = ssh.exec_command('sed -i -- s/'+oldIp+'/'+newIp+'/g /etc/sysconfig/network-scripts/ifcfg-eth0') print stdout.readlines() time.sleep(2) To install Paramiko, you can download the tar.gz file from [here](https://pypi.python.org/pypi/paramiko/1.15.2). Assuming you are really new to python, how to install this : * Download the `tar.gz` file * Extract the contents to a folder * `cd` into that extracted folder, from your terminal * execute this `python setup.py install` * then you can try something like the above example NOTE : if you get stuck with installation comment here, and I can help you.
What happens in python when you use the thread function in this code Question: My question is how does python create the thread for the testing of multiple passwords? And why is it more efficient? import zipfile from threading import Thread def extractFile(zFile, password): try: zFile.extractall(pwd=password) print '[+] Found password ' + password + '\n' except: pass def main(): zFile = zipfile.ZipFile('evil.zip') passFile = open('dictionary.txt') for line in passFile.readlines(): password = line.strip('\n') t = Thread(target=extractFile, args=(zFile, password)) t.start() if __name__ == '__main__': main()` Answer: The use of multi-threading makes this code less efficient. The work that is being down here is CPU oriented. Python threads do not work well at distributing CPU oriented work because only one thread can do work at a time (because of the Python GIL or Global Intepreter Lock)! Python threads are more useful for blocking operations such as network calls, disk reads etc. On top of this, making a lot of threads adds a great deal of overhead, because there is a thread scheduler constantly switching which thread is running so that no thread starves. In your example, there is a thread being _created for each file in the line_ , which is pretty bad if there is more than 30-50 lines. To answer your question: > how does python create the thread for the testing of multiple passwords? It simply runs the function `extractFile` in a new thread for each line in your file. > and why is it more efficient? Due to limitations of the Python GIL, and overhead of having more than 20 threads, this is definitely **not** more efficient than running through the entire file without multi-threading.
Use the same SSH object to issue "exec_command()" multiple times in Paramiko Question: I want to use the same SSH object to issue `exec_command()` multiple times in Paramiko module in Python. The objective is to get output from the same session. Is there a way to do it? The `exec_command()` closes channel once it completes executing a command and thereafter a new ssh object is needed to execute a following command .. but the sessions will differ which I do not want. **Code** import os, sys, import connectlibs as ssh s = ssh.connect("xxx.xx.xx.xxx", "Admin", "Admin") channel = s.invoke_shell() channel.send("net use F: \\\\xyz.xy.xc.xa\\dir\n") >>>32 channel.send("net use") >>>7 channel.recv(500) 'Last login: Tue Jun 2 23:52:29 2015 from xxx.xx.xx.xx\r\r\n\x1b]0;~\x07\r\r\n\x1b[32mAdmin@WIN \x1b[33m~\x1b[0m\r\r\n$ net use F: \\\\xyz.xy.xc.xa\\dir\r\nSystem error 67 has occurred.\r\r\n\r\r\nThe network name cannot be found.\r\r\n\r\r\n\x1b]0;~\x07\r\r\n\x1b[32mAdmin@WIN \x1b[33m~\x1b[0m\r\r\n$ net use' >>> Answer: An SSH session can have multiple channels indeed (but [Paramiko possibly does not support it](http://stackoverflow.com/a/19867108/850848)). But by a session you seem to imagine a "shell session". But that's not what the SSH session is. A channel is actually what corresponds to a "shell session". In other words, even if you could open multiple "exec" channels with Paramiko over the same SSH connection (session) and call `exec_command` on these, the commands get executed in a _different shell session_. So it won't help you. * * * You can test this with PuTTY SSH client. The latest version (0.64) supports [connection sharing](http://the.earth.li/~sgtatham/putty/0.64/htmldoc/Chapter4.html#config- ssh-sharing), what basically means that you can have more PuTTY windows (each using its own channel) over a single SSH connection/session. If you execute a command in one PuTTY window, and the commands changes an environment (line an environment variable or a current working directory), the change won't get reflected to the other PuTTY window, even if they share the same SSH connection. * * * So you need to execute the commands in a one channel. Depending on your needs (which are still not clear), you need to use "exec" or "shell" channel. In either case you will have troubles determining where output of one command ends and output of other command starts as they share the same "stream". You can solve that by inserting an unique separator (string) in between and search for it in the channel output stream. channel = ssh.invoke_shell() channel.send('ls\n') channel.send('echo unique-string-separating-output-of-the-commands\n') channel.send('pwd\n')
Reformatting dates in python Question: I'm stuck with this python problem, I have a date in the format of month-day- year and I need to change it to year-month-day format Answer: >>> import datetime >>> datetime.datetime.strptime("06/03/2015", "%m/%d/%Y").strftime("%Y-%m-%d") '2015-06-03' * * * This takes a date (June 3, 2015 in this case) as a string and parses it to a datetime object using [`strptime`](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime). It then converts that to a string in the format you requested (YYYY-mm-dd) using [`strftime`](https://docs.python.org/2/library/datetime.html#datetime.datetime.strftime)
How do I run a Python Script in a Java web application? Question: I need to run a Python script (write input and read output) inside my Java application that will eventually be uploaded onto the web. How do I do this such that it is compatible with the web? I've tried things like `Jython` and `Runtime.exec()` in Java and I think both require `Python` to be installed on the computer (correct me if I'm wrong) but I want the app to be run by anyone on the web. The Python script imports `win32com.client` to operate on a `COM` object. It reads in a .csv file, runs the external software, then writes a .csv file using the methods RCSV(...), Run(...) and WCSV(...). Instead of a .csv file, I would like this data to be accessed from my Java app directly. This is my python script in full for reference: import win32com.client from win32com.client import VARIANT import csv # This will import VT_VARIANT import pythoncom #dictionary function designed to read .csv file def RCSV(address): input=[] csv_reader = csv.DictReader(open(address, 'r'), delimiter=',', quotechar='"') headers = csv_reader.fieldnames for line in csv_reader: for i in range(len(csv_reader.fieldnames)): input.append(line[csv_reader.fieldnames[i]]) InVal=[] for i in range(int(len(input)/len(headers))): InVal.append([]) for i in range(len(InVal)): for j in range(i*len(headers), (i+1)*len(headers)): InVal[i].append(input[j]) return InVal #dictionary function which writes a .csv file given its address def WCSV(address, output, headers): with open(address, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=headers, lineterminator = '\n') writer.writeheader() for i in range(len(output[0])): writer.writerow({headers[x]: output[x][i] for x in range(len(headers))}) def Run(InType,InDesc,InVal,OutType,OutDesc): FieldArray = VARIANT(pythoncom.VT_VARIANT | pythoncom.VT_ARRAY, InDesc) AllValueArray=[None]*len(InVal) for i in range(len(InVal)): AllValueArray[i]=VARIANT(pythoncom.VT_VARIANT | pythoncom.VT_ARRAY, InVal[i]) object.ChangeParametersMultipleElement(InType, FieldArray, AllValueArray) object.RunScriptCommand("SolvePowerFlow") OutVal = object.GetParametersMultipleElement(OutType, OutDesc,'') return OutVal # This will establish the connection object = win32com.client.Dispatch("pwrworld.SimulatorAuto") filename= r"C:\Users\janusz\Desktop\NTU microgrid topology\ICESO Scaledown microgrid.pwb" object.OpenCase(filename) # Reading inputs from a .csv ADIN='IN.csv' InVal = RCSV(ADIN) InType = "GEN" InDesc = ["BusNum", "GenID", "GenMW"] OutType = "BUS" OutDesc = ["BUSNUM", "BUSNAME", "BUSPUVOLT", "BUSANGLE", "BUSKVVOLT"] OutVal = Run(InType,InDesc,InVal,OutType,OutDesc) ADOUT='OUT.csv' WCSV(ADOUT,OutVal[1],OutDesc) #This will close the connection del object object = None Answer: Jython works without Python being installed on the host, because it is a 100% Java implementation of Python. That being said, only `win32` clients can run win32 COM anything. So, that's never going to be compatible across any platform but win32 (and possibly win64 through wow).
CSV, keep file open between each run/measurement Question: I have a question regarding writing CSV-files. I have an instrument where I am going to read a value each minute and write the value to a CSV file together with a timestamp. I have written a simple code which works, which is the first one below. But my friend came up with a question: "Why are you opening and closing the file for each run." I couldn't answer his question since I'm a newbie when it comes to both programming and Python. Nevertheless, I tried to rewrite the code, so it became like solution number 2 below and then asked my friend whether that was better, but he couldn't answer me. So I hope you could help me out, what is the difference between #1 and #2, both gives the same result when it comes to reading the file afterwards. Is it right that #1 will open and close the file for each run in the while loop, and #2 will keep the file open and close it after the last run? This is just a simple example, in reality, I am going to expand the code so it will do a measurement every minute, run for 3-4 days and I am going to log multiple voltages and up to 8 temperatures. So, in the end, the file can become quite large and opening and closing the file can become a bit resource consuming. > Code #1: import csv import datetime import time no_meas = 5 #number of measurements cur_meas = 1 # current measurement number while cur_meas <= no_meas: cur_time = datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S') with open('test.csv', 'a', newline='') as fp: a = csv.writer(fp, delimiter=',') data = [[cur_time, 'test-text']] a.writerows(data) cur_meas += 1 time.sleep(60) > Code #2 import csv import datetime import time no_meas = 5 #number of measurements cur_meas = 1 # current measurement number with open('test.csv', 'a', newline='') as fp: while cur_meas <= no_of_meas: cur_time = datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S') a = csv.writer(fp, delimiter=csv_delimiter) data = [[cur_time, 'test-text']] a.writerows(data) cur_meas += 1 time.sleep(60) Answer: If the the frequency of your writes to the file is high you may want to avoid the open/close overhead. Nevertheless, from what you describe it doesn't seem like an issue (1 open/close per minute for writing a couple of dozens of measurements). Even after a few days your file should not exceed the 1-3MB size. Since you're planning to let it run for a few days, you should handle a scenario of failure without losing the gathered data. In the first case you won't lose any data. In the second case, I'd recommend adding a flush after each write to make sure the data is written to disk: a.writerows(data) fp.flush() os.fsync(fp.fileno())
extracting text from multiple urls Question: I'm very green when it comes to Python but I see how powerful it is. I'd like to try a few things with it but I'm pretty much teaching myself so please, feel free to explain things in their most basic terms. :/ I tried the goose extraction tool to pull some text from a URL and it work pretty well. I was pretty simple... from goose import Goose url = 'http://example.com' g = Goose() article = g.extract(url=url) article.cleaned_text I'd like to replicate the process so I can extract text from hundreds of URLs. Is there a way to set this up so I can enter a list of URLs, extract text, and then (my guess) I could join them together for NLP or whatever else I want to do? Thanks in advance... Answer: Simply put all the urls in a text file like: http://example1.com http://example2.com http://example3.com Then, use this list to loop across like, from goose import Goose # Read list of hundreds of urls from a file url_list = open("url_list.txt", "r").read().split("\n") # loop for each url for url in url_list: g = Goose() article = g.extract(url=url) # process/store ... article.cleaned_text Later, as you have the text required for analysis, go ahead with storing and then processing in a separate code blocks.
celery: daemonic processes are not allowed to have children Question: In Python (2.7) I try to create processes (with multiprocessing) in a celery task (celery 3.1.17) but it gives the error: daemonic processes are not allowed to have children Googling it, I found that most recent versions of billiard fix the "bug" but I have the most recent version (3.3.0.20) and the error is still happening. I also tried to implement [this workaround](http://stackoverflow.com/questions/6974695/python-process-pool- non-daemonic#) in my celery task but it gives the same error. Does anybody know how to do it? Any help is appreciated, Patrick EDIT: snippets of code Task: from __future__ import absolute_import from celery import shared_task from embedder.models import Embedder @shared_task def embedder_update_task(embedder_id): embedder = Embedder.objects.get(pk=embedder_id) embedder.test() _Artificial_ test function ([from here](http://stackoverflow.com/questions/6974695/python-process-pool-non- daemonic#)): def sleepawhile(t): print("Sleeping %i seconds..." % t) time.sleep(t) return t def work(num_procs): print("Creating %i (daemon) workers and jobs in child." % num_procs) pool = mp.Pool(num_procs) result = pool.map(sleepawhile, [randint(1, 5) for x in range(num_procs)]) # The following is not really needed, since the (daemon) workers of the # child's pool are killed when the child is terminated, but it's good # practice to cleanup after ourselves anyway. pool.close() pool.join() return result def test(self): print("Creating 5 (non-daemon) workers and jobs in main process.") pool = MyPool(5) result = pool.map(work, [randint(1, 5) for x in range(5)]) pool.close() pool.join() print(result) My _real_ function: import mulitprocessing as mp def test(self): self.init() for saveindex in range(self.start_index,self.start_index+self.nsaves): self.create_storage(saveindex) # process creation: procs = [mp.Process(name="Process-"+str(i),target=getattr(self,self.training_method),args=(saveindex,)) for i in range(self.nproc)] for p in procs: p.start() for p in procs: p.join() print "End of task" The init function defines a multiprocessing array and an object that share the same memory so that all my processes can update this same array at the same time: mp_arr = mp.Array(c.c_double, np.random.rand(1000000)) # example self.V = numpy.frombuffer(mp_arr.get_obj()) #all the processes can update V Error generated when task is called: [2015-06-04 09:47:46,659: INFO/MainProcess] Received task: embedder.tasks.embedder_update_task[09f8abae-649a-4abc-8381-bdf258d33dda] [2015-06-04 09:47:47,674: WARNING/Worker-5] Creating 5 (non-daemon) workers and jobs in main process. [2015-06-04 09:47:47,789: ERROR/MainProcess] Task embedder.tasks.embedder_update_task[09f8abae-649a-4abc-8381-bdf258d33dda] raised unexpected: AssertionError('daemonic processes are not allowed to have children',) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/home/patrick/django/entite-tracker-master/entitetracker/embedder/tasks.py", line 21, in embedder_update_task embedder.test() File "/home/patrick/django/entite-tracker-master/entitetracker/embedder/models.py", line 475, in test pool = MyPool(5) File "/usr/lib/python2.7/multiprocessing/pool.py", line 159, in __init__ self._repopulate_pool() File "/usr/lib/python2.7/multiprocessing/pool.py", line 223, in _repopulate_pool w.start() File "/usr/lib/python2.7/multiprocessing/process.py", line 124, in start 'daemonic processes are not allowed to have children' AssertionError: daemonic processes are not allowed to have children Answer: `billiard` and `multiprocessing` are different libraries - `billiard` is the Celery project's own fork of `multiprocessing`. You will need to import `billiard` and use it instead of `multiprocessing` However the better answer is probably that you should refactor your code so that you spawn more Celery tasks instead of using two different ways of distributing your work. You can do this using Celery [canvas](http://celery.readthedocs.org/en/latest/userguide/canvas.html) from celery import group @app.task def sleepawhile(t): print("Sleeping %i seconds..." % t) time.sleep(t) return t def work(num_procs): return group(sleepawhile.s(randint(1, 5)) for x in range(num_procs)]) def test(self): my_group = group(work(randint(1, 5)) for x in range(5)) result = my_group.apply_async() result.get() I've attempted to make a working version of your code that uses canvas primitives instead of multiprocessing. However since your example was quite artificial it's not easy to come up with something that makes sense. Update: Here is a translation of your real code that uses Celery canvas: `tasks.py`: @shared_task run_training_method(saveindex, embedder_id): embedder = Embedder.objects.get(pk=embedder_id) embedder.training_method(saveindex) `models.py`: from tasks import run_training_method from celery import group class Embedder(Model): def embedder_update_task(self): my_group = [] for saveindex in range(self.start_index, self.start_index + self.nsaves): self.create_storage(saveindex) group.extend([run_training_method.subtask((saveindex, self.id)) for i in range(self.nproc)]) result = group(my_group).apply_async()
Find XML element 'start' and 'end' using tinyxml2 (or other C++ XML library) Question: I am trying to iterate through the elements of an XML document, and firing events on 'start' elements and 'end' elements. This is pretty straight-forward in using Python's lxml module, and there is even another question on SO regarding this: [Using Python's xml.etree to find element start and end character offsets](http://stackoverflow.com/questions/8111556/using-pythons-xml-etree- to-find-element-start-and-end-character-offsets) #!/usr/bin/python import re, sys from lxml import etree from StringIO import StringIO dtd = etree.DTD (open (sys.argv [1], "r")) xml = etree.XML (open (sys.argv [2], "r").read ()) result = dtd.validate (xml) for error in dtd.error_log.filter_from_errors(): print(error.message) print(error.line) print(error.column) if result == True : for event, elem in etree.iterwalk (xml, events=('start', 'end')) : if event == 'start' : print 'starting element:', elem.tag elif event == 'end' : print 'ending element:', elem.tag if elem is not xml : print elem.tail I would like to do essentially the same thing using the tinyxml2 C++ XML library, but I have not had any luck with this so far [**specifically finding closing tags**]. I prefer tinyxml2 as it is 'tiny', but I am open to other C++ XML libs if they can achieve this end (more easily). If there is a better way to fire events on 'end tags' I am open to that as well. Answer: [tinyXml2](http://www.grinninglizard.com/tinyxml2/) offers a very basic(and very fast) implementation to parser and navigate inside a xml structure. [RapidXML](http://rapidxml.sourceforge.net/) is likely faster but it has the same basic behavior. I suggest if it is enterily mandatory catching event (start and end) use Xerces because SAXParser allows catching when the parser is inside an xml element and when it exits from the element also. The great inconvenience, in my humble opinion, is the compilation under MSVC, it is damned tedious because you must compile the apache commons in C++, but under gcc environment I think is trivial in comparission. GoodLuck!
Python smtlib raising error when trying to send e-mail Question: I copied this code right from the smtplib docs over here import smtplib def prompt(prompt): return input(prompt).strip() fromaddr = prompt("From: ") toaddrs = prompt("To: ").split() print("Enter message, end with ^D (Unix) or ^Z (Windows):") # Add the From: and To: headers at the start! msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs))) while True: try: line = input() except EOFError: break if not line: break msg = msg + line print("Message length is", len(msg)) server = smtplib.SMTP('192.168.2.4') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() However this error is raised: Traceback (most recent call last): File "C:\Python34\geenemail.py", line 24, in <module> server = smtplib.SMTP('192.168.2.4') File "C:\Python34\lib\smtplib.py", line 242, in __init__ (code, msg) = self.connect(host, port) File "C:\Python34\lib\smtplib.py", line 321, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python34\lib\smtplib.py", line 292, in _get_socket self.source_address) File "C:\Python34\lib\socket.py", line 509, in create_connection raise err File "C:\Python34\lib\socket.py", line 500, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] Kan geen verbinding maken omdat de doelcomputer de verbinding actief heeft geweigerd I looked for similar problems but couldn't find a lot, only found someone who said the firewall might be the problem --> I turned Avast/firewall off, got a bluescreen from some reason, restarted my PC, Avast/firewall was still off but still it raised the same error. I have also tried giving a port value but I still get the same error. What might be the problem? Answer: The most likely reason for this error is that there is no SMTP server running on the computer you are trying to connect to. server = smtplib.SMTP('192.168.2.4') `'192.168.2.4'` should be the address of the SMTP server you are trying to use to send the email.
Where is the history file for ipython Question: I can not determine where the ipython is storing its history. a. There is no ~/.pythonhistory: 12:49:00/dashboards $ll ~/.py* ls: /Users/steve/.py*: No such file or directory b. Nothing special in the python startup file: 12:49:07/dashboards $echo $PYTHONSTARTUP /shared/.pythonstartup 12:49:43/dashboards $cat /shared/.pythonstartup import rlcompleter import readline readline.parse_and_bind("tab: complete") c. BUT: i do have plenty of history available in ipython when I start it up. So where is that history being stored? _UPDATE_ the answer from @Stefano led the correct way: here is the actual path 13:30:05/shared $ll ~/.ipython/profile_default/history.sqlite -rw-r--r-- 1 steve staff 372736 Jun 3 12:48 /Users/steve/.ipython/profile_default/history.sqlite Answer: IPython history is stored in a SQLite database located in the profile directory. By default: ~/.ipython/profile_default/history.sqlite Older versions (1.x) stored profile data in `~/.config/ipython`, at least on platforms conforming to [XDG basedir specs](http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html) (i.e. most Linux distributions). Anyway, you can locate the profile directory with: $ ipython locate profile default Notice that the history database is shared between IPython and IPython3, if both are installed.
Parsing binary data into separate variables in Python? Question: Say I open a file in Python that contains a series of binary data. with open(sys.argv[1]) as data_file: logData = data_file.read() I basically want to create a loop saying: for each_word in logData: var1 = first 8 bytes var2 = next 16 bytes var3 = next 8 bytes C code to generate my binary file: #include <stdio.h> #include <stdlib.h> int main(void) { FILE *file; int buffer = 0x03000201; int buffer2= 0x010203; file = fopen("test.bin", "wb"); if (file != NULL) { fwrite(&buffer, sizeof(buffer), 1, file); fwrite(&buffer2, sizeof(buffer2), 1, file); fclose(file); } return 0; } and this basically continues until the loop is over, iterating through the bytes of data. How is this possible? Answer: Use the [`struct` module](http://docs.python.org/2/library/struct.html), it will also allow you to interpret the binary data in many ways; you need to define the types in a string format documented with that library: struct.unpack('=HHf255s', bytes) The above example expects native byte-order, two unsigned shorts, a float and a string of 255 characters. Your code example becomes: for each_word in logData: var1, var2, var3 = struct.unpack('8s16s8s', each_word) In case you get an error `TypeError: 'str' does not support the buffer interface`, that is because `bytes` are expected, but you passed a `str`, so convert it to bytes and specify the encoding (in this example, UTF-8): for each_word in logData: var1, var2, var3 = struct.unpack('8s16s8s', bytes(each_word, 'utf-8')) But maybe the case that your 8/16 byte strings are long integers? In that case use the appropriate format for struct. _EDIT_ : it turns out you wanted to read 8 **bits** (not bytes), then the next 16 bits, then the next 8 bits, so you can read it as one (unsigned?) byte, one short, and another byte. The format string you should use is `'=bhb'` (or `'=BHB'` for unsigned). Example: import struct with open('test.bin','rb') as f: var1, var2, var3 = struct.unpack('=BHB', f.read(4)) print(var1, var2, var3)
Using python to visit a link and print data Question: I'm writing a web scraper and trying to get back Drake lyrics. My scraper has to visit one site (main metrolyrics site) and then visit each individual song link, then print out the lyrics. I'm having trouble visiting the second link. I've searched around on BeautifulSoup and am pretty confused. I'm wondering if you can help. # this is intended to print all of the drake song lyrics on metrolyrics from pyquery import PyQuery as pq from lxml import etree import requests from bs4 import BeautifulSoup # this visits the website response = requests.get('http://www.metrolyrics.com/drake-lyrics.html') # this separates the different types of content doc = pq(response.content) # this finds the titles in the content titles = doc('.title') # this visits each title, then prints each verse for title in titles: # this visits each title response_title = requests.get(title) # this separates the content doc2 = pq(response_title.content) # this finds the song lyrics verse = doc2('.verse') # this prints the song lyrics print verse.text In response_title = requests.get(title), python isn't recognizing that title is a link, which makes sense. How do I get the actual in there, though? Appreciate your help. Answer: Replace response_title = requests.get(title) with response_title = requests.get(title.attrib['href']) Full working script (with fixed note from the comment below) #!/usr/bin/python from pyquery import PyQuery as pq from lxml import etree import requests from bs4 import BeautifulSoup # this visits the website response = requests.get('http://www.metrolyrics.com/drake-lyrics.html') # this separates the different types of content doc = pq(response.content) # this finds the titles in the content titles = doc('.title') # this visits each title, then prints each verse for title in titles: # this visits each title #response_title = requests.get(title) response_title = requests.get(title.attrib['href']) # this separates the content doc2 = pq(response_title.content) # this finds the song lyrics verse = doc2('.verse') # this prints the song lyrics print verse.text()
How to loop through list of options inside if statement in python 2.7? Question: I am extracting items from a subdirectory containing a mixture of files that are audio files in different formats and with different suffixes e.g. `_master` or `_128k`. I have specified higher up in the code a list of permitted extensions (e.g. `.mp3`) so that I extract only files of the right formats for processing. I also have a list (suffixExcluded) containing filename suffixes (e.g. `_syndication`) I explicitly want to exclude from further processing. How do I best write the line that effectively does: if fileExtension in filesAllowed and [LIST OF EXCLUDED SUFFIXES] not in fileName: Is there a neat, compact and elegant (pythonic) way of iterating through my list of exclusions within this `if` clause, or do I need to set up a subsidiary loop to test each item? Answer: You can filter as you go, passing a tuple of the extensions you want to keep and filtering those with any to remove any files with matching extensions that don't contain any substring from your list of excluded substrings. exc = [LIST OF EXCLUDED SUFFIXES] import os for f in os.listdir("path"): if f.endswith((".mp4",".mp3",".avi")) and not any(e in f for e in exc): You only need a single pass over the directory content without any need to build a list first. If you want to replace the forbidden substrings and not just exclude you can use re.sub: import os import re r = re.compile(r"|".join([e for e in exc])) for f in os.listdir("path"): if f.endswith((".mp4",".mp3",".avi")): f = r.sub("",f)
Explanation of HEX value representation and Endianess Question: I was working on a script to basically output some sample data as a binary blob. I'm a new intern in the software field and vaguely remember the idea of endianness. I realize that the most significant bits for big-endian starts at the top and works down the memory block. If I have 0x03000201 and the data is being parsed to output 0 1 2, how does this happen and what is being done to make that work in terms of bits, bytes, etc. I am wondering, in the example posted below, how the numbers are extracted to form 0 1 2 when printing out the data stored in the variables. For example: I am creating a couple lines of the binary blob using this file: #include <stdio.h> #include <stdlib.h> int main(void) { FILE *file; int buffer = 0x03000201; int buffer2= 0x010203; file = fopen("test.bin", "wb"); if (file != NULL) { fwrite(&buffer, sizeof(buffer), 1, file); fwrite(&buffer2, sizeof(buffer2), 1, file); fclose(file); } return 0; } I then created a Python script to parse this data: # Info About Parse import struct with open('test.bin','rb') as f: while True: data = f.read(4) if not data: break var1, var2, var3 = struct.unpack('=BHB', data) print(var1, var2, var3) Answer: Big or little endianness defines how to interpret a sequence of bytes longer than one byte and how to store those in memory. Wikipedia will help you with that. > I was really just looking to understand how 0x0300020 when read 2 bytes at a > time and reprinted yields 0 1 2. You don't read 2 bytes at a time, you read 4 bytes: `data = f.read(4)` f.read(size) reads some quantity of data and returns it as a string. You unpack data using =BHB - byte, 2 bytes, byte. Endianness comes into play only when you unpack data, all other IO calls in your code deal with byte sequences. Experiment with [unpack() Byte Order, Size, and Alignment](https://docs.python.org/2/library/struct.html) You may also look at file data with a HEX editor of your choice. And if, after your research, you have a concrete question, ask here.
getting an iterable output from a telnet client in python Question: I am trying to write a script to perform validation checks on a network device (router,switch). I am using telnet to send commands to the device. I store the output of the command telnetobject.read_until(prompt) into a file and then run some validation checks over the stored output by iterating over it one line at a time. Is there a way to iterate over the output without storing it in a file? the issue is the read_until option gives the output in one string and the output of the device i am trying to test has an output in a tabular form which does not have a consistent delimiter on each line. This is an example: import telnetlib tn=telnetlib.Telnet('ip address') pwd='password' uid='userid' tn.read_until("login: ") tn.write(uid + "\n") tn.read_until("Password:") tn.write(pwd +'\n') tn.read_until(">",5) tn.write('port statistics show' + '\n') op1=tn.read_until("*>",5) with open ('stattest-temp.txt','w') as stat: stat.write(op1) above code was to get a particular output and store it in a file below code is to iterate over the output..problem is it is in a tabular form and starts with multiple '_ _ _' characters and each line in the table has different number of elements if you split it using a delimiter, hence it becomes difficult to iterate over output from tn.read_until as it is all one giant string' with open ('stattest-temp.txt','r') as f: for line_no,line in enumerate(f): if line_no>5: if '+---------------------------------+----------------+-----------+-----------+------------+\r' in line: break else: x=line[:-1].split("|") #print x x1=x[1].strip() x2=x[2].strip() x3=x[3].strip() x4=x[4].strip() x5=x[5].strip() if x4 =="YES": print x1,x4 print 'Traffic loss observed' elif x4=="No": print "session recovered" I am looking for a way to do part 2 of the above code without having to write the output to a file Answer: I think if you split the output string on newline characters, this should replicate the effect of saving to a file and the iterating through lines. Basically set this before your `for` loop: f = op1.split('\n') for line_no,line in enumerate(f): if line_no>5: if '+---------------------------------+----------------+-----------+-----------+------------+\r' in line: break else: x=line[:-1].split("|") #print x x1=x[1].strip() x2=x[2].strip() x3=x[3].strip() x4=x[4].strip() x5=x[5].strip() if x4 =="YES": print x1,x4 print 'Traffic loss observed' elif x4=="No": print "session recovered"
Python encoding error? UnicodeDecodeError: 'ascii' codec can't decode byte ordinal not in range(128) Question: I have an AWS autoscale instance. On the AMI for that instance, I have a file `myfile.py` that contains the following string: X5ZŒ In my AWS Cloudformation, LaunchConfiguration, I have UserData that executes the following python instruction when the instance is spun up. It simply reads `myfile.py` and attempts to replace all occurrences of the regexp "X\dZ" with "XYZ": myString = "XYZ".join(re.compile('X\d\Z').split(open("myfile.py", "r").read())) That produces this error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 4: ordinal not in range(128) Okay. I understand that the character `Œ` is causing trouble because it is non-ASCII. But when I manually run the same statement from the python shell, it works fine without throwing any exception. How can I force the script that is run by AWS LaunchConfig's UserData to have the same behavior as when I run it manually myself? What encoding should I set and how should I set it? Answer: Your file is encoded, that means it represents unicode in a defined way. You use some literal strings (e.g. `XYZ`), which shall be used to in oprations together with the file content. These literal strings are encoded just like the file, in which this code is defined. Python tries to coerce both into the same to be able to operate on it. It is best, if you convert both into unicode. For the string literals, just prepend a `u`, like so: `u"XYZ"`. For the file you have to tell python the encoding, if you don't, it by default assumes `ascii`. Try: myString = u"XYZ".join(re.compile(u'X\d\Z').split( open("myfile.py", "r").read().decode('utf-8'))) in this version I used `utf-8`, which has some probability of being right. If you know it being different, you'd have to substitute it for the [right one](https://docs.python.org/2/library/codecs.html#standard-encodings) (your editor in which you saved the file can probably tell you). EDIT: I removed the part about console and environment settings, which don't apply, as @Martijn mentioned. He's also right about, that this error is only reproducible if your string literals _are_ already implicitly unicode (`from __future__ import unicode_literals`) - in this case there's no need to prepend the string literals with a `u`.
Python csv seek() not working Question: Hi I am trying to read a csv file using the following code. I want to read from `n` th line to `m` th line of the csv file provided. As a example I want to start reading from 10th line to 100 line and after that start from 500th line to 1000th line. I give those parameters using `start` and `end` variables. The problem that **it always start from the beginning regardless the start and end variables.** i tried and tried for a solution but failed.Can anyone help me to figure out the issue here.? Thanks a lot! (there are some duplicate questions but no one seems to have given a solution) import csv import os with open('file.csv','r') as csvfile: start=10 end=100 csvfile.seek(start) r= csv.reader(csvfile) r.next() for i in range(start,end): try: url=r.next()[2] print url except IndexError,e: print str(e), except ValueError,b: print b csvfile.close() Answer: Use the [`csv`](https://docs.python.org/3.4/library/csv.html) module. import csv n = 3 m = 5 read = 0 with open("so.csv") as csvfile: reader = csv.reader(csvfile) for record in reader: read += 1 if read >= n and read <= m: print(record)
'module' csv has no attribute next Question: I am using a csv iterator to go through a csv file, which contains data associated with time. I am sure the csv file is correct. I am using Jupyter, iPython notebook in python 3.x When I try to iterate on the first row by using .next() method, I have an AttributeError: 'module' object has no attribute 'next'. My code is divided in two parts, one part containing function and imports, one part calling them. The function I have a problem with is: def get_durations(csvfile): try: csvfile = iter(csvfile) except TypeError, te: print csvfile, 'is not iterable' print "data is", repr(csvfile) first_time = csvfile.next()[5] first_time = (first_time.replace(" ", "")); for row in csvfile: last_time = row[5] last_time = (last_time.replace(" ", "")) first_time = datetime.datetime.strptime(first_time, "%H:%M:%S") last_time = datetime.datetime.strptime(last_time, "%H:%M:%S") return first_time.replace(second = 0), last_time.replace(second = 0) I make the call to the function here: for el_mousefile in mousefiles: os.chdir(el_mousefile) print "data is", repr(csvfile) csvfile = csv.reader(open("mouse.csv", "rU"), delimiter=';', quoting=csv.QUOTE_NONE) print "data is", repr(csvfile) try: csvfile = iter(csvfile) except TypeError, te: print csvfile, 'is not iterable' first_time, last_time = get_durations(csv) I get this output when trying to run the program: data is <_csv.reader object at 0x000000000A388D08> data is <_csv.reader object at 0x000000000A388948> module 'csv' from 'C:\Users\**\AppData\Local\Continuum\Anaconda\lib\csv.pyc' is not iterable data is module 'csv' from 'C:\Users\**\AppData\Local\Continuum\Anaconda\lib\csv.pyc' 96------>first_time = csvfile.next()[5] 97 first_time = (first_time.replace(" ", "")); 98 for row in csvfile: AttributeError: 'module' object has no attribute 'next' I don't understand how can my csv be iterable in the second part, but then when being passed to the function, it is not iterable anymore which is responsible for my error. Answer: first_time, last_time = get_durations(csv) You are passing in the csv module, not a file.
Can this Python code be further shrunk? Question: Below is Python code that fetches all of the sub-domains within a domain. It takes a file as input that contains the page source for a website. The second argument is the domain name. For example: `"https://www.sometime.com"`. import re def getSubDomains(fil,domain): with open(fil) as f: subDomainLst = [] for line in f: m = re.findall(r'\bhref="\https://[\w+\.*]+%s/'%domain,line) if(m): for ele in m: subDomainLst.append(ele.split('/')[2]) else: continue subDomainLst = list(set(subDomainLst)) for ele in subDomainLst: print ele def main(): fil1,domain1 = raw_input("Enter the file name\n"),raw_input("Enter the domain\n") getSubDomains(fil1,domain1) main() if __name__ == '__main__' else Pass I've tried shrinking the inner 'if else statement' to for ele in m: subDomainLst.append(ele.split('/')[2]) if(m) else continue But this gives an error. Can the above code be shrunk further (16 lines for now) so that it takes up minimum number of lines and become more pythonic? Answer: You don't need to add _continue_. You can try doing like this, even though I DO NOT recommend as it makes the code unreadable. subDomainLst = [ele.split('/')[2] for line in f for ele in re.findall(r'\bhref="\https://[\w+\.*]+%s/' % domain, line)] Btw you should indent your code by 4 spaces and try to avoid one-line uncomprehensible statements: pythonic means also readable Complete code: if __name__ == '__main__': import re fil, domain = raw_input("Enter the file name\n"), raw_input("Enter the domain\n") with open(fil) as f: print '\n'.join([ele.split('/')[2] for line in f for ele in re.findall(r'\bhref="\https://[\w+\.*]+%s/' % domain, line)])
how to make feature vector from the lists Question: I'm new to python. Actually I have a train data which is in bag of words.Each line of the train data is an article. The labels of the train data is in another file and each i label is equal to i article in the train data. I did stemming on the train data and also removed the stop words. The output is the lists of words of each article(line). Now I want to extract a feature vector of it and then use it in my KNN classifier in python.. I don't know how to do it! I appreciate any quick answer. Here's my code up to the things I did: import nltk from nltk.corpus import stopwords from nltk import stem stemmer=stem.PorterStemmer() with open('data.txt')as file: while 1: line=file.readline().split() filtered_words = [w for w in line if not w in stopwords.words('english')] documents = [stemmer.stem(line) for line in filtered_words] print(documents) if not line: break pass Answer: Take a look at Scikit-learn's [CountVectorizer](http://scikit- learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer) or [TfIdfVectorizer](http://scikit- learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html#sklearn.feature_extraction.text.TfidfVectorizer). These can take a list of documents (these are lists of tokens, as in your example) as their input, and return a feature matrix: from sklearn.feature_extraction.text import CountVectorizer count_vect = CountVectorizer() X_train_counts = count_vect.fit_transform(your_list_of_documents) You can find more information in the [Working with Text Data Tutorial](http://scikit- learn.org/stable/tutorial/text_analytics/working_with_text_data.html).
Send email django from any host Question: I have read plenty of links for sending emails through django. I've tried all of them but they don't work. I tried sending an email through the python shell and I get '1'. \- So what are the settings that I should use for the email to work, I'm willing to use any mail server? \- I was using gmail but I read that it causes problems, if I'm going to use hotmail for example do I need to specify the email password in the settings.xml? \- how to debug this problem? Answer: You can try yagmail, it should make it a lot easier: import yagmail yag = yagmail.Connect('[email protected]', 'password') yagmail.send(email_to, subject = 'site down!', contents = 'with some error') It has a lot more features, for example how to make it easier to send attachments etc. yagmail can be found at [github](https://github.com/kootenpv/yagmail). You will probably have to install it first using pip: pip install yagmail # python 2 pip3 install yagmail # python 3
Script doesn't autorizate in strava.com Question: I want to login in strava.com with python. I try do it (using <http://www.youtube.com/watch?v=eRSJSKG4mDA>), but i can't... import requests import bs4 with requests.Session() as c: url='https://strava.com/login' url_p='https://strava.com/session' Email='[email protected]' Password='12345678' html = c.get(url,verify=True) soup = bs4.BeautifulSoup(html.text) loginForm = soup.find('form', {'id': 'login_form'}) hiddenAuthKey = soup.find('input', {'name': 'authenticity_token'})['value'] print hiddenAuthKey login_data=dict(utf8="True",authenticity_token=hiddenAuthKey,plan='',email=Email,password=Password,remember_me='on') c.post(url_p,data=login_data,headers={"Referer":"https://www.strava.com/"},verify=True) page = c.get('https://www.strava.com/dashboard/new/web',verify=True) f=codecs.open('st.html','wb') f.write(page.content) f.close() Answer: It is much easier if, instead of using requests, you use [`mechanize`](http://wwwsearch.sourceforge.net/mechanize/). >>> import mechanize >>> br = mechanize.Browser() >>> response = br.open('https://strava.com/login') >>> br.select_form(nr=0) # selects the first form on the login page View the form's fields: >>> print br.form <POST https://www.strava.com/session application/x-www-form-urlencoded <HiddenControl(utf8=✓) (readonly)> <HiddenControl(authenticity_token=XgZFBcwDxCfax4AOGoDCjMYjVvM6X/iB6nSH/Cp1Um4=) (readonly)> <HiddenControl(plan=) (readonly)> <TextControl(email=)> <PasswordControl(password=)> <CheckboxControl(remember_me=[on])> <SubmitButtonControl(<None>=) (readonly)>> Set the required values for username and password: >>> br.form['email'] = '[email protected]' >>> br.form['password'] = 'xxxxxxxx' >>> print br.form <POST https://www.strava.com/session application/x-www-form-urlencoded <HiddenControl(utf8=✓) (readonly)> <HiddenControl(authenticity_token=XgZFBcwDxCfax4AOGoDCjMYjVvM6X/iB6nSH/Cp1Um4=) (readonly)> <HiddenControl(plan=) (readonly)> <TextControl([email protected])> <PasswordControl(password=xxxxxxxx)> <CheckboxControl(remember_me=[on])> <SubmitButtonControl(<None>=) (readonly)>> And submit the form: >>> response = br.submit() You should now be logged in... >>> print br.geturl() https://www.strava.com/dashboard/new/web You can save the page to a file: with open('st.html', 'w') as f: f.write(response.read()) Note also that you have posted a working login and password, you might want to change your password to prevent undesired logins.
Insert hyperlink to a local folder in Excel with Python Question: The piece of code reads an Excel file. This excel file holds information such as customer job numbers, customer names, sites, works description ect.. What this code will do when completed (I hope) is read the last line of the worksheet (this is taken from a counter on the worksheet at cell 'P1'), create folders based on cell content, and create a hyperlink on the worksheet to open the lowest local folder that was created. I have extracted the info I need from the worksheet to understand what folders need to be created, but I am not able to write a hyperlink to the cell on the row in column B. #Insert Hyperlink to folder def folder_hyperlink(last_row_position, destination): cols = 'B' rows = str(last_row_position) position = cols + rows final_position = "".join(position) print final_position # This is just to check the value # The statement below should insert hyperlink in eps.xlsm > worksheet jobnoeps at column B and last completed row. ws.cell(final_position).hyperlink = destination The complete code is below but here is the section that is meant to create the hyperlink. I have also tried the 'xlswriter' package with no joy. Searched the internet and the above snippet is the result of what I found. Anyone know what I am doing wrong? __author__ = 'Paul' import os import openpyxl from openpyxl import load_workbook import xlsxwriter site_info_root = 'C:\\Users\\paul.EPSCONSTRUCTION\\PycharmProjects\\Excel_Jobs\\Site Information\\' # This function returns the last row on eps.xlsm to be populated def get_last_row(cell_ref = 'P1'): #P1 contains the count of the used rows global wb global ws wb = load_workbook("eps.xlsm", data_only = True) #Workbook ws = wb["jobnoeps"] #Worksheet last_row = ws.cell(cell_ref).value #Value of P1 from that worksheet return last_row # This function will read the job number in format EPS-XXXX-YR def read_last_row_jobno(last_row_position): last_row_data = [] for cols in range(1, 5): last_row_data += str(ws.cell(column = cols, row = last_row_position).value) last_row_data_all = "".join(last_row_data) return last_row_data_all #This function will return the Customer def read_last_row_cust(last_row_position): cols = 5 customer_name = str(ws.cell(column = cols, row = last_row_position).value) return customer_name #This function will return the Site def read_last_row_site(last_row_position): cols = 6 site_name = str(ws.cell(column = cols, row = last_row_position).value) return site_name #This function will return the Job Discription def read_last_row_disc(last_row_position): cols = 7 site_disc = str(ws.cell(column = cols, row = last_row_position).value) return site_disc last_row = get_last_row() job_no_details = read_last_row_jobno(last_row) job_customer = read_last_row_cust(last_row) job_site = read_last_row_site(last_row) job_disc = read_last_row_disc(last_row) cust_folder = job_customer job_dir = job_no_details + "\\" + job_site + " - " + job_disc #Insert Hyperlink to folder def folder_hyperlink(last_row_position, destination): cols = 'B' rows = str(last_row_position) position = cols + rows final_position = "".join(position) print final_position # This is just to check the value # The statement below should insert hyperlink in eps.xlsm > worksheet jobnoeps at column B and last completed row. ws.cell(final_position).hyperlink = destination folder_location = site_info_root + job_customer + "\\" + job_dir print folder_location # This is just to check the value folder_hyperlink(last_row, folder_location) * * * Now my hyperlink function looks like this after trying xlsxwriter as advised. ##Insert Hyperlink to folder def folder_hyperlink(last_row_position, destination): import xlsxwriter cols = 'B' rows = str(last_row_position) position = cols + rows final_position = "".join(position) print final_position # This is just to check the value workbook = xlsxwriter.Workbook('eps.xlsx') worksheet = workbook.add_worksheet('jobnoeps') print worksheet worksheet.write_url(final_position, 'folder_location') workbook.close() The function overwrites the exsisting eps.xlsx, creates a jobnoeps table and then inserts the hyperlink. I have played with the following lines but don't know how to get it to open the existing xlsx and existing jobnoeps tab and then enter the hyperlink. workbook = xlsxwriter.Workbook('eps.xlsx') worksheet = workbook.add_worksheet('jobnoeps') worksheet.write_url(final_position, 'folder_location') Answer: The XlsxWriter [`write_url()`](http://xlsxwriter.readthedocs.org/worksheet.html#worksheet- write-url) method allows you to link to folders or other workbooks and worksheets as well as internal links and links to web urls. For example: import xlsxwriter workbook = xlsxwriter.Workbook('links.xlsx') worksheet = workbook.add_worksheet() worksheet.set_column('A:A', 50) # Link to a Folder. worksheet.write_url('A1', r'external:C:\Temp') # Link to a workbook. worksheet.write_url('A3', r'external:C:\Temp\Book.xlsx') # Link to a cell in a worksheet. worksheet.write_url('A5', r'external:C:\Temp\Book.xlsx#Sheet1!C5') workbook.close() See the docs linked to above for more details.
Send the result of python cgi script to HTML Question: I have a toggle button on a page 'index.html'. When I click on it, it executes a python cgi script that changes the state of something on my raspberry. To do so, I do this : **HTML :** <form id="tgleq" method="POST" action="/cgi-bin/remote.py" target="python_result"> <input id="toggle-eq" type="checkbox" data-toggle="toggle" name="toggle-eq" value=""> <script> $(function() { $('#toggle-eq').change(function() { tgl_state = $('#toggle-eq').prop("checked") var toggle = document.getElementById("toggle-eq"); toggle.value = tgl_state; document.getElementById("tgleq").submit(); }) }) </script> **CGI :** #!/usr/bin/env python import cgi import cgitb cgitb.enable() print "Content-type: text/html\n\n" print form=cgi.FieldStorage() arg1 = form.getvalue('toggle-eq') And then I do what I want to do with my arg1. Now, what I want is, when you open the web interface page, to get the state of the raspberry component to initialize the toggle on the right position. To do so I send a form on page load that launch a script looking at the state of the component. But how can I get it back in the html ? I tried [urllib](http://stackoverflow.com/questions/17509607/submitting-to-a- web-form-using-python) and httplib2 but nothing worked for me... Any suggestions ? Thanks Answer: If I understand your question correctly you want to show the current-state of your switchable component on the webpage. Currently it looks like you have a pure HTML page and an CGI page, so I think you have multiple options, one of them is to combine the HTML and CGI into one page. The code below is an example of this idea and probably doesn't work correctly, so not a copy/paste solution. #!/usr/bin/env python import cgi import cgitb cgitb.enable() print "Content-type: text/html\n\n" print active=""" <form id="tgleq" method="POST" action="/cgi-bin/remote.py" target="python_result"> <input id="toggle-eq" type="checkbox" data-toggle="toggle" name="toggle-eq" value=""> """ inactive=""" <form id="tgleq" method="POST" action="/cgi-bin/remote.py" target="python_result"> <input id="toggle-eq" type="checkbox" data-toggle="toggle" name="toggle-eq" value="checked"> """ generic = """ <script> $(function() { $('#toggle-eq').change(function() { tgl_state = $('#toggle-eq').prop("checked") var toggle = document.getElementById("toggle-eq"); toggle.value = tgl_state; document.getElementById("tgleq").submit(); }) }) </script> """ def set_state(option): if (option==True): actual_state_Setting_here = 1 # <-magic happens here else: actual_state_Setting_here = 0 # <-magic happens here def get_state(): return actual_state_Setting_here # <- read actual value here form = cgi.FieldStorage() if ( form.getvalue('toggle-eq')=="checked" ): set_state(True) else: set_state(False) if ( get_state()==True ): print(active) #show as currently active else: print(inactive) #show as currently inactive print(generic) #show rest of the page
"from math import sqrt" works but "import math" does not work. What is the reason? Question: I am pretty new in programming, just learning python. I'm using Komodo Edit 9.0 to write codes. So, when I write "from math import sqrt", I can use the "sqrt" function without any problem. But if I only write "import math", then "sqrt" function of that module doesn't work. What is the reason behind this? Can I fix it somehow? Answer: You have two options: import math math.sqrt() will import the `math` module into its own namespace. This means that function names have to be prefixed with `math`. This is good practice because it avoids conflicts and won't overwrite a function that was already imported into the current namespace. Alternatively: from math import * sqrt() will import everything from the `math` module into the current namespace. [That can be problematic](http://stackoverflow.com/a/2360808/2202669).
Finding roots with scipy.optimize.root Question: I am trying to find the root y of a function called f using Python. Here is my code: def f(y): w,p1,p2,p3,p4,p5,p6,p7 = y[:8] t1 = w - 0.500371726*(p1**0.92894164) - (-0.998515304)*((1-p1)**1.1376649) t2 = w - 8.095873128*(p2**0.92894164) - (-0.998515304)*((1-p2)**1.1376649) t3 = w - 220.2054377*(p3**0.92894164) - (-0.998515304)*((1-p3)**1.1376649) t4 = w - 12.52760758*(p4**0.92894164) - (-0.998515304)*((1-p4)**1.1376649) t5 = w - 8.710859537*(p5**0.92894164) - (-0.998515304)*((1-p5)**1.1376649) t6 = w - 36.66350261*(p6**0.92894164) - (-0.998515304)*((1-p6)**1.1376649) t7 = w - 3.922692207*(p7**0.92894164) - (-0.998515304)*((1-p7)**1.1376649) t8 = p1 + p2 + p3 + p4 + p5 + p6 + p7 - 1 return [t1,t2,t3,t4,t5,t6,t7,t8] x0 = np.array([-0.01,0.3,0.1,0.2,0.1,0.1,0.1,0.1]) sol = scipy.optimize.root(f, x0, method='lm') print sol print 'solution', sol.x print 'success', sol.success Python does not find the root whatever the method I try in scipy.optimize.root. However there is one, I found it with the function fsolve in Matlab. It is: [-0.0622, 0.5855, 0.087, 0.0028, 0.0568, 0.0811, 0.0188, 0.1679]. When I specify x0 close to the root, the python algorithm converges. The problem is that I have no idea a priori on the root to specify x0. In reality I am solving many equations of this type. I really want to use Python. Can anyone help me converge with python? Answer: OK, after some fooling around, we focus on another aspect of good optimization/root finding algorithms. In the comments above we went back and forth around which method in scipy.optimize.root() to use. An equally important question for near-bulletproof 'automatic' root finding is zeroing in on good initial guesses. Often times, good initial guesses are, in fact, not near the real answer at all. Instead, they need to be arranged so that they will naturally lead the solver in the right direction. In your particular case, your guesses were, in fact, sending the algorithm off in strange directions. My toy reconstruction of your problem is: import numpy as np import scipy as sp import scipy.optimize def f(y): w,p1,p2,p3,p4,p5,p6,p7 = y[:8] def t(p,w,a): b = -0.998515304 e1 = 0.92894164 e2 = 1.1376649 return(w-a*p**e1 - b*(1-p)**e2) t1 = t(p1,w,1.0) t2 = t(p2,w,4.0) t3 = t(p3,w,16.0) t4 = t(p4,w,64.0) t5 = t(p5,w,256.0) t6 = t(p6,w,512.0) t7 = t(p7,w,1024.0) t8 = p1 + p2 + p3 + p4 + p5 + p6 + p7 - 1.0 return(t1,t2,t3,t4,t5,t6,t7,t8) guess = 0.0001 x0 = np.array([-1000.0,guess,guess,guess,guess,guess,guess,guess]) sol = sp.optimize.root(f, x0, method='lm') print('w=-1000: ', sol.x, sol.success,sol.nfev,np.sum(f(sol.x))) Note that I did not use your specific prefactors (I wanted to broaden the range I explored), although I kept your particular exponents on the p terms. The real secret is in the initial guess, which I made the same for all p terms. Having it a 0.1 or above bombed much of the time, since some terms want to go one way and some the other. Reducing it to 0.01 worked well for this problem. (I will note that the w term is very robust - varying from -1000. to +1000. had no effect on the solution). Reducing the initial guess even further has no effect on this particular problem, but it does no harm either. I would keep it very small. Yes, you know that at least some terms will be much larger. But, you are putting the solver in a position where it can clearly and directly proceed towards the real solution. Good luck.
How to detect the terminal that is running python? Question: I've already tried sys.platform, platform.system() and os.name but none of them return something related to cygwin (I always get win32, Windows and nt as output). Maybe because my python was installed on windows (8.1) and not through cygwin. I need to detect if my python file is being executed by cygwin or cmd. Answer: Cygwin uses Linux-style paths; thus you might be able to check the path separator: import sys import os.path def running_cygwin(): return sys.platform == 'win32' and os.path.sep == '/' (I don't have a Cygwin here, so this is untested.)
Python urllib2 request error Question: Python 2.7.3 (default, Mar 13 2014, 11:03:55) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib2 >>> req = urllib2.Request("http:///wp-login.php") >>> website='kseek.com.my' >>> req = urllib2.Request("http://"+website+"/wp-login.php") >>> req.add_header('User-agent', 'Mozilla 5.10') >>> req.add_header('Referer', 'http://'+website) >>> data = urllib2.urlopen(req, timeout=6).read() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen return _opener.open(url, data, timeout) File "/usr/lib/python2.7/urllib2.py", line 407, in open response = meth(req, response) File "/usr/lib/python2.7/urllib2.py", line 520, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.7/urllib2.py", line 445, in error return self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py", line 379, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 528, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 406: Not Acceptable >>> req = urllib2.Request("http://"+website+"/") >>> req.add_header('User-agent', 'Mozilla 5.10') >>> req.add_header('Referer', 'http://'+website) >>> data = urllib2.urlopen(req, timeout=6).read() >>> As you notice, When requesting /wp-login.php which i can reach manually via browser ow even curl I get 406 error while with the same method requesting /index.php , work without problem Any help? Answer: You're getting [HTTP error 406](http://www.checkupdown.com/status/E406.html) because you're missing the `Accept` header. Add the following before you open the URL: req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8') **OUTPUT:** >>> req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8') >>> data = urllib2.urlopen(req, timeout=6).read() >>> print data <!DOCTYPE html> <!--[if IE 8]> <html xmlns="http://www.w3.org/1999/xhtml" class="ie8" lang="en-US"> <![endif]--> <!--[if !(IE 8) ]><!--> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"> <!--<![endif]--> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>K SEE K architect &rsaquo; Log In</title> <link rel='stylesheet' id='buttons-css' href='http://kseek.com.my/wp-includes/css/buttons.min.css?ver=4.2.2' type='text/css' media='all' /> <link rel='stylesheet' id='open-sans-css' href='//fonts.googleapis.com/css?family=Open+Sans%3A300italic%2C400italic%2C600italic%2C300%2C400%2C600&#038;subset=latin%2Clatin-ext&#038;ver=4.2.2' type='text/css' media='all' /> <link rel='stylesheet' id='dashicons-css' href='http://kseek.com.my/wp-includes/css/dashicons.min.css?ver=4.2.2' type='text/css' media='all' /> <link rel='stylesheet' id='login-css' href='http://kseek.com.my/wp-admin/css/login.min.css?ver=4.2.2' type='text/css' media='all' /> <link rel="apple-touch-icon" sizes="57x57" href="/wp-content/uploads/fbrfg/apple-touch-icon-57x57.png"> <link rel="apple-touch-icon" sizes="114x114" href="/wp-content/uploads/fbrfg/apple-touch-icon-114x114.png"> <link rel="apple-touch-icon" sizes="72x72" href="/wp-content/uploads/fbrfg/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="144x144" href="/wp-content/uploads/fbrfg/apple-touch-icon-144x144.png"> <link rel="apple-touch-icon" sizes="60x60" href="/wp-content/uploads/fbrfg/apple-touch-icon-60x60.png"> <link rel="apple-touch-icon" sizes="120x120" href="/wp-content/uploads/fbrfg/apple-touch-icon-120x120.png"> <link rel="apple-touch-icon" sizes="76x76" href="/wp-content/uploads/fbrfg/apple-touch-icon-76x76.png"> <link rel="apple-touch-icon" sizes="152x152" href="/wp-content/uploads/fbrfg/apple-touch-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/wp-content/uploads/fbrfg/apple-touch-icon-180x180.png"> <link rel="shortcut icon" href="/wp-content/uploads/fbrfg/favicon.ico"> <link rel="icon" type="image/png" href="/wp-content/uploads/fbrfg/favicon-192x192.png" sizes="192x192"> <link rel="icon" type="image/png" href="/wp-content/uploads/fbrfg/favicon-160x160.png" sizes="160x160"> <link rel="icon" type="image/png" href="/wp-content/uploads/fbrfg/favicon-96x96.png" sizes="96x96"> <link rel="icon" type="image/png" href="/wp-content/uploads/fbrfg/favicon-16x16.png" sizes="16x16"> <link rel="icon" type="image/png" href="/wp-content/uploads/fbrfg/favicon-32x32.png" sizes="32x32"> <meta name="msapplication-TileColor" content="#da532c"> <meta name="msapplication-TileImage" content="/wp-content/uploads/fbrfg/mstile-144x144.png"> <meta name="msapplication-config" content="/wp-content/uploads/fbrfg/browserconfig.xml"><meta name='robots' content='noindex,follow' /> </head> <body class="login login-action-login wp-core-ui locale-en-us"> <div id="login"> <h1><a href="https://wordpress.org/" title="Powered by WordPress" tabindex="-1">K SEE K architect</a></h1> <form name="loginform" id="loginform" action="http://kseek.com.my/wp-login.php" method="post"> <p> <label for="user_login">Username<br /> <input type="text" name="log" id="user_login" class="input" value="" size="20" /></label> </p> <p> <label for="user_pass">Password<br /> <input type="password" name="pwd" id="user_pass" class="input" value="" size="20" /></label> </p> <p class="forgetmenot"><label for="rememberme"><input name="rememberme" type="checkbox" id="rememberme" value="forever" /> Remember Me</label></p> <p class="submit"> <input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" /> <input type="hidden" name="redirect_to" value="http://kseek.com.my/wp-admin/" /> <input type="hidden" name="testcookie" value="1" /> </p> </form> <p id="nav"> <a href="http://kseek.com.my/wp-login.php?action=lostpassword" title="Password Lost and Found">Lost your password?</a> </p> <script type="text/javascript"> function wp_attempt_focus(){ setTimeout( function(){ try{ d = document.getElementById('user_login'); d.focus(); d.select(); } catch(e){} }, 200); } wp_attempt_focus(); if(typeof wpOnload=='function')wpOnload(); </script> <p id="backtoblog"><a href="http://kseek.com.my/" title="Are you lost?">&larr; Back to K SEE K architect</a></p> </div> <div class="clear"></div> </body> </html> >>>
How to get all characters between 2 characters in a string in python Question: I am trying to scrap some data from a website, and below is a long string that I have managed to get. var playerlist=["Roger Federer", "Rainer Schuettler", "Dominik Hrbaty", "Thomas Muster", "Andy Roddick", "Nikolay Davydenko", "Tommy Haas", "Jarkko Nieminen", "Arnaud Clement", "Ivan Ljubicic", "David Ferrer", "Nicolas Massu", "Tommy Robredo", "Lleyton Hewitt", "Filippo Volandri", "Olivier Rochus", "Kevin Kim", "Juan Ignacio Chela", "Juan Carlos Ferrero", "Jimmy Connors", "Mikhail Youzhny", "Ruben Ramirez Hidalgo", "Rafael Nadal"] Above is not a javascript list, it is a String. I want to create a list of all player names from this string. So I have to extract all the substrings between " " and add it to a list. Alternatively if I can somehow convert this string as it is to a list or an array, it would be great. Can someone suggest how can we do this in python? Answer: You can use [`ast.literal_eval`](https://docs.python.org/3/library/ast.html#ast.literal_eval) >>> s = 'var playerlist=["Roger Federer", "Rainer Schuettler", "Dominik Hrbaty", "Thomas Muster", "Andy Roddick", "Nikolay Davydenko", "Tommy Haas", "Jarkko Nieminen", "Arnaud Clement", "Ivan Ljubicic", "David Ferrer", "Nicolas Massu", "Tommy Robredo", "Lleyton Hewitt", "Filippo Volandri", "Olivier Rochus", "Kevin Kim", "Juan Ignacio Chela", "Juan Carlos Ferrero", "Jimmy Connors", "Mikhail Youzhny", "Ruben Ramirez Hidalgo", "Rafael Nadal"]' >>> import ast >>> start = s.index('[') >>> ast.literal_eval(s[start:]) ['Roger Federer', 'Rainer Schuettler', 'Dominik Hrbaty', 'Thomas Muster', 'Andy Roddick', 'Nikolay Davydenko', 'Tommy Haas', 'Jarkko Nieminen', 'Arnaud Clement', 'Ivan Ljubicic', 'David Ferrer', 'Nicolas Massu', 'Tommy Robredo', 'Lleyton Hewitt', 'Filippo Volandri', 'Olivier Rochus', 'Kevin Kim', 'Juan Ignacio Chela', 'Juan Carlos Ferrero', 'Jimmy Connors', 'Mikhail Youzhny', 'Ruben Ramirez Hidalgo', 'Rafael Nadal'] As Steve mentions below in the comments, it is better to use, [`json.loads`](https://docs.python.org/2/library/json.html#json.loads) >>> import json >>> json.loads(s[start:]) [u'Roger Federer', u'Rainer Schuettler', u'Dominik Hrbaty', u'Thomas Muster', u'Andy Roddick', u'Nikolay Davydenko', u'Tommy Haas', u'Jarkko Nieminen', u'Arnaud Clement', u'Ivan Ljubicic', u'David Ferrer', u'Nicolas Massu', u'Tommy Robredo', u'Lleyton Hewitt', u'Filippo Volandri', u'Olivier Rochus', u'Kevin Kim', u'Juan Ignacio Chela', u'Juan Carlos Ferrero', u'Jimmy Connors', u'Mikhail Youzhny', u'Ruben Ramirez Hidalgo', u'Rafael Nadal']
Writing a dict into a png file Question: I'm a beginner on python and only have rudiments of this language, the question might not be a hard one but it's bogging me down. Now I have a 'dict' data structure, let's assume it being {(0,0): 'red'}, just one element. I want to draw a unit square of red color centered at point (0,0) on the 2D plane, and output the result as a .png file. Once this is down, one can easily do the case of many many more points in the dict. I think the code should be very simple( it's best not to use libs, for example matplotlib cairo .. etc), but I do not know how to interact with graphics, can anyone give me a hint? I googled but the results mostly are matplotlib, pyplot... that use lib files, I think there must be a simple solution with only plain python code, so I post here for help. Answer: Personally I find cairo the easiest one. All you need is to set up canvas and fill it with shapes. For a rectangular you will need its X, Y position as starting points and width and height to complete drawing. Colors are used in rgb float. You will have to convert named colors to rgb if you want to use them. I made an example for you: #!/usr/bin/python # -*- coding: utf-8 -*- import cairo # You need colors in rgb floats Dict= {(70,60): (1,1,0), (100,90): (0,1,0), (130,120): (0,0,1)} your_dict={(0,0): (1,0,0)} radius=10 # The radius of the dot w=100 # width of the square h=100 # height of the square WIDTH, HEIGHT = 200, 200 # Canvas size surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, WIDTH, HEIGHT) context = cairo.Context (surface) # Background Neutral Gray ---------- context.set_source_rgb(0.25, 0.25, 0.25) context.rectangle(0, 0, WIDTH, HEIGHT) context.fill() # Your Square ----------------------- for e in your_dict: posX = e[0] posY = e[1] r = your_dict[e][0] g = your_dict[e][1] b = your_dict[e][2] context.set_source_rgb(r, g, b) # rgb color context.rectangle(posX, posY, w, h) context.fill() # White Example Circle ------------------- context.set_source_rgb(1, 1, 1) # rgb color context.arc(20, 20, 10.0, 0, 360) context.fill() # Dots from Dict ------------------- for e in Dict: posX = e[0] posY = e[1] r = Dict[e][0] g = Dict[e][1] b = Dict[e][2] context.set_source_rgb(r, g, b) # rgb color context.arc(posX, posY, radius, 0, 360) context.fill() surface.write_to_png ("img.png") # Output to PNG You will get an image: <http://oi59.tinypic.com/2yy2iv7.jpg>
Compare consecutive columns of a file and return the number of non-matching elements Question: I have a text file which looks like this: # sampleID HGDP00511 HGDP00511 HGDP00512 HGDP00512 HGDP00513 HGDP00513 M rs4124251 0 0 A G 0 A M rs6650104 0 A C T 0 0 M rs12184279 0 0 G A T 0 I want to compare the consecutive columns and return the number of matching elements. I want to do this in Python. Earlier, I did it using Bash and AWK (shell scripting), but its very slow, as I have huge data to process. I believe Python would be a faster solution to this. But, I am very new to Python and I already have something like this: for line in open("phased.txt"): columns = line.split("\t") for i in range(len(columns)-1): a = columns[i+3] b = columns[i+4] for j in range(len(a)): if a[j] != b[j]: print j which is obviously not working. As I am very new to Python, I don't really know what changes to make to get this to work. (This is code is completely wrong and I guess I could use difflib, etc. But, I have never proficiently coded in Python before, so, skeptical to proceed) I want to compare and return the number of non matching elements in each column(starting from the third) to every other column in the file. I have 828 columns in totality. Hence I would need 828*828 number of outputs. (You can think of a n*n matrix where the (i,j)th element would be the number of non matching elements between them. My desired output in case of the above snippet would be: 3 4: 1 3 5: 3 3 6: 3 ...... 4 6: 3 ..etc Any help on this would be appreciated. Thanks. Answer: I highly recommend you use pandas for this rather than writing your own code: import numpy as np import pandas as pd df = pd.read_csv("phased.txt") match_counts = {(i,j): np.sum(df[df.columns[i]] != df[df.columns[j]]) for i in range(3,len(df.columns)) for j in range(3,len(df.columns))} match_counts {(6, 4): 3, (4, 7): 2, (4, 4): 0, (4, 3): 3, (6, 6): 0, (4, 5): 3, (5, 4): 3, (3, 5): 3, (7, 7): 0, (7, 5): 3, (3, 7): 2, (6, 5): 3, (5, 5): 0, (7, 4): 2, (5, 3): 3, (6, 7): 2, (4, 6): 3, (7, 6): 2, (5, 7): 3, (6, 3): 2, (5, 6): 3, (3, 6): 2, (3, 3): 0, (7, 3): 2, (3, 4): 3}
Django list rendered as string in template - cannot access list value Question: New to Django so please bare with me. _The problem :_ I try to iterate over a list which is the result of the selection of multiple items in a form (use of forms.MultipleChoiceField). This is then saved in my db using models.Charfield and passed from the view to the template through context_dict `(context_dict['attachment'] = attachment.pieces_jointes)` However I think that it is not saved as a list but as a string. Instead of: [u'essai document', u'essai document 2', u'essai document5'], I think I have (because of model field type): "[u'essai document', u'essai document 2', u'essai document5']" Indeed, in my template if I type : {% for attachment in attachments %} {{attachment.pieces_jointes.1}} {% endfor %} I get for that record: u and not : essai document 2 For your information, if I open the admin and look at the value recorded I have : [u'essai document', u'essai document 2', u'essai document5'] I have tried to get rid of the possible "" which could be around the list but I haven't succeeded. Can anyone explain my how I can turn that string back into a list and iterate over it in my template? Thanks A bit of code as requested: models.py class Document (models.Model): dpseudo = models.ForeignKey(Identite) dnom = models.CharField(max_length=128, unique=False) dphoto = models.ImageField(upload_to='profile_document', blank=False) ddate_ajout = models.CharField(max_length=128, unique=False) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.dpseudo) + slugify(self.dnom) + slugify(self.ddate_ajout) super(Document, self).save(*args, **kwargs) def __unicode__(self): #For Python 2, use __str__ on Python 3 return self.dnom class Attachment (models.Model): name = models.CharField(max_length=128, unique=True) date_creation = models.CharField(max_length=128, unique=False) statut = models.CharField(max_length=128, unique=False) pieces_jointes = models.CharField(max_length=128, unique=False) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(Attachment, self).save(*args, **kwargs) def __unicode__(self): #For Python 2, use __str__ on Python 3 return self.name views.py import ast def attacher(request): piece_list = Attachment.objects.all() attachment_list =[ast.literal_eval(i) for i in Attachment.objects.values_list('pieces_jointes', flat=True)] context_dict = {'pieces': piece_list, 'nom_pieces_jointes' : attachment_list} return render(request, 'job/attacher.html', context_dict) forms.py class AttachmentForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter the name.") pieces_jointes = forms.MultipleChoiceField(choices=[]) def __init__(self, *args, **kwargs): super(AttchmentForm, self).__init__(*args, **kwargs) self.fields['pieces_jointes'].choices = [(document.dnom, document.dnom) for document in Document.objects.all()] class Meta: model = Attchment fields = ('name','pieces_jointes') As advised, I used ast.literal_eval() in my views but I get an error : unexpected EOF while parsing (, line 1) Answer: As you said you have saved `attachment.pieces_jointes` as string : "[u'essai document', u'essai document 2', u'essai document5']" you can use `ast.literal_eval` in your `view` to pass the list in template: >>> import ast >>> l=ast.literal_eval("[u'essai document', u'essai document 2', u'essai document5']") >>> l[1] u'essai document 2'
Python: 'unicode' object has no attribute 'iteritems' Question: In my app using Python 2.6.9 I have this incoming JSON as a unicode string: {"devices": "{1540702298: u\"{'on': u'True', 'group': '2', 'time': u'2015-06-04 16:37:52', 'value': u'74.1', 'lastChange': u'2015-06-05 09:28:10'}\"}"} I have tried in various ways to parse it but I still get the same error... For example: a = unicode({"devices": "{1540702298: u\"{'on': u'True', 'group': '2', 'energyAccumBaseTime': u'2015-06-04 16:37:52', 'sensorValueRaw': u'74.1', 'lastChange': u'2015-06-05 09:28:10', 'energyAccumTotal': u'1.3', 'sensorValueUi': u'74.1'}\"}"}) b = json.loads(a) print b['devices'] # all good I get the contents... but when I do... for k, v in b['devices'].iteritems(): print k I get the error: > 'unicode' object has no attribute 'iteritems' How can I parse this incoming JSON in full? Answer: The outer object may be JSON, but it contains a string that itself is a Python dictionary literal, containing Unicode literals as values. Someone did this: python_dictionary = {} python_dictionary[integer_key] = str(another_dictionary) outer_object {"devices": str(python_dictionary)} before encoding the `outer_object` to JSON. Each value in that dictionary is itself another string representing a Python dictionary, and those dictionaries contain more strings representing dictionaries, like so many [Matryoshka dolls](http://en.wikipedia.org/wiki/Matryoshka_doll). You can use the [`ast.literal_eval()` function](https://docs.python.org/2/library/ast.html#ast.literal_eval) to turn that back into Python objects: import ast import json yourobject = json.loads(jsondata) dictionary = ast.literal_eval(yourobject['devices']) for key, nested in dictionary.iteritems(): nested = ast.literal_eval(nested) print key, nested but you should really fix whatever produced the string to avoid storing the nested dictionary as a string. Note that the keys in that nested dictionary are integers; those would have to be converted to strings to work in JSON. Demo: >>> import json >>> import ast >>> jsondata = r'''{"devices": "{1540702298: u\"{'on': u'True', 'group': '2', 'time': u'2015-06-04 16:37:52', 'value': u'74.1', 'lastChange': u'2015-06-05 09:28:10'}\"}"}''' >>> yourobject = json.loads(jsondata) >>> type(yourobject['devices']) <type 'unicode'> >>> ast.literal_eval(yourobject['devices']) {1540702298: u"{'on': u'True', 'group': '2', 'time': u'2015-06-04 16:37:52', 'value': u'74.1', 'lastChange': u'2015-06-05 09:28:10'}"} >>> dictionary = ast.literal_eval(yourobject['devices']) >>> dictionary[1540702298] u"{'on': u'True', 'group': '2', 'time': u'2015-06-04 16:37:52', 'value': u'74.1', 'lastChange': u'2015-06-05 09:28:10'}" >>> type(dictionary[1540702298]) <type 'unicode'> >>> for key, nested in dictionary.iteritems(): ... nested = ast.literal_eval(nested) ... print key, nested ... 1540702298 {'on': u'True', 'lastChange': u'2015-06-05 09:28:10', 'group': '2', 'value': u'74.1', 'time': u'2015-06-04 16:37:52'}
How to write a dictionary with multiple keys, each with multiple values to a csv in Python? Question: I have a dictionary that looks like this... cla_1results= {"Tom":[1,7,4],"Dunc":[3,9,4],"Jack":[1,3,5]} I want to write this dictionary to a csv so that it is in the following format Don't have the rep to post images but it would be something like this... Tom, 1, 7, 4 Dunc 3, 9, 4 Jack 1, 3, 5 Nothing I've tried has worked. My recent effort is below but I'm a real beginner with Python and programming in general. import csv cla_1results= {"Tom":[1,7,4],"Dunc":[3,9,4],"Jack":[1,3,5]} cla_2results = {"Jane":[1,7,4],"Lynda":[3,9,4],"Dave":[1,3,5]} cla_3results = {"Gemma":[1,7,4],"Steve":[3,9,4],"Jay":[1,3,5]} b = open ('test.csv','w') a = csv.writer(b) data = cla_1results= {"Tom":[1,7,4],"Dunc":[3,9,4],"Jack":[1,3,5]} a.writerows(data) b.close() which unfortunately only gives me: T, o, m D, u, n, c J, a, c, k etc Answer: This should work, you just needed a list to generate csv file, so it can be generated on the fly as well. import csv cla_1results= {"Tom":[1,7,4],"Dunc":[3,9,4],"Jack":[1,3,5]} with open('test.csv', 'wb') as csvfile: writer = csv.writer(csvfile, delimiter=',') for key,value in cla_1results.iteritems(): writer.writerow([key]+value)
Which dynamically created object called the function? Question: I am making a python app with a Tkinter GUI. So far it has some dynamically created listboxes which I will link all to one scrollbar. I need a way to let `yscroll()` know which listbox has been scrolled. Passing the `i` variable to `yscroll()` does not work. from Tkinter import * class MyApp(Tk): def __init__(self): Tk.__init__(self) self.title(' - My App - ') self.listboxes = [] for i in xrange(5): lb = Listbox(self, yscrollcommand=lambda i, *args: self.yscroll(i, *args)) for x in xrange(30): lb.insert('end', x) lb.pack(fill='y', side='left') self.listboxes.append( lb ) self.scrollbar = Scrollbar(self, orient='vertical') self.scrollbar.pack(side='right', fill='y') def yscroll(self, i, *args): print i print args ma = MyApp() ma.mainloop() Answer: It seems like the [usual recipe for using a variable from a loop in a lambda](http://stackoverflow.com/a/19837683/1639625) does not work properly when used together with parameter unpacking with `*args`. But since `*args` seems to always consist of two values in this case (the beginning and the end of the viewport, unless I'm mistaken), you could rewrite your `lambda` like this: lb = Listbox(self, yscrollcommand = lambda x, y, i=i: self.yscroll(i, x, y)) Or you can create a sort of "meta lambda", creating a lambda with the correct value for `i` make_callback = lambda i: lambda *args: self.yscroll(i, *args) lb = Listbox(self, yscrollcommand = make_callback(i)) Both will bind `i` to the value of `i` in the iteration when the `lambda` was defined.
Unable to zipfiles within folders using Python Question: I have multiple folders within a directory (D:/zptest). Each folder has many files. I am trying to zip all these files with in that folder and save the file in the same folder with the "foldername.zip" I have written a script for this but unfortunately it's throwing the following error PermissionError: [Errno 13] Permission denied: Can some body help me? I am using the following code #!/usr/bin/env python import os, zipfile from pathlib import Path loc=r'D:\zipfilelist' p=Path(r'D:\zptest') for x in p.iterdir(): x1=str(x) print("Processing: " + x1) dirs=os.listdir(x1) for file in dirs: file=os.path.join(x1,file) zip = zipfile.ZipFile(, "a", zipfile.ZIP_DEFLATED) zip.write(file) zip.close() Answer: Thanks for all your help. I was able to complete a working code. #!/usr/bin/env python import os, zipfile, datetime, time from pathlib import Path p=Path(r'V:\NAR_ARCHIVE') for x in p.iterdir(): x1=str(x) print("Processing: " + x1) #zipfilename = "%s.zip" % (x.stem) loc=r'Y:\StorageReports\NAR_Zips' loc=loc + '\\' + x.stem + '.zip' print (loc) print(x.stem) dirs=os.listdir(x1) #print(dirs) for file in dirs: sdate=datetime.datetime(2015,5,30) edate=datetime.datetime(2015,6,7) file=os.path.join(x1,file) crtime=time.ctime(os.path.getmtime(file)) d1=datetime.datetime.strptime(crtime,"%a %b %d %H:%M:%S %Y") if d1<edate and d1>sdate: file=os.path.join(x1,file) print(file) #logFile = open(r"Y:\StorageReports\NAR_Zips\logfile.log","a") #print >> logFile,message zip = zipfile.ZipFile(loc, "a", zipfile.ZIP_DEFLATED) zip.write(file) zip.close()
print_matrix of munkres library python throws an exception on matrix containing zeroes Question: Lowest cost through this matrix: Traceback (most recent call last): File "muncre.py", line 8, in <module> print_matrix(matrix, msg='Lowest cost through this matrix:') File "/usr/lib/python2.7/dist-packages/munkres.py", line 730, in print_matrix width = max(width, int(math.log10(val)) + 1) ValueError: math domain error When the matrix is containing zero in any of the rows, the above error is thrown. How can I fix it? This is the piece of code in python: from munkres import Munkres, print_matrix matrix = [[6, 9, 1], [10, 9, 2], [0,8,7]] m = Munkres() indexes = m.compute(matrix) print_matrix(matrix, msg='Lowest cost through this matrix:') total = 0 for row, column in indexes: value = matrix[row][column] total += value print '(%d, %d) -> %d' % (row, column, value) print 'total cost: %d' % total I installed the library munkres using the following command in Ubuntu: **sudo apt-get install python-munkres** Answer: This really looks like a bug with the munkres library. The print_matrix is just a "convenience" function and I'd suggest filing a bug report and in the interim just replacing it with something like the following (which is just their code with a fix to avoid trying to apply 0 or negative numbers to the logarithm). What there were trying to do is make it properly space each column to be the largest width for a number. Note that if you pass in negative numbers, this may have an off by 1 issue, but on the other hand, if you have negative costs, you may have bigger issues. def print_matrix(matrix, msg=None): """ Convenience function: Displays the contents of a matrix of integers. :Parameters: matrix : list of lists Matrix to print msg : str Optional message to print before displaying the matrix """ import math if msg is not None: print(msg) # Calculate the appropriate format width. width = 1 for row in matrix: for val in row: if abs(val) > 1: width = max(width, int(math.log10(abs(val))) + 1) # Make the format string format = '%%%dd' % width # Print the matrix for row in matrix: sep = '[' for val in row: sys.stdout.write(sep + format % val) sep = ', ' sys.stdout.write(']\n')
How to read xml directly from URLs with scrapy/python Question: In Scrapy you will have to define `start_url`s. But how can I crawl from other urls as well? Up to now I have a login script which logs into a webpage. After logging in, I want to extract xml from different urls. import scrapy class LoginSpider(scrapy.Spider): name = 'example' start_urls = ['login page'] urls = ['url','url'] def parse(self, response): return scrapy.FormRequest.from_response( response, formdata={'UserName': '', 'Password': ''}, callback=self.check_login_response ) def check_login_response(self, response): # check login succeed before going on if "incorrect" in response.body: self.log("Login failed", level=scrapy.log.ERROR) return How is it possible to crawl data from the urls defined in the urls array? Answer: You need to `yield` [`Request`](http://doc.scrapy.org/en/latest/topics/request- response.html#scrapy.http.Request) instances to the other URLs: def check_login_response(self, response): # check login succeed before going on if "incorrect" in response.body: self.log("Login failed", level=scrapy.log.ERROR) return for url in list_or_urls: yield Request(url, callback=self.parse_other_url) def parse_other_url(self, response): # ...
Interactive python matplotlib Question: python noob here. I'm trying to recreate this example from mpl_toolkits.mplot3d import Axes3D from matplotlib.collections import PolyCollection import matplotlib.pyplot as plt, mpld3 from matplotlib import colors from matplotlib.colors import colorConverter import matplotlib.animation as animation import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) xs = np.arange(0, 10, 0.4) verts = [] zs = [0.0, 1.0, 2.0, 3.0] for z in zs: ys = np.random.rand(len(xs)) ys[0], ys[-1] = 0, 0 verts.append(list(zip(xs, ys))) poly = PolyCollection(verts, facecolors = [cc('r'), cc('g'), cc('b'), cc('y')]) poly.set_alpha(0.7) ax.add_collection3d(poly, zs=zs, zdir='y') ax.set_xlabel('X') ax.set_xlim3d(0, 10) ax.set_ylabel('Y') ax.set_ylim3d(-1, 4) ax.set_zlabel('Z') ax.set_zlim3d(0, 1) mpld3.show() I wanted to save the interactive plot (and send it to someone who doesn't use python) so mpld3.show() seems like it could do the trick. Only I keep getting this error Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Python/2.7/site-packages/mpld3/_display.py", line 338, in show html = fig_to_html(fig, **kwargs) File "/Library/Python/2.7/site-packages/mpld3/_display.py", line 236, in fig_to_html figure_json=json.dumps(figure_json), File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps return _default_encoder.encode(obj) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode return _iterencode(o, 0) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: array([ 0., 10.]) is not JSON serializable I understand that this is because _something_ is an np array not a list, but when I type(verts) I get <type 'list'> So I'm not sure what that "array([ 0., 10.])" is/ how to fix this. Please include an explanation of how to extract/ manipulate objects of type <class 'mpl_toolkits.mplot3d.art3d.Poly3DCollection'> Excuse my noobiness. Thanks y'all. Answer: According to the [mpld3 github](https://github.com/jakevdp/mpld3/issues/223), "3D plots are not currently supported in mpld3", and thus produces the error you're seeing I ran across your question because I am looking for the same solution (the ability to share an interactive 3D matplotlib plot with someone who doesn't have Python). I realize this is not an answer, but I thought it was still worth sharing? (I'm also a noob, so I can't even comment on your question)
Python Library for Boyer-Myrvold planarity test or Kuratowski subgraph identification Question: I am working with NetworkX Graphs in Python and I would like to find the Kuratowski subgraphs of any given graph which I have. The Boyer-Myrvold planar graph testing algorithm can return an existing Kuratowski subgraph if the graph is not planar (O(n) in the number of vertices n), so I was hoping that there might already be an implementation of that algorithm or of a similar algorithm in Python. I have been so far unable to find one and I am slightly reluctant at having to re-implement it from the original research paper. It is even better if it can easily interface with NetworkX library for graphs. Answer: There is a Python wrapper for part of of John Boyer's planarity code (<https://code.google.com/p/planarity/>) that might be what you are looking for. It is at <https://github.com/hagberg/planarity>. It has a NetworkX interface that allows you to test for planarity and find the Kurotowski subgraphs if not. e.g. <https://github.com/hagberg/planarity/blob/master/examples/networkx_interface.py> import planarity import networkx as nx # Example of the complete graph of 5 nodes, K5 G=nx.complete_graph(5) # K5 is not planar print(planarity.is_planar(G)) # False # find forbidden Kuratowski subgraph K=planarity.kuratowski_subgraph(G) print(K.edges()) # K5 edges
How to set the marker color when using geojson.Feature Question: I am using python and my code is like: from geojson import Feature, FeatureCollection import json import sys, pymongo db = pymongo.MongoClient(host = '..........').database coll_name = sys.argv[1] point_list = [] citymap_cursor = db[coll_name].find() for doc in citymap_cursor: point_list.append(Feature(geometry=doc['point_latlng'])) with open('/path to/%s.json' % coll_name, 'w+') as outfile: json.dump(FeatureCollection(point_list), outfile) By this code I got a batch of points and I can use geojson.io to visualize the points. Now these point markers are grey on geojson.io but I want them to be red. I want to know whether these is an attribute about color in geojson.Feature so that I can adjust the marker color? Answer: Yes, you can manipulate the marker colors with a `marker-color` key inside the `properties` object. You pass it a hex color like `{"marker-color":"#FFF"}`. I assume you will be doing this inside your `for doc in citymap_cursor:` loop - something like `point_list.append(Feature(geometry=doc['point_latlng'],properties={'marker- color':'#FFF'}))`
Importing pymongo on OpenShift Question: My OpenShift application, which is written in Python with a MongoDB database, is failing to import pymongo. My logs say import pymongo [Fri Jun 05 12:11:01 2015] [error] [client 127.10.149.1] File "/var/lib/openshift/55706c785973ca947100005a/python/virtenv/lib/python2.7/site-packages/pymongo/__init__.py", line 83, in <module> [Fri Jun 05 12:11:01 2015] [error] [client 127.10.149.1] from pymongo.collection import ReturnDocument [Fri Jun 05 12:11:01 2015] [error] [client 127.10.149.1] File "/var/lib/openshift/55706c785973ca947100005a/python/virtenv/lib/python2.7/site-packages/pymongo/collection.py", line 28, in <module> [Fri Jun 05 12:11:01 2015] [error] [client 127.10.149.1] from pymongo import (common, [Fri Jun 05 12:11:01 2015] [error] [client 127.10.149.1] ImportError: cannot import name common I can't find any mention of "common" in the pymongo documentation. Any idea what I need to do to fix this? Answer: It was an installation problem. To fix it, I logged in using ssh, uninstalled pymongo and bson, made sure bson wasn't in requirements.txt, and pushed a change. This did a clean install of pymongo.
Parallelism/Performance problems with Scrapyd and single spider Question: # Context I am running scrapyd 1.1 + scrapy 0.24.6 with a single "selenium-scrapy hybrid" spider that crawls over many domains according to parameters. The development machine that host scrapyd's instance(s?) is an OSX Yosemite with 4 cores and this is my current configuration: [scrapyd] max_proc_per_cpu = 75 debug = on Output when scrapyd starts: 2015-06-05 13:38:10-0500 [-] Log opened. 2015-06-05 13:38:10-0500 [-] twistd 15.0.0 (/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python 2.7.9) starting up. 2015-06-05 13:38:10-0500 [-] reactor class: twisted.internet.selectreactor.SelectReactor. 2015-06-05 13:38:10-0500 [-] Site starting on 6800 2015-06-05 13:38:10-0500 [-] Starting factory <twisted.web.server.Site instance at 0x104b91f38> 2015-06-05 13:38:10-0500 [Launcher] Scrapyd 1.0.1 started: max_proc=300, runner='scrapyd.runner' ## EDIT: Number of cores: python -c 'import multiprocessing; print(multiprocessing.cpu_count())' 4 # Problem I would like a setup to process 300 jobs simultaneously for a single spider but scrapyd is processing 1 to 4 at a time regardless of how many jobs are pending: ![Scrapy console with jobs](http://i.stack.imgur.com/l7Oab.png) ## EDIT: CPU usage is not overwhelming : ![CPU Usage for OSX](http://i.stack.imgur.com/xWJXG.png) ## TESTED ON UBUNTU I have also tested this scenario on a Ubuntu 14.04 VM, results are more or less the same: a maximum of 5 jobs running was reached while execution, no overwhelming CPU consumption, more or less the same time was taken to execute the same amount of tasks. Answer: The logs show that you have up to 300 processes allowed. The limit is therefore further up the chain. My original suggestion was that it was the serialization on your project as covered by [Running multiple spiders using scrapyd](http://stackoverflow.com/questions/11390888/running-multiple-spiders- using-scrapyd). Subsequent investigation showed that the limiting factor was in fact the poll interval.
Basic Flask Issue w/ Importing Question: I'm following a Flask tutorial and am getting an import error. I have a file called `run.py` which contains: from app import app app.run(debug = True) When I run `./run.py`, I get: Traceback (most recent call last): File "./run.py", line 2, in <module> from app import app File "/Users/myName/Desktop/SquashScraper/app/__init__.py", line 1, in <module> from flask import Flask ImportError: cannot import name Flask This seems similar to this issue: `http://stackoverflow.com/questions/26960235/python3-cannot-import-name-flask` So I attempted the checked solution by running: virtualenv -p /usr/bin/python3 my_py3_env Unfortunately, I get: The executable /usr/bin/python3 (from --python=/usr/bin/python3) does not exist Any ideas what may be happening here? Thanks for the help, bclayman Answer: If you want your virtual environment to be Python 3 but don't know the installation directory, use `which python3`. Use that directory in your `virtualenv -p [directory] my_py3_env` command to set up the Python 3 virtual environment. I sounds like your pip is installing to your Python 2.X directory. If you're okay with that, you'll need to run the app either with `python2 run.py`, `python2.X run.py` where `x` is your installed version, or change the symlink of `python` in `/usr/bin/python` to your installation of Python 2. [This](http://stackoverflow.com/questions/2812520/pip-dealing-with-multiple- python-versions) question has some more information. Regardless of the version of Python that you wish to use, you will need to install Flask to _that_ version of Python. See [this](http://stackoverflow.com/questions/10919569/how-to-pip-install-to- specific-version-of-python) question for that.
Basic Flask: Adding Helpful Functions Question: I've written a python script that works in terminal and am porting it to the web using Flask. I've gone through parts of a tutorial (specifically: `http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello- world`) I'm struggling a bit with where to put all the functions I use in my Python script. The author () uses this code for a basic view: def index(): user = {'nickname': 'Miguel'} # fake user posts = [ # fake array of posts { 'author': {'nickname': 'John'}, 'body': 'Beautiful day in Portland!' }, { 'author': {'nickname': 'Susan'}, 'body': 'The Avengers movie was so cool!' } ] return render_template("index.html", title='Home', user=user, posts=posts) The problem is I don't have one function to call. I have 15 or so and it looks like Flask only lets me call one function per view. So I'm not really sure where to put all the helper functions that my "main" function will call. Take the author's example code. If I had a function `getPosts()` that returns an array of post objects, where would I put this? Even if I'm allowed to put it under the route's main function (which I don't think is allowed anyway), it seems like poor organization to do that. Edit: Here's my views.py file: 1 from flask import Flask 2 app = Flask(__name__) 3 from flask import render_template 4 from app import app 5 from app import helpfulFunctions 6 7 def testFunction(): 8 return 5; 9 10 @app.route('/') 11 @app.route('/index') 12 def index(): 13 #allPlayers = processGender(mainURL, menTeams) 14 myNum = testFunction() 15 return render_template('index.html', title = 'Home', user = user) Answer: You're not restricted to one function per view -- you can have as many as you want. from flask import Flask app = Flask(__name__) def f(): ... def g(): ... @app.route('/index') def index(): <here you can use f and g> ... Functions don't need to correspond to views -- only the `@app.route(...)` decorator makes it do that. If you have a large number of other functions, it couldn't hurt to put them in another file. Then you can `import` the file and use them as above.
make a full matrix output in python Question: I have a matrix with 236 x 97 dimension. When I print the matrix in Python its output isn't complete, having `.......` in the middle of matrix. I tried to write the matrix to a test file, but the result is exactly same. I can't post the screenshot because my reputation is not enough, and won't appear correctly if I choose another markup option. Can anyone solve this? * * * def build(self): self.keys = [k for k in self.wdict.keys() if len(self.wdict[k]) > 1] self.keys.sort() self.A = zeros([len(self.keys), self.dcount]) for i, k in enumerate(self.keys): for d in self.wdict[k]: self.A[i,d] += 1 def printA(self): outprint = open('outputprint.txt','w') print 'Here is the weighted matrix' print self.A outprint.write('%s' % self.A) outprint.close() print self.A.shape Answer: The problem is that you're specifically saving the `str` representation to a file with this line: > `outprint.write('%s' % self.A)` Which explicitly casts it to a string (`%s`) --- generating the abridged version you're seeing. There are lots of ways to write the entire matrix to output, one easy option would be to use [numpy.savetxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html), for example: import numpy numpy.savetxt('outputprint.txt', self.A)
Python regex for diffstat output Question: I would like to match the following strings using python regex and extract the numbers. 1 file changed, 1 insertion(+), 1 deletion(-) 2 files changed, 10 insertions(+), 10 deletions(-) 1 file changed, 1 insertion(+) 1 file changed, 2 deletions(-) So i though to use the named groups in python regex and look ahead patterns. But that is not working as expected. #!/usr/bin/python import re pat='\s*(\d+).*changed,\s+(\d*)(?P<in>=\s+insertion).*(\d+)(?P<del>=\s+deletion.*') diff_stats = re.compile(pat) obj = diff_stats.match(line) Answer: Remove `=` from named capture group.. Also.. your last group is not closed! \s*(\d+).*changed,\s+(\d*)(?P<in>\s+insertion).*(\d+)(?P<del>\s+deletion).* ↑ ↑ ↑ See [DEMO](https://regex101.com/r/aD2rI1/15) **Edit:** Improved regex for `+` and `-` too and named capture of digits: \s*(\d+)\s+files?\s+changed,\s*((?P<in>\d+)\s*(insertions?)\([+-]\))?,?\s*((?P<del>\d+)\s*(deletions?)\([+-]\))? See [DEMO](https://regex101.com/r/aD2rI1/19)
Python 2.7 display jpeg image contained in zip file Question: I have a set of jpeg files in a zip archive. I would like to display a member jpeg image in a Tkinter widget. I'm having trouble creating an Image object. I have tried feeding the output of ZipFile.open() and ZipFile.read() to Image() and PhotoImage(), all of which result in the same error message: "UnsupportedOperation: seek". [Documentation](http://effbot.org/imagingbook/image.htm) for Image.open() states that if a file object is given as the argument, the file object must support the read, seek, and tell methods. Apparently the "file-like object" returned by ZipFile.open() does not qualify. zfile = zipfile.ZipFile(filename,'r') ... filelikeobject = zfile.open(membername,'r') image = Image.open(filelikeobject) File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1967, in open fp.seek(0) UnsupportedOperation: seek I cannot find any relevant post dealing with zipped jpeg files. I know my zips are well-formed because I can perform this operation, using the same files, in Java and Perl (I am re-writing a large Java application in Python/Tk). A brute force method would be to extract the member file to disk, and simply call Image(pathname), but I'd rather do everything in memory. Any help, please. Answer: I was able to create a seekable memory file from a (nonseekable) ZipFile object as follows: from io import BytesIO import zipfile from PIL import Image, ImageTk ... zfile = zipfile.ZipFile(filename,'r') # non-seekable memberlist = zfile.namelist() ... zfiledata = BytesIO(zfile.read(membername)) # seekable image = Image.open(zfiledata) # image.show() will display photo = ImageTk.PhotoImage(image) Photo can then be used in any Tk widget which takes an image object (e.g., Canvas, Label, etc.) On my first try of the above code, I got an error message about missing files. Apparently ImageTk is not part of the standard 2.7 installation. Instructions for installing it I found in a SO [post](http://stackoverflow.com/questions/22788454/importerror-no-module- named-imagingtk/22788542#22788542).
Create python dictionary by enumerate function Question: I am looking for a simpler way to create this python dictionary. May I know if enumerate function can help? a_dict = {'a':0, 'b':1, 'c':2, ....} Answer: you may simply use `string.ascii_lowercase` which is string of all lowercase characters, then you `zip` the lowercase letters and list of number ranging from `0` to `len(string.ascii_lowercase)` and then convert them to `dict`. However you may want to use some other set of alphabet as `string.ascii_letters`, `string.ascii_uppercase` , `string.letters`, `string.punctuation`, etc. You can easily filter the keys that you want in your dictionary either by concatenating the above mentioned strings as `string.ascii_lowercase+string.ascii_uppercase` would give us a string containing first the 26 lowercase alphabets and then 26 uppercase alphabets, you may also apply slicing methods to get desired set of characters, like `string.ascii_lowercase[0:15]` would give you `"abcdefghijklmn"` import string alphabets = string.ascii_lowercase print dict(zip(alphabets, range(len(alphabets)))) >>> {'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'g': 6, 'f': 5, 'i': 8, 'h': 7, 'k': 10, 'j': 9, 'm': 12, 'l': 11, 'o': 14, 'n': 13, 'q': 16, 'p': 15, 's': 18, 'r': 17, 'u': 20, 't': 19, 'w': 22, 'v': 21, 'y': 24, 'x': 23, 'z': 25}
How to check if any sys.argv argument equals a specific string in Python Question: In Python I would like to check if _any_ argument that has been passed to my script equals "-h" (so that I can display a help banner and exit). Should I loop through sys.argv values or is there a more simple way to achieve this? Answer: import sys def help_required(): return "-h" in sys.argv[1:]
Adding Pygame to PYTHONPATH Question: * Windows 8 64 bit * Python 3.4.3 * Pygame-1.9.2a0.win32-py3.4 I'm in the process of trying to install Pygame now. This computer has two hard-drives, and I'm not sure if that means anything, but when I try and install Pygame it defaults to my `D:\` drive. Python itself is installed on my `C:\` drive however. [this](http://i.imgur.com/0XN8GJb.png) is what I see when I try to install Pygame and [this](http://i.imgur.com/NAJMQjZ.png) is what I think I should see when I install it (right?). That is a screenshot from a video tutorial I was following. So, I've copied all the files from the `pygame` folder to where it should installed, which are `C:\Python34\Lib\site-packages` and `C:\Python34\include`. Instead of getting the usual import error, I now get [this error](http://i.imgur.com/f7rqHod.png). I've looked at a bunch of similar problems and they all said that the problem probably is the `PYTHONPATH`. So I've gone to the environment variables > system variables and clicked `New`. `Variable name = PYTHONPATH` and `Variable_Value = C:\Python34\Lib\site-packages\pygame;` Is this right? When I type `import sys` \--> `print (sys.path)`, pygame does [show up](http://i.imgur.com/kZRM616.png), but I still get an error. Answer: I've had similar problem when installing pygame, Windows 8.1 wouldn't recognise MinGW system variable, and leading to this pygame was never found. What solved problem for me is <http://www.lfd.uci.edu/~gohlke/pythonlibs/> . Here you can find unofficial wheels for many packages that won't install for varoius reasons or simply don't work too well. You simply need pip with version >= 6. Install the one with cp34, it is corresponding with CPython 3.4.
parallel assignment variable from python to java (Pi algorithm) Question: I would like to translate a python algorithm to Java, I have this source code (using parallel asignment variable (doesn't exist in Java :( ) # -*- coding: cp1252 -*- #! /usr/bin/env python import sys def main(): k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L while 1: p, q, k = k*k, 2L*k+1L, k+1L a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 d, d1 = a/b, a1/b1 while d == d1: output(d) a, a1 = 10L*(a%b), 10L*(a1%b1) d, d1 = a/b, a1/b1 def output(d): sys.stdout.write(`int(d)`) sys.stdout.flush() #ecriture en continue du chiffre pi = open("flypi.html", "a") pi.write(`int(d)`) pi.write("\n") pi.close() main() So, first I recoded the same script without parallel assignement variable : # -*- coding: cp1252 -*- #! /usr/bin/env python import sys def main(): #k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L k = 2L a = 4L b = 1L a1 = 12L b1 = 4L while 1: #p, q, k = k*k, 2L*k+1L, k+1L kk = k p = kk*kk q = 2L*kk+1L k = kk+1L #a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 aa = a bb = b a = a1 b = b1 a1 = p*aa+q*a1 b1 = p*bb+q*b1 #d, d1 = a/b, a1/b1 d = a/b d1 = a1/b1 while d == d1: output(d) #a, a1 = 10L*(a%b), 10L*(a1%b1) a = 10L*(a%b) a1 = 10L*(a1%b1) #d, d1 = a/b, a1/b1 d = a/b d1 = a1/b1 def output(d): sys.stdout.write(`int(d)`) sys.stdout.flush() #ecriture en continue du chiffre pi = open("flypi.html", "a") pi.write(`int(d)`) pi.write("\n") pi.close() main() The output of these two script is the same: 31415926535897932384626433832795028841971693993751058209749445923078164062862089 (crt+c) Now here is the script I made in Java (almost the same as the second python script): public static void cal(){ //int i = 0; long d = 0; long k = 2L; long a = 4L; long b = 1L, a1 = 12L, b1 = 4L; long p = 0, q = 0, d1 = 0; long aa = 0, bb = 0; long kk = 0; while(true){ kk = k; p = kk*kk; q = 2L*kk+1L; k = kk+1L; aa = a; bb = b; a = a1; b = b1; a1 = p*aa+q*a1; b1 = p*bb+q*b1; d = a/b; d1 = a1/b1; while(d == d1){ System.out.print(d); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } a = 10L*(a%b); a1 = 10L*(a1%b1); d = a/b; d1 = a1/b1; } //i++; } } but the output is wrong : 31415926530000000001-100000000000000000100-300000101000000000000000000000000000000000000 (ctr+c) Thank you, and sorry for the long post :) EDIT: So yes it's a buffer overflow. I tried to implement BigInteger and it works fine !! thank you ! Answer: In Python integers can be arbitrarily large. In Java a long consists of 64 bits and can therefore only store numbers smaller than about 2**64 / 2. If a number is too big, the first bits of it are discarded and the most significant bit that is not overwrites the sign of the integer, resulting in negative numbers in mathematically impossible places. Use BigInteger as ajb suggests or change your calculations in some way.
python dictionary get by value Question: So my problem is how to get VALUE by key rather getting a pointer. I have the following code, and I want to do sth to tempA without changing the value within dictionary. temp_keys=["a","b","c","d"] temp_values=[[1,1],[2,2],[3,3],[4,4]] temp=dict(zip(temp_keys,temp_values)) tempA=temp.get('a',temp.copy()) tempA.append(2) print temp output is: {'a': [1, 1, 2], 'b': [2, 2], 'c': [3, 3], 'd': [4, 4]} See the value of key "a" has been changed. I want my variable temp unchanged, {'a': [1, 1], 'b': [2, 2], 'c': [3, 3], 'd': [4, 4]} Answer: I believe you are looking for deep copy import copy temp_keys=["a","b","c","d"] temp_values=[[1,1],[2,2],[3,3],[4,4]] temp=dict(zip(temp_keys,temp_values)) print temp temp_copy = copy.deepcopy(temp) temp_copy['a'].append(2) print temp Your `temp` will remain unchanged: > {'d': [4, 4], 'b': [2, 2], 'c': [3, 3], 'a': [1, 1]} {'d': [4, 4], 'b': [2, > 2], 'c': [3, 3], 'a': [1, 1]}
Reset password in Django Question: I have view this tutorial <https://www.youtube.com/watch?v=z6pXNf2SzQQ> that explain how to send mail to reset password, I have follow all steps but I have the same error always: No module named 'my_app.views.django'; 'my_app.views' is not a package. For this case my_app = melomanos. I have all templates for Django reset password in my site templates folder. **The complete site root is:** ![root of my app](http://i.stack.imgur.com/o4i6y.png) **The error that shows is:** I know I have a missconfigured urls but I don't understand how I can configure correctly. Thanks for your cooperation. ImportError at /resetpassword/ No module named 'melomanos.views.django'; 'melomanos.views' is not a package Request Method: GET Request URL: http://localhost/resetpassword/ Django Version: 1.8.2 Exception Type: ImportError Exception Value: No module named 'melomanos.views.django'; 'melomanos.views' is not a package Exception Location: C:\Python34\lib\importlib\__init__.py in import_module, line 109 Python Executable: C:\Python34\python.exe Python Version: 3.4.3 Python Path:['c:\\labsoft', 'C:\\Python34\\lib\\site-packages\\psycopg2-2.6-py3.4-win-amd64.egg', 'C:\\Windows\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages', 'labsoft/melomanos', '/melomanos'] here is the codes: **melomanos\urls.py** from django.conf.urls import patterns, url, include from django.views.generic.base import TemplateView from django.contrib import admin from .views import Buscar_view admin.autodiscover() urlpatterns = patterns('melomanos.views', url(r'^admin/', include(admin.site.urls)), url(r'^$','trabajos_all_view',name='url_index'), url(r'^register/$','register_view',name='vista_registro'), url(r'^login/$','login_view',name='vista_login'), url(r'^logout/$','logout_view',name='vista_logout'), url(r'^perfil/$','registro_view',name='vista_perfil'), url(r'^publicar/$','trabajomusical_view', name='vista_publicar'), url(r'^trabajos/$','trabajos_view',name='vista_trabajos'), url(r'^trabajo/(?P<id_trabajo>.*)/$','solo_trabajo_view', name='vista_trabajo'), url(r'^buscar/$',Buscar_view.as_view(),name='vista_buscar'), url('', include('django.contrib.auth.urls')), url(r'^resetpassword/passwordsent/$', 'django.contrib.auth.views.password_reset_done', name='password_reset_done'), url(r'^resetpassword/$', 'django.contrib.auth.views.password_reset', name="reset_password"), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>,+)/$', 'django.contrib.auth.views.password_reset_confirm'), url(r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete'), ) **The link at the login page:** <p>Forgot your password?<a href="/resetpassword/">Reset Password</a></p> **settings.py** INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'melomanos', ) Answer: On `melomanos\urls.py` you are using url prefix. urlpatterns = patterns('melomanos.views', url(r'^resetpassword/$', 'django.contrib.auth.views.password_reset', name="reset_password"), ) So `/resetpassword/` is calling `melomanos.views.django.contrib.auth.views.password_reset` instead of `django.contrib.auth.views.password_reset` For reset password view removing the prefix will solve this issue. You may remove `resetpassword` from prefixed block and later add it without prefix like urlpatterns += patterns('', url(r'^resetpassword/$', 'django.contrib.auth.views.password_reset', name="reset_password"), )
Inheriting and aggregating class attributes Question: A simple example: class A: attr = {'a': 1} class B(A): attr = {'b': 2} #overrides A.attr What I want is a method to aggregate the dictionaries. I can think of just these options: 1. Ignore that disconcerting feeling and copy everything by hand. 2. Manually adding the dictionaries: class B(a): attr = dict(list(six.iteritems(A.attr)) + list(six.iteritems({ 'b': 2 }))) Note `'b': 2` must come second so its keys shadow `A`'s. This must reference `A` explicitly (**is there some way to get this with`super`?**). It also needs this kind of micro inheritance to be applied manually. 3. This is also something that could be achieved with metaclasses. I've seen it [done in `DeclarativeFieldsMetaclass` in django](https://github.com/django/django/blob/master/django/forms/forms.py#L35). The idea is to have the metaclass handle dictionary merging for a specific attribute. This is far more work. Also, as it introduces magic that doesn't normally happen in python, this might be considered a poor option. I also prefer to not use metaclasses unless necessary to avoid conflicts. One major advantage is the user doesn't need to manually aggregate the attribute data. **Is there another way?** **I'd like to know what others think of each approach with regard to good programming practice.** In my case I'm using a [`MultiModelForm` from django- betterforms](http://django- betterforms.readthedocs.org/en/latest/multiform.html), and have a base form with just a few `ModelForm`s but want to extend it. I don't think the inherited class should need to duplicate the `ModelForm`s in the `form_classes` attribute from the parent. Should it be up to the user to manage inheritance as in option 2 or should `MultiModelForm` handle it automatically with a metaclass as in option 3? Are there other issues with each option I haven't discussed? Answer: You can do it using [`dictionary.update()`](https://docs.python.org/2/library/stdtypes.html#dict.update) function, which will add a new dictionary to an existing one **Example** >>> class A: ... attr = {'a': 1} ... >>> class B(A): ... attr = dict(A.attr) ... attr.update({'b' : 2 }) ... >>> >>> A.attr {'a': 1} >>> B.attr {'a': 1, 'b': 2} **What it does?** * `attr = dict(A.attr)` returns a new dictionary from `A.attr`. This is important because if we write attr = A.attr we will end up updating the `attr` of `A` class instead of `B` class. * `attr.update({'b' : 2 })` Updates the `B.attr` by adding the new dictionary `{'b' : 2 }`.
Python: Use one list to search another list and pull corresponding rows Question: I am stuck. I have a list of strings, and I want to search through a bigger list that has additional columns associated with those strings, and put the strings from my first list into a new file with their associated values from the second list (ie. take the whole row where there is a string match). This is what I have so far from sys import argv script, filename, filename2, outputfile = argv import csv #program to help manipulate csv files with open(filename,'rU') as fin1, open(filename2, 'rU') as fin2, open (outputfile,'w') as fout: #simplifies opening and closing a file into one line for row in fin1: gene = row[0] writer = csv.writer(fout, delimiter=',') #dialect must be specified, csv file so it is a , for gene in csv.reader(fin1, delimiter=','): for row in csv.reader(fin2, delimiter=','): if gene == row[4]: writer.writerow(row) break Thank you Answer: from sys import argv script, filename, filename2, outputfile = argv import csv # program to help manipulate csv files with open(filename,'rU') as fin1, open(outputfile,'w') as fout: # simplifies opening and closing a file into one line writer = csv.writer(fout, delimiter=',') # dialect must be specified, csv file so it is a , for row_fin1 in csv.reader(fin1, delimiter=','): gene = row_fin1[0] with open(filename2, 'rU') as fin2: for row_fin2 in csv.reader(fin2, delimiter=','): if gene == row_fin2[4]: writer.writerow(row_fin2) break You need to open and close the fin2 each time, because csv reader reads only in forward direction and cant go back. Hope this helps.
Python: adding value from list of lists Question: below is my list of lists; db_rows = [('a','b','c',4), ('a','s','f',6), ('a','c','d',6), ('a','b','f',2), ('a','b','c',6), ('a','b','f',8), ('a','s','f',6), ('a','b','f',7), ('a','s','f',5), ('a','b','f',2)] if first three values are same in the inner list then I need to add 4th value to create new list I need result list like this: final_list = [('a','b','c',10), ('a','s','f',17), ('a','c','d',6), ('a','b','f',19)] I have tried the below script (not working): final_list = [] for row in db_rows: temp_flag=False temp_list = [] val = 0 for ref_row in db_rows: if row != ref_row: if row[0]==ref_row[0] and row[1]==ref_row[1] and row[2]==ref_row[2]: val = val + ref_row[3] temp_flag=True temp_list=(row[0],row[1],row[2],val) if temp_flag==False: temp_list=row final_list.append(temp_list) please advice me. Answer: Use a dictionary as Dov Grobgeld commented, then convert the dictionary back to the list. from collections import defaultdict db_rows = [('a','b','c',4), ('a','s','f',6), ('a','c','d',6), ('a','b','f',2), ('a','b','c',6), ('a','b','f',8), ('a','s','f',6), ('a','b','f',7), ('a','s','f',5), ('a','b','f',2)] sums = defaultdict(int) for row in db_rows: sums[row[:3]] += row[3] final_list = [key + (value,) for key, value in sums.iteritems()] Printing `final_list` outputs: [('a', 'b', 'c', 10), ('a', 's', 'f', 17), ('a', 'b', 'f', 19), ('a', 'c', 'd', 6)] See [`collections.defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict).
Python finding bolded text in RTF Question: I'm dealing with a gigantic rich text file where every entry starts with a bold title. It'd be really helpful to import the rich text file into Python and have it split up lines wherever it sees bold text. However, I can't find a way to import non plaintext, and have resorted to looking for other methods of finding where the bold text starts. Is there a way to get Python to read where bold text is? Answer: No, not easily. Certainly not within the scope of a StackOverflow answer. The problem is that RTF is a proprietary format, with special "syntax" that describes the format. There are libraries that make attempts to read it, which are described here: [Is there a Python module for converting RTF to plain text?](http://stackoverflow.com/questions/1337446/is-there-a-python-module- for-converting-rtf-to-plain-text) However, even if one of those would read the text for you, it would be unlikely to be telling you the format. Afterall, how would it tell you? Your best bet may be finding an RTF to HTML converter (at least one is referred to in the question that I pointed to), then using BeautifulSoup to find the bolded HTML elements.
Detect if specific Python.app instance is already running Question: I am experimenting with OS X apps written in Python and need to detect if there is already an instance of Python.app running with certain script. The script modifies `CFBundleName` on-the-fly from `Python` to `MyApp` to change the app title in the menubar. bundle = NSBundle.mainBundle() info = bundle.localizedInfoDictionary() or bundle.infoDictionary() info['CFBundleName'] = 'MyApp' If I start another instance and check `CFBundleName` of the running apps, it will only tell me the original value, i.e. `Python`: for app in NSWorkspace.sharedWorkspace().runningApplications(): bundle = NSBundle.bundleWithURL_(app.bundleURL()) info = bundle.localizedInfoDictionary() or bundle.infoDictionary() name = info.get('CFBundleName') if name in ('Python', 'MyApp'): print name # => prints Python So I need to find a way to mark a Python.app instance that runs MyApp script to be able to abort launching duplicate instances. Is there such way? **Update:** Until there is a better solution, I'll be using `lockf` import fcntl lockfile = open('/tmp/myapp.lock', 'w') fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB) **Update 2:** Well, I still need to find my application to focus. Currently, I just loop through all Python.app instances and focus them one by one. Normally, there is just one, but if there are few of them it can be messy. from Foundation import NSWorkspace from Cocoa import NSApplicationActivateAllWindows, NSApplicationActivateIgnoringOtherApps try: import fcntl lockfile = open('/tmp/myapp.lock', 'w') fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError as e: assert (e.errno, e.strerror) == (35, 'Resource temporarily unavailable') for app in NSWorkspace.sharedWorkspace().runningApplications(): if app.bundleIdentifier() == 'org.python.python': app.activateWithOptions_(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps) exit() **Update 3:** I am going to use a pid file until a better solution comes up LOCK_FILE = '/tmp/myapp.lock' PID_FILE = '/tmp/myapp.pid' try: import fcntl # NOTE: needs to be assigned to a variable for the lock to be preserved lockfile = open(LOCK_FILE, 'w') fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError as e: try: with open(PID_FILE) as f: pid = int(f.read()) except: pid = None for app in NSWorkspace.sharedWorkspace().runningApplications(): if app.bundleIdentifier() == 'org.python.python': if not pid or pid == app.processIdentifier(): app.activateWithOptions_(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps) exit() from Foundation import NSProcessInfo info = NSProcessInfo.processInfo() pid = info.processIdentifier() with open(PID_FILE, 'w+') as f: f.write(str(pid)) Answer: There are several ways to solve this. Among them: * libunique - a library specifically designed for this * dbus - internal communications system Many of them are described in the answers of [this post](http://stackoverflow.com/questions/2261997/how-can-i-detect-what-other- copy-of-python-script-is-already-running). A recipe for unique instances is given [here](http://code.activestate.com/recipes/474070/).
How to write data to stdin of the first process in a Python shell pipeline? Question: I see this code snippet referenced quite a lot during discussions around Python subprocess pipelines. Obligatory link: <https://docs.python.org/3.4/library/subprocess.html#replacing-shell-pipeline> Modified slightly: p1 = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) p2 = subprocess.Popen(['head', '-n', '1'], stdin=p1.stdout, stdout=subprocess.PIPE) # Allow p1 to receive a SIGPIPE if p2 exits. p1.stdout.close() output = p2.communicate()[0] This shell pipeline is pointless, except to succinctly demonstrate the challenge. Input `"abc\ndef\nghi\n"` and only `"abc\n"` should be captured in `output`. What is the best way to write data to `p1.stdin`? I am aware of the `input` argument to `subprocess.Popen.communicate()`, but it won't work in a pipeline. Also, the solution needs to handling blocking correctly. My guess: Reverse engineer the code behind `communicate()` and create another version for this specific issue. Before I do that, I want to ask if there is a simpler solution of which I am not aware. Answer: Write to `p1.stdin` and then close it before calling `p2.communicate()`: In [1]: import subprocess In [2]: %cpaste Pasting code; enter '--' alone on the line to stop or use Ctrl-D. :p1 = subprocess.Popen(['cat'], : stdin=subprocess.PIPE, : stdout=subprocess.PIPE) :p2 = subprocess.Popen(['head', '-n', '1'], : stdin=p1.stdout, : stdout=subprocess.PIPE) :p1.stdout.close() :-- In [3]: p1.stdin.write(b'This is the first line.\n') Out[3]: 24 In [4]: p1.stdin.write(b'And here is the second line.\n') Out[4]: 29 In [5]: p1.stdin.close() In [6]: p2.communicate() Out[6]: (b'This is the first line.\n', None) (Don't forget the newlines in the data you send to `cat`, or it won't work.)
Python decorate methods with variable number of positional args and optional arg Question: I am writing my first Python (3.4) application using SQLalchemy. I have several methods which all have a very similar pattern. They take an optional argument `session` which defaults to `None`. If `session` is passed, the function uses that session, otherwise it opens and uses a new session. For example, consider the following method: def _stocks(self, session=None): """Return a list of all stocks in database.""" newsession = False if not session: newsession = True session = self.db.Session() stocks = [stock.ticker for stock in session.query(Stock).all()] if newsession: session.close() return stocks So, being new to Python and eager to learn all of its power, I thought this smelt like the perfect time to learn a little something about Python decorators. So after a lot of reading, like this [this series of blog posts](http://www.artima.com/weblogs/viewpost.jsp?thread=240808) and [this](http://stackoverflow.com/a/1594484/4530863) fantastic SO answer, I wrote the following decorator: from functools import wraps def session_manager(func): """ Manage creation of session for given function. If a session is passed to the decorated function, it is simply passed through, otherwise a new session is created. Finally after execution of decorated function, the new session (if created) is closed/ """ @wraps(func) def inner(that, session=None, *args, **kwargs): newsession = False if not session: newsession = True session = that.db.Session() func(that, session, *args, **kwargs) if newsession: session.close() return func(that, session, *args, **kwargs) return inner And it seems to work great. The original method is now reduced to: @session_manager def _stocks(self, session=None): """Return a list of all stocks in database.""" return [stock.ticker for stock in session.query(Stock).all()] HOWEVER, when I apply the decorator to a function that takes some positional arguments in addition to the optional `session`, I get an error. So trying to write: @session_manager def stock_exists(self, ticker, session=None): """ Check for existence of stock in database. Args: ticker (str): Ticker symbol for a given company's stock. session (obj, optional): Database session to use. If not provided, opens, uses and closes a new session. Returns: bool: True if stock is in database, False otherwise. """ return bool(session.query(Stock) .filter_by(ticker=ticker) .count() ) and running like `print(client.manager.stock_exists('AAPL'))` gives an `AttributeError` with the following traceback: Traceback (most recent call last): File "C:\Code\development\Pynance\pynance.py", line 33, in <module> print(client.manager.stock_exists('GPX')) File "C:\Code\development\Pynance\pynance\decorators.py", line 24, in inner func(that, session, *args, **kwargs) File "C:\Code\development\Pynance\pynance\database\database.py", line 186, in stock_exists .count() AttributeError: 'NoneType' object has no attribute 'query' [Finished in 0.7s] So I am guessing by the traceback, that I am messing up the order of the arguments, but I can't figure out how to order them properly. I have functions that I want to decorate that can take 0-3 arguments in addition to the `session`. Can someone please point out the error in my methodology? Answer: Change def inner(that, session=None, *args, **kwargs): to def inner(that, *args, session=None, **kwargs): and return func(that, session, *args, **kwargs) to return func(that, *args, session=session, **kwargs) It works: def session_manager(func): def inner(that, *args, session=None, **kwargs): if not session: session = object() return func(that, *args, session=session, **kwargs) return inner class A(): @session_manager def _stocks(self, session=None): print(session) return True @session_manager def stock_exists(self, ticker, session=None): print(ticker, session) return True a = A() a._stocks() a.stock_exists('ticker') Output: $ python3 test.py <object object at 0x7f4197810070> ticker <object object at 0x7f4197810070> When you use `def inner(that, session=None, *args, **kwargs)` any second positional argument (counting `self`) is treated as `session` argument. So when you call `manager.stock_exists('AAPL')` `session` gets value `AAPL`.
sklearn: Using CountVectorizer object to get a feature vector of a new string Question: So I create a CountVectorizer object by executing following lines. count_vectorizer = CountVectorizer(binary='true') data = count_vectorizer.fit_transform(data) Now I have a new string and I would want to map this string to the TDM matrix that i get from CountVectorizer. So what I am expecting for a string I input to the TDM, is a corresponding document term vector. I tried, count_vectorizer.transform([string]) Gave an error, AttributeError: transform not found Adding a a part of the stacktrace, Its a long stacktrace and hence I am adding just the relevant bits which are the last few lines of the trace. File "/Users/ankit/Desktop/geny/APIServer/RUNTIME/src/controller/sentiment/Sentiment.py", line 29, in computeSentiment vec = self.models[model_name]["vectorizer"].transform([string]) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/sparse/base.py", line 440, in __getattr__ raise AttributeError(attr + " not found") Please advice. Thanks Ankit S Answer: The example you showed wasn't reproducible - what is the string variable here? However following code seems to work perfectly:- from sklearn.feature_extraction.text import CountVectorizer data = ["aa bb cc", "cc dd ee"] count_vectorizer = CountVectorizer(binary='true') data = count_vectorizer.fit_transform(data) # Check if your vocabulary is being built perfectly print count_vectorizer.vocabulary_ # Trying a couple new string with added new word. new word should be ignored newData = count_vectorizer.transform(["aa dd mm", "aa bb"]) print newData # You can get the array by writing print newData.toarray() ![enter image description here](http://i.stack.imgur.com/l0r8u.png) Well, count_vectorizer.transform() accepts list of strings - not a single string. If the transform-fitting didn't work, it should have raised "ValueError: Vocabulary wasn't fitted or is empty!" In case of errors of this kind, paste the whole traceback stack (exception stack). No one can see where AttributeError is coming from - your code or some internal bug in sklearn.
(Python Unicurses) stdscr not passing between files? Question: I've been trying to learn Curses (Unicurses since I'm on Windows) and have been following a tutorial, but I've gotten stuck. I am running into this error message: D:\Python34>python ./project/cursed.py Traceback (most recent call last): File "./project/cursed.py", line 35, in <module> main() File "./project/cursed.py", line 20, in main obj_player = Player(stdscr, "@") File "D:\Python34\project\cursedplayer.py", line 10, in __init__ self.max_x = stdscr.getmaxyx()[1] - 1 AttributeError: 'c_void_p' object has no attribute 'getmaxyx' What I can glean from that is something is going wrong when trying to get the stdscr variable between the two files. Here is the file that has the function I'm trying to call: from unicurses import * from cursedfunction import * class Player: def __init__(self, stdscr, body, fg = None, bg = None, attr = None): self.max_x = stdscr.getmaxyx()[1] - 1 self.max_y = stdscr.getmaxyx()[0] - 1 self.x = self.max_x / 2 self.y = self.max_y / 2 self.body = body del stdscr #create player self.window = newwin(1, 1, self.y, self.x) waddstr(self.window, self.body) self.panel = new_panel(self.window) self.fg = fg self.bg = bg self.color = 0 self.attr = attr if (fg != None) and (bg != None): self.set_colors(fg, bg) self.show_changes() def set_colors(self, fg, bg): self.color = make_color(fg, bg) self.fg = fg self.bg = bg waddstr( self.window, self.body, color_pair(self.color) + self.attr) self.show_changes() def show_changes(self): update_panels() doupdate() Here is the main file that's calling the function defined in cursedplayer.py: from unicurses import * from cursedfunction import * from cursedplayer import * #lines is 80 #columns is 25 def main(): stdscr = initscr() if not has_colors(): print("You need colors to run!") return 0 start_color() noecho() curs_set(False) keypad(stdscr, True) obj_player = Player(stdscr, "@") update_panels() doupdate() running = True while running: key = getch() if key == 27: running = False break endwin() if (__name__ == "__main__"): main() I'd appreciate any help. I've been searching around but haven't found anything relevant to my problem. I can't proceed with the curses tutorial I'm following because of this error. Thank you for reading. (cursedfunction.py isn't included because it doesn't have any relevant info, just a function that makes colors) Answer: Ah! I am very dumb. The error message was giving me all the info I need -- specifically, that stdscr didn't have a function called 'getmaxyx'. I was inputting the command wrong! Going from this: self.max_x = stdscr.getmaxyx()[1] - 1 self.max_y = stdscr.getmaxyx()[0] - 1 To this: self.max_x = getmaxyx(stdscr)[1] - 1 self.max_y = getmaxyx(stdscr)[0] - 1 ...was able to pass the information in a format that I needed. Why it worked in the tutorial I don't know, but I blame black magic.
Create table in mysqldb Question: Traceback (most recent call last): File "****", line 17, in module cur.execute("CREATE TABLE `Project1`(`Id` INT PRIMARY KEY NOT NULL ,`TERM` VARCHAR(25) CHARACTER SET utf8 NOT NULL, `TYPE1` VARCHAR(25) CHARACTER SET utf8 NOT NULL, `ACTION` VARCHAR(30) CHARACTER SET utf8 NOT NULL, `CERTAINITY` DOUBLE(3) NOT NULL"); File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 205, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') NOT NULL' at line 1") line 1: import mysqldb as mdb after rectifying the double problem, I got a similar error, with the last sentence changed as _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1") the line to create tables was modified to CREATE TABLE `Project1`(`Id` INT PRIMARY KEY NOT NULL ,`Term` VARCHAR(25) CHARACTER SET utf8 NOT NULL, `Type1` VARCHAR(25) CHARACTER SET utf8 NOT NULL, `Action` VARCHAR(30) CHARACTER SET utf8 NOT NULL, `Certainity` DOUBLE(4,3) NOT NULL) NEW PROBLEM, I changed 'Certainity' to string File "/home/ankitaprasad/Ontology Project3/Stanford.py", line 57, in <module> cur.execute("""INSERT INT0 Project1(Term, Type1, Action, Certainity) VALUES (%s,%s,%s,%s)""",(term,type1,action,ab)); File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 205, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Project1(Term, Type1, Action, Certainity) VALUES ('','','','0')' at line 1") [Finished in 1.2s with exit code 1] here ab=str(mod) Answer: First off, your entire create statement formatted into this: CREATE TABLE `Project1` ( `Id` INT PRIMARY KEY NOT NULL, `TERM` VARCHAR(25) CHARACTER SET utf8 NOT NULL, `TYPE1` VARCHAR(25) CHARACTER SET utf8 NOT NULL, `ACTION` VARCHAR(30) CHARACTER SET utf8 NOT NULL, `CERTAINITY` DOUBLE(3) NOT NULL See where you are missing the closing parentheses? Fixing that, you still have a problem as [`DOUBLE`](https://dev.mysql.com/doc/refman/5.5/en/floating- point-types.html) require _two_ arguments, not one, so that is a syntax error for MySQL. Please read the documentation and carefully look at what you wrote before asking questions and it will save you a lot of time, especially shortly before a deadline.
NoReverseMatch at /resetpassword/ in Django Question: I´m getting this error during Reset Password. I have a login page whith the link to reset forgotten password, it shows correctly the templates, but if I write the mail to send the reset link, it shows this error: **localhost/resesetpassword** NoReverseMatch at /resetpassword/ Reverse for 'password_reset_confirm' with arguments '()' and keyword arguments '{'token': '42e-71994a9bf9d36c22eb95', 'uidb64': b'MQ'}' not found. 0 pattern(s) tried: [] Request Method: POST Request URL: http://localhost/resetpassword/ Django Version: 1.8.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_reset_confirm' with arguments '()' and keyword arguments '{'token': '42e-71994a9bf9d36c22eb95', 'uidb64': b'MQ'}' not found. 0 pattern(s) tried: [] Exception Location: C:\Python34\lib\site- packages\django\core\urlresolvers.py in _reverse_with_prefix, line 496 Python Executable: C:\Python34\python.exe Python Version: 3.4.3 Python Path: ['c:\\labsoft', 'C:\\Python34\\lib\\site-packages\\psycopg2-2.6-py3.4-win-amd64.egg', 'C:\\Windows\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages'] Server time: Dom, 7 Jun 2015 21:46:55 -0500 **Error during template rendering** In template C:\Python34\lib\site- packages\django\contrib\admin\templates\registration\password_reset_email.html, error at line 6 1 {% load i18n %}{% autoescape off %} 2 {% blocktrans %}You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktrans %} 3 4 {% trans "Please go to the following page and choose a new password:" %} 5 {% block reset_link %} 6 {{ protocol }}://{{ domain }} {% url 'password_reset_confirm' uidb64=uid token=token %} 7 {% endblock %} 8 {% trans "Your username, in case you've forgotten:" %} {{ user.get_username }} 9 10 {% trans "Thanks for using our site!" %} 11 12 {% blocktrans %}The {{ site_name }} team{% endblocktrans %} 13 14 {% endautoescape %} 15 **It shows this code in red:** {{ protocol }}://{{ domain }} {% url 'password_reset_confirm' uidb64=uid token=token %} **I think the error can be the protocol and domain parameters, but I don't know how fix it. Thanks a lot!!!** **urls.py** from django.conf.urls import patterns, url from .views import Buscar_view urlpatterns = patterns('melomanos.views', url(r'^$','trabajos_all_view',name='url_index'), url(r'^register/$','register_view',name='vista_registro'), url(r'^login/$','login_view',name='vista_login'), url(r'^logout/$','logout_view',name='vista_logout'), url(r'^perfil/$','registro_view',name='vista_perfil'), url(r'^publicar/$','trabajomusical_view', name='vista_publicar'), url(r'^trabajos/$','trabajos_view',name='vista_trabajos'), url(r'^trabajo/(?P<id_trabajo>.*)/$','solo_trabajo_view', name='vista_trabajo'), url(r'^buscar/$',Buscar_view.as_view(),name='vista_buscar'), ) urlpatterns += patterns('', url(r'^resetpassword/passwordsent/$', 'django.contrib.auth.views.password_reset_done', name='password_reset_done'), url(r'^resetpassword/$', 'django.contrib.auth.views.password_reset', name="reset_password"), url(r'^reset/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>,+)/$', 'django.contrib.auth.views.password_reset_confirm'), url(r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete',{'template_name' : 'registration/password_reset.html', 'post_reset_redirect': '/logout/' }), ) Answer: Actually your regex for the token parameter is matching a single or multiples commas. You can use `<token>.+` for match any character. Also your pattern is looking for a `-` between the `uidb64` and `token`, and this line {% url 'password_reset_confirm' uidb64=uid token=token %} is passing both parameters without the `-`. You need just to alter the url line as folow: url(r'^reset/(?P<uidb64>[0-9A-Za-z]+)/(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm', name='password_reset_confirm'),
Elements arrangement in Python Question: Every element of the array "data" have to be changed as follows: For example, 4 should be seen in names_A and data_A. The names_A for 4 is 'David'. Now 'David' should be seen in names_B and data_B. The data_B for 'David' is 30. So, the element 4 must be changed by 30; and so on. import numpy as np names_A = ['David', 'Mark', 'Brian', 'Michael'] data_A = [4,3,1,2] names_B = ['Mark', 'David', 'Michael', 'Brian'] data_B = [51,30,11,29] data = np.array([[4,4,3,3,2,2,1,1,3,3], [4,3,3,3,2,2,3,1,3,1], [4,2,3,3,2,2,4,1,4,3]]) How is the easiest and simplest way of doing it? I tried it as follows: dats = data.ravel() results = [] for d in dats: nam_A = names_A[data_A == int(d)] dat_B = data_B[names_B == nam_A] results.append(dat_B) print np.array(results).reshape(data.shape) [[51 51 51 51 51 51 51 51 51 51] [51 51 51 51 51 51 51 51 51 51] [51 51 51 51 51 51 51 51 51 51]] But, it's giving wrong results. How would you do it? Answer: Use dictionaries to create a mapping. names_A = ['David', 'Mark', 'Brian', 'Michael'] data_A = [4,3,1,2] names_B = ['Mark', 'David', 'Michael', 'Brian'] data_B = [51,30,11,29] lookup_a = dict(zip(names_A, data_A)) lookup_b = dict(zip(names_B, data_B)) mapping = {value_a: lookup_b[key_a] for key_a, value_a in lookup_a.items()} Now the keys in `mapping` will be the numbers from `data_A` with the corresponding values from `data_B`. I never worked with `numpy` but it looks like an easy task to do the replacement now. * * * Just to give an example with a simple list: data = [4, 4, 3, 3, 2, 2, 1, 1, 3, 3] data = [mapping[value] for value in data] `data` now is `[30, 30, 51, 51, 11, 11, 29, 29, 51, 51]`. * * * _Edited after installing numpy_ If you created the mapping dictionary you can do the following: data = np.array([[4, 4, 3, 3, 2, 2, 1, 1, 3, 3], [4, 3, 3, 3, 2, 2, 3, 1, 3, 1], [4, 2, 3, 3, 2, 2, 4, 1, 4, 3]]) for row in data: for index, value in enumerate(row): row[index] = mapping[value] `data` is now: [[32 30 51 51 11 11 29 29 51 51] [30 51 51 51 11 11 51 29 51 29] [30 11 51 51 11 11 30 29 30 51]] As I never worked with numpy before there might be easier (or more pythonic) solutions, but at least this does what it should do.
I can't install kivy on python Question: I want to install kivy to python. To do this I type this command: pip install -I Cython==0.21.2 It worked. But, when I type this command: pip install kivy I get this error: opengl.obj : error LNK2019: unresolved external symbol ___glewGenerateMipmap referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewGetFramebuffer AttachmentParameteriv referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewFramebufferRen derbuffer referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewFramebufferTex ture3D referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewFramebufferTex ture2D referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewFramebufferTex ture1D referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewCheckFramebuff erStatus referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewDeleteFramebuf fers referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewBindFramebuffe r referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewIsFramebuffer referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewGetRenderbuffe rParameteriv referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewRenderbufferSt orage referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewGenRenderbuffe rs referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewDeleteRenderbu ffers referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewBindRenderbuff er referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewIsRenderbuffer referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewGenFramebuffer s referenced in function _glew_dynamic_binding opengl.obj : error LNK2019: unresolved external symbol ___glewActiveTexture referenced in function ___pyx_pf_4kivy_8graphics_6opengl_glActiveTexture opengl.obj : error LNK2019: unresolved external symbol ___glewAttachShader r eferenced in function ___pyx_pf_4kivy_8graphics_6opengl_2glAttachShader opengl.obj : error LNK2019: unresolved external symbol ___glewBindBuffer ref erenced in function ___pyx_pf_4kivy_8graphics_6opengl_6glBindBuffer opengl.obj : error LNK2019: unresolved external symbol ___glewBlendColor ref erenced in function ___pyx_pf_4kivy_8graphics_6opengl_14glBlendColor opengl.obj : error LNK2019: unresolved external symbol ___glewBlendEquation referenced in function ___pyx_pf_4kivy_8graphics_6opengl_16glBlendEquation opengl.obj : error LNK2019: unresolved external symbol ___glewBlendEquationS eparate referenced in function ___pyx_pf_4kivy_8graphics_6opengl_18glBlendEquati onSeparate opengl.obj : error LNK2019: unresolved external symbol ___glewBlendFuncSepar ate referenced in function ___pyx_pf_4kivy_8graphics_6opengl_22glBlendFuncSepara te opengl.obj : error LNK2019: unresolved external symbol ___glewCompileShader referenced in function ___pyx_pf_4kivy_8graphics_6opengl_38glCompileShader opengl.obj : error LNK2019: unresolved external symbol ___glewDeleteProgram referenced in function ___pyx_pf_4kivy_8graphics_6opengl_58glDeleteProgram opengl.obj : error LNK2019: unresolved external symbol ___glewDeleteShader r eferenced in function ___pyx_pf_4kivy_8graphics_6opengl_62glDeleteShader opengl.obj : error LNK2019: unresolved external symbol ___glewDetachShader r eferenced in function ___pyx_pf_4kivy_8graphics_6opengl_70glDetachShader opengl.obj : error LNK2019: unresolved external symbol ___glewDisableVertexA ttribArray referenced in function ___pyx_pf_4kivy_8graphics_6opengl_74glDisableV ertexAttribArray opengl.obj : error LNK2019: unresolved external symbol ___glewEnableVertexAt tribArray referenced in function ___pyx_pf_4kivy_8graphics_6opengl_82glEnableVer texAttribArray opengl.obj : error LNK2019: unresolved external symbol ___glewLinkProgram re ferenced in function ___pyx_pf_4kivy_8graphics_6opengl_174glLinkProgram opengl.obj : error LNK2019: unresolved external symbol ___glewSampleCoverage referenced in function ___pyx_pf_4kivy_8graphics_6opengl_186glSampleCoverage opengl.obj : error LNK2019: unresolved external symbol ___glewStencilFuncSep arate referenced in function ___pyx_pf_4kivy_8graphics_6opengl_196glStencilFuncS eparate opengl.obj : error LNK2019: unresolved external symbol ___glewStencilMaskSep arate referenced in function ___pyx_pf_4kivy_8graphics_6opengl_200glStencilMaskS eparate opengl.obj : error LNK2019: unresolved external symbol ___glewStencilOpSepar ate referenced in function ___pyx_pf_4kivy_8graphics_6opengl_204glStencilOpSepar ate opengl.obj : error LNK2019: unresolved external symbol ___glewUniform1f refe renced in function ___pyx_pf_4kivy_8graphics_6opengl_218glUniform1f opengl.obj : error LNK2019: unresolved external symbol ___glewUniform1i refe renced in function ___pyx_pf_4kivy_8graphics_6opengl_222glUniform1i opengl.obj : error LNK2019: unresolved external symbol ___glewUniform2f refe renced in function ___pyx_pf_4kivy_8graphics_6opengl_226glUniform2f opengl.obj : error LNK2019: unresolved external symbol ___glewUniform2i refe renced in function ___pyx_pf_4kivy_8graphics_6opengl_230glUniform2i opengl.obj : error LNK2019: unresolved external symbol ___glewUniform3f refe renced in function ___pyx_pf_4kivy_8graphics_6opengl_234glUniform3f opengl.obj : error LNK2019: unresolved external symbol ___glewUniform3i refe renced in function ___pyx_pf_4kivy_8graphics_6opengl_238glUniform3i opengl.obj : error LNK2019: unresolved external symbol ___glewUniform4f refe renced in function ___pyx_pf_4kivy_8graphics_6opengl_242glUniform4f opengl.obj : error LNK2019: unresolved external symbol ___glewUniform4i refe renced in function ___pyx_pf_4kivy_8graphics_6opengl_246glUniform4i opengl.obj : error LNK2019: unresolved external symbol ___glewUseProgram ref erenced in function ___pyx_pf_4kivy_8graphics_6opengl_256glUseProgram opengl.obj : error LNK2019: unresolved external symbol ___glewValidateProgra m referenced in function ___pyx_pf_4kivy_8graphics_6opengl_258glValidateProgram opengl.obj : error LNK2019: unresolved external symbol ___glewVertexAttrib1f referenced in function ___pyx_pf_4kivy_8graphics_6opengl_260glVertexAttrib1f opengl.obj : error LNK2019: unresolved external symbol ___glewVertexAttrib2f referenced in function ___pyx_pf_4kivy_8graphics_6opengl_264glVertexAttrib2f opengl.obj : error LNK2019: unresolved external symbol ___glewVertexAttrib3f referenced in function ___pyx_pf_4kivy_8graphics_6opengl_268glVertexAttrib3f opengl.obj : error LNK2019: unresolved external symbol ___glewVertexAttrib4f referenced in function ___pyx_pf_4kivy_8graphics_6opengl_272glVertexAttrib4f opengl.obj : error LNK2019: unresolved external symbol ___glewCreateProgram referenced in function ___pyx_pf_4kivy_8graphics_6opengl_48glCreateProgram opengl.obj : error LNK2019: unresolved external symbol ___glewCreateShader r eferenced in function ___pyx_pf_4kivy_8graphics_6opengl_50glCreateShader opengl.obj : error LNK2019: unresolved external symbol ___glewGenBuffers ref erenced in function ___pyx_pf_4kivy_8graphics_6opengl_94glGenBuffers opengl.obj : error LNK2019: unresolved external symbol ___glewGetActiveAttri b referenced in function ___pyx_pf_4kivy_8graphics_6opengl_104glGetActiveAttrib opengl.obj : error LNK2019: unresolved external symbol ___glewGetActiveUnifo rm referenced in function ___pyx_pf_4kivy_8graphics_6opengl_106glGetActiveUnifor m opengl.obj : error LNK2019: unresolved external symbol ___glewGetAttachedSha ders referenced in function ___pyx_pf_4kivy_8graphics_6opengl_108glGetAttachedSh aders opengl.obj : error LNK2019: unresolved external symbol ___glewGetProgramiv r eferenced in function ___pyx_pf_4kivy_8graphics_6opengl_124glGetProgramiv opengl.obj : error LNK2019: unresolved external symbol ___glewGetProgramInfo Log referenced in function ___pyx_pf_4kivy_8graphics_6opengl_126glGetProgramInfo Log opengl.obj : error LNK2019: unresolved external symbol ___glewGetShaderiv re ferenced in function ___pyx_pf_4kivy_8graphics_6opengl_130glGetShaderiv opengl.obj : error LNK2019: unresolved external symbol ___glewGetShaderInfoL og referenced in function ___pyx_pf_4kivy_8graphics_6opengl_132glGetShaderInfoLo g opengl.obj : error LNK2019: unresolved external symbol ___glewGetShaderSourc e referenced in function ___pyx_pf_4kivy_8graphics_6opengl_136glGetShaderSource opengl.obj : error LNK2019: unresolved external symbol ___glewGetUniformfv r eferenced in function ___pyx_pf_4kivy_8graphics_6opengl_144glGetUniformfv opengl.obj : error LNK2019: unresolved external symbol ___glewGetUniformiv r eferenced in function ___pyx_pf_4kivy_8graphics_6opengl_146glGetUniformiv opengl.obj : error LNK2019: unresolved external symbol ___glewGetVertexAttri bfv referenced in function ___pyx_pf_4kivy_8graphics_6opengl_150glGetVertexAttri bfv opengl.obj : error LNK2019: unresolved external symbol ___glewGetVertexAttri biv referenced in function ___pyx_pf_4kivy_8graphics_6opengl_152glGetVertexAttri biv opengl.obj : error LNK2019: unresolved external symbol ___glewIsBuffer refer enced in function ___pyx_pf_4kivy_8graphics_6opengl_158glIsBuffer opengl.obj : error LNK2019: unresolved external symbol ___glewIsProgram refe renced in function ___pyx_pf_4kivy_8graphics_6opengl_164glIsProgram opengl.obj : error LNK2019: unresolved external symbol ___glewIsShader refer enced in function ___pyx_pf_4kivy_8graphics_6opengl_168glIsShader opengl.obj : error LNK2019: unresolved external symbol ___glewBindAttribLoca tion referenced in function ___pyx_pf_4kivy_8graphics_6opengl_4glBindAttribLocat ion opengl.obj : error LNK2019: unresolved external symbol ___glewBufferData ref erenced in function ___pyx_pf_4kivy_8graphics_6opengl_24glBufferData opengl.obj : error LNK2019: unresolved external symbol ___glewBufferSubData referenced in function ___pyx_pf_4kivy_8graphics_6opengl_26glBufferSubData opengl.obj : error LNK2019: unresolved external symbol ___glewCompressedTexI mage2D referenced in function ___pyx_pf_4kivy_8graphics_6opengl_40glCompressedTe xImage2D opengl.obj : error LNK2019: unresolved external symbol ___glewCompressedTexS ubImage2D referenced in function ___pyx_pf_4kivy_8graphics_6opengl_42glCompresse dTexSubImage2D opengl.obj : error LNK2019: unresolved external symbol ___glewDeleteBuffers referenced in function ___pyx_pf_4kivy_8graphics_6opengl_54glDeleteBuffers opengl.obj : error LNK2019: unresolved external symbol ___glewGetAttribLocat ion referenced in function ___pyx_pf_4kivy_8graphics_6opengl_110glGetAttribLocat ion opengl.obj : error LNK2019: unresolved external symbol ___glewGetBufferParam eteriv referenced in function ___pyx_pf_4kivy_8graphics_6opengl_114glGetBufferPa rameteriv opengl.obj : error LNK2019: unresolved external symbol ___glewGetUniformLoca tion referenced in function ___pyx_pf_4kivy_8graphics_6opengl_148glGetUniformLoc ation opengl.obj : error LNK2019: unresolved external symbol ___glewShaderSource r eferenced in function ___pyx_pf_4kivy_8graphics_6opengl_192glShaderSource opengl.obj : error LNK2019: unresolved external symbol ___glewUniformMatrix4 fv referenced in function ___pyx_pf_4kivy_8graphics_6opengl_254glUniformMatrix4f v opengl.obj : error LNK2019: unresolved external symbol ___glewVertexAttribPo inter referenced in function ___pyx_pf_4kivy_8graphics_6opengl_276glVertexAttrib Pointer build\lib.win32-2.7\kivy\graphics\opengl.pyd : fatal error LNK1120: 79 unres olved externals error: command '"C:\Users\ESES\AppData\Local\Programs\Common\Microsoft\Visu al C++ for Python\9.0\VC\Bin\link.exe"' failed with exit status 1120 ---------------------------------------- Command "C:\Python27\python.exe -c "import setuptools, tokenize;__file__='c:\\us ers\\eses\\appdata\\local\\temp\\pip-build-1jegbu\\kivy\\setup.py';exec(compile( getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__ , 'exec'))" install --record c:\users\eses\appdata\local\temp\pip-zzv3ab-record\ install-record.txt --single-version-externally-managed --compile" failed with er ror code 1 in c:\users\eses\appdata\local\temp\pip-build-1jegbu\kivy I have pygame module. And, all of the installation with pip command, I get this error: error: invalid command 'bdist_wheel' ---------------------------------------- Failed building wheel for kivy [or module_name]* How can I solve them ? Answer: You can install a prebuilt binary from the gohlke pythonlibs, just choose the appropriate version from [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#kivy).
Declaration of FigureCanvasTkAgg causes memory leak Question: I'm having difficulty figuring out just why the declaration of FigureCanvasTkAgg causes a memory leak, I have the following lines in my class `__init__` method: # pndwinBottom is a paned window of the main screen self.__drawplotFrame = Frame(pndwinBottom, width=WIDTH, height=HEIGHT) # the frame on which we will add our canvas for drawing etc. self.__fig = plt.figure(figsize=(16,11)) self.__drawplotCanvas = FigureCanvasTkAgg(self.__fig, master=self.__drawplotFrame) the problem is that upon running my application , and exiting, python32.exe remains in my process window and will clog up my computer. Commenting out these three lines however will allow my application to exit and the process will correctly terminate. What could these lines be doing to my application that prevents the process from ending after the application is finished? Thanks _edit_ * * * The memory leak seems to be caused by only the line `self.__fig = plt.figure(figsize=(16, 11))` . Do I need to do some sort of deconstruction with plt before exiting? Answer: I'm gonna guess this is caused by the pyplot figure not being destroyed when the Tkinter window is closed. Like in the [embedding in tk example](http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html) try using `Figure`: from matplotlib.figure import Figure self.__fig = Figure(figsize=(16,11)) example use: import Tkinter as tk import matplotlib matplotlib.use('TkAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg class App(): def __init__(self, parent): self.__drawplotFrame = tk.Frame(parent, width=500, height=500) self.__drawplotFrame.pack() self.__fig = Figure(figsize=(16,11)) self.__p = self.__fig.add_subplot(1,1,1) self.__p.plot(range(10), range(10)) self.__drawplotCanvas = FigureCanvasTkAgg(self.__fig, master=self.__drawplotFrame) self.__drawplotCanvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) root = tk.Tk() App(root) root.mainloop()
local variable referenced before assignment in strange condition Question: I have some code that takes input from an open source database, then returns a report based on some of the tables. I could have sworn that this code was working correctly yesterday, but when I boot it up today: Traceback (most recent call last): File "C:\Users\whicaso1\Downloads\eclipse-standard-luna-R-win32-x86_64\eclipse\plugins\org.python.pydev_3.6.0.201406232321\pysrc\pydevd.py", line 1845, in debugger.run(setup['file'], None, None) File "C:\Users\whicaso1\Downloads\eclipse-standard-luna-R-win32-x86_64\eclipse\plugins\org.python.pydev_3.6.0.201406232321\pysrc\pydevd.py", line 1373, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Users\whicaso1\workspace\Status based chilli list\CreateChiliLog.py", line 29, in CreateChiliLog() File "C:\Users\whicaso1\workspace\Status based chilli list\CreateChiliLog.py", line 15, in CreateChiliLog for chili in chili_database.getChilis(status): File "C:\Users\whicaso1\workspace\Status based chilli list\ChiliFunctions.py", line 99, in getChilis connection_chili.rollback() UnboundLocalError: local variable 'connection_chili' referenced before assignment Now, I'm not a moron, I checked to see if I had, in fact, referenced the variable "connection_chili" before assignment, but it looks like the error occurred _while_ assigning. (here is the code snippet that failed, the error is on the line where the connection_chili variable is being assigned to a mysqldb database object.) def getChilis(self, status): try: connection_chili = MySQLdb.connect(self.host_, self.user_, self.password_, self.database_) cursor = connection_chili.cursor() query = "SELECT id FROM issues WHERE status_id = %i" % status cursor.execute(query) connection_chili.commit() chilis = cursor.fetchall() cursor.close() return chilis except Exception, e: connection_chili.rollback() print "ERROR: " + str(e) ` is there some issue with my code, or is there some weird thing going on with my python compiler? Answer: Just checked my code against python in cmd, and it ran fine. So I'm guessing its probably some weird issue with eclipse. In any case, its no longer a programming question, so I'm going to close it
Decorated class looses acces to its attributes Question: I implemented a decorator that worked like a charm until I added attributes to the decorated class. When I instantiate the class, it cannot acces the calss attributes. Take the following minimal working example : from module import specialfunction class NumericalMathFunctionDecorator: def __init__(self, enableCache=True): self.enableCache = enableCache def __call__(self, wrapper): def numericalmathfunction(*args, **kwargs): func = specialfunction(wrapper(*args, **kwargs)) """ Do some setup to func with decorator arguments (e.g. enableCache) """ return numericalmathfunction @NumericalMathFunctionDecorator(enableCache=True) class Wrapper: places = ['home', 'office'] configs = { 'home': { 'attr1': 'path/at/home', 'attr2': 'jhdlt' }, 'office': { 'attr1': 'path/at/office', 'attr2': 'sfgqs' } } def __init__(self, where='home'): # Look for setup configuration on 'Wrapper.configs[where]'. assert where in Wrapper.places, "Only valid places are {}".format(Wrapper.places) self.__dict__.update(Wrapper.configs[where]) def __call__(self, X): """Do stuff with X and return the result """ return X ** 2 model = Wrapper() When I instantiate the Wrapper class (#1), I get the following error : --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-5-a99bd3d544a3> in <module>() 15 assert where in Wrapper.places, "Only valid places are {}".format(Wrapper.places) 16 ---> 17 model = Wrapper() <ipython-input-5-a99bd3d544a3> in numericalmathfunction(*args, **kwargs) 5 def __call__(self, wrapper): 6 def numericalmathfunction(*args, **kwargs): ----> 7 func = wrapper(*args, **kwargs) 8 return numericalmathfunction 9 <ipython-input-5-a99bd3d544a3> in __init__(self, where) 13 def __init__(self, where='home'): 14 # Look for setup configuration on 'Wrapper.configs[where]'. ---> 15 assert where in Wrapper.places, "Only valid places are {}".format(Wrapper.places) 16 17 model = Wrapper() AttributeError: 'function' object has no attribute 'places' I guess that with the decorator, Wrapper becomes a function that looses acces to its attributes... Any ideas of how I can solve this ? Maybe there is a workaround Answer: You replaced `Wrapper` (which was a class) with the `numericalmathfunction` function object. That object doesn't have any of the class attributes, no. In essence, the decorator does this: class Wrapper: # ... Wrapper = NumericalMathFunctionDecorator(enableCache=True)(Wrapper) so whatever the `NumericalMathFunctionDecorator.__call__` method returns has now replaced the class; all references to `Wrapper` now reference that return value. And when you use the name `Wrapper` in the `__init__` method, you are referencing that global, not the original class. You can still access the current class with `type(self)`, or just reference those attributes via `self` (where the name lookup falls through to the class): def __init__(self, where='home'): # Look for setup configuration on 'Wrapper.configs[where]'. assert where in self.places, "Only valid places are {}".format(self.places) self.__dict__.update(self.configs[where]) or def __init__(self, where='home'): # Look for setup configuration on 'Wrapper.configs[where]'. cls = type(self) assert where in cls.places, "Only valid places are {}".format(cls.places) self.__dict__.update(cls.configs[where]) In both cases you can end up with referencing an attribute on a subclass if you ever did subclass `Wrapper` (which you cannot do in this case anyway as you would have to fish the class out of the decorator closure). Alternatively, you could store the original class as an attribute on the returned function: def __call__(self, wrapper): def numericalmathfunction(*args, **kwargs): func = specialfunction(wrapper(*args, **kwargs)) """ Do some setup to func with decorator arguments (e.g. enableCache) """ numericalmathfunction.__wrapped__ = wrapper return numericalmathfunction then use that reference in your `__init__`: def __init__(self, where='home'): # Look for setup configuration on 'Wrapper.configs[where]'. cls = Wrapper while hasattr(cls, '__wrapped__'): # remove any decorator layers to get to the original cls = cls.__wrapped__ assert where in cls.places, "Only valid places are {}".format(cls.places) self.__dict__.update(cls.configs[where])
TypeError: encoding or errors without a string argument Question: I'm trying to write a list of datas to a csv file. Since the it's a list of byte strings, I used the below code with open(r"E:\Avinash\Python\extracting-drug-data\out.csv", "wb") as w: writer = csv.writer(w) writer.writerows(bytes(datas, 'UTF-8')) But it results in the following error: > TypeError: encoding or errors without a string argument `datas` is a list of byte strings. print(datas) yields [b'DB08873', b' MOLSDFPDBSMILESInChIView Structure \xc3\x97Structure for DB08873 (Boceprevir) Close', b'394730-60-0', b'LHHCSNFAOIFYRV-DOVBMPENSA-N', b'Organic acids and derivatives ', b'Food increases exposure of boceprevir by up to 65% relative to fasting state. However, type of food and time of meal does not affect bioavailability of boceprevir and thus can be taken without regards to food. \r\nTmax = 2 hours;\r\nTime to steady state, three times a day dosing = 1 day;\r\nCmax] I want the above list to be printed as first row in a csv file with the decoding of unicode chars. That is, `\xc3\x97` should be converted to it's corresponding character. Answer: It seems your `datas` _is_ already in bytes format, so to turn it into UTF-8 strings, you have to use `str`, not `bytes`! Also, you have to convert each element from `datas` individually, not the entire list at once. Finally, if you want to add `datas` as one row to `out.csv`, you have to use `writerow`, whereas `writerows` would write _all_ the rows at once, and accordinly would expect a list of lists. Depending on your OS, you might also have to specify the `encoding` when opening the file. Otherwise it will use the OS' default encoding, which might be something entirely different. This _seems_ to do what you want. The result is a CSV file with one row1 of data in UTF-8 format, and the `\xc3\x97` is decoded to `×`. import csv with open(r"out.csv", "w", encoding='UTF-8') as w: writer = csv.writer(w) writer.writerow([str(d, 'UTF-8') for d in datas]) * * * 1) Note that the last item in `datas` contains some line breaks, and thus will be split onto several lines. This is probably not what you want. Or is this a glitch in your `datas` list?
Python - pull things from the bottom of the code Question: I have this code: import fcntl, socket, struct import base64 import time, datetime import netifaces from Tkinter import * def getHwAddr(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15])) return '-'.join(['%02x' % ord(char) for char in info[18:24]]) tvip = "10.0.1.2" tvappstring = "UE55C8000" myip = netifaces.ifaddresses(netifaces.gateways()['default'][netifaces.AF_INET][1])[netifaces.AF_INET][0]['addr'] mymac = getHwAddr(netifaces.gateways()['default'][netifaces.AF_INET][1]) appstring = "Pepin's Samsung TV Remote" remotename = "Pepin's Samsung TV Remote" def sendKey(skey, dataSock, appstring): messagepart3 = chr(0x00) + chr(0x00) + chr(0x00) + chr(len( base64.b64encode(skey))) + chr(0x00) + base64.b64encode(skey); part3 = chr(0x00) + chr(len(appstring)) + chr(0x00) \ + appstring + chr(len(messagepart3)) + chr(0x00) + messagepart3 dataSock.send(part3); def sendText(stext, dataSock, appstring): messagepart3 = chr(0x00) + chr(0x00) + chr(0x00) + chr(len( base64.b64encode(stext))) + chr(0x00) + base64.b64encode(stext); part3 = chr(0x00) + chr(len(appstring)) + chr(0x00) \ + appstring + chr(len(messagepart3)) + chr(0x00) + messagepart3 dataSock.send(part3); root = Tk() root.title("Pepin's Samsung TV Remote") root.geometry("391x595") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((tvip, 55000)) ipencoded = base64.b64encode(myip) macencoded = base64.b64encode(mymac) messagepart1 = chr(0x64) + chr(0x00) + chr(len(ipencoded)) \ + chr(0x00) + ipencoded + chr(len(macencoded)) + chr(0x00) \ + macencoded + chr(len(base64.b64encode(remotename))) + chr(0x00) \ + base64.b64encode(remotename) part1 = chr(0x00) + chr(len(appstring)) + chr(0x00) + appstring \ + chr(len(messagepart1)) + chr(0x00) + messagepart1 sock.send(part1) messagepart2 = chr(0xc8) + chr(0x00) part2 = chr(0x00) + chr(len(appstring)) + chr(0x00) + appstring \ + chr(len(messagepart2)) + chr(0x00) + messagepart2 sock.send(part2); class Application(): """Pepin's Samsung TV Remote""" def __init__(self, master): self.master = master self.create_widgets() def create_widgets(self): btn_key_poweroff = Button(self.master, text = "Power", bg="red", width=4, height=2, command = lambda: sendKey("KEY_POWEROFF", sock, tvappstring)) entry_send_custom = Entry(self.master, width=22) entry_send_custom.grid(row=1, column=3, columnspan=4, padx=(15,0), ipady=8) btn_send_custom = Button(self.master, text = "SEND CUSTOM KEY", width=19, height=2, command = lambda: sendText(entry_send_custom.get(), sock, tvappstring)) btn_send_custom.grid(row=2, column=3, columnspan=5, padx=(15,0)) label_tvip = Label(self.master, text="TV IP:") label_tvip.grid(row=3, column=3, columnspan=1, padx=(15,0), ipady=8) self.entry_tvip = Entry(self.master, width=16) self.entry_tvip.grid(row=3, column=4, columnspan=3, ipady=8) label_tvappstring = Label(self.master, text="TV MODEL (Tv App String)") label_tvappstring.grid(row=4, column=3, columnspan=4, padx=(15,0), ipady=8, sticky=W) self.entry_tvappstring = Entry(self.master, width=22) self.entry_tvappstring.grid(row=5, column=3, columnspan=4, padx=(15,0), ipady=8) self.entry_tvappstring.insert(0, "UE55C8000") btn_connect = Button(self.master, text = "CONNECT TO TV", width=19, height=2, command = lambda: self.Connection()) btn_connect.grid(row=6, column=3, columnspan=5, padx=(15,0)) app = Application(root) root.mainloop() sock.close() But I want to use `entry_tvip.get()` in top of the code. Is there simple way to do it? And start this section of the code: sock.connect((tvip, 55000)) ipencoded = base64.b64encode(myip) macencoded = base64.b64encode(mymac) messagepart1 = chr(0x64) + chr(0x00) + chr(len(ipencoded)) \ + chr(0x00) + ipencoded + chr(len(macencoded)) + chr(0x00) \ + macencoded + chr(len(base64.b64encode(remotename))) + chr(0x00) \ + base64.b64encode(remotename) part1 = chr(0x00) + chr(len(appstring)) + chr(0x00) + appstring \ + chr(len(messagepart1)) + chr(0x00) + messagepart1 sock.send(part1) messagepart2 = chr(0xc8) + chr(0x00) part2 = chr(0x00) + chr(len(appstring)) + chr(0x00) + appstring \ + chr(len(messagepart2)) + chr(0x00) + messagepart2 sock.send(part2); After pushing button. Is there way to do it too? Thanks! I'm new to Python Answer: Since `entry_tvip` is a method of the `Application` class and `app` is an instance of this class, you can call `app.entry_tvip.get()` You will not be able to do this anywhere before the `app` is created, so I would rethink your approach.
convert kenneth French data to daily datetime format in python Question: I want to integrate date from Kenneth French's website with the following code, that works fine for monthly data. But since I need now daily data I need to know what I have to put for the variable XYZ (in the last row of code) in order to make it work: import pandas.io.data import pandas as pd from datetime import datetime, date io = pandas.io.data.DataReader("F-F_Research_Data_Factors_daily", "famafrench") ff = io[0] # Bestimmung des Dictionary Teils aus der FF Zip Datei ff.columns = ['Mkt_rf', 'SMB', 'HML', 'rf'] ff.index = [datetime(d/100, d%100, XYZ) for d in ff.index] This is how the index looks like: Int64Index([19260701, 19260702, 19260706, 19260707, 19260708, 19260709, 19260710, 19260712, 19260713, 19260714, 19260715, 19260716, 19260717, 19260719, 19260720, 19260721, 19260722, 19260723, 19260724, 19260726, 19260727, 19260728, 19260729, 19260730, 19260731, 19260802, 19260803, 19260804, 19260805, 19260806, 19260807, 19260809, 19260810, 19260811, 19260812, 19260813, 19260814, 19260816, 19260817, 19260818, 19260819, 19260820, 19260821, 19260823, 19260824, 19260825, 19260826, 19260827, 19260828, 19260830, 19260831, 19260901, 19260902, 19260903, 19260907, 19260908, 19260909, 19260910, 19260911, 19260913, 19260914, 19260915, 19260916, 19260917, 19260918, 19260920, 19260921, 19260922, 19260923, 19260924, 19260925, 19260927, 19260928, 19260929, 19260930, 19261001, 19261002, 19261004, 19261005, 19261006, 19261007, 19261008, 19261009, 19261011, 19261013, 19261014, 19261015, 19261016, 19261018, 19261019, 19261020, 19261021, 19261022, 19261023, 19261025, 19261026, 19261027, 19261028, 19261029, 19261030, ...], dtype='int64') And this is how the dataframe looks like: Mkt_rf SMB HML rf 19260701 0.10 -0.24 -0.28 0.009 # the integer 19260701 needs to get converted to a datetime copartible format such as 1926/07/01 ... ... ... ... ... 20150430 -1.11 -1.04 0.73 0.000 [23467 rows x 4 columns] I use pandas 0.16.1 Any ideas? Answer: To convert your index to a DatetimeIndex, you can use `to_datetime`: ff.index = pd.to_datetime(ff.index, format='%Y%m%d') When having your dates as integers, the above works by specifying `format='%Y%m%d'` and `to_datetime` will see the ints as a string of that format. A small example: In [2]: pd.to_datetime([19260701, 19260702], format='%Y%m%d') Out[2]: DatetimeIndex(['1926-07-01', '1926-07-02'], dtype='datetime64[ns]', freq=None, tz=None)
How to print the first line from a traceback stack Question: Suppose I am given the following traceback: Traceback (most recent call last): File "<wingdb_compile>", line 3, in <module> File "C:\Python34\lib\ftplib.py", line 419, in login resp = self.sendcmd('PASS ' + passwd) File "C:\Python34\lib\ftplib.py", line 272, in sendcmd return self.getresp() File "C:\Python34\lib\ftplib.py", line 245, in getresp raise error_perm(resp) ftplib.error_perm: 530 Login incorrect. I have managed to extract the Error details but what has stumped me is how would I extract the line: File "<wingdb_compile>", line 3, in <module> I was looking at methods in the trace back package but wondered if any one had experience with that here Answer: The function [`traceback.format_exc`](https://docs.python.org/2/library/traceback.html#traceback.format_exc) is built primarily for this > This is like `print_exc(limit)` but **_returns a string_** instead of > printing to a file. >>> import traceback >>> try: ... x = 2/0 ... except: ... error = traceback.format_exc() ... >>> error 'Traceback (most recent call last):\n File "<stdin>", line 2, in <module>\nZeroDivisionError: division by zero\n' >>> linesoferror = error.split('\n') >>> linesoferror ['Traceback (most recent call last):', ' File "<stdin>", line 2, in <module>', 'ZeroDivisionError: division by zero', ''] So now you wanted the first line then you can simply use >>> linesoferror[1] ' File "<stdin>", line 2, in <module>' Voila! You have what you want > **ALERT** \- Valid for Python 2.4.1 and above
How to get pixel coordinates from Feature Matching in OpenCV Python Question: I need to get the list of the `x` and `y` coordinates of the pixels that the feature matcher selects in the code provided. I'm using Python and OpenCV. Can anyone help me? img1=cv2.imread('DSC_0216.jpg',0) img2=cv2.imread('DSC_0217.jpg',0) orb=cv2.ORB(nfeatures=100000) kp1,des1=orb.detectAndCompute(img1,None) kp2,des2=orb.detectAndCompute(img2,None) img1kp=cv2.drawKeypoints(img1,kp1,color=(0,255,0),flags=0) img2kp=cv2.drawKeypoints(img2,kp2,color=(0,255,0),flags=0) cv2.imwrite('m_img1.jpg',img1kp) cv2.imwrite('m_img2.jpg',img2kp) bf=cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) matches=bf.match(des1,des2) matches=sorted(matches, key= lambda x:x.distance) Answer: `matches` returns a list of structures where each structure contains several fields... among them are two important fields: * `queryIdx` \- The index of the feature into `kp1` that matches * `trainIdx` \- The index of the feature into `kp2` that matches You'd use these to index into `kp1` and `kp2` and obtain the `pt` field to obtain the `(x,y)` coordinates of the matches. All you have to do is iterate through each structure in `matches`, append to a list of coordinates for both `kp1` and `kp2` and you're done. Something like this: # Initialize lists list_kp1 = [] list_kp2 = [] # For each match... for mat in matches: # Get the matching keypoints for each of the images img1_idx = mat.queryIdx img2_idx = mat.trainIdx # x - columns # y - rows # Get the coordinates (x1,y1) = kp1[img1_idx].pt (x2,y2) = kp2[img2_idx].pt # Append to each list list_kp1.append((x1, y1)) list_kp2.append((x2, y2)) Note that I could have just done `list_kp1.append(kp1[img1_idx].pt)`, as well as the same for `list_kp2`, but I wanted to make very clear on how to interpret the spatial coordinates. `list_kp1` will contain the spatial coordinates of a feature point that matched with the corresponding position in `list_kp2`. In other words, element `i` of `list_kp1` contains the spatial coordinates of the feature point from `img1` that matched with the corresponding feature point from `img2` in `list_kp2` whose spatial coordinates are in element `i`. * * * As a minor sidenote, I used this concept when I wrote a workaround for [`drawMatches`](http://docs.opencv.org/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html#drawmatches) because for OpenCV 2.4.x, the Python wrapper to the C++ function does not exist, so I made use of the above concept in locating the spatial coordinates of the matching features between the two images to write my own implementation of it. Check it out if you like! [module' object has no attribute 'drawMatches' opencv python](http://stackoverflow.com/questions/20259025/module-object-has-no- attribute-drawmatches-opencv-python/26227854#26227854)
Python: How to check the value of a non-existent list element without getting IndexError? Question: I'm using Python's one-line conditional thus: x = 'foo' if myList[2] is not None else 'bar' to assign to `x` the value of an item at a certain index of a list - **if and only if it exists** \- and a different value if it doesn't. Here's my challenge: `myList` can have up to three elements, but won't always have three. So if the index doesn't exist (i.e. if the index in question is 1+ greater than the size of the list), I'll obviously get an `IndexError list out of range` before the inline conditional can assign the variable: In [145]: myList = [1,2] In [146]: x = 'foo' if myList[2] is not None else 'bar' --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-146-29708b8c471e> in <module>() ----> 1 x = 'foo' if myList[2] is not None else 'bar' IndexError: list index out of range Checking the length of the list beforehand is not really an option, since I can't know which value I'm interested in is missing (i.e. `myList` can be missing any or all of three possible values. Knowing that it contains only one, or two, or three elements does not help). **Update:** the reason why I can't assign based on the length of the list is as follows. The list can have a maximum size of 3, and **order is important**. The values populated will be the result of three separate calls to an API. If all calls to the API succeed, I get a full list, and everything is fine. Yet if only two return a value, the list only contains two items, yet **I cannot know which API call has led to the missing item** , so assigning variables is pot luck. So, long story short: How can I check for a non-existent list item at a certain index, while getting to keep Python's one-line conditional? Answer: Just test if there are enough elements: x = 'foo' if len(myList) > 2 and myList[2] is not None else 'bar' It doesn't matter if the first 2 elements are missing or if you have more than 3 elements. What matters is that the list is long enough to have a 3rd element in the first place.
How to install scipy misc package Question: I have installed (actually reinstalled) scipy: 10_x86_64.whl (19.8MB): 19.8MB downloaded Installing collected packages: scipy Successfully installed scipy But the misc subpackage is apparently not included? 16:03:28/shared $ipython In [1]: from scipy.misc import imread --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-1-f9d3d927b58f> in <module>() ----> 1 from scipy.misc import imread ImportError: cannot import name imread What is the way to install the scipy.misc package? Answer: I think you need to install PIL as well. From [the scipy.misc docs:](http://docs.scipy.org/doc/scipy/reference/misc.html) > Note that the Python Imaging Library (PIL) is not a dependency of SciPy and > therefore the pilutil module is not available on systems that don’t have PIL > installed.
How can I get the current time in ISO formatted string with the 'Z' as time designator instead of '+00:00'"? Question: On Python 3.x `datetime.utcnow().isoformat()` gives no timezone designator and `datetime.now(timezone.utc).isoformat` gives the `+00:00`. Is there any way to force to use the `Z` (zulu timezone)? Answer: The ~~naive~~ straighforward way is from datetime import datetime, timezone datetime.utcnow().isoformat()+'Z' # '2015-06-09T07:17:55.719302Z' `datetime.utcnow()` returns a naive `datetime` on UTC , `isoformat` won't add any timezone because there is none in the naive datetime, and then we add manually the `'Z'` because we know that it's actually in the UTC / Zulu timezone or if you happen to have a timezone aware `datetime` on UTC already you can just drop the timezone (make a copy of the `datetime` first) and the do the `.isoformat()+'Z'`. from datetime import datetime, timezone datetime.now(timezone.utc).replace(tzinfo=None).isoformat()+'Z' # '2015-06-09T07:17:55.719302Z' If the timezone aware `datetime` is not on UTC then you need to bring it to the UTC timezone first. from datetime import datetime,timezone from dateutil.tz import tzutc datetime.now(tzoffset("BRST", -10800)).astimezone(tzutc()).replace(tzinfo=None).isoformat()+'Z' # '2015-06-09T08:14:02.861058Z'
Matplotlib Crash When Figure 1 not Closed Last Question: I am plotting mutliple figures using Matplotlib using Python 3.4. When the multiple figures are open and I close the windows closing the first figure last (ie once all other figures are closed) python does not crash. If, however, I close the first figure that was plotted first and then close the rest Python crashes. It seems as though you need to close the windows in such an order that the first window that was opened must be closed last. Has anyone else experienced and is there a solution? Here is a trivial example code that can be used to verify: import matplotlib.pyplot as plt plt.figure(1) # the first figure plt.plot([1,2,3]) plt.figure(2) # a second figure plt.plot([4,5,6]) plt.show() Answer: The way I have managed to solve this issue has been to use Qt4 as the matplotlib backend. Simply add the following two lines of code after importing matplotlib. import matplotlib as mpl mpl.rcParams['backend'] = "qt4agg" mpl.rcParams['backend.qt4'] = "PySide" This is what I do on Python 3 and have no plot closing errors
How do I fix this sorting error? Question: I currently have the code below but for some reason it only sorts using the first number from the array so for example if the number was 1000 and it was compared to a 50 the 50 would be greater then the 1000. How do i fix this? #!/usr/local/bin/python3.4 import operator import pygame, sys from pygame.locals import * import random placement = [1, 2, 3, 4, 5] data = [ {"score": "1000", "grade": "E", "music": "song5", "maxcombo": "1", "perfect": "20", "great": "1", "good": "20", "miss": "1"}, {"score": "200", "grade": "D", "music": "song4", "maxcombo": "2", "perfect": "20", "great": "2", "good": "20", "miss": "2"}, {"score": "500", "grade": "C", "music": "song3", "maxcombo": "3", "perfect": "20", "great": "3", "good": "20", "miss": "3"}, {"score": "400", "grade": "B", "music": "song2", "maxcombo": "4", "perfect": "20", "great": "4", "good": "20", "miss": "4"}, {"score": "300", "grade": "A", "music": "song1", "maxcombo": "5", "perfect": "20", "great": "5", "good": "20", "miss": "5"}, ] print (sorted(data, key=operator.itemgetter("score"), reverse=True)) Answer: "1000" isn't a number. It's a string whose characters happen to be digits. If you want to sort numerically, represent your data with numbers. data = [ {"score": 1000, "grade": "E", "music": "song5", "maxcombo": 1, "perfect": 20, "great": 1, "good": 20, "miss": 1}, #... etc Or, if you have to keep them as strings for some reason, convert to integer in the key function. print (sorted(data, key=lambda row: int(row["score"]), reverse=True))
What Can I be Researching to speed this python scripted mysql-query up? Question: so I spent a long time on the site yesterday to write this entire script in python (which I had never before used). I was pleased with the results (it worked on my tiny test-data set of 10,000 entries), but now that I'm using production data (many million) it is incredibly slow. Here's the code: #!/usr/bin/env python import sys import MySQLdb import argparse parser = argparse.ArgumentParser(description="This is used to actually generate matched lists. outputs those that matched") parser.add_argument("Database", help="The name of the database you want to run matching against") args = parser.parse_args() tablename = str(sys.argv[1]) mydb = MySQLdb.connect(host='localhost', user='root', passwd='[REDACTED]', db='Data') cursor = mydb.cursor() sql = "SELECT name FROM table1 WHERE md5 IN (select md5 from %s)" %tablename cursor.execute(sql) data = cursor.fetchall() for row in data : print row[0] #close the connection to the database. mydb.commit() cursor.close() to explain how my tables look: table1 | name | md5 table2 | md5 I'm sure there's some optimization I could do on the server itself to make mysql faster, but my suspicion is that there's some ways I could have made this faster in the code itself. Any suggestions on where to continue researching this would be appreciated. Cheers! Answer: Do something like this: SELECT t1.name FROM table1 t1 INNER JOIN table2 t2 ON t2.md5 = t1.md5 And you should also **index the md5 columns** on both tables! The _in_ operator acts much like a _left outer join_ , so you are giving the server an enormous amount of data to process when you only want the names of the md5 columns that match!
Swap a character with its next character in paragraph Question: **I have to swap a specific character appearing in paragraph to its next character.** let suppose that my paragraph text is: **My name is andrew. I am very addicted to python and attains very high knowledge about programming.** Now, my task is to find particular character in paragraph and swap it with the character next to it. Like, I want to swap every character 'a' with its the character next to it. After process my paragraph should look like this: **My nmae is nadrew. I ma very dadicted to python nad tatians very high knowledge baout progrmaming.** I would be very thankful if anybody define function for this in python Answer: This will do it: >>> import re >>>>regex = re.compile(r'(a)(\w)') >>>>text = 'My name is andrew. I am very addicted to python and attains very high knowledge about programming.' >>> regex.sub(lambda(m) : m.group(2) + m.group(1), text) 'My nmae is nadrew. I ma very dadicted to python nad tatians very high knowledge baout progrmaming.' Explanation: (a)(\w) Matches a, and put it on group 1, then matches another word character put in group 2. Lambda expression for replacement switch these two groups. If you want to match everything but spaces use : (a)(\S)
Best practice for using common subexpression elimination with lambdify in SymPy Question: I'm currently attempting to use SymPy to generate and numerically evaluate a function and its gradient. For simplicity, I'll use the following function as an example (keeping in mind that the real function is much lengthier): import sympy as sp def g(x): return sp.cos(x) + sp.cos(x)**2 + sp.cos(x)**3 It's easy enough to numerically evaluate this function and its derivative: import numpy as np g_expr = sp.lambdify(x,g(x),modules='numpy') dg_expr = sp.lambdify(x,sp.diff(g(x)),modules='numpy') print g_expr(np.linspace(0,1,50)) print dg_expr(np.linspace(0,1,50)) For my real function, however, lambdify is slow, both in terms of generating the numerical function and in its evaluation. As many elements in my function are similar, I'd like to use common subexpression elimination (cse) within lambdify to speed this process up. I know that SymPy has a built-in function to perform cse, >>> print sp.cse(g(x)) ([(x0, cos(x))], [x0**3 + x0**2 + x0]) but don't know what syntax to use in order to utilize this result in my lambdify function (where I'd still like to use x as my input argument): >>> g_expr_fast = sp.lambdify(x,sp.cse(g(x)),modules='numpy') >>> print g_expr_fast(np.linspace(0,1,50)) Traceback (most recent call last): File "test3.py", line 34, in <module> print g_expr1(nx1) File "<string>", line 1, in <lambda> NameError: global name 'x0' is not defined Any help on how to use cse in lambdify would be appreciated. Or, if there are better ways to speed up my gradient calculations, I'd appreciate hearing those as well. In case it's relevant, I'm using Python 2.7.3 and SymPy 0.7.6. Answer: So this might not be the most optimal way to do it, but for my small example it works. The idea of following code is lambdifying each common subexpression and generate a new function with possibly all arguments. I added a few additional sin and cos terms to add possible dependencies from previous subexpressions. import sympy as sp import sympy.abc import numpy as np import matplotlib.pyplot as pl def g(x): return sp.cos(x) + sp.cos(x)**2 + sp.cos(x)**3 + sp.sin(sp.cos(x)+sp.sin(x))**4 + sp.sin(x) - sp.cos(3*x) + sp.sin(x)**2 repl, redu=sp.cse(g(sp.abc.x)) funs = [] syms = [sp.abc.x] for i, v in enumerate(repl): funs.append(sp.lambdify(syms,v[1],modules='numpy')) syms.append(v[0]) glam = sp.lambdify(syms,redu[0],modules='numpy') x = np.linspace(-1,5,10) xs=[x] for f in funs: xs.append(f(*xs)) print glam(*xs) glamlam = sp.lambdify(sp.abc.x,g(sp.abc.x),modules='numpy') print glamlam(x) print np.allclose(glamlam(x),glam(*xs)) repl contains: [(x0, cos(x)), (x1, sin(x)), (x2, x0 + x1)] and redu contains [x0**3 + x0**2 + x1**2 + x2 + sin(x2)**4 - cos(3*x)] So `funs` contains all subexpression lambdified and the list `xs` contains each subexpression evaluated, such one can feed `glam` properly in the end. `xs` grows with each subexpression and might turn out to be a bottle neck in the end. You can do the same approach on the expression of `sp.cse(sp.diff(g(sp.abc.x)))`.
Python/Django Not Appending Slash Question: For some reason Django is not appending a slash at the end of variables that contain numeric characters: test_A -- works (goes to test_A/) test_1 -- does not (doesn't append the / at the end - giving me a 404) I do have middleware installed and APPEND_SLASH = True. Any thoughts? Thanks! url.conf: from django.conf.urls import patterns, url from dashboard import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^environment/(?P<environment_name_url>\w+)/$', views.environment, name='environment'),) models.py: from django.db import models class Environment(models.Model): name = models.CharField(max_length=128, unique=True) def __str__(self): return self.name views.py: def environment(request, environment_name_url): environment_name = environment_name_url.replace('_', ' ') context_dict = {'environment_name': environment_name} try: environment = Environment.objects.get(name=environment_name) pages = Page.objects.filter(environment=environment) context_dict['pages'] = pages context_dict['environment'] = environment except Environment.DoesNotExist: pass return render(request, 'dashboard/environment.html', context_dict) Error: Using the URLconf defined in dashboard_project.urls, Django tried these URL patterns, in this order: 1. ^admin/ 2. ^dashboard/ ^$ [name='index'] 3. ^dashboard/ ^environment/(?P<environment_name_url>\w+)/$ [name='environment'] 4. media/(?P<path>.*) The current URL, dashboard/environment/test_1, didn't match any of these. Answer: You have to extend your regular expressions. The problem is not that the slash is not appended, the problem is that none of the urls matches (with or without the slash). Simple solution, to include the dot you should update your regular expression to also allow a dot: `url(r'^environment/(?P<environment_name_url>[\w\.]-)/$', views.environment, name='environment'),)` Your could improve it further to also allow a dash: `url(r'^environment/(?P<environment_name_url>[\w\.-]+)/$', views.environment, name='environment'),)` The latter would even allow /test-1.1_10/
Django: TemplateDoesNotExist at / home.html Question: I'm trying to create first site using Django and Udemy tutorial ([here](https://www.udemy.com/learn-django-code-accept-payments-with- stripe/?dtcode=3Rdc8KM2WWhw#/lecture/2222730)) and I stuck on lesson 7: Home view. After runserver i get error: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.8.2 Python Version: 3.4.2 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'profiles') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Template Loader Error: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: Using loader django.template.loaders.app_directories.Loader: /root/Documents/tryDjango/lib/python3.4/site-packages/django/contrib/ admin/templates/home.html (File does not exist) /root/Documents/tryDjango/lib/python3.4/site-packages/django/contrib/auth/templates/home.html (File does not exist) Traceback: File "/root/Documents/tryDjango/lib/python3.4/site-packages/django/core/ handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/Documents/tryDjango/src/profiles/views.py" in home 7. return render(request, template, context) File "/root/Documents/tryDjango/lib/python3.4/site-packages/django/shortcuts.py" in render 67. template_name, context, request=request, using=using) File "/root/Documents/tryDjango/lib/python3.4/site-packages/django/template/loader.py" in render_to_string 98. template = get_template(template_name, using=using) File "/root/Documents/tryDjango/lib/python3.4/site-packages/django/template/loader.py" in get_template 46. raise TemplateDoesNotExist(template_name) Exception Type: TemplateDoesNotExist at / Exception Value: home.html I created app profiles and my structure tree looks like this: /tryDjango /src /tryDjango urls.py setting.py _init_.py wsgi.py /profiles admin.py models.py _init_.py tests.py views.py /static /templates home.html settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = XXXX # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'profiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'tryDjango.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'tryDjango.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), 'static', 'templates'), ) urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', 'profiles.views.home', name='home'), ] views.py from django.shortcuts import render # Create your views here. def home(request): context = locals() template = 'home.html' return render(request, template, context)` I also tried commands from other and here is the output: >>>from django.conf import settings >>>print (settings.TEMPLATE_DIRS) ('/root/Documents/tryDjango/static/templates',) >>> from django.template import loader >>> print(loader.get_template('home.html')) Traceback (most recent call last): File "<console>", line 1, in <module> File "/root/Documents/tryDjango/lib/python3.4/site-packages/django/ template/loader.py", line 46, in get_template raise TemplateDoesNotExist(template_name) django.template.base.TemplateDoesNotExist: home.html Thanks a lot! P.S I use Debian. Answer: It's not a good idea to put your templates in your `static` because files there will be readily available to the internet, and you probably don't want to be exposing your raw back end to the world `;)` Try this file structure (note that I have moved the `templates` directory): /tryDjango /src /tryDjango urls.py setting.py _init_.py wsgi.py /templates home.html /profiles admin.py models.py _init_.py tests.py views.py Django's [main template loader](https://docs.djangoproject.com/en/1.8/ref/templates/api/#django.template.loaders.app_directories.Loader) searches through the directories of each of the `INSTALLED_APPS`, and users the first template in a `templates` folder that matches. If you rely upon that (which I recommend), you will need to add `'home',` to your `INSTALLED_APPS`. Alternatively, the [other default template loader](https://docs.djangoproject.com/en/1.8/ref/templates/api/#django.template.loaders.filesystem.Loader) will look in paths you have defined for `templates` folders. For that, you will need to add the full path to [`TEMPLATES['dirs']` in Django 1.8+](https://docs.djangoproject.com/en/1.8/ref/templates/upgrading/#the- templates-settings) or [`TEMPLATE_DIRS` in older versions](https://docs.djangoproject.com/en/1.7/ref/settings/#template-dirs).
Django login tests session problems Question: Here are the two lines of code I'm trying to cover with tests: from django.contrib.auth import login from django.views.generic.edit import FormView from accounts.forms import UsernameLoginForm class LoginView(FormView): form_class = UsernameLoginForm success_url = '/' template_name = 'login.html' def form_valid(self, form): login(self.request, form.get_user()) return super(LoginView, self).form_valid(form) This seems to be the proper way to functionally implement a login form extended from django.contrib.auth.forms.AuthenticationForm, but I had to dig the code out of the admin login view myself so it needs decent testing. I'm having problems getting the test environment to set the user on the session. RequestFactory has no session support so this is what I tried: from django.contrib.auth.models import User from django.test import TestCase from django.test.client import RequestFactory import mox from accounts.forms import UsernameLoginForm from accounts.views import LoginView class ViewTests(TestCase): def test_login(self): user = User.objects.create(username='userfoo') view = LoginView() # request = RequestFactory() view.request = self.client self.moxx = mox.Mox() form = self.moxx.CreateMock(UsernameLoginForm) form.get_user().AndReturn(user) self.moxx.ReplayAll() view.form_valid(form) self.moxx.VerifyAll() self.assertTrue(request.user) And this is the error that causes: File "/home/renoc/.virtualenvs/alc/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 110, in login request.session.cycle_key() File "/home/renoc/.virtualenvs/alc/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py", line 283, in cycle_key data = self._session_cache AttributeError: 'SessionStore' object has no attribute '_session_cache' self.client.request.session is volatile and if I try to set an attribute on it it throws no errors but it doesn't have the attribute when accessed either. Answer: After a lot of work I found that I could attach the session generated by TestCase.client to the RequestFactory and have an instance I could alter. Here is what I came up with to make my tests work. from django.contrib.auth.models import User from django.test import TestCase from django.test.client import RequestFactory import mox from accounts.forms import UsernameLoginForm from accounts.views import LoginView class ViewTests(TestCase): def setUp(self): self.moxx = mox.Mox() def tearDown(self): self.moxx.UnsetStubs() def test_login(self): user = User.objects.create(username='userfoo') user.backend = '' view = LoginView() request = RequestFactory() request.META = {} request.user = None request.session = self.client.session request.session.create() view.request = request form = self.moxx.CreateMock(UsernameLoginForm) form.get_user().AndReturn(user) self.moxx.ReplayAll() view.form_valid(form) self.moxx.VerifyAll() self.assertTrue(request.user) I hope you will still offer suggestions including why I shouldn't be doing anything like this in the first place.