Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I want to create a SQL tabled-value function that will receive a query as n parameter through my API. In my function I want execute that query. The query will be a SELECT statement. This is what I have done so far and what to achieve but it is not the correct way to do so. ``` CREATE FUNCTION CUSTOM_EXPORT_RESULTS ( ...
Try this one - ``` CREATE PROCEDURE dbo.sp_CUSTOM_EXPORT_RESULTS @query NVARCHAR(MAX) = 'SELECT * FROM dbo.test' , @guid UNIQUEIDENTIFIER , @tableName VARCHAR(200) = 'test2' AS BEGIN SELECT @query = REPLACE(@query, 'FROM', 'INTO [' + @tableName + '] F...
What I see in your question is encapsulation of: * taking a dynamic SQL expression * executing it to fill a parametrized table Why do you want to have such an encapsulation? First, this can have a negative impact on your database performance. Please read [this on EXEC() and sp\_executesql()](http://www.sommarskog.se...
Send query as parameter to SQL function
[ "", "sql", "sql-server", "" ]
I'm writing a simple code to calculate how much change is due, with print statements thrown in to check my values. ``` cost = float(raw_input('How much did your meal cost? > ')) payment = float(raw_input('How much did you pay? > ')) change = (payment - cost) print change if change < 0: print 'You need to pay $%...
It's exactly as ignacio says. The easy fix would just be to throw in a line to round change to the second decimal place. Using a function to simplify things a little bit, your code becomes: ``` def get_change_and_coin(coin_amount, change): change = round(change, 2) return (change % coin_amount, int(change / co...
Welcome to IEEE 754 floating point. Enjoy the [inaccuracies](http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems). Use a fixed-point or integer mechanism if you want to avoid them.
Python code not working - confusion about if statement
[ "", "python", "" ]
I'm trying to figure out how to open up a file and then store it's contents into a dictionary using the Part no. as the key and the other information as the value. So I want it to look something like this: ``` {Part no.: "Description,Price", 453: "Sperving_Bearing,9900", 1342: "Panametric_Fan,23400",9480: "Converter_E...
For a `txt` file like so ``` 453 Sperving_Bearing 9900 1342 Panametric_Fan 23400 9480 Converter_Exchange 93859 ``` You can just do ``` >>> newDict = {} >>> with open('testFile.txt', 'r') as f: for line in f: splitLine = line.split() newDict[int(splitLine[0])] = ","....
You can read a file into a list of lines like this: ``` lines = thetextfile.readlines() ``` You can split a single line by spaces using: ``` items = somestring.split() ``` Here's a principial example how to store a list into a dictionary: ``` >>>mylist = [1, 2, 3] >>>mydict = {} >>>mydict['hello'] = mylist >>>mydi...
How to read and store values from a text file into a dictionary. [python]
[ "", "python", "string", "list", "dictionary", "io", "" ]
For a plot that I am making, I have: ``` plt.suptitle('Name:{0}, MJD:{1}, std dev > {2}'.format(pname, mjd[i], rmslevel), fontsize=12, fontweight='bold') ``` I want the number that will appear in the place of {2} (aka rmslevel) to only show 2 decimal places. I have seen similar questions to this of course, and the ...
You're looking for this. ``` >>> "{0:.2f}".format(123.678956) # Or "{:.2f}".format(123.678956) '123.68' ``` Your code now turns to ``` plt.suptitle('Name:{0}, MJD:{1}, std dev > {2:.2f}'.format(pname, mjd[i], rmslevel), fontsize=12, fontweight='bold') ``` You may find [this](http://docs.python.org/2/library/strin...
Maybe you can do this - ``` plt.suptitle('Name:{0}, MJD:{1}, std dev > {2}'.format( pname, mjd[i], ("%.2f" % rmslevel) ), fontsize=12, fontweight='bold') ```
limit plot title to only show a certain number of decimal places
[ "", "python", "" ]
I am new to python and working on a few programs to get a hang of it. I am making a palindrome program which takes input from a file and prints out the words that are palindromes. Here is the code i have so far ``` def isPalindrome(word): if len(word) < 1: return True else: if word[0] == word[-...
The contents of the file will be read in as a list, so fileContent will end up as: ``` fileContent = file.readlines() fileContent => ["moon\n", "mam\n", "madam\n", "dog\n", "cat\n", "bat\n"] ``` you could fix this by: ``` def fileInput(filename): palindromes = False for line in open(filename): if isP...
There should be a loop on the words in the file. Also `readline` reads the end-of-line character too. You should `strip` it before calling isPalindrome.
Palindrome program in python using file i/o
[ "", "python", "python-3.x", "" ]
I have a 60GB SciPy Array (Matrix) I must share between 5+ `multiprocessing` `Process` objects. I've seen numpy-sharedmem and read [this discussion](http://grokbase.com/t/python/python-list/1144s75ps4/multiprocessing-shared-memory-vs-pickled-copies) on the SciPy list. There seem to be two approaches--`numpy-sharedmem` ...
@Velimir Mlaker gave a great answer. I thought I could add some bits of comments and a tiny example. (I couldn't find much documentation on sharedmem - these are the results of my own experiments.) 1. Do you need to pass the handles when the subprocess is starting, or after it has started? If it's just the former, yo...
If you are on Linux (or any POSIX-compliant system), you can define this array as a global variable. `multiprocessing` is using `fork()` on Linux when it starts a new child process. A newly spawned child process automatically shares the memory with its parent as long as it does not change it ([copy-on-write](http://en....
Share Large, Read-Only Numpy Array Between Multiprocessing Processes
[ "", "python", "numpy", "multiprocessing", "shared-memory", "" ]
Given a Users table like so: Users: id, created\_at How can I get the # of users created grouped by day? My goal is to see the number of users created this Monday versus previous Monday's.
If `created_at` is of type `timestamp`, the simplest and fastest way is a plain cast to `date`: ``` SELECT created_at::date AS day, count(*) AS ct FROM users GROUP BY 1; ``` Since I am assuming that `id` cannot be `NULL`, `count(*)` is a tiny bit shorter and faster than `count(id)`, while doing the same. If you ...
``` SELECT COUNT(id) AS cnt, EXTRACT(DOW FROM created_at) AS dow FROM Users GROUP BY EXTRACT(DAY FROM created_at) ```
SQL grouping user count by Mondays
[ "", "sql", "postgresql", "" ]
I work in a small company which is running M/S SQL Server 2005 Now our head office is asking me to give the whole database backup with the table schema in a single file of \*.sql please help me to backup my database in a \*.sql including the table schema. Thanks in advance.
Use SQL Server Management Studio 1. right click on your database and choose `Generate scripts...` and hit `Next` 2. choose `Script entire database and all database objects` and hit `Next` 3. choose `Save to file` and enter a path and a file name for your future sql script file. On the same screen choose `Advanced` and...
I would go out and download Microsoft SQL Server Management Studio Express. <http://www.microsoft.com/en-us/download/details.aspx?id=8961> It is free. You will be able to connect to the database, drill down into Databases, right click and under Tasks, pick Backup Database. Make sure you pick full...CHoose Disk as the...
Microsoft SQL Server 2005 backup the database in *.sql
[ "", "sql", "sql-server", "" ]
I would like to sort the values of a dictionary (which are lists) based on one of the lists. For example say I have the dictionary: ``` data = {'AttrA':[2,4,1,3],'AttrB':[12,43,23,25],'AttrC':['a','d','f','z']} ``` and I would like to sort this based on the values associated with AttrA, such that: ``` data = {'AttrA...
Sort each value in your dictionary based on the `data['AttrA']` source list, using `sorted()` and `zip()`, all in just 3 lines of code: ``` base = data['AttrA'] # keep a reference to the original sort order for key in data: data[key] = [x for (y,x) in sorted(zip(base, data[key]))] ``` Demo: ``` >>> data = {'Attr...
``` from operator import itemgetter data = {'AttrA':[2,4,1,3],'AttrB':[12,43,23,25],'AttrC':['a','d','f','z']} sort = itemgetter(*[i for i, v in sorted(enumerate(data['AttrA']), key=itemgetter(1))]) data = dict((k, list(sort(v))) for k, v in data.items()) ``` Or a shorter but less efficient method of creating `sort`:...
Sorting values of a dictionary based on a list
[ "", "python", "sorting", "dictionary", "" ]
I am unable to solve this loop structure problem in SQL. I have two DATETIME parameters: `@Departure` and `@Arrival`. I am adding `NumberofHaltHrs` I need to get looping of @Departure and @Arrival as below. Let's say I have ``` @Departure= 13/01/01 00:00:00(YY/MM/DD) and @Arrival= 13/01/10 02:00:00(YY/MM/DD) NumofH...
**[Here is the SQLFiddel Demo](http://sqlfiddle.com/#!3/fb036/1)** **Below is the Query :** ``` create table Halts (id int,NoOfHalts int) Go insert into halts values(1,2),(2,22),(3,2),(4,22) Go select DATEADD(hour, T.sum - T.NoofHalts, Convert(datetime,'23/07/2012 00:00:00',103)) as ...
Try this: ``` DECLARE @Departure DATETIME SET @Departure = '01/13/01 00:00:00' CREATE TABLE #NumofHaltHrs(HaltTime INT, ID INT IDENTITY(1,1)) INSERT INTO #NumofHaltHrs (HaltTime) VALUES (2) INSERT INTO #NumofHaltHrs (HaltTime) VALUES (22) INSERT INTO #NumofHaltHrs (HaltTime) VALUES (26)...
Repetition of column values in next row, using SQL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Consider the following example query: ``` SELECT foo.bar, DATEDIFF( # Some more advanced logic, such as IF(,,), which shouldn't be copy pasted ) as bazValue FROM foo WHERE bazValue >= CURDATE() # <-- This doesn't work ``` How can I make the `bazValue` available later on in the query? I'd prefer this, since I beli...
There are a couple of ways around this problem that you can use in MySQL: By using an inline view (this should work in most other versions of SQL, too): ``` select * from (SELECT foo.bar, DATEDIFF( # Some more advanced logic, such as IF(,,), which shouldn't be copy pasted ) as bazValue FROM foo) buz WHERE baz...
As documented under [Problems with Column Aliases](http://dev.mysql.com/doc/en/problems-with-alias.html): > Standard SQL disallows references to column aliases in a `WHERE` clause. This restriction is imposed because when the `WHERE` clause is evaluated, the column value may not yet have been determined. For example, ...
Using AS value in later on in query
[ "", "mysql", "sql", "" ]
In Python how can I write a generic function to generate the Cartesian product of the same set repeated n times without using recursion and without using the itertools package? The function should take two parameters: the set and the n times. e.g.: ``` set1={'a','b'} print({(x,y) for x in set1 for y in set1}) {('a',...
You can generalize the comprehension-based technique you're already using by iteratively building up the result: ``` def cartesian_product(s, dim): if dim == 0: return set() res = [(e,) for e in s] for i in range(dim - 1): res = [e + (f,) for e in res for f in s] ...
``` def cartesian(A,n): tmp1,tmp2 = [],[[]] for k in range(n): for i in A: tmp1.extend([j+[i] for j in tmp2]) tmp1,tmp2 = [],tmp1 return tmp2 [In:1] A = [1,2,3] ; n = 1 [Out:1] [[1], [2], [3]] [In:2] A = [1,2,3] ; n = 4 [Out:2] [[1, 1, 1], [2, 1, 1], [3, 1, 1], [1, 2, 1], [2, 2...
Cartesian product generic function in Python
[ "", "python", "for-loop", "set", "cartesian-product", "" ]
having trouble with a multi-table query today. I tried writing it myself and it didn't seem to work, so I selected all of the columns in the Management Studio Design view. The code SHOULD work but alas it doesn't. If I run this query, it seems to just keep going and going. I left my desk for a minute and when I came ba...
A `cross join` returns a zillion records. The product of the number of records in each table . . . That might be 10,000 \* 100,000 \* 100 -- this is a big number. The one caveat is when a table is empty. Then the rows in that table is 0 . . . and 0 times anything is 0. So no rows are returned. And, no rows might be re...
Do not use cross joins especially on large tables. The link below will help. <http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html> Also **multi-part identifier could not be bound.** means the column might not exist as defined. Verify the column exists, datatype and it's assigned name for j...
SQL query either runs endlessly or returns no values
[ "", "sql", "sql-server", "" ]
So I have a line of text like this getting read into my program: ``` 00001740 n 3 eintiteas aonán beith 003 @ 00001930 n 0000 ~ 00002137 n 0000 ~ 04424418 n 0000 ``` And I want to split that in two at the first special character. Most of the time the line is split by the '@' symbol, but in some cases a different char...
You can use a regular expression: ``` >>> import re >>> line = "00001740 n 3 eintiteas aonán beith 003 @ 00001930 n 0000 ~ 00002137 n 0000 ~ 04424418 n 0000" >>> re.split(r'(?:#p|#m|%p|[@~+=])', line, 1) ['00001740 n 3 eintiteas aon\xc3\xa1n beith 003 ', ' 00001930 n 0000 ~ 00002137 n 0000 ~ 04424418 n 0000'] ```
Take a look at [re.split](http://docs.python.org/2/library/re.html#re.split). It works like the regular split but accepts a regular expression. Example: ``` import re string = "00001740 n 3 eintiteas aonán beith 003 @ 00001930 n 0000 ~ 00002137 n 0000 ~ 04424418 n 0000" print(re.split(r'\@|\~|\+|\#p|\#,|\%p|\=',...
Split a line at the first special character Python
[ "", "python", "" ]
I'm writing selenium tests, with a set of classes, each class containing several tests. Each class currently opens and then closes Firefox, which has two consequences: * super slow, opening firefox takes longer than running the test in a class... * crashes, because after firefox has been closed, trying to reopen it re...
You might want to use a session-scoped "autouse" fixture: ``` # content of conftest.py or a tests file (e.g. in your tests or root directory) @pytest.fixture(scope="session", autouse=True) def do_something(request): # prepare something ahead of all tests request.addfinalizer(finalizer_function) ``` This will...
Using session fixture as suggested by [hpk42](https://stackoverflow.com/a/17844938/347181) is great solution for many cases, but fixture will run only after all tests are collected. Here are two more solutions: ### conftest hooks Write a [`pytest_configure`](https://docs.pytest.org/en/latest/reference/reference.html...
How to run a method before all tests in all classes?
[ "", "python", "selenium", "pytest", "" ]
In my script, `requests.get` never returns: ``` import requests print ("requesting..") # This call never returns! r = requests.get( "http://www.some-site.example", proxies = {'http': '222.255.169.74:8080'}, ) print(r.ok) ``` What could be the possible reason(s)? Any remedy? What is the default timeout that...
> What is the default timeout that get uses? The default timeout is `None`, which means it'll wait (hang) until the connection is closed. Just [specify a timeout value](https://requests.readthedocs.io/en/latest/user/advanced/#timeouts), like this: ``` r = requests.get( 'http://www.example.com', proxies={'htt...
From [requests documentation](http://docs.python-requests.org/en/latest/user/quickstart/#timeouts): > You can tell Requests to stop waiting for a response after a given > number of seconds with the timeout parameter: > > ``` > >>> requests.get('http://github.com', timeout=0.001) > Traceback (most recent call last): > ...
Why doesn't requests.get() return? What is the default timeout that requests.get() uses?
[ "", "python", "get", "python-requests", "" ]
``` n = [3, 5, 7] def double(lst): for x in lst: x *= 2 print x return lst print double(n) ``` Why doesn't this return `n = [6, 10, 14]`? There should also be a better solution that looks something like `[x *=2 for x in lst]` but it doesn't work either. Any other tips about for-loops and li...
> Why doesn't this return `n = [6, 10, 14]`? Because `n`, or `lst` as it is called inside `double`, is never modified. `x *= 2` is equivalent to `x = x * 2` for numbers `x`, and that only re-binds the *name* `x` without changing the object it references. To see this, modify `double` as follows: ``` def double(lst): ...
``` n = [3, 5, 7] def double(lst): for x in lst: x *= 2 print x # item value changed and printed return lst # original lst returned print double(n) ``` you only modified item value inside a list and printed its number but returning original lst list. `[x *=2 for x in lst]` is wrong syntax, th...
How to double all the values in a list
[ "", "python", "list", "for-loop", "" ]
i am learning python from code academy, and i'm trying to complete their review assignment. I am supposed to define a function, and then set up a if/else loop to check the type of input i get, and then return either absolute value of an int/float or an error message. I tried to look at similar questions, but i don't u...
Are you trying to use the input function to get a value from the user ? if so, you must add parenthesis to it: ``` thing = input() # If you're using python 2.X, you should use raw_input instead: # thing = raw_input() ``` Also, you don't need the input parameter if that's what you're trying to do. If you do mean `inp...
You do not define the `thing`. Please try ``` def distance_from_zero(thing): if type(thing) != int or float: return "Not an integer or float!" else: return abs(thing) thing = 1 distance_from_zero(thing) ``` Or your meaning is this, accepting the user input? ``` def distance_from_zero()...
how do i fix a "NameError: name 'thing' is not defined" when calling a function ?
[ "", "python", "function", "" ]
I am trying to register a new user on the site, ``` class UserInfo(models.Model): user = models.ForeignKey(User,primary_key=True)#user profile email_id=models.CharField(max_length=32, null=True, blank=True) ``` When I am registering the user, I am getting stuck by **Integrity Error**, please help me to resolv...
From the limited information I would say the problem is it does not find a UserInfo that matches. It then tries to create a new UserInfo, but it has no User to assign to the User ForeignKey. I would suggest the following: ``` user = authenticate(username=email, password=password) if user is None: user = User(user...
If the original User object doesn't exist, you'll run into all kinds of problems. So, you need to break the process down into two steps. 1. Check if a `User` object exists or not, if it doesn't create it. 2. Check if a `UserInfo` object exists *for that user*, if it doesn't create it. As there is a `ForeignKey`, you ...
IntegrityError - Column 'user_id' cannot be null
[ "", "python", "django", "django-views", "" ]
I am running the following sql query in my web app: ``` SELECT EXISTS ( SELECT id FROM user WHERE membership=1244) ``` i was expecting **true** (boolean data) as the result but I'm getting 't' or 'f' for false. How do I get it to return to my lua code a standard boolean? I found the following post: [Reading boolean...
You are so close ``` SELECT EXISTS (SELECT id FROM user WHERE membership=1244)::int ```
Your first query do indeed return a boolean. A `t` is shown as the returned value of the query ``` select exists (select 1); exists -------- t ``` But if you check its type it is a boolean: ``` select pg_typeof(exists (select 1)); pg_typeof ----------- boolean ``` You will have to check with the lua's postgre...
checking for boolean true / false result in postgresql query
[ "", "sql", "postgresql", "lua", "" ]
When working with `simplejson` in Django, I sometimes need to send the information strictly in order. ``` values = {"entry1":"value1","entry2":"value2","entry3":"value3"} return HttpResponse(simplejson.dumps(values),content_type="application/json") ``` That's what it returns ``` {"entry2": "value2", "entry3": "value...
> I sometimes need to send the information strictly in order. Don't use a dictionary then, use a list of tuples: ``` values = [("entry1", "value1"), ("entry2", "value2"), ("entry3", "value3")] ``` Dictionaries *and* JSON objects do not have a set order. Neither will preserve your input order, nor are they required t...
The traditional way of solving this issue is by using 2-dimensional tuple/list, as suggested by Martjin Pieters. The more Pythonic way of accomplishing this is by using OrderedDict, however. For similar question/solution see: [Can I get JSON to load into an OrderedDict in Python?](https://stackoverflow.com/questions/...
simplejson returns values not in order
[ "", "python", "django", "json", "simplejson", "" ]
``` SELECT TOP 4000 Users.Id FROM Users JOIN Streams ON Users.Id = Streams.UserId JOIN Playlists ON Streams.Id = Playlists.StreamId WHERE Playlists.FirstItemId = '00000000-0000-0000-0000-000000000000' // Doesn't work HAVING COUNT(1) = ( SELECT COUNT(Playlists.Id) FROM Playlists WHERE Playlists.Stre...
try the query below, to select inactive user out ``` SELECT TOP 4000 Users.Id FROM Users JOIN Streams ON Users.Id = Streams.UserId JOIN Playlists ON Streams.Id = Playlists.StreamId WHERE Playlists.FirstItemId = '00000000-0000-0000-0000-000000000000' AND (SELECT COUNT(Playlists.Id) FROM Playlists WHERE Playlists.Stream...
I think you can accomplish this pretty easily with a WHERE NOT EXISTS clause ``` SELECT TOP 4000 Users.Id FROM Users JOIN Streams ON Users.Id = Streams.UserId JOIN Playlists ON Streams.Id = Playlists.StreamId WHERE Playlists.FirstItemId = '00000000-0000-0000-0000-000000000000' AND NOT EXISTS ( SELECT 1 F...
Select only parents with one child
[ "", "sql", "sql-server", "" ]
Have the table: ``` Game ---------- ID UploadDate LastUpdate ``` Where `UploadDate` is the date the game was uploaded, and `LastUpdate` is the date of the last update for the game. New games will have `UploadDate == LastUpdate`. I want to return `Most recently updated games`. They should be ordered by `LastUpdate` ...
The syntax you are using is appropriate for MySQL. The following works in almost all databases: ``` ORDER BY (case when UploadDate <> LastUpdate then 1 else 0 end) desc, LastUpdate DESC ```
You're very close - the order by clause needs values to order by - not boolean conditions. Instead, you can wrap the condition in a CASE statement, for example: ``` ORDER BY CASE WHEN UploadDate <> LastUpdate THEN 0 ELSE 1 END ASC, LastUpdate DESC ```
SQL Order by where dates not equal
[ "", "sql", "sql-server", "sql-order-by", "" ]
The inverse of this question (finding a string in a list) is so popular, that I wasn't able to find an answer to my question. ``` black_list = ["ab:", "cd:", "ef:", "gh:"] for line in some_file: if ":" in line and black_list not in line: pass ``` This obviously doesn't work. Some iteration over the list ...
The builtin [`any()`](http://docs.python.org/2/library/functions.html#any) function can help you here: ``` black_list = ["ab:", "cd:", "ef:", "gh:"] for line in some_file: if ":" in line and not any(x in line for x in black_list): pass ``` It's also possible to get the same effect with [`all()`](http://d...
Your example code makes it look like you're looking for an element in a file, not just in a string. Regardless, you could do something like this, which illustrates doing both with the built-in `any()`function: ``` def check_string(text, word_list): return any(phrase in text for phrase in word_list) def check_file...
How to check if elements of a list are in a string
[ "", "python", "string", "list", "if-statement", "element", "" ]
I am trying to modify a string , by replacing each alphabet by an alphabet which is two postions ahead of it. e.g. 'a' replaced by 'c', 'b' replaced by 'd'. The only exceptions is 'y' should be replaced by 'a' and 'z' by 'b' (loops back to start). I have written the following code for it, which seems to serve the purp...
The `print i,` syntax adds a space at the end of the thing that's being printed. You could solve this by putting all your characters in a list and `''.join()`ing them in the end: ``` string = "g fmnc wms bgblr rpylqjyrc gr zw fylb." print string answer = [] for i in string: if i.isalpha(): if ord(i)>120: ...
Here is a solution using string.translate: ``` from string import translate, maketrans, ascii_lowercase s='g fmnc wms bgblr rpylqjyrc gr zw fylb.' rot2=maketrans( ascii_lowercase, ascii_lowercase[2:]+ascii_lowercase[:2] ) print s.translate(rot2) ```
String Manipulation Python
[ "", "python", "string", "python-2.6", "" ]
Given that we have an HTML file as shown below: ``` </pre> <pre><img src="/icons/blank.gif" alt="Icon "> <a href="?C=N;O=D">Name</a> <img src="/icons/unknown.gif" alt="[ ]"> <a href="AAAAAAA.jpg">AAAAAAA.jpg</a> 16-Jan-2008 01:27 827K <img src="/icons/unknown.gif" alt="[ ]"> <a href="AA...
I hope this regex generalizes correctly: ``` with open('path/to/file') as infile, open('/path/to/output', 'w') as outfile: for line in infile: if line.startswith('lt="[ ]"'): hrefs = re.findall("\<a\\s+href=.*\</a\>?", line) for href in hrefs: target = href.split('...
[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) is good for webscraping: ``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup("""<img src="/icons/blank.gif" alt="Icon "> <a href="?C=N;O=D">Name</a> <img src="/icons/unknown.gif" alt="[ ]"> <a href="AAAAAAA.jpg">AAAAAAA.jpg</a> ...
Extracting some data from an HTML file and writing it to another file
[ "", "python", "python-2.7", "python-3.x", "" ]
I want to iterate through a dictionary in python by index number. Example : ``` dict = {'apple':'red','mango':'green','orange':'orange'} ``` I want to iterate through the dictionary from first to last, so that I can access the dictionary items by their indexes. For example, the 1st item will be apple, and the 2nd i...
I can't think of any reason why you would want to do that. If you just need to iterate over the dictionary, you can just do. ``` for key, elem in testDict.items(): print key, elem ``` **OR** ``` for i in testDict: print i, testDict[i] ```
You can iterate over keys and get values by keys: ``` for key in dict.iterkeys(): print key, dict[key] ``` You can iterate over keys and corresponding values: ``` for key, value in dict.iteritems(): print key, value ``` You can use `enumerate` if you want indexes (remember that dictionaries don't have an or...
Python Iterate Dictionary by Index
[ "", "python", "dictionary", "" ]
I got a table with Cities and States it looks something like: ``` cityid |city |stateid |state -------------------------------------- 0566 |abriaqui|05 |antioquia 0599 |alejand |05 |antioquia 0511 |another |05 |antioquia 0782 |dummy1 |09 |caldas 0783 |...
Just do something like this: ``` SELECT DISTINCT state, stateid FROM table ```
Try this way: ``` select distinct state, stateid from tab ``` you can also use `group by` clause ``` select state, stateid from tab group by state, stateid ``` Group by is useful if you need some aggregation function. Solution is depend of your requirements.
Use DISTINCT with two columns (or something that works)
[ "", "sql", "distinct", "" ]
I have seen questions similar to this but not quite the same. I have an expression ``` if foo == .... return -1 elif myFunction(bar) != -1: return myFunction(bar) elif ... ``` I don't want to calculate `myFunction(bar)` twice. If it were simply an `if`, I could do ``` temp = myFunction(bar) if temp != -1 retur...
If you do this a lot, it might pay to have a [memoizing decorator](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize) around. The only memoizer that is currently in the standard library (for newer Python 3.x) is `lru_cache`, which is overkill, but shows the general idea: ``` >>> def func(): ... print("foo...
If you do not want to call myFunction(bar) twice then there is no other way than using an intermediate variable to store the result in. People here start proposing complex caching solutions for this. This can be pretty convenient in extreme cases, but before doing so, let's get back to the basics a bit. You should make...
Python assignment and test of function using elif
[ "", "python", "if-statement", "variable-assignment", "" ]
How would I go about telling if my code runs on O(N) time (linear time?) or O(N^2) time or something else? Practice tests online dock points for codes that take to long to compute. I understand that it is best to have a script in which the time it takes to run is proportional to the length of input data only ( O(N) ti...
it's O(N^2). You have one loop from 0 to N and second loop goes from 0 to i. Let's see how much operations you have to perform. For each 'i' we look at the size of the list for j from 0 to i + 1 (let's take N = 7): ``` i = 0 | x x _ _ _ _ _ _ - i = 1 | x x x _ _ _ _ _ | i = 2 | x x x x _ _ _ _ | i = 3 | x x x x x _...
Well, lets consider this. The size of the input is `n = len(s)`. For each character, you loop from 0 to index. So we can get the following ``` for i = 0 to n for j = 0 to i + 1 1 ``` Which can be reduced to ``` for i = 0 to n (i + 1)(i + 2) ``` Which then gives us ``` for i = 0 to n i^2 + 3i + ...
Python Script: How to tell if in O(N) or O(N^2) time?
[ "", "python", "performance", "big-o", "palindrome", "" ]
Here is my code: ``` # library to extract cookies in a http message cj = cookielib.CookieJar() ... do connect to httpserver etc cdict = ((c.name,c.value) for c in cj) ``` The problem with this code is cdict is a generator. But I want to simply create a dictionary. How can I change the last line to assign to a dicti...
Use a dictionary comprehension. (Introduced in Python 2.7) `cdict = {c.name:c.value for c in cj}` For example, ``` >>> {i:i*2 for i in range(10)} {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18} ``` Here is the [PEP](http://www.python.org/dev/peps/pep-0274/) which introduced Dictionary Comprehensio...
You can use a [*dict comprehension*](http://www.python.org/dev/peps/pep-0274/): ``` cdict = {c.name: c.value for c in cj} ```
Convert generator object to a dictionary
[ "", "python", "" ]
As a recursion practice exercise, I am writing a Python function that recursively identifies if the input list is sorted from least to greatest, real numbers only, and then returns a Boolean value. My code is: ``` def det_sorted(listA): if len(listA) == 1: return(True) else: if listA[0] <= det...
you are close , you want to call the recursion for the return ``` else: if listA[0] <= listA[1]: return sorted(listA[1:]) ``` or you could combine both statements into the return (and get rid of the else) ``` return listA[0] <= listA[1] and sorted(listA[1:]) ```
@Joran Beasley's answer is correct, but here's another solution to the problem that should be a bit quicker: ``` def is_sorted(l, prev=None): if l: if prev is None: return is_sorted(l[1:], l[0]) else: return l[0] > prev and is_sorted(l[1:], l[0]) else: return True ```
Recursively Identifying Sorted Lists
[ "", "python", "list", "sorting", "recursion", "python-3.x", "" ]
I'm trying to find if a particular sentence pattern has an abbreviated word like R.E.M. or CEO. An abbreviated words that I am looking for is words with capital letters punctuated with period like R.E.M. or all caps. ``` #sentence pattern = 'What is/was a/an(optional) word(abbreviated or not) ? sentence1 = 'What is a ...
You've got a few issues. It's not really clear from your examples what sort of quoting might be expected, or if you want to match the ones that don't end in question marks. Your regex uses `*` (zero or any number of the previous) when I think you can use `?` (zero or one of the previous). You also will miss sentences w...
The position of the spaces before and after your abbreviation check are off. You might also want to check your quote handling. Perhaps it's just an artefact of posting your code here, but there seems to be some confusion with your ' and `'s. Try ``` ['`"]* ``` instead for both.
Regex to match certain sentence pattern with Python
[ "", "python", "regex", "" ]
I am using python to go through a file and remove any comments. A comment is defined as a hash and anything to the right of it *as long as the hash isn't inside double quotes*. I currently have a solution, but it seems sub-optimal: ``` filelines = [] r = re.compile('(".*?")') for line in f: m = r.split...
``` r'''(?: # Non-capturing group "[^"]*" # A quote, followed by not-quotes, followed by a quote | # or [^"#] # not a quote or a hash ) # end group * # Match quoted strings and not-quote-not-hash characters until... (#) # the comment begins! ''' `...
You can remove comments using this script: ``` import re print re.sub(r'(?s)("[^"\\]*(?:\\.[^"\\]*)*")|#[^\n]*', lambda m: m.group(1) or '', '"Phone #"#:"555-1234"') ``` The idea is to capture first parts enclosed in double-quotes and to replace them by themself before searching a sharp: ``` (?s) # the ...
Removing hash comments that are not inside quotes
[ "", "python", "regex", "comments", "quotes", "strip", "" ]
Looking at this django code from the djangobook: ``` from django.http import Http404, HttpResponse import datetime def hours_ahead(request, offset): try: offset = int(offset) except ValueError: raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = "<htm...
`%s` calls the `str()` method on its corresponding argument... (similar to `%r` calls `repr()`) - so either of those can be used for *any* object... Unlike `%d` (`%i` is the same) and `%f` for instance which will require appropriate types.
If `offset` is an **integer** (in this particular case, it's not true for any object type), then you can use any of `%s`, `%d`, `%r` and you'll get the same result. `%d` formats an integer number for display, `%s` calls `str()` on an argument, `%r` calls `repr()`: ``` >>> n = 5 >>> str(n) '5' >>> repr(n) '5' ``` Als...
can %s be an integer? *Python code*
[ "", "python", "" ]
I have three tables I need to join in order to tell what documents a product needs. Not all documents are needed on each product. There is a Document table, a Product table, and a DocTracking table that tracks the documents associated with products ``` Product Table ProdID ProdName 1 Ball 2 Wheel ``` ...
If you have only those documents and they are fix you can use this query: ``` SELECT ProdID, ProdName, [Needs Word Doc] = CASE WHEN EXISTS( SELECT 1 FROM Document d INNER JOIN DocTracking dt ON d.DocID=dt.DocID WHERE dt.ProdID = p.ProdID AND d.[Doc Name] = 'Word Document' ) T...
``` select P.ProdID, P.ProdName, case when DW.DocID is null then 'Yes' else 'No' end as NeedsWordDoc, case when DE.DocID is null then 'Yes' else 'No' end as NeedsExcelDoc from Product P left join DocTracking DTW on DTW.ProdId = P.ProdId left j...
SQL Group By Join
[ "", "sql", "sql-server", "join", "group-by", "" ]
Is there a way to do ``` tcpdump -i lo -A ``` and have it print all urls, any connections made? I have done: ``` sudo tcpdump -i lo -A | grep Host: ``` which works great. But I was wondering if there are options to do the same in tcpdump Finally, is there a way to do this in python without using a sys command or ...
you can use scapy the sniff function and use regex or grep ``` import scapy tcpdump = sniff(count=5,filter="host 64.233.167.99",prn=lambda x:x.summary()) print tcpdump ``` change the filter for your filter text :) or maybe you want to save the traffic and see it in wireshark ``` wrpcap("temp.cap",pkts) ```
tcpdump cannot filter based upon the content of the packets (no deep packet inspection) as it only uses pcacp-filter. You could improve your performance by only dumping those packages for `incoming TCP connections to your HTTP port`. ``` tcpdump -i lo -A tcp port 80 ``` TCPDUMP python: use [Pcapy](http://corelabs.cor...
tcpdump to only print urls
[ "", "python", "tcpdump", "" ]
I have the following table `routes` : ``` from | to --------- abc | cde cde | abc klm | xyz xyz | klm def | ghi ghi | mno mno | ghi ghi | def ``` I then extract each unique pair of routes (in my project abc -> cde = cde -> abc) : ``` SELECT DISTINCT LEAST(from,to) AS point_a, GREATEST(from,to) AS point_B FRO...
You can use `LEFT JOIN` for that: ``` SELECT r.point_a, r.point_b , l1.description as a_description, l2.description as b_description FROM (SELECT DISTINCT LEAST(`from`,`to`) AS point_a ,GREATEST(`from`,`to`) AS point_B FROM routes) AS r LEFT JOIN location l1 ON r.point_...
One approach: ``` SELECT LEAST(r.from,r.to) AS point_a, GREATEST(r.from,r.to) AS point_B, MAX(CASE l.code WHEN LEAST(r.from,r.to) THEN l.description END) a_description, MAX(CASE l.code WHEN GREATEST(r.from,r.to) THEN l.description END) b_description FROM routes r JOIN locati...
Query to join a table on another query
[ "", "mysql", "sql", "duplicates", "" ]
I need to find the next 10 digit number in a query. I try to use round(n,-1) but it rounds off to nearest 10 digit but I need next 10 digit. Please help me. ``` select round(5834.6,-1) from dual ``` gives 5830 but i need 5840
``` select ceil(5834.6/10)*10 from dual ```
Then add "5": ``` select round(5834.6 + 5,-1) from dual ```
how to round off to next 10 in oracle?
[ "", "sql", "plsql", "oracle11g", "" ]
Lets say I have a table like this: ``` Id*|value ``` For each `Id` I want to count how many times the corresponding `value` exist. Like with this sample data: ``` 1, a 2, b 3, a 4, b 5, c 6, a ``` I want: ``` 1, a, 3 2, b, 2 3, a, 3 4, b, 2 5, c, 1 6, a, 3 ``` This is what I have right now and I believe it is wo...
Try this ``` SELECT t1.Id, t1.value, t2.cnt FROM Table1 AS t1 INNER JOIN ( SELECT value, COUNT(value) as cnt FROM Table1 GROUP BY value ) AS t2 ON (t1.value = t2.value) ORDER BY t1.Id ``` OR ``` SELECT t1.id,t1.value,COUNT(t2.id) AS cnt FROM Table1 AS t1 INNER JOIN Table1 AS t2 ON t1.value = t2.value GRO...
Left join it with GROUP BY query running on itself: SQL Fiddle here - <http://sqlfiddle.com/#!2/5b8f5/18> ``` SELECT tbl.id, tbl.value, cnts.counts FROM tbl LEFT JOIN ( SELECT value, COUNT(value) AS counts FROM tbl GROUP BY value ) AS cnts ON (tbl.value = cnts.value) ```
Count repeated values - help my mysql query is dead slow
[ "", "mysql", "sql", "performance", "" ]
Basically I'm trying to be able to rotate images via user interface, however I've noticed that the image quality severely decreases upon each rotation. Does anyone know how to fix that? Also when the image is rotated it crops off parts of the image each time. here are some pictures of before and after: <https://i.stac...
``` rotated_small = photo_small.rotate(angle, resample=Image.BICUBIC, expand=True) ``` This tells it to use the highest quality interpolation algorithm that it has available, and to expand the image to encompass the full rotated size instead of cropping. The documentation does not say what color the background will be...
An image is a grid of pixels. If you rotate it (and angle isn't a multiple of 90) the rotated grid must be rematched to a new non-rotated grid to display the image. Some loss can't be avoided in this process. Only option would be to keep the unrotated image somewhere and sum up the angles of multiple rotations and alw...
How to preserve Image Quality when rotating with PIL
[ "", "python", "python-imaging-library", "" ]
I have 3 tables.. `House1` `House2` `results` ``` house1 ID, Name, Monday, Tuesday 1 john 1 1 2 jack 1 0 ``` and ``` House2 ID, Name, Monday, Tuesday 3 Dan 0 0 1 John 1 0 ``` and I want to fill the `results` table, s...
You recognize the problem with your query. The inner join only keeps matching rows. You can keep all rows by using `union all` instead. The following calculates the `total` for each table and then uses `aggregation` to sum them: ``` INSERT INTO results(ID, name, total) SELECT ID, name, SUM(Total) as TOTAL FRO...
What about something like ``` SELECT ID, Name, SUM(Monday)+SUM(Tuesday) as Total FROM ( SELECT ID, Name, Monday, Tuesday FROM House1 Union ALL SELECT ID, Name, Monday, Tuesday FROM House2 ) a Group BY a.ID, a.Name ```
Sum data in two tables and insert it in another one without duplucate ID
[ "", "sql", "database", "ms-access", "" ]
I have a txt file contains more than 100 thousands lines, and for each line I want to create a XML tree. BUT all lines are sharing the same root. Here the txt file: ``` LIBRARY: 1,1,1,1,the 1,2,1,1,world 2,1,1,2,we 2,5,2,1,have 7,3,1,1,food ``` The desired output: ``` <LIBRARY> <BOOK ID ="1"> <CHAPTE...
One method would be to create the full tree and print it. I used the following code: ``` from lxml import etree as ET def create_library(lines): library = ET.Element('LIBRARY') for line in lines: split_line = line.split(',') library.append(create_book(split_line)) return library def creat...
Here is a suggestion that uses lxml (tested with Python 2.7). The code can easily be adapted to work with ElementTree too, but it's harder to get nice pretty-printed output (see <https://stackoverflow.com/a/16377996/407651> for some more on this). The input file is library.txt and the output file is library.xml. ``` ...
creating a xml file with For Loop in python
[ "", "python", "xml", "elementtree", "" ]
I am working with a database that stores dates in multiple fields as integers (mock field names): * Century: CC01: 20 * Year: YR01: 13 * Month: MO01: 7 * Day: DY01: 22 I can formulate a date as so: `DATE((CC01 * 100 + YR01) || '-' || MO01 || '-' || DY01)` The problem is when I need to filter over a range of dates. F...
I believe I may have found a solution. ``` CC01 = 20 AND YR01 >= RIGHT(YEAR(CURRENT DATE - 220 DAYS),2) AND NOT ( YR01 = RIGHT(YEAR(CURRENT DATE - 220 DAYS),2) AND MO01 = MONTH(CURRENT DATE - 220 DAYS) AND DY01 < DA...
Do you have access to modify the DB schema? If so you could consider a 'generated column' for the date : <https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/expression_generated_columns?lang=en>
Filter by date range when the date is split into multiple fields
[ "", "sql", "db2", "" ]
I have 2D list in python ``` list = [[9, 2, 7], [9, 7], [2, 7], [1, 0], [0, 5, 4]] ``` I would like to get union of list items if there occurs any intersection. For example `[9, 2, 7]`, `[9, 7]`, `[2, 7]` has intersection of more than one digit. The union of this would be `[9,2,7]`. How can i get the final list as f...
You have a graph problem. You want to build connected components in a graph whose vertices are elements of your sublists, and where two vertices have an edge between them if they're elements of the same sublist. You could build an adjacency-list representation of your input and run a graph search algorithm over it, or ...
Here is a theoretical answer: This is a **connected component** problem: you build a graph as follows: * there is a vertex for each set is the list * there is an edge between two sets when they have a common value. what you want is the union of the [connected components](http://en.wikipedia.org/wiki/Connected_compone...
How can i get union of 2D list items when there occurs any intersection (in efficient way)?
[ "", "python", "list", "set", "intersection", "" ]
## The goal Convert `99999999` into `99999-999`. ## The problem I do not know the syntax. ## What I already thought about I was thinking to use`FORMAT()` function — but I'm working with *INT* instead of *DECIMAL*. ## My query ``` Select city.ZipCode As zipCode From app_cities As city Where city.Id = 1 ``` So, t...
The problem you're going to have with zip codes is that there can be a leading 0. So the length of the zip code can either be 7 or 8 digits. So, the zipcode might be 02323-213 or 12133-333. As an int, you will lose the first digit. Taking what Jurgen D already posted and modifying it. ``` SELECT insert(LPAD(zipcode,...
Use [INSERT()](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_insert) ``` select insert(ZipCode , 6, 0, '-') As zipCode from app_cities As city where Id = 1 ``` ## [SQLFiddle demo](http://sqlfiddle.com/#!2/d41d8/16786)
Make a simple format (MySQL)
[ "", "mysql", "sql", "" ]
I followed this to pass functions as arguments: [Passing functions with arguments to another function in Python?](https://stackoverflow.com/questions/803616/passing-functions-with-arguments-to-another-function-in-python) However, I could not figure out how to pass function with its own arguments as names parameters ...
`*args` and it's sibling `**kwargs` are the names generally used for extra arguments and key word arguments. You are passing a kew word argument when you pass `namedArg=arg2`. So, try this instead: ``` def retry(func, *args, **kwargs): func(*args, **kwargs) def action(*args, **kwargs): do something retry(action...
Read this, [keyword arguments in python doc](http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments). As the error clearly states that `got an unexpected keyword argument 'namedArg'`. where as you are providing only arguments in \*args. You will find plenty of examples to understand keyword arguments.
passing functions as argument with named parameters
[ "", "python", "" ]
I'm trying to get a subset of data based on the latest id and dates. It seems that when selecting other fields in the table they are not in sync with the max id and dates returned. Any idea how I can fix this? MySQL: ``` SELECT MAX(m.id) as id, m.sender_id, m.receiver_id, MAX(m.date) as date, m.content, l.username, ...
To answer the question in the title, "Why doesn't my content field match my MAX(id) field", that's because there is no guarantee that the values returned for the non-aggregate fields will be from the row where the MAX value is found. This is the documented behavior, and this is what we expect. Other DBMS would throw a...
Well, you *could* probably solve it without a subselect, but doing one is fairly straight forward. Something like this should work, just make the subselect return the id's of the interesting rows in messages, and get the data for only them. ``` SELECT m.id as id, m.sender_id, m.receiver_id, m.date as date, m.c...
Why doesn't my content field match my MAX(id) field in MySQL?
[ "", "mysql", "sql", "" ]
This is a fairly simple question, but I am looking for the most Pythonic method of doing it. I have two lists: ``` a = [..., 5, 7, 4, 8] b = [a, b, c, d] ``` I need to combine these two lists, overwriting the last 3 numbers of list `a`, such that it produces the following list: ``` c = [..., 5, a, b, c, d] ``` The ...
If you need a *new* list, use slicing and concatenation: ``` c = a[:-3] + b ``` Python slice notation allows for *negative* indices, interpreted as relative to the length of the list. `[:-3]` is the same as `[0:len(a) - 3]`; slicing everything but the last three elements. You can also alter `a` in-place by assigning...
First of all, I'd save the value 3 as a constant (to avoid magic numbers). Then I'd simply use: ``` NUMBER_FROM_END = 3 c = a[:-NUMBER_FROM_END] + b ```
Python: Combine two lists, overwriting the final few lines of the first list
[ "", "python", "list", "concatenation", "" ]
I'm aware that it's possible to ignore exceptions in Python using try...except statements. Is it possible to ignore exceptions in Python when they occur, but still print them? I tried ignoring the exception here, and therefore, the exception was not printed when it was encountered: ``` try: num = 0 if num == ...
You can print an exception like this. ``` try: x = 1 / 0 except Exception as e: print e ``` **EDIT:** As user1354557, gcbirzan, and Jonathan Vanasco pointed out, you can use the [`traceback`](http://docs.python.org/2/library/traceback.html) and [`logging`](http://docs.python.org/2/library/logging.html) modul...
If you want a printout of the stack trace, you can use the [`traceback`](http://docs.python.org/2/library/traceback.html) module: ``` import traceback try: 0/0 except: traceback.print_exc() ``` This would print something like: ``` Traceback (most recent call last): File "example.py", line 3, in <module> ...
In Python, is it possible to print exceptions even when they are being ignored?
[ "", "python", "" ]
I want to match IP range using a Python regex. For Ex. the google bot IP range as follow 66.249.64.0 - 66.249.95.255 ``` re.compile(r"66.249.\d{1,3}\.\d{1,3}$") ``` I can not figure out how to do this? I found [this](https://stackoverflow.com/questions/15525974/regex-to-match-an-ip-range) one done using Java.
You can use this: ``` re.compile(r"66\.249\.(?:6[4-9]|[78]\d|9[0-5])\.\d{1,3}$") ``` if you are motivated you can replace `\d{1,3}` by : ``` (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) ``` Explanation: A regex engine doesn't know what a numeric range is. The only way to describe a range is to write all the possibilit...
Use `socket.inet_aton`: ``` import socket ip_min, ip_max = socket.inet_aton('66.249.64.0'), socket.inet_aton('66.249.95.255') if ip_min <= socket.inet_aton('66.249.63.0') <= ip_max: #do stuff here ```
Python regex to match IP range
[ "", "python", "regex", "ip", "" ]
I have been attempting to follow a [**tutorial**](http://pyopengl.sourceforge.net/context/tutorials/shader_1.xhtml) online and I have followed every single line and for some reason I get the following error: ``` Traceback (most recent call last): File "C:/Users/User/Desktop/OpenGLContextTest.py", line 2, in <module>...
The instructions (apparently incorrectly) say to install `pydispatcher`. I had the same problem you did until I installed the module `PyDispatcher`. Confusingly, both exist.
To clarify on @Phil's answer. I saw: `No module named pydispatch` And so I did: `sudo pip install pydispatch` The install worked, but Scrapy still didn't work because we were supposed to: `sudo pip install pydispatcher`
No Module Named pydispatch when using pyOpenGL
[ "", "python", "pyopengl", "" ]
I've a text file (say test.txt) e.g. ``` a ...... aa ...... a+a ..... aa+ ..... a+ ..... aaa ..... ......... ``` Now I would like to find the line number of any particular strings e.g. 'a', 'aa+' etc. I've tried to find an exact match of the input string using regex. ``` name='a' import re p = re.compile(r'\b'+re...
Why would it *not* print 2 and 4? `a+a` and `a+` both contain `a` surrounded by word boundaries, exactly as you have specified with `\b`. Perhaps you want to match the start and end of the line instead? E.g. ``` name='a' import re p = re.compile('^'+re.escape(name)+ '$') with open('test.txt') as inpfile: for num...
The problem is making exact sense of your regular expression. In lay terms, you are matching the expression: "word border" followed by an 'a' followed by another "word border" and that is why is matching lines 0 (a), 2 (a+a) and so on. Here, spaces and non-printable characters (start of line, end of line) and '+' mar...
python regex with variable input
[ "", "python", "regex", "" ]
I have a .txt file with the following lines in it: ``` 23;Pablo;SanJose 45;Rose;Makati ``` I have this program: ``` file = open("C:/Users/renato/Desktop/HTML Files/myfile2.txt") def query(id): for line in file: table = {} (table["ID"],table["name"],table["city"]) = line.split(";") if id ...
What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this: ``` def query(id): for line in file: table = {} (table["ID"],table["name"],table["city"]) = line.split(";") if id == int(table["ID"]): f...
``` def query(id): for line in file: table = line.split(";") if id == int(table[0]): yield table id = int(input("Enter the ID of the user: ")) for id_, name, city in query(id): print("ID: " + id_) print("Name: " + name) print("City: " + city) file.close() ``` Using yie...
How to return a dictionary | Python
[ "", "python", "python-3.x", "" ]
I am new to Python. I need to know how to convert a list of integers to a list of strings. So, ``` >>>list=[1,2,3,4] ``` I want to convert that list to this: ``` >>>print (list) ['1','2','3','4'] ``` Also, can I add a list of strings to make it look something like this? ``` 1234 ```
You can use *List Comprehension*: ``` >>> my_list = [1, 2, 3, 4] >>> [str(v) for v in my_list] ['1', '2', '3', '4'] ``` or [*`map()`*](http://docs.python.org/2/library/functions.html#map): ``` >>> str_list = map(str, my_list) >>> str_list ['1', '2', '3', '4'] ``` In Python 3, you would need to use - `list(map(str, ...
``` >>>l=[1,2,3,4] ``` I've modified your example to not use the name `list` -- it shadows the actual builtin `list`, which will cause mysterious failures. Here's how you make it into a list of strings: ``` l = [str(n) for n in l] ``` And here's how you make them all abut one another: ``` all_together = ''.join(l)...
Converting an integer list into a string list
[ "", "python", "python-3.3", "" ]
I have a table with many integers in column named 'data' ``` data | param 123 1 432 1 123 1 423 2 234 1 423 2 ``` I have a query ``` SELECT data FROM data_table WHERE param=*something* GROUP BY data ORDER BY rand() LIMIT 1 ``` That returns a random distinct integer from the tabl...
This works. I normally don't recommend putting a query in the selector because it evaluates for each row returned. However in this case you are only returning one row so it is OK. ``` select count(distinct data) as cnt, (SELECT data FROM data_table GROUP BY data WHERE param='xxx' ORDER BY rand() LIMIT 1) as r...
I think the easiest is to join another select statement to get the total number of rows and add that to your main SELECT statement. ``` SELECT data AS data, count.count FROM data JOIN (SELECT COUNT(DISTINCT(data)) AS count FROM data WHERE parameter = "test") AS count WHERE parameter = "test" ORDER BY rand() LIMIT 1; ...
Count distinct elements and return only one
[ "", "mysql", "sql", "" ]
My requirement to compare two table data with in one database and stored the uncommon data in separate table named relation data within same database. How to compare this tables data? To compare is their any tools and can we stored uncommon data in separately table using any tool? i forgot to tell one thing that two ...
Try this query, I think its work ``` insert into relational(r1,r2,r3,....rn) (select s1,s2,s3,...sn from information info where info.informationcity not in (select customercity from customer) and info.informationstate not in (select customerstate from customer) ) ```
As an alternative to writing a SQL script, you could copy the entire results from both tables to a .csv file and then use win merge to compare the two: <http://winmerge.org/downloads/> I have used this technique in the past when comparing mass amounts of data and it has worked quite well.
Compare data between two tables with in single database
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to add sorting feature of my pagination stored procedure. How can I do this, so far I created this one. It works fine but when pass the `@sort` parameter, it didn't work. ``` ALTER PROCEDURE [dbo].[sp_Mk] @page INT, @size INT, @sort nvarchar(50) , @totalrow INT OUTPUT AS BEGIN DECLARE @offset INT...
One way (possibly not the best) to do it is to use dynamic SQL ``` CREATE PROCEDURE [sp_Mk] @page INT, @size INT, @sort nvarchar(50) , @totalrow INT OUTPUT AS BEGIN DECLARE @offset INT DECLARE @newsize INT DECLARE @sql NVARCHAR(MAX) IF(@page=0) BEGIN SET @offset = @page SET ...
I'm adding an answer since so many of the other answers suggest dynamic SQL, which is not a best practice. You can add pagination using an `OFFSET-FETCH` clause, which provides you with an option to fetch only a window or page of results from a result set. **Note**: `OFFSET-FETCH` can be used only with the `ORDER BY` ...
Pagination with the stored procedure
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I have a `x,y` distribution of points for which I obtain the `KDE` through [scipy.stats.gaussian\_kde](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html). This is my code and how the output looks (the `x,y` data can be obtained from [here](http://pastebin.com/RXbHzGfV)): ``` import nump...
Here is a way to do it using monte carlo integration. It is a little slow, and there is randomness in the solution. The error is inversely proportional to the square root of the sample size, while the running time is directly proportional to the sample size (where sample size refers to the monte carlo sample (10000 in ...
Currently, it is available `kernel.integrate_box([-np.inf,-np.inf], [2.5,1.5])`
Integrate 2D kernel density estimate
[ "", "python", "integration", "kernel-density", "probability-density", "" ]
I have two CheckButtons widgets with 3 elements each. I'd like to read the status of both widgets when either one of the CheckButtons is selected then update the chart accordingly. The slider widget has a `.val` for returning the status of a slider, but the CheckButtons widget seems a bit more awkward (or am I missing...
There might perhaps be a more elegant way but you can always keep track of the states of each of the checkboxes yourself, e.g. in a `dict`. The function that you specify using `on_clicked()` will receive the label string of the active checkbox as its second argument, which you can then use to update the status appropri...
I know it's a bit awkward, but you can check for visibility of on of the cross lines in check boxes. ``` import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons colourax = plt.axes([0.5, 0.4, 0.09, 0.2]) colours = CheckButtons(colourax, ('Red', 'Green', 'Blue'), (False, False, False)) isRedChecke...
Retrieving the selected values from a CheckButtons object in matplotlib
[ "", "python", "matplotlib", "" ]
I'm struggling to access a streaming API using Python and Requests. What the API says: "We’ve enabled a streaming endpoint to for requesting both quote and trade data utilizing a persistent HTTP socket connection. Streaming data from the API consists of making an Authenticated HTTP request and leaving the HTTP socket ...
Not sure if you figured this out, but TradeKing doesn't put newlines in between their JSON blobs. You thus have to use iter\_content to get it byte by byte, append that byte to a buffer, try to decode the buffer, on success clear the buffer and yield the resultant object. :(
As verbsintransit has stated, you need to solve your authentication problems, your streaming problems however can be fixed by using this example: ``` s = requests.Session() def streaming(symbols): payload = {'symbols': ','.join(symbols)} headers = {'connection': 'keep-alive', 'content-type': 'application/json...
Understanding Python HTTP streaming
[ "", "python", "http", "streaming", "python-requests", "chunked-encoding", "" ]
[This question](https://stackoverflow.com/questions/1312101/how-to-find-a-gap-in-running-counter-with-sql) explains how to find the first "unused" number in a table, but how can I find the same so that I can define extra constraints. How do I alter the query so that I get the first unused number after that's greater th...
in mysql and postgresql ``` SELECT id + 1 FROM test mo WHERE NOT EXISTS ( SELECT NULL FROM test mi WHERE mi.id = mo.id + 1 ) and mo.id> 100 ORDER BY id LIMIT 1 ``` [fiddle for mysql](http://www.sqlfiddle.com/#!2/43771/6) and [fiddle for postgresql](http://w...
In Oracle Sql, you may try: ``` SELECT id FROM (SELECT ID, lead(ID) OVER(ORDER BY ID) next_val FROM my_table t ) WHERE id +1 <> next_val AND id >100; ```
How to find a gap in range in SQL
[ "", "sql", "sqlite", "postgresql", "gaps-and-islands", "" ]
I have a pandas dataframe and would like to plot values from one column versus the values from another column. Fortunately, there is `plot` method associated with the dataframes that seems to do what I need: ``` df.plot(x='col_name_1', y='col_name_2') ``` Unfortunately, it looks like among the plot styles (listed [he...
You can specify the `style` of the plotted line when calling [`df.plot`](http://pandas.pydata.org/pandas-docs/version/0.15.0/generated/pandas.DataFrame.plot.html?highlight=plot#pandas-dataframe-plot): ``` df.plot(x='col_name_1', y='col_name_2', style='o') ``` The `style` argument can also be a `dict` or `list`, e.g.:...
For this (and most plotting) I would not rely on the Pandas wrappers to matplotlib. Instead, just use matplotlib directly: ``` import matplotlib.pyplot as plt plt.scatter(df['col_name_1'], df['col_name_2']) plt.show() # Depending on whether you use IPython or interactive mode, etc. ``` and remember that you can acces...
How to plot two columns of a pandas data frame using points
[ "", "python", "pandas", "dataframe", "matplotlib", "scatter-plot", "" ]
I have a link like this `<a href=abc.asp?xyz=foobar&baz=lookatme´_beautiful.jpg>` , where there is this unusual symbol `´` , which is not even present in a standard English keyboard. It is the mirror reflection of the symbol that `Ctrl+k` produces in this editor . So after I ran this code found on stackoverflow: ``` s...
Upgrade to the latest version of BeautifulSoup and install `html5lib`, which is a very lenient parser: ``` import requests from bs4 import BeautifulSoup html = requests.get('http://www.atlasdermatologico.com.br/listar.asp?acao=indice').text soup = BeautifulSoup(html, 'html5lib') for a in soup.find_all('a'): href...
You can include **[\u0000-\uFFFF]** as a subrange in re pattern or only include \xb4 as **[\u00b4]**
Parsing uncommon symbol using BeautifulSoup
[ "", "python", "regex", "beautifulsoup", "" ]
Say that I have 2 tables, one with entries of films that an user likes and an other with events that an user has gone. Each table has a column for knowing the user. Something like: Table Films: ``` id | iduser | film | number of watches | note .... ``` Table events: ``` id | iduser | event | date | .... ``` both i...
If you for some reason need to fetch your data in using exactly one SELECT you can unify your resultsets for `UNION ALL` like this ``` SELECT 'film' type, iduser, film name, watches, note, NULL date FROM films WHERE iduser = ? UNION ALL SELECT 'event' type, iduser, event name, NULL, NULL, date FROM events WHERE ...
Doing two SELECTs is the correct solution here. You're loading two different sets of data. **IF** the two tables had similar schemas (e.g, same column names and types), you could combine the two using: ``` SELECT * FROM table1 WHERE userid = ? UNION SELECT * FROM table2 WHERE userid = ? ``` However, this **will not*...
Is there a better way than using 2 SELECT?
[ "", "mysql", "sql", "" ]
I'm using SQL Server 2008 RD. I've got the following table say `myTable` consisting of a number of columns. `AccID` and `AccName` are the columns in which I'm interested in and non of them is a primary-key. So I want to obtain all the records having at least a duplicate (there could be more than 2 rows agreeing on `Ac...
Try this way: ``` select m1.AccID, m1.AccName from myTable m1 join ( select AccID,AccName from myTable group by AccID,AccName having count(1) = 2 ) m2 on m1.AccID = m2.AccID and m1.AccName = m2.AccName ```
Use GROUP BY clause and COUNT aggregate function with condition specified by ``` HAVING COUNT(*) > 1 ```
SQL: Find records with matching values on a set of columns
[ "", "sql", "sql-server-2008", "" ]
THIS IS MY TABLE STRUCTURE: ``` Anees 1000.00 Rick 1200.00 John 1100.00 Stephen 1300.00 Maria 1400.00 ``` I am trying to find the MAX(salary) and the persons name . this is the query I use Select MAX(salary),emp\_name FROM emp1 I get `1400.00 and Anees.` While the 1400 is correct the Ane...
Gordon gave an explanation why and the simplest way to get want you want. But if you for some reason want to use `MAX()` you can do it like this ``` SELECT emp_name, salary FROM emp1 WHERE salary = ( SELECT MAX(salary) salary FROM emp1 ) ``` Output: ``` | EMP_NAME | SALARY | --------------------- | Mar...
MySQL allows you to have columns in the `select` statement that are not in aggregate functions and are not in the `group by` clause. Arbitrary values are returned. The easiest way to do what you want is: ``` select t.* from t order by salary desc limit 1; ```
SQL max() function returns wrong value for row with maximum value
[ "", "mysql", "sql", "max", "" ]
I am trying to encrypt an integer using RSA. I observed that I can encrypt a string but cannot encrypt an Integer. here are the relevant code snippets: Could not encrypt the integer, 4: ``` crypto:~$ python Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "...
The traceback tells clearly the `rsa.encrypt` wants an argument of long type. If it is a string, it will turns it to long type. ``` rsa.encrypt(4L,"") ``` This will work and the `4L` is still a number but it is of type long. I think the reason to ask a long is, to perform an encryption, you have to do some padding a...
Python 2.x has two types of integers: * The `int` type, which matches the C type `long` on the local platform. The precision is limited, but it is at least 32 bits. * The `long` type, which has infinite precision. The `encrypt` and `decrypt` method of the RSA key object in PyCrypto only works with `long` or binary st...
Python RSA encrypt integers
[ "", "python", "rsa", "pycrypto", "" ]
I want to profile python code on Widnows 7. I would like to use something a little more user friendly than the raw dump of cProfile. In that search I found the GUI RunSnakeRun, but I cannot find a way to download RunSnakeRun on Windows. Is it possible to use RunSnakeRun on windows or what other tools could I use? **Ed...
The standard solution is to use cProfile (which is in the standard library) and then open the profiles in RunSnakeRun: <http://www.vrplumber.com/programming/runsnakerun/> cProfile, however only profiles at the per-functions level. If you want line by line profiling try line profiler: <https://github.com/rkern/line_pro...
I installed runsnake following these [installation instructions](http://www.vrplumber.com/programming/runsnakerun/). The step `python runsnake.py profile.pfl` failed because the installation step (`easy_install SquareMap RunSnakeRun`) did not create a file `runsnake.py`. For me (on Ubuntu), the installation step crea...
What tools should I use to profile Python code on window 7
[ "", "python", "windows", "python-2.7", "profiling", "cprofile", "" ]
I want to make a script which will type string letters one by one ``` def autotype(info): count = len(info) #Countign number of letters of the string splitlist = list(info) i = int(count) #getting an error on this line! it accept i=int(0) but my loop doesnt work because of this while i>0: sys....
The length of a list is the number of elements in a list. But, lists start at index `0`, and so they will end at index `length - 1`. So, to fix your code as is, it should be `i = count - 1`. (You don't need to cast it to an `int`, it's already one.) Better yet, rather than iterating using a counter in a `while` loop, ...
Your script is quite un-pythonic. Here is something that would do the same. Strings are iterables, so: ``` def autotype(info): for x in info: sys.stdout.write(x) sys.stdout.flush() # you need this, because otherwise its' buffered! time.sleep(0.2) ``` That's all you need.
Iterating over a string in Python
[ "", "python", "" ]
I am trying to iterate over an array twice to have pairs of elements (e\_i,e\_j) but I only want the elements such that i < j. Basically, what I want would look like this is C-like languages. ``` int my_array[N] = ...; for (int i=0; i<N; i++) for (int j=i+1; j<N; j++) something(my_array[i],my_...
Just use `itertools.combinations(my_list, 2)`.
Can't you just use the `range` function and go with: ``` vect = [...] for i in range(0, len(vect)): for j in range(i+1, len(vect)): do_something() ```
Iterate over array twice (cartesian product) but consider only half the elements
[ "", "python", "iterator", "combinations", "python-itertools", "" ]
I am using MS SQL server 2008. Here I need to compare the newly entered start time and End time of an event with the existing event timings. In the Database I need to check the new Starting time and End time values and the time Period should not match with the existing/ already booked event timings. I need to check th...
``` SELECT @count = COUNT (EventID) FROM TblEvent WHERE (('@STARTTIME' BETWEEN StartTime AND EndTime) or ('@ENDTIME' BETWEEN StartTime AND EndTime)); IF @count = 0 Begin Select @count = COUNT (EventID) FROM TblEvent WHERE (('@STARTTIME' < StartTime and '@ENDTIME' > EndTime)); END IF @count > 0 ...
Answer is `(StartA <= EndB) and (EndA >= StartB)`. Please, read these: [Determine Whether Two Date Ranges Overlap](https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap)
How to compare Starting time and End time of a event with existing events of same time on same day?
[ "", "asp.net", "sql", "sql-server-2008", "" ]
I have a function that takes in a list of class instances (but sometimes it could just be a single no list class instance) and I want to print it out regardless if it is a list or not. I know you can do it by doing something like this: ``` def func(obj): if type(obj) == list: for o in obj: prin...
My initial thought using simplest python code would be: ``` def func(obj): if not isinstance(obj,list): obj = [obj] for o in obj: print o ```
``` def func(obj): return map(some_function,obj) if isinstance(obj,(list,tuple)) else some_function(obj) ``` maybe? for some definition of better
Printing out a list of unknown size in a function in python
[ "", "python", "" ]
Suppose I have a dictionary: ``` D1 = {'A1' : [2, 3], 'B1': [3, 3], 'C1' : [4, 5]} ``` and I wanted to remove the all `3`s from `D1` so that I would get: ``` D1 = {'A1' : [2], 'B1': [], 'C1' : [4, 5]} ```
Something like this works, assuming 3 is always appears in the value, not in the key ``` >>> for v in D1.values(): ... if 3 in v: ... v.remove(3) ... >>> D1 {'A1': [2], 'C1': [4, 5], 'B1': [3]} ``` EDIT: just realized can be multiple occurence, try this one ``` >>> D1 = {'A1' : [2, 3], 'B1': [3, 3], 'C1'...
Here's a one-liner: ``` threeless = {k: [e for e in v if e != 3] for k, v in D1.iteritems()} ```
How to remove a value but keep the corresponding key in a dictionary?
[ "", "python", "" ]
I have a working web application on Flask with SqlAlchemy for moderation of news, it has some api methods to handle moderation requests, such as approve, deny currently selected news, list them, etc. I want to write unit tests to this methods, and I made them work, but I don't understand how to implement executing all...
I suggest you use the [Flask-Testing](http://pythonhosted.org/Flask-Testing/) extension. This is an approved extension which lets you do the unit testing as you desire. It has a specific section for SQLAlchemy as well. **Testing with SQLAlchemy** This covers a couple of points if you are using Flask-Testing with SQLA...
This is the way I've been running unit tests recently. I'm assuming since you are using SQLAlchemy that you're using model classes. I'm also assuming that all of your tables are defined as SQLAlchemy model classes. ``` from flask import Flask import unittest from app import db from app.models import Log from constant...
How can I test a Flask application which uses SQLAlchemy?
[ "", "python", "session", "testing", "flask", "sqlalchemy", "" ]
Alrigt, lets say I have these two dictionaries: ``` A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9} B = {(3,'y'):4, (6,'y'):6} ``` I am trying to add them together such that I get a dict similar to this: ``` C = {(3,'x'):-2,(3,'y'):4, (6,'y'):9, (8, 'b'):9} ``` I have tried making a comprehension that does this for dicts o...
Since you're using Python 3, one possible approach would be: ``` >>> A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9} >>> B = {(3,'y'):4, (6,'y'):6} >>> {k: A.get(k,0) + B.get(k,0) for k in A.keys() | B.keys()} {(8, 'b'): 9, (3, 'x'): -2, (6, 'y'): 9, (3, 'y'): 4} ``` In Python 3, `.keys()` returns a `dict_keys` object, and w...
I would use a [collections.Counter](http://docs.python.org/2/library/collections.html#collections.Counter) for this: ``` >>> A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9} >>> B = {(3,'y'):4, (6,'y'):6} >>> import collections >>> C = collections.Counter(A) >>> C.update(B) >>> dict(C) {(3, 'y'): 4, (8, 'b'): 9, (3, 'x'): -2, ...
Python: adding two dicts together
[ "", "python", "" ]
Im trying to query some data and one of them is a datetime format. I want that is shows `dd/mm/yy` with no time on it directly form the select. Is this possible? My query is and the join\_date is datetime that i need to be changed to short date: ``` $query = mysql_query("SELECT id,username,join_date,is_active FROM me...
Use the MySQL [`DATE_FORMAT` function](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format) for this: ``` SELECT id, username, DATE_FORMAT(join_date, '%d/%m/%y') AS join_formatted, is_active FROM members ``` In this example, the column name for the formatted date will be `join_for...
try this : ``` "SELECT id, username, DATE_FORMAT(join_date,'%d/%m/%y'), is_active FROM members" ```
Change datatime to date dd/mm/yy
[ "", "mysql", "sql", "" ]
I am trying to create a simple calculator where it accepts arguments at the command line. For example at the command line: ``` Calculator.py 1 2 44 6 -add ``` will give me the sum of the numbers. However, how can the user input infinite amount of arguments. I know you have to use \*args or something of the like in fu...
``` import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max,...
You don't need to, command line arguments are stored in [`sys.argv`](http://docs.python.org/2/library/sys.html#sys.argv) which will give you a list of the command line arguments. You just need to sum over them. ``` from sys import argv print sum(map(int, argv[1:])) # We take a slice from 1: because the 0th argument ...
Infinite Amount of Command Line Arguments in Python
[ "", "python", "argparse", "" ]
I've been reading on Wikipedia and it seems that NeXT developed an object-relational mapping framework for Objective-C called Enterprise Objects Framework. And then Apple absorbed NeXT and EOF became WebObjects. And then WebObjects became Java. Is there any part of the EOF or Objective-C based WebObjects lying around?...
EOF has become CoreData and CoreData doesn't support arbitrary schemas or backing stores. So I made a couple of frameworks that do. [ORDA](https://github.com/Firelizzard-Inventions/ORDA), the **O**bjective-C **R**elational **D**atabase **A**bstraction framework, is a 'standard' interface for creating Objective-C datab...
I'm pretty sure you're looking for [Core Data](http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.html). From [wikipedia](http://en.wikipedia.org/wiki/Core_Data): > On computer systems running Mac OS X and mobile devices running iOS, > Core Data is an object graph and p...
Objective-C and SQL?
[ "", "sql", "objective-c", "webobjects", "" ]
I am trying to write a query to count the number of records based on a number of different ranges. I have success with using `union`, but I feel there is a better way to do it. Here is what I've done: ``` select count(col1) as range1 from tbl1 where col1 <= 15000 union select count(col1) as range2 from tbl1 where co...
One way is with conditional summation (for the values in separate columns): ``` select sum(case when col1 <= 15000 then 1 else 0 end) as range1, sum(case when col1 > 15001 and col1 <= 30000 then 1 else 0 end) as range2, sum(case when col1 > 30001 and col1 <= 45000 then 1 else 0 end) as range3 from tbl1; ...
Personally I prefer using a derived (or physical) table to store my range boundaries which I then join back to in order to find my results. I reckon the code is simpler and easier to extend if required Something a little like this: ``` ; WITH ranges (lbound, ubound) AS ( SELECT 0, 1500 UNION ALL SELECT 1500, 300...
Counting number of records for specific ranges sql server
[ "", "sql", "sql-server", "coldfusion", "" ]
given a dictionary of lists ``` vd = {'A': [1,0,1], 'B':[-1,0,1], 'C':[0,1,1]} ``` I want to add the lists element wise. So I want to add first element from list A to first element of list B vice versa the complexity is that you cannot rely on the labels being A, B, C. It can be anything. second the length of the dic...
In short: ``` >>> map(sum, zip(*vd.values())) [0, 1, 3] ``` --- # Explanation Given a dictionary: ``` >>> vd = {'A': [1,0,1], 'B': [-1,0,1], 'C': [0,1,1]} ``` We can [get the values](http://docs.python.org/2/library/stdtypes.html#dict.values): ``` >>> values = vd.values() >>> values [[1, 0, 1], [-1, 0, 1], [0, 1...
So you just want to add up all the values elementwise? `[sum(l) for l in zip(*vd.values())]`
How to add elements from a dictonary of lists in python
[ "", "python", "" ]
Is there are a way to pass a variable between two python decorators applied to the same function? The goal is for one of the decorators to know that the other was also applied. I need something like decobar\_present() from the example below: ``` def decobar(f): def wrap(): return f() + "bar" return wra...
You can add the function to a "registry" when `decobar` is applied to it, then later check the registry to determine whether `decobar` was applied to the function or not. This approach requires preserving original function's `__module__` and `__name__` properties intact (use `functools.wraps` over the wrapper function ...
To pass a variable between two python decorators you can use the decorated function's keyword arguments dictionary. Only don't forget to pop the added argument from there before calling the function from within the second decorator. ``` def decorator1(func): def wrap(*args, **kwargs): kwargs['c...
passing variables between two python decorators
[ "", "python", "decorator", "chaining", "" ]
I have this `select` statement and what I am trying to accomplish is to get data in the `DosagePerUnits` column only if `Dosage` is not equal to empty or 1 and if `Units` is not empty or 1. Can someone help me please ? ``` select sbd.Code, c.Description, sbd.Dosage, Case when sbd.Units = '' then ...
According to your description, it should be like this: ``` CASE WHEN ISNULL(sbd.Dosage, '1') <> '1' AND ISNULL(sbd.Units, '1') <> '1' THEN sbd.Dosage + '/' + sbd.Units ELSE NULL END AS DosagePerUnits ``` `ISNULL(x, 1)` replaces x with 1 if it is null. So `ISNULL(x, 1)` is = 1 if x is either 1 or NULL. EDIT: Changed ...
instead of Case when sbd.Units = '' then '1' else sbd.Units end as Units, try Coalesce(sbd.Units,1) as Units,
CASE statement IF ELSE in SQL Server
[ "", "sql", "sql-server", "t-sql", "" ]
I'm using the [mutagen](https://code.google.com/p/mutagen/) module for Python to get the artist of various MP3 files I have. Here's the code giving the error: ``` audio = EasyID3(C:\Users\Owner\Music\Music\Blue Öyster Cult\Blue Öyster Cult\Cities on Flame) print audio["artist"] ``` The code is working for most of my...
Most likely, you're looking for a key which doesn't exist in mutagens id3 dictionary. Do a simple check like you would do for a regular dictionary: ``` if 'artist' in audio: print audio['artist'] ``` I've tried with and without ensuring that the argument is Unicode and it works in both cases with `Python 2.7.3`
This is probably because you removed its value manually via the file properties/details. That's what happened with me (with Python 3.4). You could redefine the key by following: ``` if not 'keyname' in Dic: 'keyname' = "" ``` If that was the reason it should work again.
What is the "TPE1" KeyError?
[ "", "python", "mp3", "id3", "mutagen", "" ]
I'm trying to figure out the best way to design a database to support private user-defined groups. Pretty much identical to how Google Circles are. These are to be for **JUST** the user, much like circles are - that's why creating a user group design like I found here: <https://stackoverflow.com/a/9805712/2580503> woul...
This must involve at least three (3) tables if you want a normalized design. USERS, USER\_GROUPS, and USER\_GROUPS\_MEMBERS. You are correct that the PK of USER\_GROUPS would be a dyad (USER, GROUP). The PK of USER\_GROUPS\_MEMBERS would be a triad (USER, GROUP, USER).
What about? ``` Groups (GROUP_ID, USER_ID, GROUP_NAME) Members (MEMBER_ID, GROUP_ID, USER_ID) ``` Although `Groups` might appear backwards, it actually lists the `USER_ID` that owns a `GROUP_ID` while `Members` gives the `MEMBER_ID` to which could be associated rows that have to do with this `USER_ID` in the given `G...
Database Design for user defined groups
[ "", "sql", "database", "database-design", "" ]
Okay so I'm using the Violent Python book and made an SSH brute force program. When I run the following code ``` import pxssh import optparse import time from threading import * maxConnections = 5 connection_lock = BoundedSemaphore(value=maxconnections) Found = False Fails = 0 def connect(host, user, password, releas...
You have some problems with identation in various parts of the code Other than line 17, it looks like you have an identation problem also on line 20, line 23 (the elif block), line 27, line 38, and lines from 48 to 59 seems to be bad indented. Also you have a missing ' on line 34 and an extra ) on line 25
The indentation is wrong. Should be ``` try: s = pxssh.pxssh() s.login(host, user, password) print '[+} Paassword Found: ' + password Found = True except Exception, e: if 'read_nonblocking' in str(e): Fails += 1 ```
Syntax Error which I can't seem to find
[ "", "python", "" ]
I have a table with three fields: `ID`, `date` and `action`. The three possible values of `action` are `X`, `Y` and `Z`. I want a query which, for each `ID` in the table for which there ia a row with a `Z` action, will return the most recent row for the same `ID` with an `X` action, if one exists. Here is what I want ...
This works (although it may be able to be simplified): ``` SELECT a.id, max(a."date") as Xdate, b."date" as Zdate, a.action FROM a INNER JOIN (SELECT * FROM a WHERE a.action = 'Z') b ON a.ID = b.ID WHERE a."date" < b."date" AND a.action = 'X' GROUP BY a.id, b."date", a.action ``...
Here other solution: ``` WITH temp AS ( SELECT a.id, a.date_f, a.action FROM a WHERE a.action = 'Z' ) SELECT a.id, max(a.date_f) as Xdate, temp.date_f as Zdate, a.action FROM a INNER JOIN temp ON temp.id = a.id AND a.date_f < temp.date_f WHERE a.action = 'X' GROUP BY a.id,temp.date_f,a.action...
Nested subquery in Oracle is slow
[ "", "sql", "oracle", "" ]
So I'm learning Python and hacking at the same time from "Violent Python" and I ran into a problem Here's my code: ``` import optparse import socket from socket import * from threading import * screenLock = Semaphore(value = 1) def connScan(tgtHost, tgtPort): try: connSkt = socket(AF_INET, SOCK_STREAM) ...
First of all, you are misunderstanding how your command line is being parsed. You pass in: ``` python port_scanner.py -H 74.207.244.221 -p 21, 22, 80 ``` which means that Python sees: ``` ['-H', '74.207.244.221', '-p', '21,', '22,', '80'] ``` and the `optparse.OptionParser` thus parses *just* `'21,'` as the value ...
You have a comma in the value of the port, so Python can't convert the string into integer smoothly. You can reproduce this exception in interpreter easily: ``` >>> int("2,") Traceback (most recent call last): File "<pyshell#27>", line 1, in <module> int("2,") ValueError: invalid literal for int() with base 10: '2,' ...
Violent Python: port inputs not being seperated
[ "", "python", "" ]
I am learning regular expressions and trying to do the following: Below is the format of a series of alpha numeric digits. It starts with 4 digits followed by 2 spaces followed by 8 digits followed by a single space followed by 8 digits followed by a single space followed by 8 digits followed by a single space followe...
You could use one regular expression for a single 8 digit group and then find all the matches in a line. ``` line = #string regex = re.compile(r' (\w{8})') groups = regex.findall(line) #gives a list of the matches in order of appearance ```
You can indeed use [lookarounds](http://www.regular-expressions.info/lookaround.html): ``` (?<=\d{4}\s{2})(\d{8}\s){4}(?=[\s|]) ```
Python Regular expressions for alpha numeric digits
[ "", "python", "regex", "" ]
2 I have two tables one logs.emails: ``` EmailNum EmployeeID, Emailcontent, EmailReceivers ,is_read 1 1 , "sasa" , "sas@google.com" ,1 2 1 , "sasa" , "sas@google.com" ,0 3 2 , "sasa" , "sas@google.com" ,0 4 2 , "sasa"...
You should specify a `WHERE` clause here instead of using `HAVING`, as you are trying to filter out the records that have `is_read=0` prior to doing any aggregation. Also, in order to get only the fields desired, don't use `*` . Simply specify the fields you want. ``` SELECT b.FirstName, b.LastName, COUNT(a.Emai...
Try this way: ``` SELECT b.FirstName, b.LastName, sum( case when a.is_read=0 than 1 else 0 end ) as NumOfUnreadEmails FROM logs.emails a inner join Employees.user b on a.EmployeeID=b.id group by b.FirstName, b.LastName ```
MySQL Query (Group by)
[ "", "mysql", "sql", "" ]
I want to write a loopless program (probably using comprehension) to remove duplicate elements in a sorted array in Python (and most efficiently too).
Since the list is sorted - meaning all the duplicates are already grouped, you can use `itertools.groupby` ``` >>> testList = [1, 1, 1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 8, 9] >>> from itertools import groupby >>> [k for k, g in groupby(testList)] [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` This is more efficient (in memory and time) t...
I would personally just use this. ``` >>> testList = [1, 1, 1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 8, 9] >>> sorted(set(testList)) [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` You can even sort a list from the beginning. ``` >>> from random import shuffle >>> shuffle(testList) >>> testList [1, 4, 5, 6, 2, 1, 3, 3, 4, 9, 8, 1, 7, 8] >>> s...
Loopless program to remove duplicate elements in a sorted array
[ "", "python", "" ]
I tried PyGame for playing a WAV file like this: ``` import pygame pygame.init() pygame.mixer.music.load("mysound.wav") pygame.mixer.music.play() pygame.event.wait() ``` but It change the voice and I don't know why! I read [this link](https://stackoverflow.com/questions/307305/play-a-sound-with-python) solutions and...
You can use [PyAudio](https://people.csail.mit.edu/hubert/pyaudio/docs/#class-pyaudio). An example here on my Linux it works: ``` #!usr/bin/env python #coding=utf-8 import pyaudio import wave #define stream chunk chunk = 1024 #open a wav format music f = wave.open(r"/usr/share/sounds/alsa/Rear_...
Works for me on Windows: <https://pypi.org/project/playsound/> ``` >>> from playsound import playsound >>> playsound('/path/to/a/sound/file/you/want/to/play.wav') ``` NOTE: This has a bug in Windows where it doesn't close the stream. I've added a PR for a fix here: <https://github.com/TaylorSMarks/playsound/pull/53/c...
Play WAV file in Python
[ "", "python", "audio", "pygame", "pyglet", "" ]
Python 3.2 ``` t = (1, 2, 3) t2 = (5, 6, 7) z = zip(t, t2) for x in z: print(x) ``` Result: ``` (1, 5) (2, 6) (3, 7) ``` Putting in EXACTLY the same loop immediately after, nothing is printed: ``` for x in z: print(x) ``` `z` still exists as `<zip object at 0xa8d48ec>`. I can even reassign the `t`, `t2` ...
That's how it works in python 3.x. In python2.x, `zip` returned a list of tuples, but for python3.x, `zip` behaves like `itertools.izip` behaved in python2.x. To regain the python2.x behavior, just construct a list from `zip`'s output: ``` z = list(zip(t,t2)) ``` Note that in python3.x, a lot of the builtin functions...
Because `zip` returns an iterator in Python 3.x. If you want to re-use it, then make it a `list` first: ``` z = list(zip(t, t2)) ```
zip variable empty after first use
[ "", "python", "python-3.x", "iterator", "" ]
I am new to SQL development. So I would like to get some help from SO. I have three tables : **student**, **student\_addresses**, **student\_phones**. Their schema is roughly as follows : ``` student ------- student_id (Primary Key) student_name father_name mother_name student_addresses ----------------- student_ad...
This should work on MySQL and PostgreSQL: ``` SELECT s.student_id, max(s.student_name) student_name, max(s.father_name) father_name, max(s.mother_name) mother_name, COUNT(distinct a.student_address_id) total_addresses, COUNT(distinct p.student_phone_id) total_phones FROM students...
Just add `GROUP BY`: ``` SELECT students.student_id,student_name,father_name,mother_name, COUNT(student_addresses.student_id) AS total_addresses, COUNT(student_phones.student_id) AS total_phones FROM students,student_phones,student_addresses WHERE students.student_id = student_phones.student_id AND...
SQL Query to get the data
[ "", "mysql", "sql", "database", "postgresql", "" ]
Here is the information in the file: ``` "Part no.","Description","Price" "453","Sperving_Bearing","9900" "1342","Panametric_Fan","23400" "9480","Converter_Exchange","93859" ``` I'm trying to figure out how to open up a file and then store it's contents into a dictionary using the Part no. as the key and the other in...
A SCV is a comma separated variable file so I'm going to assume that each variable is indeed separated by commas: ``` f = open("myfile.csv", 'r') data = f.read().split('\n') #separates the contents into lines with while leaving out the newline characters myDict = {} for x in range(len(data)): data[x] = data[x].spl...
Perhaps like this: ``` wordlist = {} with open(textname, 'r') as thetextfile: for line in thetextfile: line = line.split() wordlist[line[0]] = line[1:] ``` That makes the dict values the (more convenient) list of remaining items. But, if you really wanted the "," string syntax that you have above, maybe: `...
How to extract contents of a csv file and place them in a dict file type without using csv module. [python]
[ "", "python", "string", "list", "dictionary", "io", "" ]
I really like using docstrings in Python to specify type parameters when projects get beyond a certain size. I'm having trouble finding a standard to use to specify that a parameter is a list of specific objects, e.g. in Haskell types I'd use [String] or [A]. Current standard (recognisable by PyCharm editor): ``` de...
In comments section of [PyCharm's manual](http://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html) there's a nice hint from developer: ``` #: :type: dict of (str, C) #: :type: list of str ``` It works for me pretty well. Now it makes me wonder what's the best way to document parametrized classes in Pyth...
As pointed out in the [PyCharm docs](https://www.jetbrains.com/help/pycharm/type-syntax-for-docstrings.html), *a* (legacy, pre-[PEP-484](https://www.python.org/dev/peps/pep-0484/)) way of doing this is using square brackets: > list[Foo]: List of Foo elements > > dict[Foo, Bar]: Dict from Foo to Bar `list of str`, as ...
How to specify that a parameter is a list of specific objects in Python docstrings
[ "", "python", "pycharm", "docstring", "" ]
Does the BeautifulSoup library for Python have any function that can take a list of nodes and return the lowest common ancestor? If not, has any of you ever implemented such a function and care to share it?
I think this is what you want, with link1 being one element and link2 being another; ``` link_1_parents = list(link1.parents)[::-1] link_2_parents = list(link2.parents)[::-1] common_parent = [x for x,y in zip(link_1_parents, link_2_parents) if x is y][-1] print common_parent print common_parent.name ``` It'll basic...
The accepted answer does not work if the distance from a tag in the input list to the lowest common ancestor is not the exact same for every nodes in the input. It also uses every ancestors of each node, which is unnecessary and could be very expensive in some cases. ``` import collections def lowest_common_ancestor(...
BeautifulSoup lowest common ancestor
[ "", "python", "algorithm", "graph", "beautifulsoup", "" ]
I've been trying to generate a working regex that finds attributes of html tags for a while now but they all seem to fail one way or another. Using regex because loading beautifulsoup takes too long for just checking one html tag. Here is an example of the tag/property which needs to be checked: ``` <meta content="h...
# Description This expression will * find the meta tag which has an attribute `property="og:image"` * avoid some really difficult edge cases * capture the value of the content attribute * allow the attributes to appear in any order `<meta(?=\s|>)(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\sproperty=(?:'og:image|"...
Have you actually benchmarked it and found that BeautifulSoup was the bottleneck? ``` content = soup.find('meta', property='og:image').get('content') ``` You could also use [lxml](http://lxml.de/), which is much faster: ``` import lxml.html root = lxml.html.fromstring(html) # Use .parse() on a file-like object ins...
Regex in python that finds the attribute of some HTML tag?
[ "", "python", "regex", "beautifulsoup", "" ]
Today I have encountered an odd issue with ISNULL function in SQL I have table contains the customer information I have to display a full name concatenating First, Middle Initial and Last Name, In the table I know Middle Initial is a nullable column. So I used ISNULL function in SQL to return the Middle Initial if it...
– Original statement ``` SELECT FirstName + ' ' + LastName + ' '+ ISNULL(MI + '.', '') As MiddleInitial FROM CS_tblMaster WHERE CustomerNo = 2627240 ``` – My original answer (edited) ``` SELECT FirstName + ' ' + LastName + ' '+ (ISNULL(MI, '') + '.') As MiddleInitial FROM CS_tblMaster WHERE CustomerNo = 2627240 ``...
If you want to put a period if the MI is null use this: (You just have your `'.'` in the wrong spot) ``` SELECT FirstName + ' ' + LastName + ' '+ ISNULL(MI, '.') As MiddleInitial FROM CS_tblMaster WHERE CustomerNo = 2627240 ```
ISNULL in SQL Server 2008
[ "", "sql", "sql-server-2008", "" ]
persons.CSV file looks like: ``` Firstname,Surname,Birth Year,Hobby John,Smith,1990,"tenis,piano" Andrew,Josh,1988,"surfing,art" ``` I would like that in program hobby will be represented as list not as string. How can I force to that DictReader? The python code I use look as follows: ``` import csv class Person(ob...
As you're reading the rows in, you need to `split()` the hobby field: ``` one_row = {'Birth Year': '1990', 'Hobby': 'tenis,piano', 'Surname': 'Smith', 'Firstname': 'John'} one_row['Hobby'] = one_row['Hobby'].split(',') one_row Out[7]: {'Birth Year': '1990', 'Firstname': 'John', 'Hobby': ['tenis', 'piano'], 'Surnam...
``` class MyDictReader(csv.DictReader): def next(self): if self.line_num == 0: # Used only for its side effect. self.fieldnames row = self.reader.next() self.line_num = self.reader.line_num # unlike the basic reader, we prefer not to return blanks, # ...
CSV DictReader, how to force a part in "" to be read as list not as string
[ "", "python", "oop", "csv", "" ]