Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm trying to compare terms/expressions which would (or not) be semantically related - these are not full sentences, and not necessarily single words; e.g. -
'Social networking service' and 'Social network' are clearly strongly related, but how to i quantify this using nltk?
Clearly i'm missing something as even the ... | There are some measures of semantic relatedness or similarity, but they're better defined for single words or single expressions in wordnet's lexicon - not for compounds of wordnet's lexical entries, as far as I know.
This is a nice web implementation of many similarity wordnet-based measures
* <http://wn-similarity.... | Here is a solution you can use.
```
w1 = wordnet.synsets('social')
w2 = wordnet.synsets('network')
```
w1 and w2 will have an array of synsets. Find the similarity between each synset of w1 with w2. The one with maximum similarity give you combined synset (which is what you are looking for).
Here is the fu... | Compare similarity of terms/expressions using NLTK? | [
"",
"python",
"nltk",
""
] |
I am trying to convert Mac OSX (HFS Plus) timestamps to human readable format with python (on a linux system).
HFS Plus timestamps represent the time in seconds since midnight Jan 1, 1904.
For example, the timestamp: **3453120824**
In human date time: **Mon, 03 Jun 2013 16:13:44 GMT**
Is there a python way to do th... | How about just using [datetime](http://docs.python.org/2/library/datetime.html) with [timedelta](http://docs.python.org/2/library/datetime.html#timedelta-objects)? You'll want to pay particular attention to the list of formatting characters [here](http://docs.python.org/2/library/datetime.html#strftime-and-strptime-beh... | You don't need datetime at all. Apple stores their times from the beginning of their time which is 2001-01-01. Super annoying but easy to overcome. Just add the difference between 1970-01-01 and 2001-01-01 in seconds to the variable and use time to format it like this in one line of code:
```
import time
mac_date = ti... | Convert Mac Timestamps with python | [
"",
"python",
"macos",
"datetime",
"timestamp",
""
] |
I'm building an stock exchange simulation game. I have a table called 'Market\_data' and in the game players simulate being in particular dates and are allowed to use SQL queries to retrieve the historical data and plan their course of action. My difficulty is that I need to limit the rows they can access based on the ... | **Solution is SQL Views, Views are used for several different reasons:**
\**1.*\*To hide data complexity. Instead of forcing your users to learn the T-SQL JOIN syntax you might wish to provide a view that runs a commonly requested SQL statement.
\**2.*\*To protect the data. If you have a table containing sensitive da... | 1)You can use mysql proxy <http://dev.mysql.com/downloads/mysql-proxy/> with custom rules restricting access.
2)You can use stored procedures/functions
3)You can use views | How can I allow users sql access to a table limited to certain rows? | [
"",
"mysql",
"sql",
"limit",
""
] |
I have a problem to decide whether to use a view or a temp table.
I have a stored procedure that i call from program. In that SP i store the result of a long query in a temp table, name the columns and make another queries on that table store the results in labels or a gridview or whatever and drop the Temp Table. I c... | If the query is "long" and you are accessing the results from multiple queries, then a temporary table is the better choice.
A view, in general, is just a short-cut for a `select` statement. If does not imply that the results are ever run and processed. If you use a view, the results will need to be regenerated each t... | **depends**
A view must replicate the processing of your "long query" each time it is run, while a temp table stores the results.
so do you want to use more processing or more storage?
You can store some view values (persistent index) which could help on processing, but you don't provide enough info to really explor... | View or Temporary Table - which to use in MS SQL Server? | [
"",
"sql",
"sql-server",
"view",
"temp-tables",
""
] |
Why does **list comprehension** have better performance than a **for** loop, in Python?
*list comprehension:*
```
new_items = [a for a in items if a > 10]
```
*for loop:*
```
new_items = []
for a in items:
if a > 10: new_items.append(a)
```
Are there other examples (not loops), where one Python structure has w... | Essentially, list comprehension and for loops does pretty similar things, with list comprehension doing away some overheads and making it look pretty.
To understand why this is faster, you should look in [Efficiency of list comprehensions](https://web.archive.org/web/20190319205826/http://blog.cdleary.com/2010/04/effic... | Assuming we're talking CPython here, you could use the [`dis`](http://docs.python.org/2/library/dis.html) module to compare the generated bytecodes:
```
>> def one():
return [a for a in items if a > 10]
>> def two():
res = []
for a in items:
if a > 10:
res.append(a)
>> ... | Python List Comprehension vs For | [
"",
"python",
""
] |
I have a Django project with several apps. My project is now getting to the point it needs an API. I'm planning to have the API on a different server using tastypie. However, the API will use the same models as the website.
So far I see my only option is as follows...
Copy the apps to the server which means I have tw... | I wouldn't recommend splitting your project like this.
Every time you edit a model you have to edit it on both immediately or risk things getting out of sync. This will get very very painful, instead;
**Is the server the bottleneck?** Split site and api machines (but using the same `models.py`) and share the connecti... | 1. For this to be meaningful, you likely need to connect to the same database
2. Why would you need two codebases? You have two copies of a single codebase. | Does a Django site with a Tastypie interface need two codebases? | [
"",
"python",
"django",
"web-applications",
""
] |
So, I need to sort this kind of list with some random data in it by first `element` of second nested list (with elements like `01, 02, 03`, etc):
```
[['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']], etc]
```
this random data is later used in defaultdict with some other data, in order t... | ```
lis = [['00553', ['01', '3.4']], ['00553', ['02', '2.1']],
['00551', ['02', '5.3']], ['00551', ['01', '5.3']],['00551', ['04', '5.3']]]
import operator
newlist = sorted(lis, key=operator.itemgetter(1))
```
result
```
>>> newlist
[['00553', ['01', '3.4']], ['00551', ['01', '5.3']],
['00553', ['02', '2... | ```
>>> lis = [['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]
>>> sorted(lis, key = lambda x: int(x[1][0]))
[['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]
``` | sorting lists in python 3 | [
"",
"python",
"list",
"defaultdict",
""
] |
I've to order sql results by ascending numeric values.
My code is something like that:
```
ORDER BY CAST(`baseData` AS DECIMAL(10,2)) {$dir} ";
```
It works so good, but there is a problem: it puts all NULL values on the bottom, i think it considers them like "0".
I need to put on the bottom all NULL values, how can ... | Yeah, It works:
```
ORDER BY baseData = '', CAST(`baseData` AS DECIMAL(10,2)) {$dir} ";
``` | Try this SQL
For MYSQL
```
ORDER BY COALESCE(CAST(`baseData` AS DECIMAL(10,2)),0)
```
For Oracle
```
ORDER BY NVL(CAST(baseData AS DECIMAL(10,2)),0)
```
[SQL Fiddle](http://sqlfiddle.com/#!2/7522e/2)
**MySQL 5.5.30 Schema Setup**:
```
create table test(
t varchar(5)
);
insert into test
values('123'),('234'),(... | SQL Ordering when having NULL values | [
"",
"sql",
"decimal",
"numeric",
""
] |
The 'row' variable returns a single row but it appears the select statement returns a 'rows' object. I want to extract field a and field d from the 'row' variable.
I tried just doing row.a or row.d but this returns an error.
```
def d_comp():
c_id = request.args(0)
evo_id = request.args(1)
row = db(... | I solved the question by doing the following inside the html file:
```
{{for val in row:}}
{{=val.a}}
{{=val.d}]
{{pass}}
``` | The `.select()` method always returns a DAL Rows object, even if it contains no records or just one record. The Rows object acts like a list, so you can extract individual records (which are DAL Row objects) by subscripting:
```
rows = db((db.tbl_stat.c_id == c_id) & (db.tbl_stat.evo_type == evo_id)).select()
row = ro... | web2py: getting field from rows object | [
"",
"python",
"web2py",
""
] |
I have a set of data that resembles the following format.
```
GROUP | ELEMENT
---------------
1 | A
1 | B
1 | C
2 | A
3 | B
4 | A
4 | B
5 | A
5 | C
```
I'd like to be able to verify that both elements A AND B exist in each of the groups. Ideally I would return onl... | This is more of a `Relational Division` problem but you need to display each individual `GROUP` with each `Element`.
* [SQL of Relational Division](http://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division/)
Query:
```
SELECT a.*
FROM TableName a
WHERE EXISTS
(
... | Not sure whether the following work but you can give a try
```
SELECT group, COUNT(DISTINCT(element))
FROM table
group by group
having COUNT(DISTINCT(element)) = 2
```
I am not sure whether `COUNT(DISTINCT(element))` will work! | Query to validate if items exist in partition group | [
"",
"sql",
"oracle",
""
] |
I am using SQL Server, the column is a `VARCHAR(50)` and I want to sort it like this:
```
1A
1B
2
2
3
4A
4B
4C
5A
5B
5C
5N
14 Draft
21
22A
22B
23A
23B
23C
23D
... | Your WHERE statement is... oddly complex.
It looks like you want to sort by any leading numeric digits in integer order, and then sort by the remainder. If so, you should do that as separate clauses, rather than trying to do it all in one. The specific issue you're having is that you're only allowing for a single-digi... | If all numbers within the string are reasonably small, say *not exceeding* 10 digits,
you may expand all the numbers in the string to be *exactly* 10 digits:
123A -> 0000000123A
```
S4 -> S0000000004
```
A3B89 -> A0000000003B0000000089
and so on and then sort them
```
-- Expand all numbers within S by zeros to be... | Sorting VARCHAR column with alphanumeric entries | [
"",
"sql",
"sql-server",
"sorting",
"alphanumeric",
""
] |
Within SAS
I have a proc-sql step that I'm using to create macro variables to do some list processing.
I have ran into a confusing step where using a case statement rather than a where statement results in the first row of the resulting data set being a null string ('')
There are no null strings contained in either ... | So the difference is that without a WHERE clause you aren't limiting what you are selecting, IE every row is considered. The CASE statement can bucket items by criteria, but you don't lose results just because your buckets don't catch everything, hence the NULL. WHERE limits the items being returned. | Yes, the first has no `then` clause in the case statement. I'm surprised that it even parses. It wouldn't in many SQL dialects.
Presumably you mean:
```
create table test as
select distinct
case
when brand in (select distinct core_brand from new_tv.core_noncore_brands)
t... | Proc Sql case confusion | [
"",
"sql",
"sas",
""
] |
I have a strange issue. Using IPython Notebook, I created a quite extensive script using pandas and matplotlib to create a number of charts.
When my tinkering was finished, I copied (and cleaned) the code into a standalone python script (so that I can push it into the svn and my paper co-authors can create the charts a... | Extending Matt's answer (lots of credit to him, but I think the answers can be less complex), this is how I eventually solved it.
(a) I looked up ipython's default matplotlib settings in `C:\Python27\Lib\site-packages\IPython\zmq\pylab\backend_inline.py` (see Matt's answer).
(b) and overwrote them with the values as ... | To complete Joe answer, the inlinebackend (IPython/kernel/zmq/pylab/backend\_inline.py) have some default matplotlib parameters :
```
# The typical default figure size is too large for inline use,
# so we shrink the figure size to 6x4, and tweak fonts to
# make that fit.
rc = Dict({'figure.figsize': (6.0,4.0),
# p... | Why is matplotlib plot produced from ipython notebook slightly different from terminal version? | [
"",
"python",
"matplotlib",
"jupyter-notebook",
""
] |
I want to write two variable to a file using Python.
Based on what is stated [in this post](https://stackoverflow.com/questions/899103/python-write-a-list-to-a-file) I wrote:
```
f.open('out','w')
f.write("%s %s\n" %str(int("0xFF",16)) %str(int("0xAA",16))
```
But I get this error:
```
Traceback (most recent call l... | You are not passing enough values to `%`, you have two specifiers in your format string so it expects a tuple of length 2. Try this:
```
f.write("%s %s\n" % (int("0xFF" ,16), int("0xAA", 16)))
``` | Better use [`format`](http://docs.python.org/3.3/library/string.html#format-string-syntax) this way:
```
'{0} {1}\n'.format(int("0xFF",16), int("0xAA",16))
```
Also there is no need to wrap `int` with `str`. | Write multiple variables to a file | [
"",
"python",
""
] |
As a follow up to another question that was answered, I now have data in the following format:
```
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 ... | ```
>>> strs = """0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0"""
>>> for x in strs.splitlines(): ... | You're probably reinventing the wheel. Look around for libraries that do "sparse matrix" manipulations, and think about whether they will do what you need.
I don't know much about the problem you're solving, but if it's really a data analysis project rather than about producing a nice interface for solving such proble... | Translate strings of 0's and 1's into lines of vectors for SVM Analysis | [
"",
"python",
""
] |
I want to animate the creation of a cylinder. That means I want to set the scale for the first keyframe to 0 and for the last keyframe to the actual cylinder size.
First I create a cylinder between two points like this:
```
# p1 is point 1 and p2 is point 2
dx, dy, dz = p2.x - p1.x, p2.y - p1.y, p2.z - p1.z
v_axis = m... | I think the approach people use is first translating the volume so that the desired pivot point is at (0,0), and then rotating, and translating it back to the proper position.
You can also see 6.1 of the following webpage:
<http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/> | What I ended up doing was scaling from 0 to 100% and at the same time changing the location of the cylinder so that the bottom of the cylinder is always at p1.
But I am still looking for a better solution. | How to move the pivot point of an object to a specific location | [
"",
"python",
"pivot",
"blender",
""
] |
I've got some code in a decorator that I only want run once. Many other functions (utility and otherwise) will be called later down the line, and I want to ensure that other functions that may have this decorator aren't accidentally used way down in the nest of function calls.
I also want to be able to check, at any p... | Here is an example of using a global for this task - in what I believe is a relatively safe way:
```
from contextlib import contextmanager
from functools import wraps
_within_special_context = False
@contextmanager
def flag():
global _within_special_context
_within_special_context = True
try:
yie... | The obvious solution is to have `special_wrapper` set a global flag, and just skip its magic if the flag is set.
This is about the only good use of a global variable - to allow a single piece of code to store information that is only used within that code, but which needs to survive the life of execution in that code.... | Preventing function (or decorator) from being nested | [
"",
"python",
""
] |
I have `n` elements as a input and a function `make_grid(n)` which will calculate the dimensions of a grid that will contain the elements. Let's suppose that `n = 12`, then the function must calculate that the width is 4 and the height is 3 and not 1 and 12 or so. Similarly, `n = 24` should return 6 and 4.
I tried to ... | The approach is as follows:
Take the integer `n` as the input of the function. The goal is to obtain the "squarest" table. As @John suggested we must calculate `sqrt(n)` to get an idea of the dimensions. On the other hand we must calculate all the divisors of `n` in order to do choose the nearest divisors to `sqrt(n)`... | You're looking for numbers that divide `n` evenly, so you'll need to compute the factors of `n`, and take the two that are closest to `sqrt(n)`. One will be the largest factor less than or equal to `sqrt(n)` (call this `f`) and the other will be `n/f`.
However, you'll get strange-looking grids for many numbers, like 7... | How to maximize grid dimensions given the number of elements | [
"",
"python",
"maximize",
""
] |
I am not sure if I am asking the question correctly but I mean the following:
Lets say I have dictionary
```
p = {'A' : 1, 'B' : 2, 'C' : 3}
```
then I have list
```
q = ['A', 'B']
```
how do I sum q so that the result is 3?
Thanks! | Use the built-in function `sum` and a generator expression:
```
>>> p = {'A' : 1, 'B' : 2, 'C' : 3}
>>> q = ['A','B']
#using generator expression
>>> sum(p.get(x,0) for x in q)
3
#using list comprehension, not memory efficient
>>> sum( [p.get(x,0) for x in q] )
3
```
In case any of the element in `q` is not found in ... | You can do
```
sum(p[k] for k in q)
```
This expression `p[k] for k in q` is a [generator comprehension](https://stackoverflow.com/questions/364802/generator-comprehension)- similar to a [list comprehension](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) except that it never has to construct the entire ... | How to sum a list that contains dictionary elements | [
"",
"python",
"list",
"dictionary",
""
] |
I have 3 tables in this scenario: `Teams`, `Players` and `PlayersInTeams`.
A `Player` is just a registered user. No W/L data is associated with a `Player`.
A `Team` maintains win/loss records. If a player is playing by himself, then he plays with his "solo" team (a `Team` with only that Player in it). Every time Bob ... | To fix your query, add a `group by`. To compute the count per team, you'll need to change the `where` clause to return all teams that player 1 is on:
```
select fkTeamId
from PlayersInTeams
where fkTeamId in
(
select fkTeamId
from PlayersInTeams
where fkPlayerId = 1
... | The most natural thing to do is to count the rows to see what is going on:
```
select fkTeamId, count(*)
from PlayersInTeams
where fkPlayerId=1
group by fkTeamId;
```
The `group by` clause is a more natural way to write the query:
```
select fkTeamId
from PlayersInTeams
where fkPlayerId=1
having count(fkteamid) = 1
... | Correct use of the HAVING clause, to return the unique row | [
"",
"mysql",
"sql",
""
] |
What is the most efficient way in Python to double (or repeat n times) every letter in a string?
```
"abcd" -> "aabbccdd"
```
or
```
"abcd" -> "aaaabbbbccccdddd"
```
I have a long string that needs to be mutated in this fashion and the current solution involves a loop with `n` concatenations for every letter, which... | Since you specifically asked about efficiency:
```
# drewk's answer, optimized by using from_iterable instead of *
def double_chain(s):
return ''.join(chain.from_iterable(zip(s, s)))
# Ashwini Chaudhary's answer
def double_mult(s):
return ''.join([x*2 for x in s])
# Jon Clements' answer, but optimized to tak... | Use `str.join`:
```
>>> strs = "abcd"
>>> "".join([x*2 for x in strs])
'aabbccdd'
>>> "".join([x*4 for x in strs])
'aaaabbbbccccdddd'
```
From [docs](http://wiki.python.org/moin/PythonSpeed/PerformanceTips#String_Concatenation):
```
s = ""
for substring in list:
s += substring
```
Use `s = "".join(list)` instea... | Double every letter in string | [
"",
"python",
"string",
""
] |
I get this annoying error when I try to insert data from db1 to db2 in MaridaDB 10 using mysql CLI. This is while all the columns exist.
```
INSERT INTO db2.thread (threadid, title, postuserid, dateline, views)
SELECT `nid`, `title`, `uid`, `created`,
`comment` from db1.node where type = 'forum' and status = 1;... | Looks like there are invisible garbage characters in your query.
Try retyping the query (don't copy and paste or you'll most likely include the garbage character) and it should work. | If you've typed it like this:
```
INSERT INTO Details (Name, Age) VALUES (Anamika, 24);
```
Try changing it to:
```
INSERT INTO Details (Name, Age) VALUES ('Anamika',24);
``` | ERROR 1054 (42S22): Unknown column '' in 'field list' | [
"",
"sql",
"mysql",
"database",
"mariadb",
"mysql-command-line-client",
""
] |
I have a list of list which goes as follows:
```
A = [['05-22-2013', '0.5553', '0.887', '0.14'],
['05-22-2013', '0.3442', '0.345', '0.0'],
['05-22-2013', '0.3', '0.7', '0.4'],
['05-23-2013', '0.53', '0.87', '0.4'],
['05-23-2013', '0.9', '0.8', '0.1'],
['05-23-2013', '0.0', '0.799', '0.214... | If linear-time preprocessing is an option, then first get the keys (dates) out into a separate list. To make them orderable, convert them to `datetime` objects first.
```
>>> from datetime import datetime
>>> def parsedate(s):
... return datetime.strptime(s, '%M-%d-%Y')
>>> keys = [parsedate(x[0]) for x in A]
```
... | I don't know if this is the "best" way, because let's be honest, "best" is a very subjective term.
```
from datetime import date
start_date = date(2013, 5, 22)
end_date = date(2013, 5, 24)
data = []
for i in A:
month, day, year = i[0].split('-')
record_date = date(year, month, day)
if record_date >= sta... | Get Elements between two dates from a list | [
"",
"python",
""
] |
I'm making a program using the website <http://placekitten.com>, but I've run into a bit of a problem. Using this:
```
im = urllib2.urlopen(url).read()
f = open('kitten.jpeg', 'w')
f.write(im)
f.close()
```
The image turns out distorted with mismatched colors, like this:
<http://imgur.com/zVg64Kn.jpeg>
I was wonder... | You need to open the file in binary mode:
```
f = open('kitten.jpeg', 'wb')
```
Python will otherwise translate line endings to the native platform form, a transformation that breaks binary data, as documented for the [`open()` function](http://docs.python.org/2/library/functions.html#open):
> The default is to use ... | Change
```
f = open('kitten.jpeg', 'w')
```
to read
```
f = open('kitten.jpeg', 'wb')
```
See <http://docs.python.org/2/library/functions.html#open> for more information. What's happening is that the newlines in the jpeg are getting modified in the process of saving, and opening as a binary file will prevent this. | Python urllib2 Images Distorted | [
"",
"python",
"image",
"urllib2",
"extract",
""
] |
I have a database that stores the complete details of the employees of a firm.
I need to select column names from multiple tables in the database which when executed would provide me the columns required to list specific details. So, I tried the following query which returns the columns of the specified table only.
``... | You need to dynamically create a SQL statement and then run that command
***Update 22.06.2013***
```
IF OBJECT_ID('dbo.Table1') IS NOT NULL DROP TABLE dbo.Table1
CREATE TABLE dbo.Table1
(
EmployeeId int PRIMARY KEY,
Name varchar(100),
Address varchar(100),
Mode int
)
INSERT dbo.Table1
VALUES(1, 'abc', 'Ad... | Try this one -
**DDL:**
```
SET NOCOUNT ON;
IF OBJECT_ID (N'dbo.Table1') IS NOT NULL
DROP TABLE dbo.Table1
CREATE TABLE dbo.Table1
(
EmployeeId INT
, Name VARCHAR(30)
, [Address] VARCHAR(150)
, Mode INT
, Img IMAGE
, UpdateDate DATETIME
, IpAddress VARCHAR(20)
)
IF OBJECT_ID (... | How to select column names from multiple tables in SQL server 2008 by avoiding certain columns which reoccur in all tables | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I was going through a **[blog](http://drilian.com/2009/02/25/lightning-bolts/#uniquepost)** on Creating Lightning effect in 2D game.I wanted to implement the same in python. However I am stuck at a place.
Lets say **startpoint** and **endPoint** are co-ordinates in 2D plane , representing extreme points of a line segm... | I don't know of built-in or third-party methods, but they are really simple:
```
import numpy as np
def perpendicular( a ) :
b = np.empty_like(a)
b[0] = -a[1]
b[1] = a[0]
return b
def normalize(a):
a = np.array(a)
return a/np.linalg.norm(a)
if __name__ == "__main__":
a = [1,2]
pr... | As @SethMMorton and @ThoestenKranz indicated, numpy has a lot of support for vector manipulation. I don't think there is built-in support in Python to get what you want. However using simple trigonometric functions you can calculate normalize and perpendicular pretty easily using the built-in math module.
```
import m... | Normalise and Perpendicular Function in python | [
"",
"python",
"python-2.7",
""
] |
I'm currently doing this by using a sort of a greedy algorithm by iterating over the sets from largest to smallest set. What would be a good algorithm to choose if i'm more concerned about finding the best solution rather than efficiency?
Details:
1) Each set has a predefined range
2) My goal is to end up with a l... | This is a very complex question. It could well be that using more complex graph algorithms this can be solved in a more efficient way than what I came up with, but here is what I've got. It will be pretty slow to produce *all* solutions, but since it is a generator, maybe choosing a solution from the first *n* could be... | Here is an approximation, using dynamic programming:
<http://ideone.com/SI1wEs>
```
from operator import itemgetter
def find_maximum_set(sets):
results = []
for si,s in enumerate(sets):
sn = len(s)
new_set = set(s) # if nothing else works, add the set by itself
new_len = sn
ne... | What is a good way to merge non intersecting sets in a list to end up with denseley packed sets? | [
"",
"python",
"algorithm",
""
] |
For languages with `{}` to denote blocks, vim has the almighty `%` key. What is the equivalent movement thing for python code? Or at least to move to next / previous line with the same indent. | The [vim wiki](http://vim.wikia.com/wiki/Move_to_next/previous_line_with_same_indentation) suggest bindings such as:
```
nnoremap <M-,> k:call search('^'. matchstr(getline(line('.')+1), '\(\s*\)') .'\S', 'b')<CR>^
nnoremap <M-.> :call search('^'. matchstr(getline(line('.')), '\(\s*\)') .'\S')<CR>^
```
As well as offe... | Vim has the `{` and `}` motions to move between "paragraphs" and the corresponding `p` text-object (`vip`, `dap`).
The default Python ftplugin also (re)defines `[[` and `]]` to move to next and previous class and `]m` and `[m` to move to next and previous method.
The [indent-object](http://www.vim.org/scripts/script.... | Equivalent of % movement for Python files | [
"",
"python",
"vim",
""
] |
I have a file with the following format :
```
# a, b, c
0.1 0 0
0.2 0.4 0.5
4 5 0.9
0.3 0 10
```
which is a file with 3 columns of data and the name of these columns are `a`, `b` and `c`.
Currently to read these data, I use :
```
def readdata(filename):
a, b, c = np.loadtxt(filename, unpack=True)
... | This functionality is provided by the numpy function [`np.genfromtxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html), if you call it with the keyword `names=True`.
Example:
```
>>> s = """# a, b, c
... 0.1 0 0
... 0.2 0.4 0.5
... 4 5 0.9
... 0.3 0 10
... """
>>> data = np.genfromtxt(Strin... | With this file:
```
#a, b, c
0.1 0 0
0.2 0.4 0.5
4 5 0.9
0.3 0 10
```
Assuming your first line defines header rows, in Numpy, you can do this:
First, read the header row:
```
>>> with open('/tmp/testnp.txt','r') as f:
... header=[n.strip() for n in f.readline().strip().lstrip('#').split(',')]
...
>>>... | Get a python map with the title of the column and the column of data from a data file | [
"",
"python",
"file",
"csv",
"dictionary",
"numpy",
""
] |
I need to execute a Python script from the Django shell. I tried:
```
./manage.py shell << my_script.py
```
But it didn't work. It was just waiting for me to write something. | The `<<` part is wrong, use `<` instead:
```
$ ./manage.py shell < myscript.py
```
You could also do:
```
$ ./manage.py shell
...
>>> execfile('myscript.py')
```
For python3 you would need to use
```
>>> exec(open('myscript.py').read())
``` | You're not recommended to do that from the `shell` - and this is intended as you shouldn't really be executing random scripts from the django environment (but there *are* ways around this, see the other answers).
If this is a script that you will be running multiple times, it's a good idea to set it up as a [custom co... | How to execute a Python script from the Django shell? | [
"",
"python",
"django",
"django-shell",
""
] |
I have a list of four numbers:
```
mylist=[3,5,67,4]
```
I want to remove all the odd numbers. So, I've written the following:
```
for item in mylist:
if item%2==1:
mylist.remove(item)
```
When I print `mylist`, I get the following:
```
[5,4]
```
I cannot figure out why this is happening. However, when I ad... | It's a bad idea to modify a list in-place while iterating it. As the list changes while you iterate over it, your iteration continues as though the list were unaltered - producing weird results.
The best solution is to build a new list - optimally with a [list comprehension](http://www.youtube.com/watch?v=pShL9DCSIUw)... | You need to iterate over a copy of the list. Modifying the list directly in a loop is what's causing the problem you experienced. Here's the preferred way to do it:
```
for item in mylist[:]:
if item%2==1:
mylist.remove(item)
``` | Unexpected behaviour in looping a list | [
"",
"python",
"list",
"for-loop",
"modulo",
""
] |
I want to run third part tool written in python on my ubuntu machine ([corgy tool](https://github.com/pkerpedjiev/corgy)).
However I don't know how to add additional modules to Python path.
```
cat doc/download.rst
There is currently no setup.py, so you need to manually add
the download directory to your PYT... | Create a `.bash_profile` in your home directory. Then, add the line
```
PYTHONPATH=$PYTHONPATH:new_dir
EXPORT $PYTHONPATH
```
Or even better:
```
if [ -d "new_dir" ] ; then
PYTHONPATH="$PYTHONPATH:new_dir"
fi
EXPORT $PYTHONPATH
```
The `.bash_profile` properties are loaded every time you log in.
The `source` com... | [@fedorqui](https://stackoverflow.com/users/1983854/fedorqui-so-stop-harming)'s answer above was almost good for me, but there is at least one mistake (I am not sure about the `export` statement in all caps, I am a complete newbie).
There should not be a `$` sign preceding PYTHONPATH in the export statement. So the opt... | Ubuntu add directory to Python path | [
"",
"python",
"ubuntu",
"importerror",
""
] |
My end goal is to turn my Raspberry Pi into a FTP Server. It is connected to the network, but with no internet connection. It seems like this would be extremely easy to accomplish if I could just run the "sudo apt-get install ...." command, but since I have no internet this is not possible.
I downloaded the "ftplib" f... | Doing this is never ever clean, and never perfect. But below is what I've done to get it to work at times.
You will need a machine that is similar to the FTP server and from the FTP server you will need to download all packages and dependencies. Typically, from the internet machine you will first run:
```
sudo apt-ge... | You'll have to download the packages **and** it's dependencies. Then place them on the sd card and execute:
```
cd folder_with_debs
sudo dpkg -i *.deb
```
Btw, it would be easier in most cases to plug an eth cable into the raspberry pi for short (As you are posting here on SO, you should have access to the internet i... | Run sudo apt-get install without internet connection | [
"",
"python",
"linux",
"ftp",
"raspberry-pi",
"apt",
""
] |
So what I have here is a query that displays a Baseball players Name, Salary, and then shows normal baseball stats such as Hits, RBIs, etc. What I want to is have the code create a query at the end that will contain the player's name and and the result of an expression that looks like
```
IIf([H]<>0,Format(([Salary]/... | Sorry, brother. Last shot. This code works. However, it needs a small tweak because it doesn't loop through all the records.
```
Public Function HitTest()
Dim db As Database
Dim rec As DAO.Recordset
Dim fld As DAO.Field
Set db = CurrentDb
Set rec = db.OpenRecordset("tblPlayers")
EditTable = "tblPlayers"
For Each fl... | I'm sure I'm not understanding the question, but you could do something like this:
```
Dim db as database
dim rec as recordset
Dim fld as Field
Set db = CurrentDB
Set rec = db.OpenRecordset("PlayerSal")
For each Fld.name in rec
If Fld.Name <> "Name" and Fld.Name <> "Salary" then
Per_" & Fld.Name & " = IIf([" &... | Using VBA to loop through a query and outputting results | [
"",
"sql",
"vba",
"ms-access",
""
] |
I'm looking for a fast solution to MATLAB's [`accumarray`](http://www.mathworks.com/help/matlab/ref/accumarray.html) in numpy. The `accumarray` accumulates the elements of an array which belong to the same index. An example:
```
a = np.arange(1,11)
# array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
accmap = np.array([0... | Use [`np.bincount`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html) with the `weights` optional argument. In your example you would do:
```
np.bincount(accmap, weights=a)
``` | Late to the party, but...
As @Jamie says, for the case of summing, `np.bincount` is fast and simple. However in the more general case, for other `ufuncs` such as `maximum`, you can use the [`np.ufunc.at`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.at.html) method.
I've put together ~~[a gist](htt... | Is there a MATLAB accumarray equivalent in numpy? | [
"",
"python",
"numpy",
"accumulator",
""
] |
I have a Numpy 2-D array in which one column has Boolean values i.e. `True`/`False`. I want to convert it to integer `1` and `0` respectively, how can I do it?
E.g. my `data[0::,2]` is boolean, I tried
```
data[0::,2]=int(data[0::,2])
```
, but it is giving me error:
`TypeError: only length-1 arrays can be converte... | Ok, the easiest way to change a type of any array to float is doing:
`data.astype(float)`
The issue with your array is that `float('True')` is an error, because `'True'` can't be parsed as a float number. So, the best thing to do is fixing your array generation code to produce floats (or, at least, strings with valid... | boolarrayvariable.astype(int) works:
```
data = np.random.normal(0,1,(1,5))
threshold = 0
test1 = (data>threshold)
test2 = test1.astype(int)
```
Output:
```
data = array([[ 1.766, -1.765, 2.576, -1.469, 1.69]])
test1 = array([[ True, False, True, False, True]], dtype=bool)
test2 = array([[1, 0, 1, 0, 1]])
``` | How to convert from boolean array to int array in python | [
"",
"python",
"numpy",
""
] |
I want to generate different/unique id per request in django from models field. I did this but I keep getting the same id.
```
class Paid(models.Model):
user=models.ForeignKey(User)
eyw_transactionref=models.CharField(max_length=100, null=True, blank=True, unique=True, default=uuid.uuid4()) #want to generate... | If you are using Django 1.8 or superior, [madzohan's answer](https://stackoverflow.com/a/30637668/11573842) is the right answer.
---
Do it like this:
```
#note the uuid without parenthesis
eyw_transactionref=models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4)
```
The reason why is because ... | Since version 1.8 Django has [`UUIDField`](https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.UUIDField)
```
import uuid
from django.db import models
class MyUUIDModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
# other fields
``` | Generate unique id in django from a model field | [
"",
"python",
"django",
"django-models",
""
] |
I have a multi-line string, and I would like to replace the last line of the string with a different line. How do I most efficiently do this? | Split on the last linebreak and attach a new line:
```
new = old.rstrip('\n').rsplit('\n', 1)[0] + '\nNew line to be added with line break included.'
```
This first removes any trailing newline after the last line, splits *once* on the last newline in the text, takes everything before that last newline, and concatena... | I would suggest this approach:
```
>>> x = """
... test1
... test2
... test3"""
>>> print "\n".join(x.splitlines()[:-1]+["something else"])
test1
test2
something else
>>>
``` | How do I efficiently replace the last line in a string? | [
"",
"python",
""
] |
I'm trying to remove the lists from a list which have same first and third items but only keeping the first one. Example list and output:
```
li=[ [2,4,5], [1,3,5], [1,6,5] ]
output_list = [ [2,4,5], [1,3,5] ]
```
The code I've written takes a very long time to execute as the original list contains millions of list.
... | An improved version:
```
b_li = set()
output_list = []
b_li_add = b_li.add
output_list_append = output_list.append
for x in li:
s = (x[0], x[2])
if s not in b_li:
b_li_add(s)
output_list_append(x)
```
The changes are:
* Use a `set()` for `b_li` which makes lookups faster.
* Turn `s` into a tu... | Use a set for storing the seen elements. That is faster:
```
seen = set()
res = []
for entry in li:
cond = (entry[0], entry[2])
if cond not in seen:
res.append(entry)
seen.add(cond)
[[2, 4, 5], [1, 3, 5]]
```
**ADDITION**
Also, the time spend on thinking about telling variables names is typ... | Removing the lists from a list which are duplicated for some items | [
"",
"python",
"list",
""
] |
I have a column in my schema which contains values as follows:
```
male, Brown, Blue, Small body build, 1.63
male, Brown, Blue, Small body build, 1.85
male, Brown, Blue, Small body build, 1.75
```
i want to make a query that extracts all the objects which has numbers lies between 1.63 and 1.75, Note that the number... | You can do this in many SQL dialects as:
```
select *
from t
where right(col, 4) between '1.63' and '1.75'
```
The string comparison works because the numbers have the decimal place in the same position. | ```
select * from tableName
where convert(int, substr(columnName,LENGTH(columnName)-4,4)) BETWEEN 1.75 AND 1.63
```
This should work without limiting the Integer part to some syntax ((d.dd) for example) but requires it to be of length 4.
**Edit**
Between has more elegant usage. | How to extract numbers within a specified range from a column? | [
"",
"sql",
""
] |
I am trying to run a script (see below) to read in a fasta file and output a taxonomy file (printing only the sequence header without the '>' character) but I keep getting a syntax error which I have not been able to resolve. As a result the script creates the cleanseqs.tax file but the file is blank. Could anyone help... | A [file object](http://docs.python.org/2/library/stdtypes.html#file.close) is a [context manager](http://docs.python.org/2/library/stdtypes.html#context-manager-types), so you can use the [with statement](http://docs.python.org/2.7/reference/compound_stmts.html#with) to automatically close the files:
```
with open("te... | Add in an extra line, as `... Fasta.close()` isn't necessarily the end of the while loop. It could take in another keyword, like `else`. Adding another line implies the end of the while loop.
Or did you mean to indent `Fasta.close()`? | Issue with invalid syntax error in python 2.7.3 | [
"",
"python",
"fasta",
""
] |
I'm attempting to write out a batch job schedule based on a table stored in an Oracle database.
I really have no idea where to start.
The table only has two relevant columns:
```
JOBSTREAM | FOLLOW_JOBSTREAM
```
JOBSTREAM is the name of the job stream that is going to run. FOLLOW\_JOBSTREAM is the name of the... | At first, we need full job list from both columns with hierarchy links:
```
select
all_jobs.job_id as jobstream,
job_depends.follow_jobstream as parent_jobstream
from
(
select jobstream job_id from job_list
union
select follow_jobstream job_id from job_list
) all_jo... | [Hierarchical queries](http://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm) can help you in such cases:
```
SELECT JOBSTREAM, FOLLOW_JOBSTREAM
FROM <jobstreams>
START WITH FOLLOW_JOBSTREAM NOT IN (SELECT JOBSTREAM
FROM jobstreams
... | Find order of jobs from schedule table? | [
"",
"sql",
"oracle",
"plsql",
""
] |
So i have the following output in file (thousands of lines)
input.txt
```
2956:1 1076:1 4118:1 1378:1 2561:1
1039:1 1662:1
1948:1 894:1 1797:1 1662:1
```
the problem is i need to have each line sorted in ascending number
Desired output:
output.txt
```
1076:1 1378:1 2561:1 2956:1 4118:1
1039:1 1662:1
894:1 1662:1 1... | ```
with open('input.txt') as f, open('output.txt', 'w') as out:
for line in f:
line = line.split() #splits the line on whitespaces and returns a list
#sort the list based on the integer value of the item on the left side of the `:`
line.sort(key = lambda x: int(x.split(':')[0]))
ou... | Not sure about python, but in general, I'd take each line as a "record" then "explode" the line into an array separated by a space (or regex a group of spaces or tab, or whatever is the separator), then a simple array sort, then "implode" back to a string.
My "quotes" are equivalent to PHP functions. | sorting numbers into ascending order on a line | [
"",
"python",
"python-2.7",
""
] |
I would like a print function that can print inner list.
The expected result of my function should be:
```
a
b
aa
bb
aaa
bbb
```
However, now the result is: (the added space is not expected)
```
a
b
aa
bb
aaa
bbb
```
How can I get the expected resul... | Global state (the add\_space variable) isn't necessary here when the first call to printList is done with level 0 (e.g. printList(testlist, 0)). That simplifies the code and makes it easier to test and debug.
When you add a print statement for the level to your code you'll also see that the level ends up as 2 for the ... | Using a recursive method.
```
testlist = ["a", "b", ["aa", "bb", ["aaa", "bbb"]]]
def recursive_list_print(lst, level=0):
for item in lst:
if isinstance(item, list):
recursive_list_print(item, level+1)
else:
print('{}{}'.format('\t'*level, item))
recursive_list_print(testl... | How to control the format of this list printing function | [
"",
"python",
"python-3.x",
""
] |
Here is the thing: I have 2 databases ADatabaseCX and ADatabaseRH. Databases are the same. I have some records in both datatables. What I would like to do is insert entries from ADatabaseCX to ADatabaseRH, BUT only entries, that doesn't exist in ADatabaseRH - in RH there is incomplete data.
I tried with nested SQL, so... | The problem is you are initializing an `ALIAS` on the database name but you have not used it in the `ON` clause, it should be
```
SELECT a.*
FROM ADatabaseCX.dbo.Recipes AS a
LEFT JOIN ADatabaseRH.dbo.Recipes AS b
ON a.recipeId = b.recipeId
WHERE b.recipeId IS NULL
```
database name and table na... | Try using this referencing `a.recipeId` and `b.recipeId`:
```
SELECT a.*
FROM ADatabaseCX.dbo.Recipes AS a
LEFT JOIN ADatabaseRH.dbo.Recipes AS b ON a.recipeId = b.recipeId
WHERE b.recipeId IS NULL
```
Or this would also work using `NOT IN`:
```
SELECT *
FROM ADatabaseCX.dbo.Recipes
WHERE recipeId NOT IN (
SE... | SQL copy unique records between two equal databases in two separate databases | [
"",
"sql",
"select",
"insert",
"copy",
""
] |
When I try installing the PyQt5 on Windows using the command
```
python configure.py
```
I get this error:
> ```
> Error: Make sure you have a working Qt qmake on your PATH.
> ```
I got the pyQt5 from [PyQt5 Download](http://www.riverbankcomputing.co.uk/software/pyqt/download5).
How can I install PyQt5?
---
**Up... | The easiest way to install PyQt is to just use the installer (Link in your answer, step #5). If you install python 3.3, the installer will add all of the PyQt5 extras to that python installation automatically. You won't need to do any compiling (none of: nmake, nmake install, python configure).
All of the build option... | Mainly I use the following command under the `cmd`
```
pip install pyqt5
```
And it works with no problem! | How to install PyQt5 on Windows? | [
"",
"python",
"windows",
"qt",
"nmake",
"pyqt5",
""
] |
I have a list which contains numbers and letters in string format.
```
mylist=['1','orange','2','3','4','apple']
```
I need to come up with a new list which only contains numbers:
```
mynewlist=['1','2','3','4']
```
If I have a way to check if each item in list can be converted to Integer, I should be able to come ... | Try this:
```
mynewlist = [s for s in mylist if s.isdigit()]
```
---
From the [docs](http://docs.python.org/2/library/stdtypes.html#str.isdigit):
> **`str.isdigit()`**
>
> Return true if all characters in the string are digits and there is at least one character, false otherwise.
>
> For 8-bit strings, this method ... | Fast, simple, but maybe not always right:
```
>>> [x for x in mylist if x.isdigit()]
['1', '2', '3', '4']
```
More traditional if you need to get numbers:
```
new_list = []
for value in mylist:
try:
new_list.append(int(value))
except ValueError:
continue
```
**Note**: The result has integers... | Python check if list items are integers? | [
"",
"python",
"string",
"list",
"integer",
""
] |
I am looking at a `cursor` with `decode(1, 1, 1, NULL, 0)` in the `SELECT` statement. The query returns records of employees that have worked for 5 years or more. I assume that the intention of the decode statement was to check if a record is returned or not (meaning that said employee has worked for five or more years... | The `decode` statement is affecting the return values on the row or rows that are returned.
To guarantee that a row *is* returned, you are better off using an aggregation:
```
CURSOR worked_more_then_five_years
IS
SELECT (case when count(*) > 0 then 1 else 0 end)
FROM table
WHERE /*query conditions*/
```
The `case` ... | To guarantee the return of a single row with an indication of whether the condition was met or not:
```
select count(*) row_found
from table
where ...
and rownum <= 1;
```
As long as there are no other (non-aggregating) columns then you will always get a single row returned.
If your predicates guarantee that o... | Oracle decode function to check if row returned? | [
"",
"sql",
"oracle",
"cursor",
""
] |
We having a really hard time to figure out two similar strings given to sys.dm\_fts\_parser gives different results
```
select * from sys.dm_fts_parser('"0 CAD"', 0, null, 0)
```
seems to think that "0 CAD" is one token (returns 2 token)
```
select * from sys.dm_fts_parser('"0 cad"', 0, null, 0)
```
returns 3 token... | **When using SQL 2008**
```
select * from sys.dm_fts_parser('"0 CAD"', 0, null, 0) - gives 2 tokens
select * from sys.dm_fts_parser('"0 CAD"', 1033, null, 0) - gives 3 tokens
```
**On SQL 2012 (11.0.3218):**
```
select * from sys.dm_fts_parser('"0 CAD"', 1033, null, 0) - gives 2 tokens
```
In SQL 2012 Microsoft ... | My team also ran into this strange tokenization behavior. Our fix was to apply [LOWER](http://technet.microsoft.com/en-us/library/ms174400.aspx) to the query and search text.
As [Haroon previously identified](https://stackoverflow.com/a/21296751/317), the issue appears to arise from the tokenizer identifying certain u... | sys.dm_fts_parser sql full text | [
"",
"sql",
"sql-server",
"full-text-search",
"noise-words",
""
] |
Is there a Python argument to execute code from the shell without starting up an interactive interpreter or reading from a file?
Something similar to:
```
perl -e 'print "Hi"'
``` | This works:
```
python -c 'print("Hi")'
Hi
```
From the manual, `man python`:
> ```
> -c command
> Specify the command to execute (see next section). This termi-
> nates the option list (following options are passed as arguments
> to the command).
> ``` | Another way is to you use bash redirection:
```
python <<< 'print "Hi"'
```
And this works also with perl, ruby, and what not.
p.s.
To save quote ' and " for python code, we can build the block with EOF
```
c=`cat <<EOF
print(122)
EOF`
python -c "$c"
``` | How to execute Python inline from a bash shell | [
"",
"python",
"shell",
"inline",
"execution",
""
] |
I bumped into the problem while playing around in Python: when I create a random string, let's say "test 1981", the following Python call returns with an empty string.
```
>>> re.search('\d?', "test 1981").group()
''
```
I was wondering why this is. I was reading through some other posts, and it seems that it has to ... | Your pattern matches a digit or the empty string. It starts at the first character and tries to match a digit, what it is doing next is trying to match the alternative, means the empty string, voilà a match is found before the first character.
I think you expected it to move on and try to match on the next character, ... | Regex
```
\d?
```
simply means that it should optionally (`?`) match single digit (`\d`).
If you use something like this, it will work as you expect (match single digit anywhere in the string):
```
\d
``` | Python Regex: Question mark (?) doesn't match in middle of string | [
"",
"python",
"regex",
"regex-greedy",
""
] |
Here is my file structure that I am working with for my application. My problem is that I cannot get my test\_ctd.py file to see my ctd.py file.
Here is my directory structure
```
FileParser
--Parsers
----ctd.py
--tests
----__init__.py
----test_ctd.py
--parse.py
```
I never used an **init**.py file and am struggling... | `Parsers` and `FileParser` must contain `__init__.py` if you want to import something from `ctd.py`. See [Importing modules in Python and \_\_init\_\_.py](https://stackoverflow.com/questions/5910379/importing-modules-in-python-and-init-py).
Then, you can import `ctd.py` from your tests scripts by doing relative import... | Move the `__init__.py` file into `Parsers` and add the directory `FileParser` as absolute path to your PYTHONPATH. For example with `sys.path.append('full/path/to/FileParser')`. | Access modules from test file | [
"",
"python",
"path",
""
] |
I need this query for testing exception handling, so I would prefer that the query is not schema dependent. I am looking for something like `SELECT 1;` but of course that doesn't fail.
I am using Java and MySQL but I hope to find answers that doesn't depend on programming languages and/or RDBMSs. | there are tons of ways to make a query fail, like mispelling a field, or selecting from non existing tables. for example:
```
SELECT some_fake_field FROM table_that_doesnt_exists
``` | What about "SELECT 1/0" for starters? | How do I write an SQL query that fails? | [
"",
"mysql",
"sql",
"testing",
"assertions",
""
] |
If I want to use the results of `argparse.ArgumentParser()`, which is a `Namespace` object, with a method that expects a dictionary or mapping-like object (see [collections.Mapping](http://docs.python.org/2/library/collections.html#collections.Mapping)), what is the right way to do it?
```
C:\>python
Python 2.7.3 (def... | You can access the namespace's dictionary with [*vars()*](http://docs.python.org/3/library/functions.html#vars):
```
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}
```
You can modify the dictionary directly if you wish:... | [Straight from the horse's mouth](https://docs.python.org/3/library/argparse.html#the-namespace-object):
> If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, [`vars()`](https://docs.python.org/3/library/functions.html#vars):
>
> ```
> >>> parser = argparse.ArgumentParser()
>... | What is the right way to treat Python argparse.Namespace() as a dictionary? | [
"",
"python",
"dictionary",
"duck-typing",
""
] |
So basically i have a big list of words in a text file that i want to be able to search through for matching words when the user inputs one to check the spelling, this is what i have so far.
```
f = open('words.txt', 'r')
wordCheck = input("please enter the word you would like to check the spelling of: ")
for line in... | You can do this:
```
wordCheck = raw_input("please enter the word you would like to check the spelling of: ")
with open("words.txt", "r") as f:
found = False
for line in f:
if line.strip() == wordCheck:
print ('That is the correct spelling for '+ wordCheck)
found = True
... | Because you've only looped through the first line before it breaks.
```
wordCheck = input("please enter the word you would like to check the spelling of: ")
with open('words.txt', 'r') as f:
for line in f:
if wordCheck in line.split():
print('That is the correct spelling for '+wordCheck)
... | searching a text file for an inputted word in python | [
"",
"python",
"list",
"text",
"for-loop",
"while-loop",
""
] |
This is such a simple issue that I don't know what I'm doing wrong. Basically I want to iterate through the items in an empty list and increase each one according to some criteria. This is an example of what I'm trying to do:
```
list1 = []
for i in range(5):
list1[i] = list1[i] + 2*i
```
This fails with an `list... | Ruby (for example) lets you assign items beyond the end of the list. Python doesn't - you would have to initialise list1 like this
```
list1 = [0] * 5
``` | So when doing this you are actually using i so you can just do your math to i and just set it to do that. there is no need to try and do the math to what is going to be in the list when you already have `i`. So just do list comprehension:
```
list1 = [2*i for i in range(5)]
```
Since you say that it is more complex, ... | Basic python: how to increase value of item in list | [
"",
"python",
""
] |
There is any way to dismember a row into many rows by a value into row column?
Doing my query, i got the result:
```
ID TmpShoppingCart_ID StoreSKU_ID QuantityΞΞ Enabled
26 34 448 2 True
27 34 3465 4 True
28 34 3468 1 T... | One more option with the master..spt\_values system table. Also you can replace the system table on the own sequence table
```
SELECT ID, TmpShoppingCart_ID, StoreSKU_ID, o.Quantity, [Enabled]
FROM [dbo].[tmpShoppingCartItem] t
CROSS APPLY (
SELECT 1
FROM master..spt_values v
WH... | You can generate numbers in SQL Server using a recursive CTE. Once you have a list of numbers, you can do the query.
Here is an example with 100 as the maximum:
```
with nums as (
select 1 as n
union all
select n + 1
from nums
where n < 100
),
t as (select 26 as id, 34 as TmpSh... | How to split a row into many equals rows by a value in a column? | [
"",
"sql",
"sql-server",
"linq",
"sql-server-2008-r2",
"union",
""
] |
I'd like to use peewee to [create](http://peewee.readthedocs.org/en/latest/peewee/api.html#Model.create) records from a csv. It looks like the syntax requires keyword args:
```
user = User.create(username='admin', password='test')
```
If the rows in the csv look like `(admin, test)`, it would be convenient to know th... | Looks like it's `User._meta.get_field_names()`
I just saw someone else mention it in [another question](https://stackoverflow.com/questions/13864940/python-dumping-database-data-with-peewee). | The accepted answer is for an older version of Peewee. The proper way to do this is either:
```
class SomeModel(db.Model):
...
sorted_field_names = SomeModel._meta.sorted_field_names
``` | Get ordered field names from peewee Model | [
"",
"python",
"orm",
"peewee",
""
] |
OK the code is pretty basic. Since I'm using multiple threads, and I want shared variables between them, I'm using a global.
Why does the code in ThreadClass sometimes not execute when I hit "C"? I know it's a concurrency problem, but I'm not sure how to fix it. I've reading up on semaphores and locking lately, but I'... | You have two synchronization problems here.
Let's deal with the easier one first, the fact that you're sharing a global `buff_list` that the two threads fight over. There's nothing stopping one thread from trying to `append` at the same time the other thread `pop`s, which is illegal. And, even if you get lucky and tha... | Well you never know instance of which class got your input. If you hit “C” and that was `ThreadClass2` reading your input, it will just do nothing since `"B" == raw_input()` will be `False`.
Exactly one thread should be responsible for I/O. | Basic threading in python | [
"",
"python",
"multithreading",
"python-multithreading",
""
] |
```
class myDecorator(object):
def __init__(self, f):
print "inside myDecorator.__init__()"
f() # Prove that function definition has completed
def __call__(self):
print "inside myDecorator.__call__()"
@myDecorator
def aFunction():
print "inside aFunction()"
def main():
print ... | The decorator syntax:
```
@myDecorator
def aFunction():
…
```
is equivalent to this:
```
def aFunction():
…
aFunction = myDecorator(aFunction)
```
If `myDecorator` is a class, then you would expect `__init__` to get called when the function is defined. The instance of the class is then used in place of the ... | A function definition in Python
```
def foo():
pass
```
is actually a programmer-friendly way to say something like (pseudocode)\*:
```
foo = function(code=compile('pass', ...), globals=globals(), name='foo')
```
so a wrapper simply gets in between:
```
foo = my_wrapper(function(...))
```
if the wrapper is a ... | why and how __call__ is invoked in python decorators | [
"",
"python",
"python-2.7",
""
] |
I'm using Sympy to substiture a set of expressions for another using the Subs function, and I would like for the program not to rearrage or simplify the equations.
i.e if i were substituting `x+y` for `a` in
`a+b+c+a` to return `x+y+b+c+x+y`
Does anyone know of a way to perform this?
Many thanks | The only way to do it is to do `Add(x, y, b, c, x, y, evaluate=False)`, which unfortunately isn't very easy to work with. | I have found a better way of going about this rather than using classes like `Add`. What if you have an expression that has a lot of operations? Using these classes would be cumbersome.
Instead, we can use the `evaluate` function, which is used inside of a context manager. Here is an example of an expression that has ... | prevent Sympy from simplifying expression python after a substitution | [
"",
"python",
"sympy",
""
] |
I open a text file and loop on all the lines sorting each into a personally accustomed dictionary.
```
def load(fileName):
file = open(fileName+'.txt')
for line in file:
row = line.split()
id = int(row[0])
number = int(row[2])
values = [int(row[3]),int(row[4]),int(row[5]),int(ro... | ```
from collections import OrderedDict as od
with open("abc") as f:
dic = od()
for line in f:
row = map(int,line.split())
idx, num = row[2], row[0]
val = [num] + [row[3:-1]]
dic.setdefault(idx,[]).append(val)
for k,v in dic.items():
for val in v:
print k,val
```
**outp... | Just keep the numbers and ids you've seen in a dictionary you append to as you go along. Since both must match, you can group them as a tuple:
```
def load(fileName):
dupes_dic = {}
file = open(fileName+'.txt')
for line in file:
row = line.split()
id = int(row[0])
number = int(row[2... | How to find duplicate values in next lines? | [
"",
"python",
""
] |
My original 2.7 code is here:
```
myFile = open(prjFile, 'w+')
myFile.write("""<VirtualHost 192.168.75.100:80>
ServerName www.{hostName}
ServerAlias {hostNameshort}.* www.{hostNameshort}.*
DocumentRoot {prjDir}/html
CustomLog \\|/usr/sbin/cronolog /var/log/httpd/class/{prjCode}/... | The error tells it all, you're passing a `tuple` to `__mod__` when it requires a mapping (`dict`). e.g. you want something like:
```
print """<VirtualHost 192.168.75.100:80>
ServerName www.%(hostName)s
ServerAlias %(hostNameshort)s.* www.%(hostNameshort)s.*
DocumentRoot %(prjDir)s/html
CustomLog \\|/us... | you can remove the names from the format strings, like `%(hostNameshort)s` to `%s` or feed that data as a dictionary. | Python: 2.4 Format String Not Working | [
"",
"python",
""
] |
I'm doing some testing to see if I can speed up a particular result set, but can't seem to get this particular solution working. I have data coming a few different tables and want to combine the data. I want to try this without using a union select to see if I get a performance improvement.
When I have a custom table/... | I don't think that approach will be faster, in fact I expect it to be much slower.
But if you do want to do it, you need to put the rows from the second select into an intermediate collection and then join both using `multiset union`.
Something like this:
```
create or replace function
academic_history(p_student_i... | Thanks a\_horse\_with\_no\_name for pointing out that doing the multiple selects one at a time will probably be slower. I was able to reduce the execution time by filtering each select by student\_id and then union-ing (rather than union-ing everything then filtering). On the data set I'm working with this solution was... | oracle results from tables using function | [
"",
"sql",
"oracle",
""
] |
Is it possible to delete a group (by group name) from a groupby object in pandas? That is, after performing a groupby, delete a resulting group based on its name. | Filtering a DataFrame groupwise has been [discussed](https://stackoverflow.com/questions/13446480/python-pandas-remove-entries-based-on-the-number-of-occurrences#comment18556837_13447176). And a future release of pandas may include [a more convenient way to do it](https://github.com/pydata/pandas/pull/3680).
But curre... | Seems there's no direct way to delete a group from a groupby object. I think you can filter out those groupby before groupby by
```
df = df[df[group] != group_name]
``` | Delete a group after pandas groupby | [
"",
"python",
"pandas",
""
] |
i have 3 tables
**Buyer**
```
buyer_id | name
50 |Joe
60 |Astor
70 |Cloe
```
**Item**
```
item_id | description
1 | iphone
2 | ipod
3 | imac
```
**Item\_Sold**
```
buyer_id | item_id
50 | 1
50 | 2
60 | 1
60 | 3
70 | 1
70 | 2
70 | 3
```
... | This query will give all item id decription whose sale is maximum i.e. when two or more item id have equal amount of sale....
```
;WITH CTE1(Id,Counts) as
(
SelectItem_Id,COUNT(buyer_id ) AS C FROM T GROUP BY ID
)
Select Item.Description from CTE1 A inner join
(Select MAX(Counts) AS MaxCount FROM CTE1 ) b on a.Cou... | ```
SELECT description AS Best_Selling
FROM item
WHERE item_id = (SELECT item_id FROM( SELECT item_id ,COUNT(*) as num_items
FROM Item_Sold
GROUP BY item_id
ORDER BY num_items DESC
... | select max value from a table looking for description in another table | [
"",
"sql",
"sqlite",
"count",
"nested",
"max",
""
] |
I have a table full of user payments. Each user can have multiple payments. I'm looking to select the latest payment for each user.
```
SELECT DATE_FORMAT(FROM_UNIXTIME(MAX(p.date)), "%D %M %Y") as last_payment, p.user_id, p.amount, p.period, p.txn_id, u.name
FROM payments as p
INNER JOIN users as u
ON u.id = p.user_... | You are looking for the [groupwise maximum](http://dev.mysql.com/doc/en/example-maximum-column-group-row.html); the most common way is to join the payments table back to the grouped results:
```
SELECT DATE_FORMAT(FROM_UNIXTIME(p.date), '%D %M %Y') AS last_payment,
p.user_id, p.amount, p.period, p.txn_id, u... | ```
SELECT u.*
, x.*
FROM payments x
JOIN (SELECT user_id,MAX(date) max_date FROM payments GROUP BY user_id) y
ON y.user_id = x.user_id
AND x.date = y.max_date
JOIN users u
ON u.id = x.user_id;
``` | MySQL Selecting the latest payments from a table with a list of users with multiple payments | [
"",
"mysql",
"sql",
""
] |
I'm trying to write a PL/SQL function that takes the name of a player as a parameter and returns the number of matches played in his favorite stadiums.
If the player doesn't exist in the players table, the function should returns -2. If the player exists but he doesn't have any favorite stadium, the function returns -... | ```
if (count(case when favstadiums.stadium = matches.stadium then 1 else null end) > 0) then
return fav_stadium_count;
end if;
```
should just be:
```
if (fav_stadium_count > 0) then
return fav_stadium_count;
end if;
```
As far as the following statement:
```
if players.name is null then
return -2;
end if... | I think it's your joins that have the incorrect syntax. Try: INNER JOIN and LEFT OUTER JOIN. Doing and an outer join without specifying which side has got to be wrong. | PL/SQL function compilation errors | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have a SQLite3 table with the following fields:
```
id INTEGER PRIMARY KEY,
street_name TEXT NOT NULL,
house_number INTEGER NOT NULL,
entrance TEXT DEFAULT NULL,
postal_code INTEGER NOT NULL,
city TEXT NOT NULL
```
So as you can see, the **entrance** can be `NULL`, and is even set to that by default. This is a prob... | > but I can't edit the query to say `entrance IS ?` since that won't work when I pass anything other than `NULL`.
Yes, you can. This is not standard SQL, but a SQLite extension. From [SQLite Query Language](http://www.sqlite.org/lang_expr.html):
> The IS and IS NOT operators work like = and != except when one or both... | (NULL is a thoroughly broken concept, but let's not go there just now…)
You can substitute a magic string to represent NULL — the empty string usually does the trick — and do this:
```
WHERE
…
COALESCE(entrance, '') = ? AND
…
```
If you need to treat the empty string as different to NULL, the output of `... | Why does matching NULL require special syntax in SQL, and how do I get around it? | [
"",
"sql",
""
] |
I have two databases `LIVE` and `DEVEL`. I am currently working in `DEVEL` and have created and modified a number of stored procedures however I am running out of test data so I need to find a way to copy data from `LIVE` to `DEVEL` but I don't want to lose my stored procedures.
I am using SQL Server 2008 Management S... | I would ensure all my SP's are scripted off into files I can re-run on demand.
There are comparison tools within VS which allow you to script off changes, or you can manually go into the DEVEL database, expand the `Programmability` > `Stored Procedures` node, right click you new SP's and select `Script Stored Procedur... | Execute this query for your tables, copy output data and run it's on another database.
**Query:**
```
DECLARE
@TableName SYSNAME
, @ObjectID INT
, @IsImportIdentity BIT = 1
DECLARE [tables] CURSOR READ_ONLY FAST_FORWARD LOCAL FOR
SELECT
'[' + s.name + '].[' + t.name + ']'
, t.[... | How to migrate SQL data and keep SP's | [
"",
"sql",
"sql-server",
"database",
""
] |
I have this code:
```
select CAST(OPERATOR_NAME AS NVARCHAR(MAX)) as 'Utilizador',
TERMINAL_DESCRIPTION as 'Terminal',
DOCUMENT_DATE as 'Data de Inicio',
PAYMENT_LIMIT_DATE as 'Data de Fim',
ORIGIN_WAREHOUSE_NAME as 'Loja',
DOCUMENT_TYPE_DESCRIPTION as 'Tipos de Documentos'
from MRD_DOCUMENT_HEADER
GROUP BY CAST(OPE... | Try this one -
```
SELECT
Utilizador = OPERATOR_NAME
, Terminal = TERMINAL_DESCRIPTION
, [Data de Inicio] = DOCUMENT_DATE
, [Data de Fim] = PAYMENT_LIMIT_DATE
, Loja = ORIGIN_WAREHOUSE_NAME
, [Tipos de Documentos] = DOCUMENT_TYPE_DESCRIPTION
FROM dbo.MRD_DOCUMENT_HEADER
GROUP BY
O... | You have to put those columns in a `GROUP BY` clause. It will solve your problem. Just use the below code:
```
select CAST(OPERATOR_NAME AS NVARCHAR(MAX)) as 'Utilizador',
TERMINAL_DESCRIPTION as 'Terminal',
DOCUMENT_DATE as 'Data de Inicio',
PAYMENT_LIMIT_DATE as 'Data de Fim',
ORIGIN_WAREHOUSE_NAME as 'Loja',
DOCUME... | Is there any way to group by a text column? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
actuals and peaks are both lists of lists of integers.
In my code, I attempted to make a dictionary from lists of integers to lists of lists of integers as follows:
```
mapping={}
for a in actuals:
mapping[a]=[v for v in peaks if v[0]==a[0]]
```
It returned, however, the error
```
TypeError: unhashable type: 'l... | Looks like `a` is of type list (`actuals` being a list of lists). You are trying to assign a key to a dictionary to a `list` which is not possible. you have to come up with some other key, which is hashable. | if each `a` is a list you are not going to change, you can make a tuple out of it:
```
mapping={}
for a in actuals:
mapping[tuple(a)]=[v for v in peaks if v[0]==a[0]]
``` | List unhashable error? | [
"",
"python",
"list",
"hash",
"dictionary",
""
] |
I am asking because of the classic problem where somebody creates a list of lambdas:
```
foo = []
for i in range(3):
foo.append((lambda: i))
for l in foo:
print(l())
```
and unexpectedly gets only twos as output.
The commonly proposed solution is to make `i` a named argument like this:
```
foo = []
for i in... | The issue here is how you think of names.
In your first example, `i` is a variable that is assigned to every time the loop iterates. When you use `lambda` to make a function, you make a function that accesses the name `i` and returns it's value. This means as the name `i` changes, the value returned by the functions a... | Python doesn't exactly pass by reference **or** by value (at least, not the way you'd think of it, coming from a language like C++).
In many other languages (such as C++), variables can be thought of as synonymous with the values they hold.
However, in Python, variables are names that point to the objects in memory.
[(... | When is a new name introduced in Python? | [
"",
"python",
"reference",
"scope",
"immutability",
""
] |
Currently I have an SQL query that selects some columns and then does ORDER\_BY ID.
Simple enough. The output is i.e. 92, 101, 105, 200, 1234
Problem is, the program I am trying to use it in will only accept input in alphanumerical order. That means I need it to be 101, 105, 1234, 200, 92.
How can I modify the SQL q... | One option would be to convert the column to a `VARCHAR` then sort on that
```
SELECT OrderID
FROM dbo.FooTable
ORDER BY CAST(OrderID AS VARCHAR(255))
``` | You can do this by converting the number to a character string:
```
order by cast(col as varchar(255))
```
For instance. | SQL order numbers alphabetically | [
"",
"sql",
"sql-order-by",
""
] |
I have a large string more than 256 bits and and I need to byte swap it by 32 bits. But the string is in a hexadecimal base. When I looked at numpy and array modules I couldnt find the right syntax as to how to do the coversion. Could someone please help me?
An example:(thought the data is much longer.I can use pack b... | If they really are strings, just do string operations on them?
```
>>> input = "12345678abcdeafa"
>>> input[7::-1]+input[:7:-1]
'87654321afaedcba'
``` | Convert the string to bytes, unpack big-endian 32-bit and pack little-endian 32-bit (or vice versa) and convert back to a string:
```
#!python3
import binascii
import struct
Input = b'12345678abcdeafa'
Output = b'78563412faeacdab'
def convert(s):
s = binascii.unhexlify(s)
a,b = struct.unpack('>LL',s)
s =... | How to byteswap 32bit integers inside a string in python? | [
"",
"python",
""
] |
Trying to get the SSL certificate from a response in [`requests`](http://docs.python-requests.org/en/latest/).
What is a good way to do this? | `requests` deliberately wraps up low-level stuff like this. Normally, the only thing you want to do is to [verify that the certs are valid](http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification). To do that, just pass `verify=True`. If you want to use a non-standard cacert bundle, you can pass ... | To start, [abarnert's answer](https://stackoverflow.com/a/16904808/2197939) is very complete. While chasing the proposed `connection-close` issue of [Kalkran](https://stackoverflow.com/users/5384754/kalkran) I actually discovered that the `peercert` didn't contain detailed information about the SSL Certificate.
I dug ... | How to get response SSL certificate from requests in python? | [
"",
"python",
"http",
"https",
"request",
"python-requests",
""
] |
I store some SQL queries in a table, in a `varchar` column. Then I execute them in my Birts Reports Data Sets, that's ok, but sometimes I need to check the SQL query but when I copy from the SQL editor then I get the query in a single line.. I would like to know how to get that column and give some indentation, like be... | I found this sp at [T-SQL\_Exceeding\_the\_8000\_Byte\_Limit\_of\_the\_PRINT\_Statement](http://blog.falafel.com/Blogs/adam-anderson/2007/02/28/T-SQL_Exceeding_the_8000_Byte_Limit_of_the_PRINT_Statement)
```
-- Works around the 4000/8000 character limit of the print statement
CREATE PROCEDURE dbo.LongPrint( @string nv... | I've used this tool in the past and it works pretty well:
<http://www.dpriver.com/pp/sqlformat.htm> | How to format a SQL query from a table column? | [
"",
"sql",
"sql-server",
"t-sql",
"code-formatting",
""
] |
How to start an always on Python Interpreter on a server?
If bash starts multiple python programs, how can I run it on just one interpreter?
And how can I start a new interpreter after tracking number of bash requests, say after X requests to python programs, a new interpreter should start.
EDIT: Not a copy of <http... | You cannot have new Python programs started through bash run on the same interpreter, each program will always have its own. If you want to limit the number of Python programs running the best approach would be to have a Python daemon process running on your server and instead of creating a new program through bash on ... | To run a program forever in python:
```
while True :
do_work()
```
You could look at spawning threads for incoming request. Look at threading.Thread class.
from threading import Thread
```
task = new Thread(target=do_work, args={})
task.start()
``` | Python: How to Run multiple programs on same interpreter | [
"",
"python",
"python-2.7",
""
] |
```
ABC:123 UVW XYZ NN-000
```
What is the best method to get the value after the last space using `substr()`? In this case I want to get `NN-000` but also be able to get that last value in the case that it's greater than or less than 6 characters. | In MySQL you could use [`reverse`](http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_reverse) and [`substring_index`](http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_substring-index):
```
select data,
rv,
reverse(substring_index(rv, ' ', 1)) yd
from
(
select data,
... | In Oracle, use `SUBSTR` and `INSTR` functions
```
SELECT SUBSTR('ABC:123 UVW XYZ NN-000', INSTR('ABC:123 UVW XYZ NN-000', ' ', -1))
AS LASTOCCUR
FROM DUAL
```
***RESULT:***
```
| LASTOCCUR |
-------------
| NN-000 |
```
Refer **[LIVE DEMO](http://sqlfiddle.com/#!4/d41d8/11924)** | Substring from last index | [
"",
"mysql",
"sql",
"oracle",
"substring",
""
] |
I have two dictionaries created this way :
```
tr = defaultdict(list)
tr = { 'critic' : '2_critic',
'major' : '3_major',
'all' : ['2_critic','3_major']
}
```
And the second one :
```
scnd_dict = defaultdict(list)
```
And contains values like this :
```
scnd_dict = {'severity': ['all']}
```
I want to have a th... | Well...
```
from collections import defaultdict
tr = {'critic' : '2_critic',
'major' : '3_major',
'all' : ['2_critic','3_major']}
scnd_dict = {'severity': ['all']}
third_dict = {}
for k, v in scnd_dict.iteritems():
vals = []
if isinstance(v, list):
for i in v:
vals.append(t... | Your problem is that `v` is a list, not an item of a list. So, the `if v in tr:` will be false. Change your code so that you iterate over the items in `v` | Python : Match a dictionary value with another dictionary key | [
"",
"python",
"dictionary",
""
] |
```
def insert(array):
connection=sqlite3.connect('images.db')
cursor=connection.cursor()
cnt=0
while cnt != len(array):
img = array[cnt]
print(array[cnt])
cursor.execute('INSERT INTO images VALUES(?)', (img))
cnt+= 1
connection.commit()
connection... | You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:
```
cursor.execute('INSERT INTO images VALUES(?)', (img,))
```
Without the comma, `(img)` is just a grouped expression, not a tuple, and thus the `img` string is treated as the input sequence. If that string is 74 characters lon... | For me this problem happened when the number of columns are not same as the inserting values.
For example:
```
conn = sqlite3.connect(',ySQL.db')
c = conn.cursor()
sql = "INSERT INTO mytable (X1, X2, X3) VALUES (?,?,?)"
project = (Y1, Y2)
print(project)
c.execute(sql, pro... | sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied | [
"",
"python",
"sqlite",
""
] |
I'm using mod\_wsgi to serve up a django website, but I've got an internal server error. Here's the apache log:
```
[Fri May 31 10:11:25 2013] [error] python_init: Python version mismatch, expected '2.7.2+', found '2.7.3'.
[Fri May 31 10:11:25 2013] [error] python_init: Python executable found '/usr/bin/python'.
[Fri ... | You have to compile mod\_wsgi from source and reinstall.
Most likely as simple as:
```
$ ./configure
$ make
$ sudo make install
```
[The mod\_wsgi documentation](https://code.google.com/p/modwsgi/wiki/QuickInstallationGuide) covers this in detail. | I didn't have to compile from source, this helped me:
```
$ apt-get remove libapache2-mod-python libapache2-mod-wsgi
$ apt-get build-dep libapache2-mod-python libapache2-mod-wsgi
``` | How can I rebuild my mod_wsgi to use python 2.7.3? | [
"",
"python",
"apache",
"mod-wsgi",
""
] |
I have a CSV file with the column names in upper case. I am reading the data using csv.dictreader but need the column names in lowercase.
I found this code here [Accessing csv header white space and case insensitive](https://stackoverflow.com/questions/12956930/accessing-csv-header-white-space-and-case-insensitive)
`... | You could lowercase the first line of the file before passing it to `DictReader`:
```
import csv
import itertools
def lower_first(iterator):
return itertools.chain([next(iterator).lower()], iterator)
with open(ifs_data_file, 'rU') as datafile:
csvDict = csv.DictReader(lower_first(datafile))
for row in cs... | `DictReader` is an old-style object, so `super()` doesn't work at all here. You need to directly access the `property` object in the parent class. In Python 2, you want to override the `.next()` method, not `.__next__()`:
```
class DictReaderInsensitive(csv.DictReader):
# This class overrides the csv.fieldnames pr... | Python dictreader - How to make CSV column names lowercase? | [
"",
"python",
"python-2.7",
"csv",
""
] |
For an example, I would like to select id with max date group by category,
the result is: 7, 2, 6
```
id category date
1 a 2013-01-01
2 b 2013-01-03
3 c 2013-01-02
4 a 2013-01-02
5 b 2013-01-02
6 c 2013-01-03
7 a 2013-01-03
8 b 2013-01-0... | This is a perfect use-case for [**`DISTINCT ON`**](https://www.postgresql.org/docs/current/sql-select.html#SQL-DISTINCT) - a Postgres specific extension of the standard `DISTINCT`:
```
SELECT DISTINCT ON (category)
id -- , category, date -- any other column (expression) from the same row
FROM tbl
ORDER BY ... | Try this one:
```
SELECT t1.* FROM Table1 t1
JOIN
(
SELECT category, MAX(date) AS MAXDATE
FROM Table1
GROUP BY category
) t2
ON T1.category = t2.category
AND t1.date = t2.MAXDATE
```
### See [this SQLFiddle](http://sqlfiddle.com/#!17/144a9/96) | How to select id with max date group by category in PostgreSQL? | [
"",
"sql",
"postgresql",
"greatest-n-per-group",
""
] |
**My Database:**
```
CREATE DATABASE `cars` /*!40100 DEFAULT CHARACTER SET latin1 */;
DROP TABLE IF EXISTS `cars`.`employees`;
CREATE TABLE `cars`.`employees` (
`emp_id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(40) DEFAULT NULL,
`last_name` varchar(40) DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGI... | This is a design decision that goes over the 1NF direction you ( or somebody else over your organization ) must considerate prior to development. To respond your concrete question, this is the typical case where a XRef table is needed to put together all the Customer-Vehicle associations along with extra details refere... | Possibly create a table for holding which employees sold which cars?
```
EmployeeSales
---------------
emp_id
prod_id
OtherInfo
``` | SQL database design advice needed | [
"",
"sql",
"database",
"database-design",
""
] |
I have this text file made up of numbers and words, for example like this - `09807754 18 n 03 aristocrat 0 blue_blood 0 patrician` and I want to split it so that each word or number will come up as a new line.
A whitespace separator would be ideal as I would like the words with the dashes to stay connected.
This is w... | Given this file:
```
$ cat words.txt
line1 word1 word2
line2 word3 word4
line3 word5 word6
```
If you just want one word at a time (ignoring the meaning of spaces vs line breaks in the file):
```
with open('words.txt','r') as f:
for line in f:
for word in line.split():
print(word)
```
Prints:... | ```
f = open('words.txt')
for word in f.read().split():
print(word)
``` | Reading a text file and splitting it into single words in python | [
"",
"python",
"string",
"split",
""
] |
I'm trying to check if a string is numeric or not, using the `isnumeric` function, but the results are not as expected. The function works only if it's a unicode string.
```
>>> a=u'1'
>>> a.isnumeric()
True
>>> a='1'
>>> a.isnumeric()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeE... | > Often you will want to check if a string in Python is a number. This
> happens all the time, for example with user input, fetching data from
> a database (which may return a string), or reading a file containing
> numbers. Depending on what type of number you are expecting, you can
> use several methods. Such as pars... | Just different name.
'1'.isdigit()
True | Python isnumeric function works only on unicode | [
"",
"python",
""
] |
I am trying to read 2 files at the same time right now, but I get a "too many values to unpack error". Here is what I have:
```
for each_f, each_g in f, g :
line_f = each_f.split()
line_g = each_g.split()
```
I am a little new to python but I assumed I would be able to do this. If this is impossible, is there... | ```
import itertools
# ...
for each_f, each_g in itertools.izip(f, g):
# ...
``` | You can use a context manager, i.e. the with statement to read two files at the same time:
```
with open('file1', 'r') as a, open('file2', 'r') as b:
do_something_with_a_and_b
``` | Is there a way to read two files at the same time in python? (with the same loop?) | [
"",
"python",
""
] |
I'm trying to convert an integer to binary using the bin() function in Python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit:
Example:
```
bin(1) -> 0b1
# What I would like:
bin(1) -> 0b00000001
```
Is there a way of doing this? | Use the [`format()` function](http://docs.python.org/2/library/functions.html#format):
```
>>> format(14, '#010b')
'0b00001110'
```
The `format()` function simply formats the input following the [Format Specification mini language](http://docs.python.org/2/library/string.html#format-specification-mini-language). The ... | ```
>>> '{:08b}'.format(1)
'00000001'
```
See: [Format Specification Mini-Language](https://docs.python.org/2/library/string.html#format-specification-mini-language)
---
Note for Python 2.6 or older, you cannot omit the positional argument identifier before `:`, so use
```
>>> '{0:08b}'.format(1)
'00000001'
``` | Convert to binary and keep leading zeros | [
"",
"python",
"binary",
"formatting",
"bitwise-operators",
""
] |
The Python code I have looks like this
```
f = open('data.tsv', 'r')
for line in f:
a = line.split("\t")
e_id = a[1]
name = a[2]
start = a[3]
end = a[4]
loc = a[5]
tags = a[6]
url = a[7]
cur = con.cursor(mdb.cursors.DictCursor)
cur.execute("INSERT INTO data_table VALUES (" + e_... | Your true problem likes in that your `"City, State"` line is a sequence of characters. You cannot directly insert a sequence of characters in SQL like this:
```
INSERT INTO test VALUES (My String);
```
Instead, you treat it like a string. MySQL expects strings to be wrapped in single quotes, so you would change the a... | Be careful when building queries in this format. Before and after concatenating an string you need to put commas. For example,
```
INSERT INTO data_table VALUES ('" + e_id + "','" + name + "','" + start + "','" + end + "','" + loc + "','" + tags + "','" + url + "');")
```
I hope it helps to solve your issue.
Also, y... | Using Python to insert in MySQL database, but gets stuck on commas in data | [
"",
"python",
"mysql",
""
] |
I am a novice python learner, though I know printing text containing strings and variables but I want to ask a basic question regarding this. Here is my code:
```
x=5
print ("the value of x is ",x) ... | Print is a statement in py2x not function. so printing `("the value of x is ",x)` actually prints a tuple:
```
>>> type(('hello'))
<type 'str'>
>>> type(('hello',)) # notice the trailing `,`
<type 'tuple'>
```
In py2x just remove the `()` to get the correct output:
```
>>> print "the value of x is","foo"
the valu... | Because `('hello')` is just `'hello'`, not a 1-tuple. | printing string containing variables in python | [
"",
"python",
""
] |
I have two tables that are identical in structure. `Table1` holds moderated data, `table2` holds data that still has not been moderated.
**Table 1**
```
+------+-----------+-----------------+--------+-----------+----------+
| "id" | "name" | "description" | "type" | "country" | "status" |
+------+-----------+---... | While you can update two tables with the following syntax
```
UPDATE TBL1, TBL2
SET TBL1.status = 'Blah', TBL2.status = 'blah'
WHERE TBL1.id = TBL2.id
AND TBL2.id = 2;
```
but this could be harmful. Consider the following case: when TBL2 contains row with id = 2, while TBL1 does not have a row with id = 2. It ... | Rather going to update 2 tables with a single statement(which is cumbersome), It can be a easy n safer way to use `Transactions` in your Query/ Stored procedure. It will ensure update for both of tables in a go.
```
START TRANSACTION;
UPDATE table1 SET summary=@A WHERE type=1;
UPDATE table2 SET summary=@A WHERE type=1... | Updating a column in two different tables with one sql | [
"",
"mysql",
"sql",
""
] |
Suppose I owned a business that sold cars and motorcycles. I want to track data on each. My company provides a free warranty for every car, but we do not even offer warranties on motorcycles. Initially, I thought I'd have two tables - a "Vehicles" table and a "Warranties" table, like this
```
Vehicles ... | Store the motorcycles and cars in the same table.
It's totally ordinary to allow a column to be NULL when the attribute does not pertain to the type of data in a given row. NULL is for "unknown, missing, or inapplicable data." | Sounds like you could consider a join table.
```
Vehicle VehicleWarranty Warranty
--------- --------------- ----------
VehicleId VehicleId WarrantyId
SalePrice WarrantyId EffectiveDate
```
That way, there's no Warranty ID in ... | How do I properly design a database schema for this scenario | [
"",
"sql",
"database",
"database-design",
""
] |
I want to generate dynamically a geoJSON with a variable number of polygons. Example for 2 polygons:
```
{
"type": "FeatureCollection",
"features": [
{"geometry": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Polygon",
... | If you can get the libraries installed, django has some good tools for dealing with geometry objects, and these objects have a `geojson` attribute, giving you access to the GeoJSON representation of the object:
<https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/>
```
>>> from django.contrib.gis.geos impor... | There is the python-geojson library (<https://github.com/frewsxcv/python-geojson>), which seems to make this task also much easier. Example from the library page:
```
>>> from geojson import Polygon
>>> Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]])
{"coordinates": [[[2.3..., 57.3... | Building a GeoJSON with Python | [
"",
"python",
"json",
"dictionary",
"geojson",
""
] |
Recently I've got a small problem with if else statement. Namely I want to create a function that asks user for input whether he wants to read the file that script has created or not, so if the input is correct function does its thing however when input is incorrect I want it to revert to question again.
Here's the co... | How about this
```
import sys
def getUserResponse():
print """
Do you want me to read your newly created file?
Type [Y]es or [N]o
"""
return raw_input("> ")
def read_the_file(output_file):
output = open(output_file)
question = getUserResponse()
while (True):
if question == 'yes' or question ... | You can realize this using a while loop. It returns to the start whenever there was no break or sys.exit, which means on every wrong input here. Hope this helps
```
def read_the_file(output):
while True:
print """
Do you want me to read your newly created file?
Type [Y]es or [N]o
... | How to repeat function in Python depending on output? | [
"",
"python",
"if-statement",
"repeat",
""
] |
I need to select the last row in `mytable` for a given pair of columns in Oracle v11.2:
```
id type timestamp raw_value normal_value
-- ---- --------- --------- ------------
1 3 3pm 3-Jun "Jon" "Jonathan"
1 3 5pm 3-Jun "Jonathan" "Jonathan"
1 3... | You can do this with the `row_number()` function:
```
select raw_value, normal_value, timestamp
from (select myt.*, ROW_NUMBER() over
(partition by id, type order by timestamp desc)
as seqnum
from mytable myt
) tmp
where seqnum = 1
and id = 1 and type = 3;
```
`row_number()` is an analytic... | Try this:
```
SELECT m1.raw_value, m1.normal_value
FROM mytable m1
WHERE id = 1 and type = 3 and timestamp = (
SELECT MAX(timestamp)
FROM mytable m2
WHERE m1.id = m2.id and m1.type = m2.type
GROUP BY m2.id, m2.type
)
``` | How to select last entry for one distinct pairing of two columns in Oracle? | [
"",
"sql",
"oracle",
"oracle11g",
"greatest-n-per-group",
""
] |
Is there some easy way to access an object in a list, without using an index or iterating through the list?
In brief:
I'm reading in lines from a text file, splitting up the lines, and creating objects from the info. I do not know what information will be in the text file. So for example:
roomsfile.txt
> 0\bedroom\A... | At least one dictionary is the right answer here. The way you want to set it up is at least to index by name:
```
def roomSetup():
roomsfile = "roomsfile.txt"
infile = open(roomsfile, 'r')
rooms = {}
for line in infile:
newroom = makeRooms(line)
rooms[newroom.roomName] = newroom
inf... | You can use `in` to check for membership (literally, if something is *in* a container). This works for lists, strings, and other iterables.
```
>>> li = ['a','b','c']
>>> 'a' in li
True
>>> 'x' in li
False
``` | Is there a way to find objects in a list without iterating through the list? | [
"",
"python",
"object",
""
] |
I have a dictionary with location and quantity, like
```
{'loc1': 1000.0,'loc2': 500.0, 'loc3': 200.0,'loc4': 100.0,'loc5': 50.0, }
```
Now when i'll make a order the scenario should be like below,
* for `150 quantity` it should take product from `loc5` and `loc4`
* for `210 quantity` it should take product from `lo... | Put the quantities in a list, sorted. [Use `bisect` to find an appropriate quantity.](http://docs.python.org/2/library/bisect.html#searching-sorted-lists) Calculate if the lower quantities can fulfill, and if not pick the next higher quantity. Subtract the selected quantity. If still greater than 0, go back to the `bis... | ```
def find_combination(d,val):
"""(dict,int)->list
Given a dict with values as numbers, returns the combination of keys whose values sums up to "val"
In case no values form a perfect sum, picks up the next best case
"""
new_list = sorted(d.items(),key=lambda y: y[1],reverse=True)
result = []
... | Fetching data from the list | [
"",
"python",
"dictionary",
""
] |
What is a good way to check to see if a collection of properties exist inside a dict object in Python?
Currently we are doing this, but it seems like there may be a better way:
```
properties_to_check_for = ['name', 'date', 'birth']
for property in properties_to_check_for:
if property not in dict_obj or dict_obj[... | You can use `all` with a generator:
```
all(key in dict_obj for key in properties_to_check_for)
```
It'll short-circuit, just like your `for` loop. Here's a direct translation of your current code:
```
all(dict_obj.get(key) is not None for key in properties_to_check_for)
```
`d.get(key)` will return `None` if the k... | You could use `any()`:
```
any(dict_obj.get(prop) is None for prop in properties_to_check_for )
```
This will return True if any `property` is not found in `properties_to_check_for` or if it's value is `None`. | Check to see if a collection of properties exist inside a dict object in Python | [
"",
"python",
"dictionary",
""
] |
I have a Table:
`Date, HoursToWork, Workers_ID, Contract_ID, ContractStartDate`
My goal is to sum all hours for the CURRENT contract since the contract can change every day a year the date goes from the 01.01. - 31.12.. There are 'n' contracts possible. We can work with the Contract\_ID (if there is more than one ID,... | Your clarification is that you want this by user. To get the current contract, use `row_number()` and choose the most recent `ContractId` for each user. Then, just do the aggregation:
```
select workers_id, ContractId, ContractStartDate, SUM(HoursToWork)
from (select t.*,
ROW_NUMBER() over (partition by W... | Try:
```
select sum(h.HoursToWork)
from (select max(contract_ID) contract_ID
from contracts_table
where XXX=workers_ID) c
join hours_table h on c.contract_ID = h.contract_ID
``` | Sum values depending on Date | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.