Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have seen many questions on SO regarding this question but none is relevant to my scenario. I am nowhere near an SQL guy apart from doing basic CRUD operations. Hence I am quite stuck with this.
I have a table.
`myTable [rID, newsID, OrderPosition]` where;
```
rID is primaryKey int column,
newsID int is the ID of... | When inserting the row, you need to "move" the rows below to make the room for it. For example, inserting on a position 4 could be done like this:
```
DELETE FROM myTable WHERE OrderPosition = 10; -- If you want the keep the table from growing beyond 10 rows.
UPDATE myTable SET OrderPosition = OrderPosition + 1 WHERE ... | Something like this will work for you, I guess:
```
CREATE PROC uspMyTableInsert
(
@newsID INT, @order int
)
AS
BEGIN
UPDATE MyTable
SET OrderPosition = OrderPosition + 1
WHERE OrderPosition >= @Order;
INSERT INTO MyTable VALUES (@newsID, @order);
DELETE FROM dbo.myTable WHERE OrderPosition ... | Re-ordering rows based on position SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
What is the easiest way to set Python 2.7 (and Django) up for web development under Windows 7 (64-bit) with Apache and MySQL?
I know I have to install Apache, MySQL, Python 2.7, Django and mod\_wsgi, but I don't understand dependencies, order of actions etc. Is there anyone who understands all this server/database/int... | > What is the easiest way to set Python 2.7 (and Django) up for web
> development under Windows 7 (64-bit) with Apache and MySQL?
The first thing you need to understand is for development on django you don't need Apache (or even MySQL) installed.
Here is a step-by-step guide (you need to have Administrator privileges... | The documentation (especially the tutorial) for Django, especially the tutorial, is really quite helpful. Among other things, it points out that there is absolutely no need to install any of Apache, mod\_wsgi or MySQL to get started - in fact there is no reason at all to install Apache/mod\_wsgi on your development mac... | Setting up Python for web development on Windows | [
"",
"python",
"python-2.7",
""
] |
OK, teaching python to the kids. We just wrote our first little program:
```
b = 0
for a in range (1, 10)
b = b + 1
print a, b
```
Stops at 9, 9. They asked "why is that" and I can't say that I know the answer.
My code *always* involves files, and my "for row in reader" doesn't stop one line short, so I don'... | This is just how python's `range` works. Quote from [docs](http://docs.python.org/2/library/functions.html#range):
> This is a versatile function to create lists containing arithmetic
> progressions. It is most often used in for loops. The arguments must
> be plain integers. If the step argument is omitted, it default... | It's just usually more useful than the alternatives.
* `range(10)` returns exactly 10 items (if you want to repeat something 10 times)
* `range(10)` returns exactly the indices in a list of 10 items
* `range(0, 5) + range(5, 10) == range(0, 10)`, which makes it easier to reason about ranges | Why does range in python "stop short"? | [
"",
"python",
"range",
""
] |
Hi guys I have this code here where outputs two column, 1 column is 1-30 and the other 1 is 30 days before today.
```
DECLARE @StartDate date
SELECT @StartDate = GETDATE()
;WITH cte AS (
SELECT
1 AS idx,
DATEADD(d,-1,@StartDate) AS idxDate
UNION ALL
SELECT idx -1, DATEADD(d,-1,idxDate)
... | You mean like this:
```
DECLARE @StartDate date
SELECT @StartDate = GETDATE();
WITH cte AS
(
SELECT -1 AS idx, DATEADD(d,-1,@StartDate) AS idxDate
UNION ALL
SELECT idx -1, DATEADD(d,-1,idxDate)
FROM cte
WHERE idx >-30
)
SELECT idx DateValue, CONVERT(VARCHAR(10),idxDate,110) + ', ' + CAST(i... | add
```
order by DateValue desc
```
to the end of your query. | add number before dates on visual studio | [
"",
"sql",
"t-sql",
"visual-studio-2008",
""
] |
The context is splitting a list of integers into their own even and odd lists.
```
even = []
odd = []
for i in my_list:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
```
Is there a way to turn the above into a nice, compact list comprehension..? | Not without using side effects and throwing away the result. You can do this though:
```
even = []
odd = []
for i in my_list:
(odd if i % 2 else even).append(i)
```
This problem in general is called *partitioning* the list, you can find [some solutions](https://stackoverflow.com/questions/4578590/python-equivalen... | Not really, you can hack something up using sideeffects, but this is not what list comprehensions are for
```
>>> even = []
>>> odd = []
>>> [(odd if i%2 else even).append(i) for i in range(10)]
[None, None, None, None, None, None, None, None, None, None] # it's a waste to make this list
>>> even
[0, 2, 4, 6, 8]
>>> o... | Is it possible to compile results into unique lists from inside of a comprehension? | [
"",
"python",
""
] |
I have a SQL query that is causing me trouble. The SQL That I have so far is the following:
```
SELECT Dated, [Level 1 reason], SUM(Duration) AS Mins
FROM Downtime
GROUP BY Dated, [Level 1 reason]
```
Now the problem I am having is that the results include multiple reasons, rather than being grouped together as I req... | In Access you ace use the [`DateValue`](http://office.microsoft.com/en-us/access-help/datevalue-function-HA001228814.aspx) function to remove the time from a date column:
```
SELECT DateValue(Dated) Dated, [Level 1 reason], SUM(Duration) AS Mins
FROM Downtime
GROUP BY DateValue(Dated), [Level 1 reason]
``` | It seems like you want to remove the time component. How to do that varies between database systems. In SQL Server it would be:
```
SELECT DATEADD(day,DATEDIFF(day,0,Dated),0), [Level 1 reason],
SUM(Duration) AS Mins
FROM Downtime
GROUP BY DATEADD(day,DATEDIFF(day,0,Dated),0), [Level 1 reason]
```
This works b... | SQL Simple Group By causing duplicates sections | [
"",
"sql",
"ms-access",
""
] |
I'm trying to write to a model in the GAE datastore that will have three fields: date, integer, integer.
```
class fusSent(db.Model):
""" Models a list of the follow-ups due and follow-ups sent """
date_created = db.DateTimeProperty(auto_now_add=True)
fu_date = db.DateProperty()
fus_due = db.IntegerPro... | I hope `fus_d` and `fus_s` dictionaries actually have dates, because your example of `2013-01-01` is actually a math expression that evals to `2011`. But the following should work
```
s = set(fus_d.keys())
s.update(fus_s.keys())
fu_list = [(k, fus_d.get(k), fus_s.get(k)) for k in s]
```
---
Edit: Also with python 2.... | Improving @cmd answer.
In order to write to the database, you should construct a list of model instances and call `db.put` to save them into the database, like this:
```
fus_d = {'2013-01-01': 1, '2013-04-01': 1, '2013-02-01': 1, '2013-03-01': 1}
fus_s = {'2013-01-01': 0, '2013-04-01': 0, '2013-02-01': 1, '2013-03-01... | How can I create a list from two dictionaries? | [
"",
"python",
"list",
"google-app-engine",
"dictionary",
"google-cloud-datastore",
""
] |
I am new to OOPS
I want to know when a Parent Class instance `P` is initialized and I want to initialize a child class instance `C`
like
```
class A(object):
def __init__(self):
print "A created"
P = A()
class B(A):
def __init__(self):
print super((B), self).__init__ # Q1: How to get "A cre... | ```
class A(object):
def __init__(self):
print "A created"
class B(A):
def __init__(self):
super(B, self).__init__() # Q1: How to get "A created" from parent class?
b = B()
--output:--
A created
```
> I want to create z as a sub-instance of P i.e. z should only be
> created if an earlier in... | You are not calling `__init__` in `B`. Using the name of the function just gives you that function object. The brackets after `__init__()` actually execute the function.
`super(B, self)` returns a class, not an object (which makes sense - a class doesn't have a superinstance, it has a superclass), so you then call `__... | Python: Child instance class of an instance of Parent Class | [
"",
"python",
"class",
"oop",
"python-2.7",
""
] |
I used **pymongo** to dump a list of collections in MongoDB. The length of the list is greater than 10000, about 12000 or longer(The length of the list is not a certain number).
However, I need only 10000 instances of the list. I know that a list **'l'** is able to slice by `l[:10000]` or `l[len(l)-10000:]`. But I thi... | Shuffle the list first and then slice it:
```
from random import shuffle
shuffle(your_lis)
your_lis = your_lis[:10000]
```
If order matters:
```
from random import randrange
diff = len(your_lis) - 10000
for _ in xrange(diff):
ind = randrange(len(your_lis))
your_lis.pop(ind) #a quick timing check suggests th... | If you want to keep order, you can remove random indexes, for instance:
```
def remove_random(l, count):
for i in range(count):
index = random.randint(0, len(l) - 1)
del l[index]
```
This function will remove up to `count` items from list `l`. | How to delete random items in a list to keep the list in a certain length? | [
"",
"python",
"algorithm",
"list",
"random",
""
] |
I have a column that can have either `NULL` or empty space (i.e. `''`) values. I would like to replace both of those values with a valid value like `'UNKNOWN'`. The various solutions I have found suggest modifying the value within the table itself. However, this is not an option in this case in that the database is for... | Try this
```
COALESCE(NULLIF(Address.COUNTRY,''), 'United States')
``` | Sounds like you want a view instead of altering actual table data.
```
Coalesce(NullIf(rtrim(Address.Country),''),'United States')
```
This will force your column to be null if it is actually an empty string (or blank string) and then the coalesce will have a null to work with. | Replacing NULL and empty string within Select statement | [
"",
"sql",
"t-sql",
""
] |
I have a datetime object with integer number of seconds (ex: `2010-04-16 16:51:23`). I am using the following command to extract exact time
```
dt = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S.%f
```
(generically, I have decimals (ex: `2010-04-16 16:51:23.1456`) but sometimes I don't. So when I run this comma... | It's because you don't have the format you specified. You have the format:
```
'%Y-%m-%d %H:%M:%S'
```
There are multiple solutions. First, always generate the data in the same format (adding `.00` if you need to).
A second solution is that you `try` to decode in one format and if you fail, you decode using the othe... | Another way avoiding using the exception handling mechanism is to default the field if not present and just try processing with the one format string:
```
from datetime import datetime
s = '2010-04-16 16:51:23.123'
dt, secs = s.partition('.')[::2]
print datetime.strptime('{}.{}'.format(dt, secs or '0'), '%Y-%m-%d %H:... | Datetime format does not match | [
"",
"python",
""
] |
I have an html file that has instances of:
```
<p>[CR][LF]
Here is the text etc
```
and:
```
...here is the last part of the text.[CR][LF]
</p>
```
where `[CR]` and `[LF]` represent carriage returns and new lines resp.
These paragraphs are within divs with a specific class eg `my_class`.
I want to target the para... | `p.string.strip()` will remove leading, trailing spaces.
`p.string.replaceWith(NEW_STRING)` will replace the text of p tag to NEW\_STRING.
```
from bs4 import BeautifulSoup
with open('file.html', 'r') as f:
html_file_as_string = f.read()
soup = BeautifulSoup(html_file_as_string, "lxml")
for div in soup.find_all(... | You need to check if the first and last content element of your `p` is a text node (an instance of `bs4.NavigableString`, which is a subclass of `str`). This should work:
```
from bs4 import BeautifulSoup, NavigableString
import re
html_file_as_string = """
<p>test1</p>
<p>
test2</p>
<p>test3
</p>
<p></p>
<p>
test... | How to perform re substitutions on <p> tags within a specific class? | [
"",
"python",
"regex",
"python-2.7",
"beautifulsoup",
""
] |
I'm trying to grab any text outside of brackets with a regex.
**Example string**
> Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith
> [2560 OAK ST, GLENMEADE, WI 14098]
I'm able to get the text *inside* the square brackets successfully with:
```
addrs = re.findall(r"\[(.*?)\]", example_str)
prin... | If there are no nested brackets, you can just do this:
```
re.findall(r'(.*?)\[.*?\]', example_str)
```
---
However, you don't even really need a regex here. Just split on brackets:
```
(s.split(']')[-1] for s in example_str.split('['))
```
---
The only reason your attempt didn't work:
```
re.findall(r"(.*?)\[.*... | If there are never nested brackets:
```
([^[\]]+)(?:$|\[)
```
Example:
```
>>> import re
>>> s = 'Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]'
>>> re.findall(r'([^[\]]+)(?:$|\[)', s)
['Josie Smith ', 'Mugsy Dog Smith ']
```
Explanation:
```
([^[\]]+) # ... | regex to get all text outside of brackets | [
"",
"python",
"regex",
""
] |
Today I solved a problem given in [Project Euler](http://projecteuler.net/), it's [problem number 10](http://projecteuler.net/problem=10) and it took **7 hrs** for my python program to show the result.
But in that forum itself a person named *lassevk* posted solution for this and it took only **4 sec**.
And its not pos... | Question:
> Find the sum of all the primes below two million.
It's a simple [sieve](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes). You should read about it but the general idea is to iterate over each number - if the value at index number is `0`, it's prime and you mark off multiples of that number (since all t... | The code is basically using the [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) to find primes, which might be clearer once you take out the code that keeps track of the sum:
```
marked = [0] * 2000000
value = 3
while value < 2000000:
if marked[value] == 0:
i = value
whi... | Explanation needed for sum of prime below n numbers | [
"",
"python",
"algorithm",
"primes",
""
] |
Hi I'd like to get a table from a database, but include the field names so I can use them from column headings in e.g. Pandas where I don't necessarily know all the field names in advance
so if my database looks like
`table test1`
```
a | b | c
---+---+---
1 | 2 | 3
1 | 2 | 3
1 | 2 | 3
1 | 2 | 3
1 | 2 | 3
```... | The column names are available as `cr.description[0][0]`, `cr.description[1][0]`, etc. If you want it in exactly the format you show, you need to do some work to extract it and stick it in front of the result set. | If what you want is a dataframe with the data from the db table as its values and the dataframe column names being the field names you read in from the db, then this should do what you want:
```
import psycopg2 as pq
cn = pq.connect('dbname=mydb user=me')
cr = cn.cursor()
cr.execute('SELECT * FROM test1;')
tmp = cr.fe... | Python psycopg2 postgres select columns including field names | [
"",
"python",
"postgresql",
"psycopg2",
""
] |
I want to write a script to automatically setup a brand new ubuntu installation and install a django-based app. Since the script will be run on a new server, the Python script needs to automatically install some required modules.
Here is the script.
```
#!/usr/bin/env python
import subprocess
import os
import sys
d... | I solved my problem using the [`imp`](http://docs.python.org/2/library/imp.html) module.
```
#!/usr/bin/env python
import pip
import imp
def install_and_load(package):
pip.main(['install', package])
path = '/usr/local/lib/python2.7/dist-packages'
if path not in sys.path:
sys.path.append(path)
... | You can import pip instead of using subprocess:
```
import pip
def install(package):
pip.main(['install', package])
# Example
if __name__ == '__main__':
try:
import pexpect
except ImportError:
install('pexpect')
import pexpect
```
Another take:
```
import pip
def import_with_au... | How to install and import Python modules at runtime | [
"",
"python",
"linux",
"subprocess",
""
] |
I am trying to install python. Or actually, have installed and deinstalled it a few times now. I am using pythonxy with the spyder IDE (i am used to matlab is why i want to use spyder). The 3.3.2 python would not even start with spyder on my win8 machine, so now I have the 2.7 version installed.
Spyder starts up now, ... | (Spyder dev here) I'm almost sure your problem is because of a firewall issue. It seems your firewall is too strict and it's blocking all attempts to try to open a port for our purposes.
To avoid blocking the full application while evaluating stuff, we run our python interpreter on a different process than the one Spy... | Following Carlos Cordoba's answer, I did the following (using Ubuntu 15.10):
1-) Disabled the firewall
```
sudo ufw disable
```
2-) Reset spyder and applied default settings:
```
spyder --reset
spyder --default
```
3-) Ran Spyder again
```
spyder
```
4-) Enabled the firewall
```
sudo ufw enable
```
And it is w... | 'import sitecustomize' failed upon starting spyder | [
"",
"python",
"installation",
"spyder",
""
] |
I'm trying to use Python to generate a collection of HTML tables with values pulled from a CSV. The script is working fine, however it's adding in odd " " characters wherever a value is pulled in.
This is the code I used to grab the CSV data:
```
import csv
import fileinput
import re
out=open("audiencestats.csv","r... | There's nothing wrong with your data—it's pure ASCII. The problem is in your source code.
Clicking the Edit button to copy your actual source, rather than your formatted source, it's got non-breaking space (U+00A0) characters in the middle of the `template` string literal.
Assuming your editor and the browser you cop... | You still haven't answered the questions I asked to clarify this, so I'm going to take a guess here.
First, the reason your `re.sub` doesn't work is that your pattern is a UTF-8 ` ` (`'\xc2\xac\xe2\x80\xa0'`), but you're trying to match a cp1252 ` ` (`'\xac\x86'`). Obviously, those don't match.
Second, the reason y... | Python Inserting Unwanted Characters | [
"",
"python",
"html",
"regex",
"html-table",
"import-from-csv",
""
] |
i am trying to use split() by reading using readlines(). My portion of the code is follows:
```
with contextlib.nested(open("inpfile","r"), open("numberAmpdus", "w")) as (inf, ouf):
line = inf.readlines()
ampdu = line.split()
```
Is this not the way to apply split after reading lines using readlines()? While ... | `file.readlines()` returns a list of all lines, lists don't have any `split` method that's why you're getting that error.
```
lines = inf.readlines()
```
If you're trying to apply `str.split` to each item of `lines` then you have to iterate over this list and apply `str.split` to each item one by one.
```
ampdu = [x... | Try this:
```
with contextlib.nested(open("inpfile","r"), open("numberAmpdus", "w")) as (inf, ouf):
lines = inf.readlines()
for line in lines:
ampdu = line.split()
``` | split() after file.readines() giving an error | [
"",
"python",
""
] |
This is kind of a part two to [a previous question](https://stackoverflow.com/questions/17242718/counting-new-customers-per-month) I asked and already got an answer for.
There I had wanted a count of all new customers per month, per year. Now I want to actually see a list of who is new, by email address (but I don't r... | The following query gets you the first order date for each customer:
```
select email, min(orderdate) as FirstOrderDate
from orders o
group by email;
```
To get the count of new customers by month:
```
select year(FirstOrderDate) as yr, month(FirstOrderDate) as mon, count(*)
from (select email, min(orderdate) as Fir... | ```
SELECT MIN(OrderDate) AS MOD FROM dbo.tblOrders;
```
gives you the smalest OrderDate in your table.
```
SELECT Email, MIN(OrderDate) AS MOD
FROM dbo.tblOrders
GROUP BY Email;
```
gives you the first order's date per unique email address.
```
SELECT Email, MIN(OrderDate) AS MOD
FROM dbo.tblOrders
GROUP BY Emai... | Listing New Customers Per Month | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a list `L` containing sorted numbers.
I have a number `x`, arbitrary. I wish to find the largest number from `L` that is `<= x`. I can do this with a loop but curious if there is a Pythonic one-liner or fancy function for this. | Use [`bisect`](http://docs.python.org/2/library/bisect.html) module. The complexity of this approach is `O(LogN)` compared to a simple loop which is `O(N)`.
```
>>> import bisect
def solve(lis, item):
ind = bisect.bisect_right(lis, item, hi = len(lis)-1)
return lis[ind] if lis[ind] <= item else lis[ind-1]
>... | The fastest you can do this is to use [`bisect.bisect_left`](http://docs.python.org/2/library/bisect.html#bisect.bisect_left):
```
>>> r = range(300)
>>> import bisect
>>> r[bisect.bisect_left(r,280)]
280
```
This results in an algorithm which takes O(log(N)) operations (on average) whereas the straight loop will tak... | Finding the max number <= some other number | [
"",
"python",
"list",
""
] |
I would like to download file over `HTTP` protocol using `urllib3`.
I have managed to do this using following code:
```
url = 'http://url_to_a_file'
connection_pool = urllib3.PoolManager()
resp = connection_pool.request('GET',url )
f = open(filename, 'wb')
f.write(resp.data)
f.close()
resp.release_conn()
```
B... | Your code snippet is close. Two things worth noting:
1. If you're using `resp.data`, it will consume the entire response and return the connection (you don't need to `resp.release_conn()` manually). This is fine if you're cool with holding the data in-memory.
2. You could use `resp.read(amt)` which will stream the res... | The most correct way to do this is probably to get a file-like object that represents the HTTP response and copy it to a real file using shutil.copyfileobj as below:
```
url = 'http://url_to_a_file'
c = urllib3.PoolManager()
with c.request('GET',url, preload_content=False) as resp, open(filename, 'wb') as out_file:
... | What's the best way to download file using urllib3 | [
"",
"python",
"download",
"urllib3",
""
] |
I cannot figure out to solve this problem:
```
class Clazz:
EMPTY=Clazz1(None,None)
def __init__(self):
self.item=Clazz1("a","b")
class Clazz1:
def __init__(self,key,value):
self.key=key
self.value=value
if __name__=='__main__':
h=Clazz()
```
When I try to run it returns :
`... | `Clazz1` has to be defined before `Clazz`:
```
class Clazz1:
def __init__(self, key, value):
self.key = key
self.value = value
class Clazz:
EMPTY = Clazz1(None, None)
def __init__(self):
self.item = Clazz1("a", "b")
if __name__ == '__main__':
h = Clazz()
``` | You should put the Clazz1 definition before the Clazz.
If You don't do this Clazz can't see the Clazz1 | How assign to a class attribute an instance from another class residing on the same module | [
"",
"python",
""
] |
This is what I have...
```
SELECT COUNT(DISTINCT customer_number)
FROM leads
WHERE ( dealer_id = '75'
OR dealer_id = '76'
OR dealer_id = '77'
OR dealer_id = '78'
OR dealer_id = '70'
OR dealer_id = '2692'
OR dealer_id = '2693' )
AND date BETWEEN '201... | I believe you want `SELECT COUNT(DISTINCT customer_number)`
Try this query
```
SELECT COUNT(DISTINCT customer_number)
FROM leads
WHERE ( dealer_id = '75'
OR dealer_id = '76'
OR dealer_id = '77'
OR dealer_id = '78'
OR dealer_id = '70'
OR dealer_id = '2692'
... | or maybe...
```
SELECT COUNT(DISTINCT customer_number)
FROM leads
LEFT
JOIN leads xleads
ON xleads.customer_number = leads.customer_number
AND xleads.date < '2013-04-01'
WHERE leads.dealer_id IN(75,76,77,78,70,2692,2693)
AND leads.date BETWEEN '2013-04-01' AND '2013-04-06'
AND xleads.cust... | Select count for a date range where the data is NOT IN the rest of the table | [
"",
"mysql",
"sql",
""
] |
If I have a table like that :
```
ID MANAGER_ID NAME
1 2 Ahmed
2 3 Mostafa
3 NULL Mohamed
4 1 Abbas
5 3 Abdallah
```
If I wanted a sql statement ... | The question is a little trickier than it seems at first glance:
```
select Name
from t
where id in (select manager_id from t)
```
The query seems to require some sort of self-join, because the information about who is a manager is in the `manager_id` column. This does the self-join using `in` in the `where` clause | You just need
```
SELECT NAME from table_name
```
I just realized that you want it only where the Manager is NULL,
```
SELECT NAME from table_name WHERE MANAGER_ID IS NOT NULL
```
As I have been pointed out this will exude manager 3 because he is a manager as he manages other users. See @Gordon's answer. | SELECT in Table (SQL) | [
"",
"mysql",
"sql",
"database",
""
] |
I have a group of items that are labeled like `item_labels = [('a', 3), ('b', 2), ('c', 1), ('d', 3), ('e', 2), ('f', 3)]`
I want to sort them by the size of group. e.g., label 3 has size 3 and label 2 has size 2 in the above example.
I tried using a combination of `groupby` and `sorted` but didn't work.
```
In [162... | In python2.7 and above, use Counter:
```
from collections import Counter
c = Counter(y for _, y in item_labels)
item_labels.sort(key=lambda t : c[t[1]])
```
In python2.6, for our purpose, this `Counter` constructor can be implemented using `defaultdict` (as suggested by @perreal) this way:
```
from collections impor... | ```
from collections import defaultdict
import operator
l=[('c', 1), ('b', 2), ('e', 2), ('a', 3), ('d', 3), ('f', 3)]
d=defaultdict(int)
for p in l: d[p[1]] += 1
print [ p for i in sorted(d.iteritems(), key=operator.itemgetter(1))
for p in l if p[1] == i[1] ]
``` | Python list sort by size of group | [
"",
"python",
"python-2.6",
"python-itertools",
"sorting",
""
] |
I think I have a basic question here that many might have encountered. When I run a query in SQL Server it will load in memory all the data it needs for query execution (for example, if there is a join then it would load the necessary data from those two tables) but when the query finishes executing the memory consumed... | SQL Server is indeed designed to request as much RAM as possible which will not be released unless this memory is explicitly required by the operating system. I think the best approach is to limit the amount of RAM the server can use which will allow the OS to have a set amount of resources to use no-matter-what. To se... | I too faced same issue mentioned above.
But running below query in releasing the RAM memory but in less than 5 hour the RAM memory is getting occupied. So again i have to forcefully free the RAM memory.
```
EXEC sys.sp_configure N’show advanced options’, N’1' RECONFIGURE WITH OVERRIDE
GO
EXEC sys.sp_configure N’max se... | SQL Server not releasing memory after query executes | [
"",
"sql",
"sql-server-2008",
"memory-management",
""
] |
I have a situation in which I'm asked to read collections of database update instructions from a variety of sources. All sources will contain a primary key value so that the code that applies the updates to the database can find the correct record. The files will vary, however, in what additional columns are reported.
... | I don't see anything particularly wrong with your implementation. however, `1` isn't necessarily the best sentinel value as it is a cached constant in Cpython. (e.g. `-1+2 is 1` will return `True`). In these cases, I might consider using a sentinel object instance:
```
NotInFile = object()
```
python also provides a ... | No, using the integer one is a bad idea. It might work out in this case if `MiddleName` is always a string or `None`, but in general the implementation is free to intern integers, strings, tuples and other immutable values as it pleases. CPython does it for small integers and constants of the aforementioned types. PyPy... | Defining my own None-like Python constant | [
"",
"python",
"singleton",
"constants",
""
] |
Im new to python so please forgive my Noob-ness. Im trying to create a status bar at the bottom of my app window, but it seems every time I use the pack() and grid() methods together in the same file, the main app window doesn't open. When I comment out the line that says statusbar.pack(side = BOTTOM, fill = X) my app ... | You cannot use both `pack` and `grid` on widgets that have the same master. The first one will adjust the size of the widget. The other will see the change, and resize everything to fit it's own constraints. The first will see these changes and resize everything again to fit *its* constraints. The other will see the ch... | Yeah thats right. In following example, i have divided my program into 2 frames. frame1 caters towards menu/toolbar and uses pack() methods wherein frame2 is used to make login page credentials and uses grid() methods.
```
from tkinter import *
def donothing():
print ('IT WORKED')
root=Tk()
root.title(string='LOG... | python pack() and grid() methods together | [
"",
"python",
"grid",
"tkinter",
"pack",
""
] |
I am trying to run a shell command from within my Python (version 2.6.5) code, but it is generating different output than the same command run within the shell (bash):
bash:
```
~> ifconfig eth0 | sed -rn 's/inet addr:(([0-9]{1,3}\.){3}[0-9]{1,3}).*/\1/p' | sed 's/^[ \t]*//;s/[ \t]*$//'
192.168.1.10
```
Python:
`... | The reason your code is not working is that you're not escaping enough. You escaped the quotes, but nothing else that needed to be escaped.
Let's look at your intended command line:
```
ifconfig eth0 | sed -rn 's/inet addr:(([0-9]{1,3}\.){3}[0-9]{1,3}).*/\1/p' | sed 's/^[ \t]*//;s/[ \t]*$//'
```
And print out your... | In python if you use double quotes around the string then you can use single quotes within that string with no need for escaping and vice versa. However, and backslashes will need to be escaped with an additional \ prefix.
Probably your best bet for debugging this would be to add:
```
print cmd_string
```
just after... | Unexpected output using subprocess in Python | [
"",
"python",
"bash",
"subprocess",
""
] |
I am looking into gstreamer as a means to choose a video device from a list to feed it to an opencv script.
I absolutely do not understand how to use gstreamer with python in windows. I installed the **Windows gstreamer 1.07 binaries** from the [gstreamer official website](http://gstreamer.freedesktop.org/). However, ... | This is a bit late, but hopefully it will help.
The easiest way to use GStreamer 1.0 is to download the latest version from:
<http://sourceforge.net/projects/pygobjectwin32/files/>
This will install Python (2.7 or 3.3) modules and, optionally, GStreamer with plugins.
However, if you already have GStreamer 0.10 SDK (... | Step 1: Windows 8.1 64-bit
Step 2: Download and Install Python
```
C:\>wget https://www.python.org/ftp/python/2.7.9/python-2.7.9.amd64.msi
C:\>./python-2.7.9.amd64.msi
C:\>cd C:\Python27
C:\>pwd
C:\Python27
```
Step 3: Download install Python bindings for Gstreamer 1.0
```
C:\>wget http://sourceforge.net/projects/p... | gstreamer python bindings for windows | [
"",
"python",
"windows",
"gstreamer",
"python-gstreamer",
""
] |
I have the following table
```
# amount type
1 10 0
1 10 0
1 5 1
1 5 1
2 10 0
2 10 0
2 5 1
2 5 1
```
*where 0 means cash and 1 means credit in the type column*
The problem is to find the total of cash usages and credit usages an... | ```
SELECT id,
SUM(CASE WHEN type = 0 THEN amount ELSE 0 END) as "cash",
SUM(CASE WHEN type = 1 THEN amount ELSE 0 END) as "credit",
SUM(amount) as "total"
FROM your_table
GROUP BY id
``` | ```
SELECT
num,
SUM(CASE WHEN type=0 THEN amount END) cash,
SUM(CASE WHEN type=1 THEN amount END) credit,
SUM(amount) total
FROM
yourtable
GROUP BY num
``` | How to build that query (sum,group by) | [
"",
"sql",
"group-by",
"sum",
""
] |
I have calculated a number of new columns in my query and I was wondering if it is possible to save the query results into a new table/sheet. So when I open the new table I can see the query results without having to re-run the query every time upon opening SQL.
Here is the code I am using:
```
SELECT a.[CUSIP NUMBER... | ```
SELECT a.[CUSIP NUMBER],
...
INTO newTable
FROM DBO.mbs032013 a
...
``` | Yes, the syntax is shown here: <http://www.w3schools.com/sql/sql_select_into.asp>
```
SELECT *
INTO newtable [IN externaldb]
FROM table1;
``` | SQL: Creating a new table with query results | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I was trying to fetch the `count(*)` from the table, which has almost 7 million records and it taking more than an hour for returning the result.
Also the table has 153 columns out of which index has been created for column 123, so tried to run the following query in parallel, but it didn't help.
```
select /*+ paral... | Counting the number of rows of large table takes long time. It's natural. Some DBMS stores the number of records, however, this kinds of DBMS limits concurrency. It should lock the entire table before DML operation on the table. (The entire table lock is necessary to update the count properly.)
The value in `ALL_TABLE... | A few issues to mention:
1. For "select count(\*) from table" to use an index, the indexed column must be non-nullable, or the index must be a bitmap type.
2. If there are known to be no nulls in the column but there is no not null constraint on it, then use "select count(\*) from table where column\_name is not null"... | Oracle count (*) is taking too much time | [
"",
"sql",
"performance",
"oracle",
""
] |
I'm trying to implement a redirecting pattern, similar to what StackOverflow does:
```
@route('/<int:id>/<username>/')
@route('/<int:id>/')
def profile(id, username=None):
user = User.query.get_or_404(id)
if user.clean_username != username:
return redirect(url_for('profile', id=id, username=user.clean... | ### debugging routes:
Update: to address the primary question "what's wrong with my routes", the simplest way to debug that is to use `app.url_map`; e.g:
```
>>> app.url_map
Map([<Rule '/user/<id>/<username>/' (HEAD, OPTIONS, GET) -> profile>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
<Rule '/user... | You've almost got it. `defaults` is what you want. Here is how it works:
```
@route('/<int:id>/<username>/')
@route('/<int:id>/', defaults={'username': None})
def profile(id, username):
user = User.query.get_or_404(id)
if username is None or user.clean_username != username:
return redirect(url_for('pr... | Flask redirecting multiple routes | [
"",
"python",
"redirect",
"routes",
"flask",
""
] |
What is the efficient way to read elements into a list and keep the list sorted apart from searching the place for a new element in the existing sorted list and inserting in there? | @Aswin's comment is interesting. If you are sorting each time you insert an item, the call to `sort()` is O(n) rather than the usual O(n\*log(n)). This is due to the way the sort(timsort) is implemented.
However on top of this, you'd need to shift a bunch of elements along the list to make space. This is also O(n), so... | Use a specialised data structure, in Python you have the [bisect](http://docs.python.org/2/library/bisect.html) module at your disposal:
> This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operatio... | how to keep a list sorted as you read elements | [
"",
"python",
"algorithm",
""
] |
Let's say I have a struct:
```
type User struct {
Name string
Id int
Score int
}
```
And a database table with the same schema. What's the easiest way to parse a database row into a struct? I've added an answer below but I'm not sure it's the best one. | Here's one way to do it - just assign all of the struct values manually in the `Scan` function.
```
func getUser(name string) (*User, error) {
var u User
// this calls sql.Open, etc.
db := getConnection()
// note the below syntax only works for postgres
err := db.QueryRow("SELECT * FROM users WHERE... | Go package tests often provide clues as to ways of doing things. For example, from [`database/sql/sql_test.go`](https://golang.org/src/database/sql/sql_test.go?h=TestQuery#L252),
```
func TestQuery(t *testing.T) {
/* . . . */
rows, err := db.Query("SELECT|people|age,name|")
if err != nil {
t.Fa... | How do I convert a database row into a struct | [
"",
"sql",
"go",
""
] |
I'm learning python and had a quick question.
I have to write a code to find the cube root, which I've done.
I want to give the user the option of calculating another cube root, or quitting.
Here's what I have come up with:
```
x = int(raw_input('Enter an integer: '))
## start guessing with 0
ans = 0
while ans*... | You can put all inside a function:
```
def my_func():
x = int(raw_input('Enter an integer: '))
## start guessing with 0
ans = 0
while ans*ans*ans < abs(x):
ans = ans + 1
print 'current guess =', ans
print 'last guess = ', ans
print 'ans*ans*ans = ', ans*ans*ans
##if its a per... | As an alternative to the function route, you could do it in a while loop, though it would be cleaner to use functions. You could do:
```
choice = 'y'
while choice.lower() == 'y':
#code for the game
choice = raw_input ('run again? (y/n)')
``` | How to optionally repeat a program in python | [
"",
"python",
"loops",
"python-2.x",
""
] |
I'm creating a program that uses the Twisted module and callbacks.
However, I keep having problems because the asynchronous part goes wrecked.
I have learned (also from previous questions..) that the callbacks will be executed at a certain point, but this is unpredictable.
However, I have a certain program that goes ... | Maybe what you're looking for is `twisted.internet.defer.gatherResults`:
```
d = gatherResults([calc(a), calc2(b), calc3(c)])
def calculated((j, i, f)):
if s:
return combine(i, j, f)
d.addCallback(calculated)
```
However, this still has the problem that `s` is undefined. I can't quite tell how you expect ... | You have to put `if` in the callback. You may use `Deferred` to structure your callback. | Conditional if in asynchronous python program with twisted | [
"",
"python",
"python-2.7",
"twisted",
""
] |
Given this list:
```
['MIA', 'BOS', '08:17 AM', '-107', '-103', '08:17 AM', '+1 -111', '-1 +103', u'91', u'93']
```
I want to split `+1 -111`, `-1 +103` on the space for the result of:
```
['MIA', 'BOS', '08:17 AM', '-107', '-103', '08:17 AM', '+1', '-111', '-1', '+103', u'91', u'93']
```
This is the regex I will n... | Using your existing `re` you can use the following which flattens out the single element splits:
```
import re
from itertools import chain
some_list = ['MIA', 'BOS', '08:17 AM', '-107', '-103', '08:17 AM', '+1 -111', '-1 +103', u'91', u'93']
print list(chain.from_iterable(re.split('(?<=\d)\s(?=[-+]\d\d\d)', s) for s ... | not sure if this is the most efficient way, but:
```
output = []
for x in input:
if re.search('(?<=\d)\s(?=[-+]\d\d\d)', x):
output += x.split(" ")
```
should work. | How to split elements of list with regex | [
"",
"python",
"regex",
"python-2.7",
""
] |
I'd like to create a function that will print the sum and the position of the maximum value within a list of numbers, but I'm not sure how to go about doing so.. This is what I've started with so far:
I used some code off a similar question that was asked.
```
def maxvalpos(variables):
max = 0
for i in range... | Then give it one argument, or modify the definition.
```
print maxvalpos([4, 2, 5, 10])
```
or
```
def maxvalpos(*variables):
``` | The pythonic way of doing this:
```
my_list_sum=sum(my_list)
index_max=my_list.index(max(my_list))
```
This finds the sum of the list and the index of the maximum of the list
But the problem in your code is: You are sending four variables to the function and receiving only 1 variable. For that to work, use:
```
max... | Find the sum and position of the maximum value in a list | [
"",
"python",
"list",
"max",
""
] |
I have a line that i want to split into three parts:
```
line4 = 'http://www.example.org/lexicon#'+synset_offset+' http://www.monnetproject.eu/lemon#gloss '+gloss+''
```
The variable gloss contains full sentences, which I dont want to be split. How do I stop this from happening?
The final 3 split parts should be:
`... | I'm struggling to understand, but why not just create a list to start with:
```
line4 = [
'http://www.example.org/lexicon#' + synset_offset,
'http://www.monnetproject.eu/lemon#gloss',
gloss
]
```
Simplified example - instead of joining them all together, then splitting them out again, just join them prope... | ```
>>> synset_offset = "foobar"
>>> gloss = "This is a full sentence."
>>> line4 = 'http://www.example.org/lexicon#'+synset_offset+' http://www.monnetproject.eu/lemon#gloss '+gloss
>>> import string
>>> string.split(line4, maxsplit=2)
['http://www.example.org/lexicon#foobar', 'http://www.monnetproject.eu/lemon#gloss',... | How to split a line but keep a variable in the line unsplit in python | [
"",
"python",
""
] |
I am using Python (and have access to pandas, numpy, scipy).
I have two sets strings set A and set B. Each set A and B contains c. 2000 elements (each element being a string). The strings are around 50-100 characters long comprising up to c. 20 words (these sets may get much larger).
I wish to check if an member of s... | Firstly, 2000 \* 100 chars is'nt that big, you could use a set directly.
Secondly, *if your strings are sorted*, there is a quick way (which I found [here](http://www.skorks.com/2010/02/lets-roll-our-own-boolean-query-search-engine/))to compare them, as follows:
```
def compare(E1, E2):
i, j = 0, 0
I, J = len... | As mentioned in the comments:
```
def compare(A, B):
return list(set(A).intersection(B))
``` | Best way to compare two large sets of strings in Python | [
"",
"python",
"string",
"bloom-filter",
""
] |
I am trying to print several lists (equal length) as columns of an table.
I am reading data from a .txt file, and at the end of the code, I have 5 lists, which I would like to print as columns separated but space. | I'll show you a 3-list analog:
```
>>> l1 = ['a', 'b', 'c']
>>> l2 = ['1', '2', '3']
>>> l3 = ['x', 'y', 'z']
>>> for row in zip(l1, l2, l3):
... print ' '.join(row)
a 1 x
b 2 y
c 3 z
``` | You can use my package [beautifultable](https://github.com/pri22296/beautifultable) . It supports adding data by rows or columns or even mixing both the approaches. You can insert, remove, update any row or column.
## Usage
```
>>> from beautifultable import BeautifulTable
>>> table = BeautifulTable()
>>> table.colum... | Print list in table format in python | [
"",
"python",
"tabular",
""
] |
Although poorly written, this code:
```
marker_array = [['hard','2','soft'],['heavy','2','light'],['rock','2','feather'],['fast','3'], ['turtle','4','wet']]
marker_array_DS = []
for i in range(len(marker_array)):
if marker_array[i-1][1] != marker_array[i][1]:
marker_array_DS.append(marker_arra... | ```
from collections import defaultdict
d1 = defaultdict(list)
d2 = defaultdict(list)
for pxa in marker_array:
d1[pxa[1]].extend(pxa[:1])
d2[pxa[1]].extend(pxa[2:])
res = [[' '.join(d1[x]), x, ' '.join(d2[x])] for x in sorted(d1)]
```
If you really need 2-tuples (which I think is unlikely):
```
for p in res:... | Quick stab at it... use `itertools.groupby` to do the grouping for you, but do it over a generator that converts the 2 element list into a 3 element.
```
from itertools import groupby
from operator import itemgetter
marker_array = [['hard','2','soft'],['heavy','2','light'],['rock','2','feather'],['fast','3'], ['turtl... | Merge nested list items based on a repeating value | [
"",
"python",
"list",
""
] |
I have a list of tuples, as shown below:
```
[
(1, "red")
(1, "red,green")
(1, "green,blue")
(2, "green")
(2, "yellow,blue")
]
```
I am trying to roll up the data, so that I can get the following dict output:
```
{
1: ["red", "green", "blue"]
2: ["green", "yellow", "blue"]
}
```
Notes ar... | You can use `collections.defaultdict`:
```
>>> from collections import defaultdict
>>> lis = [
(1, "red"),
(1, "red,green"),
(1, "green,blue"),
(2, "green"),
(2, "yellow,blue"),
]
>>> dic = defaultdict(set) #sets only contain unique items
for k, v in lis:
dic[k... | Another solution without defaultdict.
```
>>> input = [
... (1, "red"),
... (1, "red,green"),
... (1, "green,blue"),
... (2, "green"),
... (2, "yellow,blue")
... ]
>>> result1 = {s[0]: set(s[1].split(',')) for s in input}
>>> for num, cols in input:
... result1[num].update(cols.split(','))
... ... | Can I group / aggregate elements in a list (or dict) comprehension? | [
"",
"python",
"list-comprehension",
""
] |
I come from a PHP (as well as a bunch of other stuff) background and I am playing around with Python. In PHP when I want to include another file I just do `include` or `require` and everything in that file is included.
But it seems the recommended way to do stuff in python is `from file import` but that seems to be mo... | Things are totally different between PHP and Python, and there are many reasons why.
> But it seems the recommended way to do stuff in python is `from file import` but that seems to be more for including libraries and stuff?
Indeed, `import` statements are for importing objects from another module to current module. ... | I guess I understand what you are tring to say and to do.
Here is the random include example from PHP:
File #1 - vars.php
```
<?php
$color = 'green';
$fruit = 'apple';
?>
```
File #2 - main.php
```
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
```
The fis... | Little confused with import python | [
"",
"python",
"python-2.7",
"import",
"module",
""
] |
I have two columns in a file which is in the format below:
```
00:01:02 aa:bb:cc 1
03:04:05 dd:ee:ff 2
```
and so on....
I want to make a key by combining first and second columns and make 3rd column as value. I am trying in this way. This is the only partial code:
```
maindict = dict()
lines = inf.readline... | Your `ampdu` is a list of lists, so when you use `join` you're trying to join the first and second lines of the file. Try iterating through that list to get each line individually.
```
for columns in ampdu:
```
Also you can use a tuple instead of a join to make a key.
```
ckey = (columns[0], columns[1])
``` | Your `ampdu` is a list of lists:
```
ampdu = [x.split() for x in lines]
```
so your `ampdu[0]` is actually the first line of your file, `ampdu[1]` your second, etc.
The reason why you're getting a `TypeError: unhashable type: list` is because dictionary requires their keys to be hashable [documentation](http://docs.... | Making both columns of a line as a dictionary key | [
"",
"python",
""
] |
I have found [this](https://stackoverflow.com/questions/4566327/python-logger-logging-things-twice-to-console) answer to a seemingly similar issue, however (since I'm novice into Python) I am not sure how to implement this solution in my code (if it's the same issue after all).
In my code I have the following section:... | It seems that I have figured out the source of this problem.
The thing is that I used to get logger at module level. It looked pretty logical but there is a pitfall – Python logging module respects all created logger before you load the configuration from a file. So basically, when I was importing a module(which uses ... | Typically duplicate log statements occur because there are two separate handlers attached that are directing your log statements to the same place. There are a couple of things worth trying to get to the root of the problem:
1. Comment out the call to logging.basicConfig - if this eliminates the duplicate log statemen... | Logging messages appear twice in console Python | [
"",
"python",
"logging",
"jython",
""
] |
Is there a way I can take a screenshot of the right half of my pygame window?
I'm making a game using pygame and I need to take a snapshot of the screen but not the whole screen, just the right half.
I know of:
```
pygame.image.save(screen,"screenshot.jpg")
```
But that will include the entire screen in the image.
... | If you always want the screenshot to be of the same portion of the screen, you could use the `subsurface`.
<http://www.pygame.org/docs/ref/surface.html#pygame.Surface.subsurface>
```
rect = pygame.Rect(25, 25, 100, 50)
sub = screen.subsurface(rect)
pygame.image.save(sub, "screenshot.jpg")
```
The `subsurface` would w... | This didn't exactly work on my system with Python 3.7.4. Here is a version which worked:
```
rect = pygame.Rect(25, 25, 100, 50)
sub = screen.subsurface(rect)
screenshot = pygame.Surface((100, 50))
screenshot.blit(sub, (0,0))
pygame.image.save(screenshot, "screenshot.jpg")
``` | How to take screenshot of certain part of screen in Pygame | [
"",
"python",
"pygame",
"screenshot",
"crop",
""
] |
I am trying to list all the courses for a person, where the course code doesn't start with a 'C'. The following code is still bring up 'C-...' codes. Any idea how to fix it?
```
SELECT u.idnumber, u.firstname, u.lastname, r.id, c.idnumber AS m_name, c.id AS c_id
FROM mdl_user u
LEFT JOIN mdl_role_assignments r ON u.... | Just put the `NOT`just before the `LIKE`:
```
... c.id NOT LIKE 'C%'
``` | You not like syntax is not correct use it:
```
SELECT u.idnumber,u.firstname,u.lastname,r.id,c.idnumber AS m_name,c.id AS c_id
FROM mdl_user u
LEFT JOIN mdl_role_assignments r ON u.id = r.userid
LEFT JOIN mdl_context c1 ON r.contextid = c1.id
LEFT JOIN mdl_course c ON c1.inst... | NOT LIKE clause not working in SQL | [
"",
"mysql",
"sql",
"moodle",
"sql-like",
""
] |
I used the following code to read from a text file line by line and print it on screen.
```
with open("source.txt") as f:
content = f.readlines()
print(content)
print('\n')
f.close()
```
But the `\n` was just getting appended to the output and the output was coming in a single line instead. For example if... | You can use [`rstrip()`](http://docs.python.org/2/library/stdtypes.html#str.rstrip):
```
>>> for i in content:
... print i.rstrip()
...
abc
def
ghi
```
The problem with your code is that it isn't doing what you would expect it to do. `content` is a list, and printing the list would just have `['abc\n', etc]`. Yo... | You should do it this way:
```
with open('source.txt', 'r') as f:
for line in f: #iterate over lines
line = line.strip() #removes whitespaces and new lines
print line #print the line, the print function adds new line
```
readlines() loads the whole file in memory and if the file is bigger than you... | Next line escape character not working python | [
"",
"python",
"macos",
"unix",
""
] |
I'm trying to dynamically create an MS SQL query based on query string parameters.
I'm currently using variables that request the values of any valid query string parameters: if the parameter isn't empty, then that variable forms part of the SQL statement. If it is empty, the variable remains blank.
For example:
```... | You can use `null` parameters:
```
select *
from items
where (@name is null or item_name like '%' + @name + '%')
and (@price is null or item_price < @price)";
```
Then you would add the parameters, and specify a `null` value for those that haven't been given, this will make that part of the WHERE statement not filt... | Personally, [Lasse V. Karlsen](https://stackoverflow.com/users/267/lasse-v-karlsen)'s approach is what I tend to use, although I've got one application where I use dynamic SQL to generate a more efficient query based on what the user wants to do (i.e., less joins when I can get away with it) . If you really have your h... | Forming a dynamic SQL statement using query string parameters in ASP.NET | [
"",
"asp.net",
"sql",
"sql-server-2008",
""
] |
I'm using Django 1.5.1, Python 3.3.x, and can't use raw queries for this.
Is there a way to get a QuerySet grouped by weekday, for a QuerySet that uses a date `__range` filter? I'm trying to group results by weekday, for a query that ranges between any two dates (could be as much as a year apart). I know how to [get r... | Since `extra` is deprecated, here is a new way of grouping on the day of the week using [ExtractDayOfWeek](https://docs.djangoproject.com/en/1.10/_modules/django/db/models/functions/datetime/).
```
from django.db.models.functions import ExtractWeekDay
YourObjects.objects
.annotate(weekday=ExtractWeekDay('timestamp... | Well man I did an algorithm this one brings you all the records since the beginning of the week (Monday) until today
for example if you have a model like this in your app:
```
from django.db import models
class x(models.Model):
date = models.DateField()
from datetime import datetime
from myapp.models import... | Django Group By Weekday? | [
"",
"python",
"django",
"python-3.x",
"django-1.5",
""
] |
With my data I have individuals taking an assessment multiple times at different dates. It looks something like this:
```
╔════════╦═══════════╦═══════════╦═══════╗
║ Person ║ ID Number ║ Date ║ Score ║
║ John ║ 134 ║ 7/11/2013 ║ 18 ║
║ John ║ 134 ║ 8/23/2013 ║ 16 ║
║ John ║ 134 ║ 9/... | ```
select *
, datediff(day, min(Date) over (partition by [ID Number]), Date)
from YourTable
```
[Live example at SQL Fiddle.](http://sqlfiddle.com/#!3/b58cd/2/0) | I like Andomar's answer, but if you wanted to find both days between and total days since first you could do this:
```
SELECT a.*
,ISNULL(DATEDIFF(day,b.Date,a.Date),0)'Since Previous'
,datediff(day, min(a.Date) over (partition by a.[ID Number]), a.Date)'Since First'
FROM (select *,ROW_NUMBER() OVER(P... | SQL: Calculating Number of Days Between Dates of One Column In Different Rows | [
"",
"sql",
"sql-server",
""
] |
```
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
def scrabble_score(word):
count=0
word.lower()
... | This modified code will work:
```
def scrabble_score(word):
count=0
word = word.lower() #assign the result of word.lower() to word
```
`word.lower()` returns the modified word, it doesn't modify the string *inplace*. Strings are ***immutable*** in Python. The fact that `.lower()` returns a string is defined a... | [`str.lower()`](http://docs.python.org/2/library/string.html#string.lower) returns a copy of the string - it does not change the original string. Try this:
```
word = word.lower()
``` | This code snippet is not working for both upper case and lower case letters | [
"",
"python",
""
] |
I've found quite a few questions that appear identical to this - but despite my best efforts I'm not able to get any of the solutions to work.
I'm trying to print extended-ascii characters to make an old text-based menu. Here is my original code:
```
print('╔════════════════════════════════════╗')
print('║ ... | There must be a better way, but how about something like this:
```
dic = {
'\\' : b'\xe2\x95\x9a',
'-' : b'\xe2\x95\x90',
'/' : b'\xe2\x95\x9d',
'|' : b'\xe2\x95\x91',
'+' : b'\xe2\x95\x94',
'%' : b'\xe2\x95\x97',
}
def decode(x):
return (''.join(dic.get(i, i.encode('utf-8')).decode('utf-8') for i in x))
pr... | With Python 3 and its Unicode strings, your original code should work just fine as long as you follow these rules:
* Save your file in an encoding that supports the characters.
* Declare source encoding via `#coding: <encoding>` if it is not the UTF-8 default.
* The default console encoding supports the characters.
* ... | Printing Extended-Ascii Characters In Python 3 In Both Windows and Linux | [
"",
"python",
"python-3.x",
"ascii",
""
] |
the following code worked until today when I imported from a Windows machine and got this error:
**new-line character seen in unquoted field - do you need to open the file in universal-newline mode?**
```
import csv
class CSV:
def __init__(self, file=None):
self.file = file
def read_file(self):
... | It'll be good to see the csv file itself, but this might work for you, give it a try, replace:
```
file_read = csv.reader(self.file)
```
with:
```
file_read = csv.reader(self.file, dialect=csv.excel_tab)
```
Or, open a file with `universal newline mode` and pass it to `csv.reader`, like:
```
reader = csv.reader(op... | I realize this is an old post, but I ran into the same problem and don't see the correct answer so I will give it a try
Python Error:
```
_csv.Error: new-line character seen in unquoted field
```
Caused by trying to read Macintosh (pre OS X formatted) CSV files. These are text files that use CR for end of line. If u... | CSV new-line character seen in unquoted field error | [
"",
"python",
"django",
"csv",
""
] |
Despite the advice from the previous questions:
[-9999 as missing value with numpy.genfromtxt()](https://stackoverflow.com/questions/12274709/9999-as-missing-value-with-numpy-genfromtxt)
[Using genfromtxt to import csv data with missing values in numpy](https://stackoverflow.com/questions/3761103/using-genfromtxt-to-... | The issue is that numpy doesn't like ragged arrays. Since there is no character in the third position of the last row of the file, so genfromtxt doesn't even know it's something to parse, let alone what to do with it. If the missing value had a filler (any filler) such as:
```
1 2 3
4 5 6
7 8 ''
```
Then you'd be abl... | Using [pandas](http://pandas.pydata.org/):
```
import pandas as pd
df = pd.read_table('data', sep='\s+', header=None)
df.fillna(0, inplace=True)
print(df)
# 0 1 2
# 0 1 2 3
# 1 4 5 6
# 2 7 8 0
```
`pandas.read_table` replaces missing data with `NaN`s. You can replace those `NaN`s with some other value ... | Filling missing values using numpy.genfromtxt | [
"",
"python",
"parsing",
"numpy",
"genfromtxt",
""
] |
I have a table called `Houses` on an sql server database that has a column containing (Danish) addresses. In Denmark the street name always comes before the house number and then the apartment information if it's an apartment. I want to separate the street name and the number into two strings and disregard the apartmen... | Here is a solution:
```
SELECT *
,LEFT(Address,PATINDEX('% [0-9]%',Address)-1)'Street'
, SUBSTRING(Address,PATINDEX('% [0-9]%',Address)+1,PATINDEX('%[0-9],%',Address+ ',')-PATINDEX('% [0-9]%',Address))'House Number'
FROM T
```
Demo: [SQL Fiddle](http://sqlfiddle.com/#!3/ac3cc/1/0)
UPDATE: If house nu... | Try something like this:
```
SELECT
CASE WHEN a.NumStart> 0 then LEFT(a.Adresse, a.NumStart-1) ELSE a.Adresse END as Vejnavn,
Substring(a.adress, a.Numstart, a.Comma - a.Numstart + 1) as HouseNumber
FROM (
SELECT
PATINDEX('%[0-9]%', Adress) as [NumStart],
CHARINDEX(',', Adress + ',') as Comma,
Adr... | Separating an address string in SQL | [
"",
"sql",
"sql-server",
"string",
""
] |
I had a program that read in a text file and took out the necessary variables for serialization into turtle format and storing in an RDF graph. The code I had was crude and I was advised to separate it into functions. As I am new to Python, I had no idea how to do this. Below is some of the functions of the program.
I... | You question is mainly a question about what object oriented programming is. I will try to explain quickly, but I recommend reading a proper tutorial on it like
<http://www.voidspace.org.uk/python/articles/OOP.shtml>
<http://net.tutsplus.com/tutorials/python-tutorials/python-from-scratch-object-oriented-programming/>
a... | First, I suggest you figure out the basic functional decomposition on its own - don't worry about writing a class at all.
For example,
```
def split_pointer_part(self, before_at, after_at, line):
before_at, after_at = line.split('@', 1)
return before_at, after_at
```
doesn't touch any instance variables (it ... | Running multiple functions in Python | [
"",
"python",
""
] |
I have a large dataframe with 423244 lines. I want to split this in to 4. I tried the following code which gave an error? `ValueError: array split does not result in an equal division`
```
for item in np.split(df, 4):
print item
```
How to split this dataframe in to 4 groups? | Use [`np.array_split`](https://numpy.org/doc/stable/reference/generated/numpy.array_split.html):
```
Docstring:
Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that ... | I wanted to do the same, and I had first problems with the split function, then problems with installing pandas 0.15.2, so I went back to my old version, and wrote a little function that works very well. I hope this can help!
```
# input - df: a Dataframe, chunkSize: the chunk size
# output - a list of DataFrame
# pur... | Split a large pandas dataframe | [
"",
"python",
"pandas",
""
] |
I currently have two options to store some images on the blobstore.
I have a User model `class User(db.Model)` ,where I am saving an avatar for the user.
One option is to save the avatar as `blobstore.BlobReferenceProperty()` and then serve the image with get\_serving\_url from the user.avatar reference.
```
class Us... | You should store both. The `BlobReference` to be able to delete the actual blob and the URL in order to avoid calling every time the `get_serving_url()`, which can be potentially slow. The URL that is returned by [`get_serving_url()`](https://developers.google.com/appengine/docs/python/images/functions#Image_get_servin... | You should save both references in your model. You use the blobReferenceProperty to reference the latest version of the blob for maintenance (delete and update) and the url for serving the image, because you only need to get the serving url once. | Proper way of storing blob images on GAE | [
"",
"python",
"google-app-engine",
""
] |
In python, i have a function that returns a list of the latest links(to folders) on a website. I also have another function that downloads the latest files from those folders. I plan to run this script everyday. I have a global list with the folder links that the download function accesses everytime it runs for the lat... | Use `global` statement. But there's no need of `global` for mutable objects, if you're modifying them in-place.
You can use modules like [`pickle`](http://docs.python.org/2/library/pickle.html) to store your list in a file. You can load the list when you want to use it and store it back after doing your modifications.... | Normal declaration of the variable will make it local.
Use global keyword to make it render as global.
Just write the list to a file and access it read it from there later.
If you don't want to self run the code you can use cron-job to do it for you.
```
def read_file(filename):
f = open(filename).read().split... | how to update global variable in python | [
"",
"python",
"list",
"function",
"global",
""
] |
My query is as follows:
```
Select h.ord_no
from sales_history_header h
INNER JOIN sales_history_detail d
ON d.NUMBER = h.NUMBER
WHERE d.COMMENTS LIKE '%3838CS%'
```
And I get no results as shown here :

But I should get results because :
I ran t... | I think this is because you have different data type for number in both table | Your query is returning nothing because the execution engine is using an index that is incorrectly referenced by this specific application (Sage BusinessVision) you have to work around the issue.
# Explanation:
The issue you are having is related to the way BusinessVision created the index **index** of the table SALE... | Query returning nothing | [
"",
"sql",
"pervasive",
"pervasive-sql",
""
] |
I have input values in the format of string (separated with comma).
```
customerID = "1,2,3,4,5"
```
How I can insert these value into the column `cutomerID` of temp customer table? | Thanks Devart. This is one more alternate solution. Thanks all for helping me out.
```
DECLARE @customerID varchar(max) = Null ;
SET @customerID= '1,2,3,4,5'
DECLARE @tempTble Table (
customerID varchar(25) NULL);
while len(@customerID ) > 0
begin
insert into @tempTble (customerID ) value... | Try this one -
**Query:**
```
DECLARE @customerID VARCHAR(20)
SELECT @customerID = '1,2,3,4,5'
SELECT customerID = t.c.value('@s', 'INT')
FROM (
SELECT field = CAST('<t s = "' +
REPLACE(
@customerID + ','
, ','
, '" /><t s = "') + '" />' AS XML)
) d
CROS... | insert separated comma values into sql table | [
"",
"mysql",
"sql",
"sql-server",
"database",
""
] |
So here's my dilema... I'm writing a script that reads all .png files from a folder and then converts them to a number of different dimensions which I have specified in a list. Everything works as it should except it quits after handling one image.
Here is my code:
```
sizeFormats = ["1024x1024", "114x114", "40x40", ... | Why not keep it simple:
```
for image in folderToResizeContents:
for fmt in sizeFormats:
(w,h) = fmt.split('x')
```
**N.B. You are overwriting the files produced as you are not changing the name of the outpath.** | Nest your for loops and you can apply all 7 dimensions to each image
```
for image in folderToResizeContents:
for w,h in zip(widthList,heightList):
```
the first for loop will ensure it happens for each image, whereas the second for loop will ensure that the image is resized to each size | How to loop through one element of a zip() function twice - Python | [
"",
"python",
"image",
"loops",
"resize",
"zip",
""
] |
Given this base date:
```
base_date = "10/29 06:58 AM"
```
I want to find a tuple within the list that contains the closest date to the `base_date`, but it must not be an earlier date.
```
list_date = [('10/30 02:18 PM', '-103', '-107'), ('10/30 02:17 PM', '+100', '-110'), \
('10/29 02:15 AM', '-101', '... | ```
>>> from datetime import timedelta, datetime
>>> base_date = "10/29 06:58 AM"
>>> b_d = datetime.strptime(base_date, "%m/%d %I:%M %p")
def func(x):
d = datetime.strptime(x[0], "%m/%d %I:%M %p")
delta = d - b_d if d > b_d else timedelta.max
return delta
...
>>> min(list_date, key = func)
('10/30 02:17... | This can be done using `datetime` module, which is able to parse date string into datetime object, which supports comparison and arithmetic with dates:
```
from datetime import datetime
# function for parsing strings using specific format
get_datetime = lambda s: datetime.strptime(s, "%m/%d %I:%M %p")
base = get_dat... | Getting the closest date to a given date | [
"",
"python",
"date",
"python-2.7",
""
] |
If a python string is immutable, how can it be changed as follows:
```
a = "abc"
print a
a = "cde"
print a
```
Outputs:
```
abc
cde
```
Is this actually creating a new variable and changed a to point to that instead? | Python strings *are* immutable. What you're doing is just reassigning the `a` variable with two different strings, that has nothing to do with immutability.
In the code shown no new variables are being created, there's just `a`. And in the assignments, `a` is pointed to a different string each time. To see that string... | * Yes, in Python, strings are immutable
* Your code is not creating a new variable
* Your code assigns the variable `a` a reference to another string | Python are strings immutable | [
"",
"python",
""
] |
For example, I have 100 pictures whose resolution is the same, and I want to merge them into one picture. For the final picture, the RGB value of each pixel is the average of the 100 pictures' at that position. I know the `getdata` function can work in this situation, but is there a simpler and faster way to do this in... | Let's assume that your images are all .png files and they are all stored in the current working directory. The python code below will do what you want. As Ignacio suggests, using numpy along with PIL is the key here. You just need to be a little bit careful about switching between integer and float arrays when building... | I find it difficult to imagine a situation where memory is an issue here, but in the (unlikely) event that you absolutely cannot afford to create the array of floats required for my [original answer](https://stackoverflow.com/a/17383621/2015542), you could use PIL's blend function, [as suggested](https://stackoverflow.... | How to get an average picture from 100 pictures using PIL? | [
"",
"python",
"image",
"python-imaging-library",
""
] |
I'm trying to mock a class function which uses a c extension class inside it as follows, but I get `TypeError: can't set attributes of built-in/extension type 'y.cExtensionClass'`.
code.py is a legacy code, and I really rather not to change it. Any suggestion?
code.py:
```
from x.y import cExtensionClass
class CodeC... | Patch `code.cExtensionClass` (not `x.y.cExtensionClass`).
Do `import code` instead of `from code cExtensionClass`.
```
import unittest
from mock import patch, Mock
import code
class test(unittest.TestCase):
def test_code_function(self):
with patch('code.cExtensionClass') as m:
m.return_value... | You can try the [forbidden fruit](http://clarete.github.io/forbiddenfruit/)
# Forbidden Fruit

> This project aims to help you reach heaven while writing tests, but it
> may lead you to hell if used on production code.
>
> It basically allows you to... | In Python, how to mock a c extension class? | [
"",
"python",
"testing",
"mocking",
"typeerror",
""
] |
in this code I am trying to create a function anti\_vowel that will remove all vowels (aeiouAEIOU) from a string. I think it *should* work ok, but when I run it, the sample text "Hey look Words!" is returned as "Hy lk Words!". It "forgets" to remove the last 'o'. How can this be?
```
text = "Hey look Words!"
def anti... | You're modifying the list you're iterating over, which is bound to result in some unintuitive behavior. Instead, make a copy of the list so you don't remove elements from what you're iterating through.
```
for char in textlist[:]: #shallow copy of the list
# etc
```
---
To clarify the behavior you're seeing, che... | Other answers tell you why `for` skips items as you alter the list. This answer tells you how you should remove characters in a string without an explicit loop, instead.
Use [`str.translate()`](http://docs.python.org/2/library/stdtypes.html#str.translate):
```
vowels = 'aeiou'
vowels += vowels.upper()
text.translate(... | Loop "Forgets" to Remove Some Items | [
"",
"python",
"string",
"list",
""
] |
Is there a way in Flask to send the response to the client and then continue doing some processing? I have a few book-keeping tasks which are to be done, but I don't want to keep the client waiting.
Note that these are actually really fast things I wish to do, thus creating a new thread, or using a queue, isn't really... | Sadly teardown callbacks do not execute after the response has been returned to the client:
```
import flask
import time
app = flask.Flask("after_response")
@app.teardown_request
def teardown(request):
time.sleep(2)
print("teardown_request")
@app.route("/")
def home():
return "Success!\n"
if __name__ ==... | ***QUICK*** and ***EASY*** method.
We will use pythons ***Thread*** Library to acheive this.
Your API consumer has sent something to process and which is processed by ***my\_task()*** function which takes ***10 seconds*** to execute.
But the consumer of the API wants a response as soon as they hit your API which is *... | Flask end response and continue processing | [
"",
"python",
"flask",
""
] |
Previous question: [SQL query of relationship between two items from the same table](https://stackoverflow.com/questions/12993179/sql-query-of-relationship-between-two-items-from-the-same-table).
I'd like to be able to relate items from the same table with a join table. Similarly to question above but I was wondering ... | Sweet, doubly linked list with UNION instead of UNION ALL to handle already traveled entries seems to work fine.
```
INSERT INTO similars
(one_id, two_id)
VALUES
(1, 2),
(2, 1),
(1, 3),
(3, 1),
(3, 4),
(4, 3),
(6, 7),
(7, 6);
WITH RECURSIVE linked_list AS
(
SELECT * FROM entries WHERE name = 'Bicycle'
UNION
... | ```
select e.name as "Entry",
es.name as "Similar_To"
from entries e
inner join similars s
on e.id = s.one_id
inner join entries es
on s.two_id = es.id
```
Is that what you are looking for? | SQL query of related items from the same table | [
"",
"mysql",
"sql",
"postgresql",
""
] |
I'm a little new to Python and very new to Scrapy.
I've set up a spider to crawl and extract all the information I need. However, I need to pass a .txt file of URLs to the start\_urls variable.
For exmaple:
```
class LinkChecker(BaseSpider):
name = 'linkchecker'
start_urls = [] #Here I want the list to start... | Run your spider with `-a` option like:
```
scrapy crawl myspider -a filename=text.txt
```
Then read the file in the `__init__` method of the spider and define `start_urls`:
```
class MySpider(BaseSpider):
name = 'myspider'
def __init__(self, filename=None):
if filename:
with open(filenam... | you could simply read-in the .txt file:
```
with open('your_file.txt') as f:
start_urls = f.readlines()
```
if you end up with trailing newline characters, try:
```
with open('your_file.txt') as f:
start_urls = [url.strip() for url in f.readlines()]
```
Hope this helps | Pass Scrapy Spider a list of URLs to crawl via .txt file | [
"",
"python",
"web-scraping",
"command-line-arguments",
"scrapy",
""
] |
I'm still kinda new with Python, using Pandas, and I've got some issues debugging my Python script.
I've got the following warning message :
```
[...]\pandas\core\index.py:756: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
return self._engine... | You can [filter the warnings](http://docs.python.org/2/library/warnings.html#the-warnings-filter) to raise which will enable you to debug (e.g. using pdb):
```
import warnings
warnings.filterwarnings('error')
```
\*The [warnings filter](http://docs.python.org/2/library/warnings.html#warnings.filterwarnings) can be ma... | You can also use the commandline to control the warnings:
```
python -W error::UnicodeWarning your_code.py
```
From the man page:
> -W argument
> [...] **error** to raise an exception instead of printing a warning message.
This will have the same effect as putting the following in your code:
```
import warnings
... | How to find out where a Python Warning is from | [
"",
"python",
"debugging",
"warnings",
"pandas",
""
] |
I always use this query in sql server to get Row number in a table:
```
SELECT *
FROM (SELECT *,
Row_number()
OVER(
ORDER BY [myidentitycolumn]) RowID
FROM mytable) sub
WHERE rowid = 15
```
Now I am working in Access 2010 and this seems to be not working... | MS-Access doesn't support ROW\_NUMBER(). Use TOP 1:
```
SELECT TOP 1 *
FROM [MyTable]
ORDER BY [MyIdentityCOlumn]
```
If you need the 15th row - MS-Access has no simple, built-in, way to do this. You can simulate the rownumber by using reverse nested ordering to get this:
```
SELECT TOP 1 *
FROM (
SELECT TOP 15 *
... | Another way to assign a row number in a query is to use the `DCount` function.
```
SELECT *, DCount("[ID]","[mytable]","[ID]<=" & [ID]) AS row_id
FROM [mytable]
WHERE row_id=15
``` | Row numbers in query result using Microsoft Access | [
"",
"sql",
"ms-access",
""
] |
I'm a beginner in python. I'm not able to understand what the problem is?
```
def list_benefits():
s1 = "More organized code"
s2 = "More readable code"
s3 = "Easier code reuse"
s4 = "Allowing programmers to share and connect code together"
return s1,s2,s3,s4
def build_sentence... | You return four variables s1,s2,s3,s4 and receive them using a single variable `obj`. This is what is called a `tuple`, `obj` is associated with 4 values, the values of `s1,s2,s3,s4`. So, use index as you use in a list to get the value you want, in order.
```
obj=list_benefits()
print obj[0] + " is a benefit of functi... | You're returning a [`tuple`](http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange). Index it.
```
obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"
``` | AttributeError: 'tuple' object has no attribute | [
"",
"python",
"python-2.7",
""
] |
My python test code:
```
import socket
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s1.bind(('192.168.1.1', 80))
s1.listen(5)
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2.bind(('0.0.0.0', 80))
s2.listen(5)
```
I got this error:
```
fpemud-workstation test # ./test.py
Traceback (most recent... | You cannot bind to both 0.0.0.0:80 and any other IP on port 80, because 0.0.0.0 covers every IP that exists on the machine, including your 192.168.1.1 address. It doesn't mean 'any other destination address', it means 'all interfaces on this box'. | Because it's a contradiction in terms. 0.0.0.0 means 'accept connections from any local IP address'. 192.168.1.1 means 'accept connections only that are addressed to 192.168.1.1'. What exactly do you expect to happen if someone connects to 192.168.1.1? | why can't bind to 0.0.0.0:80 and 192.168.1.1:80 simultaneously? | [
"",
"python",
"linux",
"sockets",
""
] |
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods=["GET"])
app.add_url_rule('/<page>/',
view_func=Main.as_view('main'),
methods=["G... | Your view names need to be unique even if they are pointing to the same view method.
```
app.add_url_rule('/',
view_func=Main.as_view('main'),
methods = ['GET'])
app.add_url_rule('/<page>/',
view_func=Main.as_view('page'),
methods = ['GET'])
``` | This same issue happened to me when I had more than one API function in the module and tried to wrap each function with 2 decorators:
1. @app.route()
2. My custom @exception\_handler decorator
I got this same exception because I tried to wrap more than one function with those two decorators:
```
@app.route("/path1")... | AssertionError: View function mapping is overwriting an existing endpoint function: main | [
"",
"python",
"flask",
""
] |
I'm not sure that this is possible, but I'm trying to generate a number of thumbnails from pdfs in an automated way and then store them within elasticsearch. Basically I would like to convert the pdf to a series of jpgs (or pngs, or anything similar) and then index them as binaries. Currently I'm producing these jpgs l... | You can have it send the data to stdout instead...
```
import subprocess
params = ['convert', 'pdf_file', 'jpg:-']
image_data = subprocess.check_output(params)
``` | you can use imagemagick's [python API](http://www.imagemagick.org/download/python/), for example something like:
```
import PythonMagick
img = PythonMagick.Image("file.pdf")
img.depth = 8
img.magick = "RGB"
data = img.data
```
or use [wand](http://docs.wand-py.org/en/0.3-maintenance/):
```
from wand.image import Im... | Capture jpgs produced in subprocess in main script | [
"",
"python",
"image",
"pdf",
"thumbnails",
"stdout",
""
] |
This is some really simple code I am using with sqlalchemy and I am missing something basic here about how classes work.
```
class Game(Base):
__tablename__ = "games"
id = Column(Integer, primary_key=True)
a_name = Column(String)
def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
... | thanks for the comments. is it just me or is sqlalchemy kind of confusing?
anyway, as people have pointed out above the `__init__` method apparently is not called when you do a query.
> The SQLAlchemy ORM does not call `__init__` when recreating objects from
> database rows. The ORM’s process is somewhat akin to the ... | You're not creating a Game instance in your queries above, you only pass the Game class object. Hence the **init**() constructor is never called.
If you need a Game instance for query, you need this: `session.query(Game()).first().stuff`. | Python Class __init__ Not Working | [
"",
"python",
"class",
"sqlalchemy",
""
] |
This code snippet:
```
a = [3, 2, 1]
a.sort()
```
produces `[1, 2, 3]` list. Why
```
[3, 2, 1].sort()
```
doesn't produce the same result? Is there a "one-liner" to accomplish this? | You can use
`sorted_array = sorted([2,3,1])` | ```
>>> [3, 2, 1].sort()
```
It does sort this list object but as the number of references(variables pointing) to this list are **0**, so it is garbage collected.(i.e we can't access this list anymore)
Coming to your first question, `list.sort()` sorts a list in-place and returns `None`.
```
>>> a = [3, 2, 1]
>>> a.... | Why this Python expression doesn't produce expected result? | [
"",
"python",
"syntax",
"expression",
""
] |
I'm about to begin designing a database for an MVC web app and am considering using a table called 'changes' or 'events' to keep track of all changes made to the database. It would have a field for the table name, record id, user making the change, the timestamp and whether it was a creation or modification event.
My ... | This is a matter of weighing up the benefit of having the granular info against the overhead of writing to this table every time something in the database changes and the additional storage required.
If you are concerned about using a function on the model class then an alternative would be database triggers. This wou... | I think your approach is fine. One advantage of having these events in a separate table is you can capture *multiple* edits. If you just have `ModifiedDate/ModifiedBy` columns you only see the *last* edit.
The main thing to be aware of is table size since audit tables can get VERY big. You may also decide to split int... | Is it practical to record table creation/modificaion events in a separate table? | [
"",
"sql",
"model-view-controller",
"database-design",
""
] |
I'm working on a script that is renaming most of the folders in my database. Material is so sensitive that I really don't like the idea of playing around with the script in the original database. I would love the idea of copy the structure only and test the script with the simulated structure.
Got this idea after a ba... | Following code will duplicate structure of `a` to `b`.
```
import os
def dup_structure(src, dst):
os.makedirs(dst)
for p, ds, fs in os.walk(src):
for dn in ds:
dp = os.path.relpath(os.path.join(p, dn), src)
os.makedirs(os.path.join(dst, dp))
#for fn in fs:
# ... | I suggest you do this bit of shell script as part of the setup for the tests for your folder restructing program
```
cd /mytest/; find /folder/with/database -type d -print0 | xargs -0 mkdir -p
```
How it works:
chdir to the target you want the copy of the empty folders to go
The `find` command works with an absolute... | Simulate database structure | [
"",
"python",
"database",
"unix",
""
] |
I am facing a strange question, which despite of trying many times, i am not able to find the logic and proper code to the problem.
I have a file in the format below:
```
aa:bb:cc dd:ee:ff 100 ---------->line1
aa:bb:cc dd:ee:ff 101 ---------->line2
dd:ee:ff aa:bb:cc 230 ---------->line3
dd:ee:ff aa:bb:cc 231 ----... | ```
with open("abc") as f:
#read the first line and set the number from it as the value of `prev`
num, col4 = next(f).rsplit(None,2)[-2:] #use `str.rsplit` for minimum splits
prev = int(num)
col4_prev = col4
count = 1 #initialize `count` to 1
for lin in f:
... | ```
from collections import defaultdict
results = defaultdict(int)
for line in open("input_file.txt", "r"):
columns = line.split(" ")
key = " ".join(columns[:2])
results[key] += 1
with output_file = open("output_file.txt", "w"):
for key, count in results:
output_file.write("{0} -> {1}".format(ke... | Challenging way of counting entries of a file dynamically | [
"",
"python",
""
] |
```
Select * from Table
Date Value
2013-06-24 12
2013-06-24 3
2013-06-24 -4
2013-06-24 33
2013-06-25 12
2013-06-25 -2
2013-06-25 43
2013-06-25 1
2013-06-25 -3
```
and now I will count all negative, positive and zero values group by Date in one SQL-Command. | ```
SELECT
Date,
SUM(CASE WHEN Value > 0 THEN 1 ELSE 0 END) AS pos,
SUM(CASE WHEN Value < 0 THEN 1 ELSE 0 END) AS neg,
SUM(CASE WHEN Value = 0 THEN 1 ELSE 0 END) AS zero
FROM yourTable
GROUP BY Date
``` | You could;
```
select
DATE,
SUM(case when value < 0 then 1 else 0 end) as NEGATIVE,
SUM(case when value > 0 then 1 else 0 end) as POSITIVE,
SUM(case when value = 0 then 1 else 0 end) as ZERO
from
T
group by date
``` | SQL Select Count Values negative positive and zero values | [
"",
"sql",
"select",
"count",
""
] |
Say i have a table, `values`, which looks like:
```
id|field_id|value|date
1 |1 |2 |2013-06-01
2 |2 |5 |2013-06-01
3 |1 |3 |2013-06-02
4 |2 |9 |2013-06-02
5 |1 |6 |2013-06-03
6 |2 |4 |2013-06-03
```
And another table, `fields`, which looks like
```
id|code
1 |sma... | How about something like
```
SELECT *
FROM [values] v
WHERE EXISTS(
SELECT 1
FROM [values] vl
WHERE vl.FIELD_ID = 2
AND vl.date = v.date
AND vl.value < v.value
)
AND v.FIELD_ID = 1
```
## [SQL Fiddle DEMO](http://sqlfiddle.com/#!3/3073e/2)
Here is another possible example
```
SELECT *
FROM [values] vs I... | One way:
```
select [date],
max(case field_id when 1 then [value] end) small_value,
max(case field_id when 2 then [value] end) large_value
from [values]
group by [date]
having max(case field_id when 1 then [value] end) >
max(case field_id when 2 then [value] end)
```
SQLFiddle [here](http://sqlf... | SQL - Select rows where one column is greater than other column on the same date | [
"",
"sql",
"sql-server",
""
] |
Slowly transitioning from Matlab to Python...
I have this list of the form
```
list1 = [[1, 2, nan], [3, 7, 8], [1, 1, 1], [10, -1, nan]]
```
and another list with the same number of items
```
list2 = [1, 2, 3, 4]
```
I'm trying to extract the elements of list1 not containing any nan values, and the corresponding ... | You can use `zip`.
`zip` returns the items on the same index from the iterables passed to it.
```
>>> from math import isnan
>>> list1 = [[1, 2, 'nan'], [3, 7, 8], [1, 1, 1], [10, -1,'nan']]
>>> list2 = [1, 2, 3, 4]
>>> out = [(x,y) for x,y in zip(list1,list2)
if not any(isn... | You can simply do this:
```
ans = [(x,y) for x,y in zip(list1,list2) if all(~isnan(x))]
#[(array([ 3., 7., 8.]), 2), (array([ 1., 1., 1.]), 3)]
```
From where you can extract each value doing:
```
l1, l2 = zip(*ans)
#l1 = (array([ 3., 7., 8.]), array([ 1., 1., 1.]))
#l2 = (2,3)
```
Using `izip` from `ite... | List comprehension and logical indexing | [
"",
"python",
"list",
"matrix-indexing",
""
] |
This is a question asked here before more than once, however I couldn't find what I was looking for. I am looking for join two tables, where the joined table is set by the last register ordered by date time, until here all is ok.
My trouble start on having more than two records on the joined table, let me show you a s... | [**`DISTINCT ON`**](http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-DISTINCT) or is your friend. Here is a solution with *correct* syntax:
```
SELECT a.id, b.updated, b.col1, b.col2
FROM table_a as a
LEFT JOIN (
SELECT DISTINCT ON (table_a_id)
table_a_id, updated, col1, col2
... | You can use Postgres's `distinct on` syntax:
```
select a.id, b.*
from table_a as a left join
(select distinct on (table_a_id) table_a_id, . . .
from table_b
order by table_a_id, updated desc
) b
on a.id = b.table_a_id
```
Where the `. . .` is, you should put in the columns that you want. | SQL joined by last date | [
"",
"sql",
"postgresql",
"greatest-n-per-group",
""
] |
I have a vanilla pandas dataframe with an index. I need to check if the index is sorted. Preferably without sorting it again.
e.g. I can test an index to see if it is unique by index.is\_unique() is there a similar way for testing sorted? | How about:
`df.index.is_monotonic` | Just for the sake of completeness, this would be the procedure to check whether the dataframe index is monotonic increasing and also unique, and, if not, make it to be:
```
if not (df.index.is_monotonic_increasing and df.index.is_unique):
df.reset_index(inplace=True, drop=True)
```
> NOTE `df.index.is_monotonic_inc... | How can I check if a Pandas dataframe's index is sorted | [
"",
"python",
"pandas",
""
] |
Right now I have a sample ASP script below:
```
<%Set objConn = CreateObject("ADODB.Connection")
objConn.Open Application("WebUsersConnection")
sSQL="SELECT * FROM Users where Username=? & Request("user") & _"?and Password=? & Request("pwd") & "?
Set RS = objConn.Execute(sSQL)
If RS.EOF then
... | One of the problem of directly writing user input into a SQL query:
```
sSQL="SELECT * FROM Users where Username='" & Request("user") & "' and Password='" & Request("pwd") & "'"
```
is that if user submitted
```
username' OR 1=1 --
```
which makes your query eventually looks like this:
```
SELECT * FROM Users wher... | It is always good to use Regular Expressions to check for characters in the input (querystring / form variables / etc...) before you pass them onto your database for processing. The check should be done to see if all the characters in the input are within the allowed characters (whitelist check).
```
Function ReplaceR... | SQL Injection vulnerablities in ASP script | [
"",
"sql",
"asp-classic",
"sql-injection",
""
] |
Say I have the values:
```
Reference Class Timestamp
XXHAG70 11 2013-05-07 14:29:59.820
XXHAG70 11 2013-05-07 14:33:19.780
XXHAG70 17 2013-05-07 14:30:19.930
XXHAG70 17 2013-05-07 14:33:44.690
PAF7010 06 2008-11-06 10:25:07.140
PAF7010 06 2009-02-... | To get the oldest for each class/reference, use `MIN` and `GROUP BY`:
```
SELECT Reference, Class, MIN(Timestamp)
FROM myTable
GROUP BY Reference, Class
``` | You could use the row\_number function.
```
SELECT Reference ,
Class ,
Timestamp
FROM ( SELECT Reference ,
Class ,
Timestamp ,
ROW_NUMBER() OVER ( PARTITION BY Reference, Class ORDER BY Timestamp) AS rnum
FROM MyTable
... | Deleting one of a pair of values based on the date | [
"",
"sql",
"sql-server",
"algorithm",
"select",
""
] |
Using sample data:
```
df = pd.DataFrame({'key1' : ['a','a','b','b','a'],
'key2' : ['one', 'two', 'one', 'two', 'one'],
'data1' : np.random.randn(5),
'data2' : np. random.randn(5)})
```
df
```
data1 data2 key1 key2
0 0.361601 0.375297 a one
1 ... | First groupby the key1 column:
```
In [11]: g = df.groupby('key1')
```
and then for each group take the subDataFrame where key2 equals 'one' and sum the data1 column:
```
In [12]: g.apply(lambda x: x[x['key2'] == 'one']['data1'].sum())
Out[12]:
key1
a 0.093391
b 1.468194
dtype: float64
```
To explain wh... | I think that today with pandas 0.23 you can do this:
```
import numpy as np
df.assign(result = np.where(df['key2']=='one',df.data1,0))\
.groupby('key1').agg({'result':sum})
```
The advantage of this is that you can apply it to more than one column of the same dataframe
```
df.assign(
result1 = np.where(df['key... | Conditional Sum with Groupby | [
"",
"python",
"pandas",
"group-by",
""
] |
Thanks to some organizational oddities, my work team now has somewhat limited access to a random database, but we're not entirely sure what syntax we should be using with it. In an ideal world, we'd like it to be MySQL.
Can anyone describe or point me toward a set of table-creation and selection queries that will allo... | Try running the MySQL select version command:
```
SELECT VERSION()
```
<http://dev.mysql.com/doc/refman/5.0/en/installation-version.html>
Does it have to be a table creation and/or selection query or will the above work? | Each RDBMS has their respective protocol and client library. The client of one RDBMS generally won't work to connect to the wrong brand of RDBMS.
I would suggest you test connecting using the MySQL client. If that doesn't work, it isn't MySQL. :-)
---
Re comments:
MySQL does not restrict *syntax* based on privilege... | Test that I'm using MySQL syntax? | [
"",
"mysql",
"sql",
"unit-testing",
"syntax",
""
] |
Say I want to print like this:
```
print 1,"hello", 2, "fart"
```
but with tabs instead of spaces, what is the most pythonic way of doing this, in python 2?
It's a really silly question but I couldn't seem to find an answer! | Another approach is to **look towards the future!**
```
# Available since Python 2.6
from __future__ import print_function
# Now you can use Python 3's print
print(1, 'hello', 2, 'fart', sep='\t')
``` | Using `str.join`:
```
print '\t'.join(map(str, (1, "hello", 2, "fart")))
``` | Printing with tab separation instead of spaces | [
"",
"python",
"printing",
"tabs",
""
] |
After running this code in Python 3:
```
import pdb
def foo():
nums = [1, 2, 3]
a = 5
pdb.set_trace()
foo()
```
The following expressions work:
```
(Pdb) print(nums)
[1, 2, 3]
(Pdb) print(a)
5
(Pdb) [x for x in nums]
[1, 2, 3]
```
but the following expression fails:
```
(Pdb) [x*a for x in nums]
**... | if you type `interact` in your [i]pdb session, you get an interactive session, and list comprehensions do work as expected in this mode
source: <http://bugs.python.org/msg215963> | It works perfectly fine:
```
>>> import pdb
>>> def f(seq):
... pdb.set_trace()
...
>>> f([1,2,3])
--Return--
> <stdin>(2)f()->None
(Pdb) [x for x in seq]
[1, 2, 3]
(Pdb) [x in seq for x in seq]
[True, True, True]
```
Without showing what you are actually doing nobody can tell you why in your specific case you g... | Possible bug in pdb module in Python 3 when using list generators | [
"",
"python",
"python-3.x",
"generator",
"pdb",
"ipdb",
""
] |
I need to get driving time between two sets of coordinates using Python. The only wrappers for the Google Maps API I have been able to find either use Google Maps API V2 (deprecated) or do not have the functionality to provide driving time. I'm using this in a local application and do not want to be bound to using Java... | Using URL requests to the Google Distance Matrix API and a json interpreter you can do this:
```
import simplejson, urllib
orig_coord = orig_lat, orig_lng
dest_coord = dest_lat, dest_lng
url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins={0}&destinations={1}&mode=driving&language=en-EN&sensor=false... | ```
import googlemaps
from datetime import datetime
gmaps = googlemaps.Client(key='YOUR KEY')
now = datetime.now()
directions_result = gmaps.directions("18.997739, 72.841280",
"18.880253, 72.945137",
mode="driving",
... | Python Google Maps Driving Time | [
"",
"python",
"google-maps",
"google-maps-api-3",
""
] |
I'm refactoring a document processing app and I think I see an opportunity to substitute a query for a lot of code. A db table contains a row for each occurrence of a dictionary term in a document. A row contains the character position in the document of the first letter of the dictionary entry and a code number that i... | ```
select doc, code, min(pos) as pos
from t
group by doc, code
``` | ```
SELECT doc, MIN(pos),code
FROM Table1
group by doc, code
```
Demo: [SQL Fiddle](http://sqlfiddle.com/#!3/9cb8a/2/0) | Can this be done with a group by clause? | [
"",
"sql",
"group-by",
""
] |
I have an image encoded with base 64 that I want to store in my datastore model.
```
class Surveys(db.Model):
name = db.StringProperty(required = True)
text = db.TextProperty(required = True)
image = db.BlobProperty()
created = db.DateTimeProperty(auto_now_add = True)
```
How do I turn the base64 stri... | Are you looking for a way to decode base64 data?
You might wish to take a look at the various [base64 utilities](http://docs.python.org/2/library/base64.html) available with Python. For example, `base64.b64decode`:
```
import base64
binary_data = base64.b64decode(base64_encoded_string)
```
Assuming the JPEG file wa... | You can either store the base64 string to datastore directly, then decode it during runtime when you need to send the JPEG bytes.
Or do it the other way round... I'd prefer decode the base64 first before storing to datastore as it's more byte efficient and you only need to decode once.
And you don't need the concept ... | How to store base64 image as a file in GAE datastore | [
"",
"python",
"google-app-engine",
"base64",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.