python,python-2.7,button,label,kivy
Well! there was a real need for improvement in your code. (I understand it as you are not experienced.) Improvement: 1 An application can be built if you return a widget on build(), or if you set self.root.(You shouldn't make all of the gui in build function itself.) def build(self):...
python,django,osx,python-2.7,python-3.x
Recommended: Try using virtualenv and initiate your environment with Python3. Or a quicker solution is to use python interpreter directly to execute django-admin: <path-to-python3>/python /usr/local/bin/django-admin startproject mysite ...
python,api,python-2.7,instagram,instagram-api
Unfortunately, Instagram is not very consistent in their API. The creation time of a media object is called created_time, but for a comment it is created_at. Also note there's no need to request the comments separately: they are already available for each media object, in media.comments....
simply use re.match(myregex.decode('utf-8'), mytext.decode('utf-8')) ...
python,list,python-2.7,data-structures,tuples
Sounds like you're describing a dictionary (dict) # Creating a dict >>> d = {'Date': "12.6.15", 'FilePath': "C:\somewhere\only\we\know"} # Accessing a value based on a key >>> d['Date'] '12.6.15' # Changing the value associated with that key >>> d['Date'] = '12.15.15' # Displaying the representation of the updated dict >>>...
Two processes are created because you call Popen with shell=True. It looks like the only reason you need to use a shell is so you make use of the file association with the interpreter. To resolve your issue you could also try: from subprocess Popen, PIPE, STDOUT pyTivoPath = "c:\pyTivo\pyTivo.py"...
How about using Regular Expression def get_info(string_to_search): res_dict = {} import re find_type = re.compile("Type:[\s]*[\w]*") res = find_type.search(string_to_search) res_dict["Type"] = res.group(0).split(":")[1].strip() find_Status = re.compile("Status:[\s]*[\w]*") res = find_Status.search(string_to_search) res_dict["Status"] = res.group(0).split(":")[1].strip() find_date = re.compile("Date:[\s]*[/0-9]*") res = find_date.search(string_to_search) res_dict["Date"] = res.group(0).split(":")[1].strip() res_dict["description"] =...
You seem to be confused between defining a function and calling it and how parameters work. def blackjack(A,B): print "Welcome to Blackjack!" print "Your cards are",name[A-1],"&",name[B-1] total = value[A-1] + value[B-1] print "Your card total is",total In your function A and B are place holders. They will be replaced by...
The operator "<>" means 'not equal to', and the operator "==" means 'equal to'. The former evaluates to true if two things being compared are not equal, and the latter evaluates to true if two things being compared are equal. http://www.tutorialspoint.com/python/comparison_operators_example.htm...
python-2.7,slice,ordereddictionary
The ordered dict in the standard library, doesn't provide that functionality. Even though libraries existed for a few years before collections.OrderedDict that have this functionality (and provide essentially a superset of OrderedDict): voidspace odict and ruamel.ordereddict (I am the author of the latter package, which a reimplementation of odict in...
python,python-2.7,threadpool,mysql-python
A finally clause is guaranteed to execute, even if the try clause raises an exception. What is probably happening here is that an exception is being raised, preventing the update from being committed, but the threads are triggered anyway. This doesn't really seen to be an appropriate use of try/finally....
My answer didn't satisfy me so I solved your problem. Changes: Added self keyword to currAmount1, currAmount2, and reflected this change everywhere in the script. (currAmount1 -> self.currAmount1) Called .get() on the Tkinter variables at the start of curr_search(): cur1 = self.curr_start1.get() cur2 = self.curr_start2.get() amount = self.currAmount1.get() Instead of...
python,python-2.7,csv,datetime
Use datetime.timedelta() objects to model the durations, and pass in the 3 components as seconds, minutes and hours. Parse your file with the csv module; no point in re-inventing the character-separated-values-parsing wheel here. Use a dictionary to track In and Out values per user; using a collections.defaultdict() object will make...
Obviously, /dev/tnt0 is not a serial device, or there is something wrong with that. Otherwise, your code looks valid.
python,python-2.7,logging,configuration-files
A potential problem is that you are importing the module before you set up the logger configuration. That way, the module requests a logger before the logging is setup. Looking a fileConfig()'s documentation, the reason subsequent logging to the pre-obtained loggers fails is the default value for its disable_existing_loggers argument:...
python,python-2.7,user-interface,user-input
The issue is in the lines - selectfile = file(raw_input("Enter Filename: "), 'r') with open(selectfile, 'r') as inF: You need to open the filename (which is inputted from user) directly, as below - with open(raw_input("Enter Filename: "),'r') as inF: Also, there seems to be an indentation issue in your code,...
python,python-2.7,selenium,selenium-webdriver,web-scraping
You need to explicitly wait for the search results to appear before getting the page source: from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC wd = webdriver.Firefox() wd.get("https://www.leforem.be/particuliers/offres-emploi-recherche-par-criteres.html?exParfullText=&exPar_search_=true& exParGeographyEdi=true") wd.switch_to.frame("cible") wait = WebDriverWait(wd, 10)...
python,windows,python-2.7,web-scraping,scrapy
Your spider is being blocked from visiting pages after the start page by your allowed_domains specification. The value should include just the domain, not the protocol. Try allowed_domains = ["www.WebStore.com"] Also the line desc_out = Join() in your WebStoreItemLoader definition may give an error as you have no desc field....
Use the steps outlined in diveintopython (copied and slightly cleaned bellow) if you want to use stdlib only. Otherwise, use something more nuanced (like Mechanize) to follow redirects. class SmartRedirectHandler(urllib2.HTTPRedirectHandler): def http_error_301(self, req, fp, code, msg, headers): result = urllib2.HTTPRedirectHandler.http_error_301( self, req, fp, code, msg, headers) result.status = code return...
python-2.7,amazon-web-services,amazon-ec2,amazon-s3,boto
This is a slightly difficult request because Security Groups are used by many different resources, including: Amazon EC2 instances Amazon RDS instances VPC Elastic Network Interfaces (ENIs) Amazon Redshift clusters Amazon ElastiCache clusters Amazon Elastic MapReduce clusters Amazon Workspaces ...and most probably other services, too To obtain a list of...
python,django,python-2.7,memory,scrapy
You can process your urls by batch by only queueing up a few at time every time the spider idles. This avoids having a lot of requests queued up in memory. The example below only reads the next batch of urls from your database/file and queues them as requests only...
python,regex,algorithm,python-2.7,datetime
What about fuzzyparsers: Sample inputs: jan 12, 2003 jan 5 2004-3-5 +34 -- 34 days in the future (relative to todays date) -4 -- 4 days in the past (relative to todays date) Example usage: >>> from fuzzyparsers import parse_date >>> parse_date('jun 17 2010') # my youngest son's birthday datetime.date(2010,...
string,python-2.7,concatenation,slice,string-length
Just change your first attempt to following: if len(str(row[1])) >= 16: row[2] = str(row[1])+" "+str(row[2]) row[1] = str(row[1][0:16]) My answer is freely adapted from comment by @phylogenesis. Update: The above answer wont work because row is a tuple and hence it is immutable. You will need to assign the values...
python-2.7,image-processing,numpy
Use array slicing. If xmin, xmax, ymin and ymax are the indices of area of the array you want to set to zero, then: a[xmin:xmax,ymin:ymax,:] = 0. ...
python,python-2.7,numpy,nested-lists
Lists are not hashable so we need to convert the inner list to tuple then we can use set intersection to find common element t1 = [[3, 41], [5, 82], [10, 31], [11, 34], [14, 54]] t2 = [[161, 160], [169, 260], [187, 540], [192, 10], [205, 23], [3,41]] nt1...
Delete from table_xyz where right(lower(source),4) not in ('.txt','.xls','xlsx') ...
You need: total = value[c1-1]+value[c2-1] ...
python,string,python-2.7,random
you can use random.sample() random.sample(population, k) Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. In [13]: "+".join(random.sample(sentences,3)) Out[13]: 'a+b+c' ...
python,python-2.7,multiprocessing,parallel-python
You're having this issue because you're passing the queue object when you submit the job: job = jobServer.submit(startt,(e,),(),("time", ), globals = globals()) # ^ here Two things to note: The queue is already global. You don't need to pass it as an argument. You can pass the queue as an...
Try something like the below code to generate the keys - from datetime import datetime as dt, timedelta as td start = '2015-01-01' end = '2015-03-23' sd = dt.strptime(start,'%Y-%m-%d') ed = dt.strptime(end,'%Y-%m-%d') delta = ed - sd for i in range(delta.days+1): dict[sd + td(days=i)] = <something> ...
You can use numpy.searchsorted for this: import numpy as np lat=np.linspace(15,30,61) long=np.linspace(91,102,45) def find_index(x,y): xi=np.searchsorted(lat,x) yi=np.searchsorted(long,y) return xi,yi thisLat, thisLong = find_index(16.3,101.6) print thisLat, thisLong >>> 6, 43 # You can then access the `data` array like so: print data[thisLat,thisLong] NOTE: This will find the index of the lat and...
Just iterate the keys and values of the first dict and add the values from the second dict corresponding to the same key. mydict = {41100: 'Health Grant', 50050: 'Salaries', 50150: 'Salaries', 50300: 'Salaries'}; mytb = {'': '', 41100: -3450200.40, 50050: 1918593.96, 50150: 97.50, 50300: 8570.80} result = {} for...
You need to use subprocess.check_output: mycat = int(subprocess.check_output(cmd, shell=True)) ...
python,python-2.7,ssl,tornado,sni
It is very hard to tell without having ore information about the server, but I'll try: OpenSSL 0.9.8zd 8 Jan 2015 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) You are restricting the protocol to TLS 1.0. It might be that the server expects TLS 1.2 or TLS 1.1 or SSL 3.0. Note that TLS...
ls is a *nix command, and is not installed under Windows by default. Use dir and its appropriate options instead.
A counter dict is not the best approach for your problem, if you want to associate the value with the first part you encounter you can use the following approach which use a tuple of (Value, Package) as the key and sets the part to the first part we encounter...
You can access all the fields of that table from the browsable object. id = browse_record.id name = browse_record.name Similarly you can access all the relational tables data as well, like customer in sale order. partner_id = sale_order_object.partner_id.id partner_name = sale_order_object.partner_id.name You can also update tables data through that browsable...
I think you'll really like the pandas module! http://pandas.pydata.org/ Put your list into a DataFrame This could also be done directly from html, csv, etc. df = pd.DataFrame(table[1:], columns=table[0]).astype(str) Access columns df['Column A'] Access first row by index df.iloc[0] Process row by row df.apply(lambda x: '_'.join(x), axis=0) for index,row in...
The following replaceString.py should do it: with open('script.py') as myFile: content = myFile.readlines() with open('script.py', 'w') as myFile: for line in content: newLine = line.replace("string1 = 'OriginalValue'", "string1 = 'newValue'") myFile.write(newLine) ...
You can use collections.defaultdict: tups = [ ('a1',['b1','b2','b3']), ('a2',['b2']), ('a3',['b1','b2']) ] d = collections.defaultdict(list) for a, bs in tups: for b in bs: d[b].append(a) Then: >>> d.items() [('b1', ['a1', 'a3']), ('b2', ['a1', 'a2', 'a3']), ('b3', ['a1'])] ...
You can simply filter the tuples from the list as a generator expression and then you can stop taking the values from the generator expression when you get the first tuple whose second element is -1, like this >>> s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)] >>>...
I don't know what you are exactly trying to achieve but if you are trying to count R and K in the string there are more elegant ways to achieve it. But for your reference I had modified your code. N = int(raw_input()) s = [] for i in range(N):...
One problem (but not the only one) with your code is that you are always adding the elements to the same possible_list, thus the lists in bigger_list are in fact all the same list! Instead, I suggest using [-1] to access the last element of the list of subsequences (i.e....
python,python-2.7,dynamic-programming
The process for a single step is to replace all 'M's with 'MNNN' and all 'N's with 'M', so: def step(state): return ''.join(['MNNN' if s == 'M' else 'M' for s in state]) For example: >>> s = 'N' >>> for _ in range(5): print s, len(s) s = step(s)...
python,python-2.7,matplotlib,plot,histogram
As far as I know, matplotlib does not have this function built-in. However, it is easy enough to replicate import numpy as np heights,bins = np.histogram(data,bins=50) heights = heights/sum(heights) plt.bar(bins[:-1],heights,width=(max(bins) - min(bins))/len(bins), color="blue", alpha=0.5) Edit: Here is another approach from a similar question: weights = np.ones_like(data)/len(data) plt.hist(data, bins=50, weights=weights, color="blue",...
Python 3.3.5 installation fixed this issue for me. Downloaded from - https://www.python.org/downloads/release/python-335/
What is best depends on how much data you have to process. Half the problem in this case is that the data retrieval and the printing are all jumbled up. Unless you are working with really large amounts of data it is advisable to split them up. If the data...
python,python-2.7,error-handling,popen
about the deadlock: It is safe to use stdout=PIPE and wait() together iff you read from the pipe. .communicate() does the reading and calls wait() for you about the memory: if the output can be unlimited then you should not use .communicate() that accumulates all output in memory. what...
json,python-2.7,elasticsearch,google-search-api
here is a possible answer to your problem. def myfunk( inHole, outHole): for keys in inHole.keys(): is_list = isinstance(inHole[keys],list); is_dict = isinstance(inHole[keys],dict); if is_list: element = inHole[keys]; new_element = {keys:element}; outHole.append(new_element); if is_dict: element = inHole[keys].keys(); new_element = {keys:element}; outHole.append(new_element); myfunk(inHole[keys], outHole); if not(is_list or is_dict): new_element = {keys:inHole[keys]}; outHole.append(new_element);...
Yes, it's a variable scoping issue. py_process doesn't exist on your subsequent invocations of exec_menu (after you have set it in the choice=='1'). Make it global and then it will be available when you want to stop....
python,python-2.7,tkinter,mysql-python
Like Bryan said, that may be the issue with your code, instead of making the button call conn.getConnection() directly, try an approach, where you save the entry variables into 'self' and then when the button is invoked, you create the connection at that time. The code would look something like...
python-2.7,matplotlib,computer-science,floating-point-conversion
You can't append to a tuple at all (tuples are immutable), and extending to a list with + requires another list. Make curveList a list by declaring it with: curveList = [] and use: curveList.append(curve) to add an element to the end of it. Or (less good because of the...
The issue is in the code - curr_file = open('myfile',w) curr_file.write('hello world') curr_file.close() The second argument should be a string, which indicates the mode in which the file should be openned, you should use a which indicates append . curr_file = open('myfile','a') curr_file.write('hello world') curr_file.close() w mode indicates write ,...
Instead of doing the "OR" inside the append, you'll need to do an if statement: if category == 'bulky item': items.append((Address, x, y, x, y, ReasonCode, SRNumber, SRNumber, FullName, ResolutionCode, HomePhone, CreatedDate, UpdatedDate, BulkyItemInfo, k_bulky_comm, ServiceDate, CYLA_DISTRICT, SCCatDesc, # ServiceNotes, Prior_Resolution_Code, CYLA_DISTRICT, )) elif category == 'e-waste': items.append((Address, x, y,...
python,python-2.7,pandas,dataframes
I believe the following does what you want: In [24]: df['New_Col'] = df['ActualCitations']/pd.rolling_sum(df['totalPubs'].shift(), window=2) df Out[24]: Year totalPubs ActualCitations New_Col 0 1994 71 191.002034 NaN 1 1995 77 2763.911781 NaN 2 1996 69 2022.374474 13.664692 3 1997 78 3393.094951 23.240376 So the above uses rolling_sum and shift to generate the...
The functions are returning tuples, because return only gives back one item. You can "unpack" the tuple returned by prepending it with an asterisk. The syntax will look like this: print function1(*function2(1,2)) ...
Correctness Think about what happens if your directory name contains spaces: mkdir hello world ...creates two directories, hello and world. And if you just blindly substitute in quotes, that won't work if your filename contains that quoting type: 'mkdir "' + somedir + '"' ...does very little good when somedir...
python,xml,python-2.7,pandas,lxml
There are several things wrong here. (Asking questions on selecting a library is against the rules here, so I'm ignoring that part of the question). You need to pass in a file handle, not a file name. That is: y = BeautifulSoup(open(x)) You need to tell BeautifulSoup that it's dealing...
python,python-2.7,python-3.x,numpy,shapely
Without downloading shapely, I think what you want to do with lists can be replicated with strings (or integers): In [221]: data=['one','two','three'] In [222]: data1=['one','four','two'] In [223]: results=[[],[]] In [224]: for i in data1: if i in data: results[0].append(i) else: results[1].append(i) .....: In [225]: results Out[225]: [['one', 'two'], ['four']] Replace...
[s for s, c in counts.iteritems() if c >= 2] # => ['a', 'c', 'b'] ...
python,python-2.7,csv,dictionary
I think I understand the table that you have, but if the following does not work let me know. I have tried to make this code as generic as possible (i.e. reading in the header line and not assuming 4 bases as header so this could work for say a...
print list(open("my_text.txt")) is probably a pretty easy way to do it ... ofc people are gonna come screaming about dangling pointers so for the sake of good habits with open("my_text.txt") as f: print list(f) alternatively f.readlines() you might need to strip off some newline characters [line.strip() for line in f]...
python,python-2.7,pandas,py.test
Suppose you want to select columns two and three to add: col_to_add = ['two', 'three'] Use sum(axis=1) to concatenate these columns: df['uid'] = df[col_to_add].sum(axis=1) ...
If I you're asking what I think you're asking, then yes. In fact, that's the whole point. Functions are sections of reusable code that you define first (they don't run when they're defined!) and then you call that function later. For example, you can define a function, helloworld like this:...