Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm writing a set of python functions that perform some sort of conformance checking on a source code project. I'd like to specify quite verbose names for these functions, e.g.: `check_5_theVersionOfAllVPropsMatchesTheVersionOfTheAutolinkHeader()`
Could such excessively long names be a problem for python? Is there a m... | [2.3. Identifiers and keywords](https://docs.python.org/2/reference/lexical_analysis.html#identifiers) from The Python Language Reference:
> Identifiers are unlimited in length.
---
But you'll be violating [PEP-8](http://www.python.org/dev/peps/pep-0008/#maximum-line-length) most likely, which is not really cool:
>... | They could be a problem for the programmer. Keep the function names reasonably short, and use docstrings to document them. | What is the maximum length for an attribute name in python? | [
"",
"python",
"python-2.7",
""
] |
I frequently find myself creating homogeneous sets of objects, which i usually store in a dict or list dictionaries.
```
a,b,c = MyClass(...), MyClass(...), MyClass(...)
my_set = {'a':a,'b':b,'c':c}
```
On a set like this, common needs are
* returning homogeneous sets from the object properties or methods
+ ... | You are look for special methods of classes. Have a look `__getattr__` and `__getitem__`. You can write your own class. Its instances of this class can have `a`, `b` and `c` as attributes and can do what you describe.
Some thing like this might do part of what you like to do:
```
class DictCollcetion(object):
def... | I've run into cases where I have manipulated big lists of dictionaries or objects, much like you have. Often those objects are pulled out of a database and populated via an ORM, but I've done it with CSV files as well.
I am not sure that my needs are frequent/common enough that I would look for a module to give me syn... | Python class for homogenous sets of objects | [
"",
"python",
""
] |
I need to join both deptno and sal same time when comm is not null. I came up with following. But it only accept either deptno or sal. not both in same time.
```
select ename,deptno,sal,comm from emp where deptno,sal in(select sal,deptno from emp where comm is not null);
```
This is a self join.
I am trying it on or... | Your purpose is not clear, although it seems you want to write a multi-column semi-join using `IN`. In that case you can simply add parentheses:
```
SELECT ename, deptno, sal, comm
FROM emp
WHERE (sal, deptno) IN (SELECT sal, deptno FROM emp WHERE comm IS NOT NULL);
``` | You could use a real join:
```
SELECT e1.ename, e1.deptno, e1.sal, e1.comm
FROM emp e1
JOIN (SELECT distinct sal, deptno
FROM emp
WHERE comm IS NOT NULL) e2
ON e1.sal = e2.sal AND e1.deptno = e2.deptno
``` | Joining multiple column with multiple column | [
"",
"sql",
"oracle",
""
] |
I have this format of string
```
2013-06-05T11:01:02.955 LASTNAME=Jone FIRSTNAME=Jason PERSONNELID=salalm QID=231412 READER_NAME="CAZ.1 LOBBY LEFT TURNSTYLE OUT" ACCESS_TYPE="Access Granted" EVENT_TIME_UTC=1370480141.000 REGION=UTAH
```
some of them looks like this
```
2013-06-05T11:15:48.670 LASTNAME=Ga FIRSTNAME... | One hack I've found useful in the past is to use [`shlex.split`](http://docs.python.org/2/library/shlex.html#shlex.split):
```
>>> s = '2013-06-05T11:01:02.955 LASTNAME=Jone FIRSTNAME=Jason PERSONNELID=salalm QID=231412 READER_NAME="CAZ.1 LOBBY LEFT TURNSTYLE OUT" ACCESS_TYPE="Access Granted" EVENT_TIME_UTC=1370480141... | Let's analyze the problem: You want to match one of the four identifiers, then an `=` sign, and then either a quoted string or a sequence of non-whitespace characters.
That's a perfect job for a regular expression:
```
>>> s= ' 2013-06-05T11:01:02.955 LASTNAME=Jone FIRSTNAME=Jason PERSONNELID=salal
m QID=231412 READE... | how to separate string from unformed string | [
"",
"python",
""
] |
Select Users Who were 17 During a range of dates (From and End Date)--
Thanks everyone!
**Users**
* id
* birthdate
**Example:**
1. User\_1 Birthdate **09/28/1996**
2. User\_2 Birthdate **08/25/1996**
3. User\_3 Birthdate **07/28/1995**
4. User\_4 Birthdate **05/25/1995**
If Range of dates are **FROM 03/05/2013** ... | These should do it;
```
SELECT * FROM users
WHERE birthdate BETWEEN DATEADD(year, -18, '2013-03-05') -- lo date of range
AND DATEADD(year, -17, '2013-06-05'); -- hi date of range
SELECT * FROM users
WHERE birthdate BETWEEN DATEADD(year, -18, '2012-02-10') -- lo date of range
... | **My Preferred Method:**
Use date datatypes and explicit comparisons between dates. I recommend storing birthdate as a date datatype in SQL Server 2008+, and also using [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) format for datetime literals to avoid ambiguity.
```
select id, birthdate
from Users
where birthdat... | SQL Select Users Who age is 17 between Date Range | [
"",
"sql",
"sql-server-2008",
""
] |
I have a table containing records for patient admissions to a group of hospitals.
I would like to be able to link each record to the most recent previous record for each patient, if there is a previous record or return a null field if there is no previous record.
Further to this I would like to place some criteria of... | You could use `row_number()` to assign increasing numbers to records for each patient. Then you can `left join` to the previous record:
```
; with numbered_records as
(
select row_number() over (partition by PatientID, Hospital
order by Record desc) as rn
, *
... | It will give you the First 2 records of the same patients. If you want the same Hospital then add another check of Hospital with the `PatientID`. Also can add the Date as well.
```
SELECT * FROM T1 t
WHERE (2 >= (SELECT Count(*) FROM T1 tmp
WHERE t.PatientID = tmp.PatientID
AND t.Record <= ... | Link subsequent patient visits from same table in SQL | [
"",
"sql",
"sql-server-2008",
"self-join",
""
] |
I have a DQL query like:
```
$em->createQuery("
SELECT r
FROM WeAdminBundle:FamilyRelation r
WHERE r.col like :query
")
```
Now I want to change "col" depending on various parameters. How can i achieve this with DQL since the normal setParameter doesn't work here. | In short: you can't the way you want it.
To do it you'd need something like `$dql->setColumn(array('variable_column' => 'some_column_name'))` just as the [`bindColumn`](http://php.net/manual/en/pdostatement.bindcolumn.php) method from PDO, but there's no equivalent method ([bindColum](https://github.com/doctrine/doctr... | You can use setParameter with DQL, as [many examples are provided](http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html#dql-select-examples) but for LIKE clauses, make sure the variable is wrapped in `%`.
```
$em->createQuery("
SELECT r
FROM WeAdminBundle:FamilyRelation r
W... | Doctrine, escape variable field name in DQL | [
"",
"sql",
"doctrine",
"dql",
""
] |
I am writing an app and I want users to be able to input python files for corner cases. In my head the best way I can think of doing this is to save their file to disk and save the location to a DB then dynamically import it using `__import__()` and then execute it. The first part of my question is: is this the best wa... | You can use a combination of the `compile` and `exec` builtins for executing in memory. The downside is that you don't get source lines in tracebacks.
Not much hope about security though. Even if you put ridiculously restrictive filters in place, like restricting everything to a single expression and removing most bui... | you can do several things to limit powers (see my comment on OP)
but really my two cents ... just give each user their own VM (maybe AWS?) ... that way they cant screw up much... and you can always just restart it ...
a more complicated approach (but arguably cooler) would be to use lex/yacc (in python its PLY) and d... | Dynamically reading in a python file and executing it safely | [
"",
"python",
""
] |
Here's what I have at this point:
```
def checkPlayerCardInput(answer):
while True:
for x in range(len(player1Cards)):
if answer.lower() == player1Cards[x]:
return player1[x]
```
What I don't know is how to repeat the loop if the user misspells a word or enters something incorr... | Does this do what you want?
```
def checkPlayerCardInput(answer):
while True:
for x in range(len(player1Cards)):
if answer.lower() == player1Cards[x]:
return player1[x]
answer = raw_input('incorrect answer!')
``` | To check that an item is contained in a list use `in` operator. Like this:
```
if answer.lower() in player1CArds:
#...
```
Use a `while` loop to keep asking for `raw_input` until you're given a string found in the list. | How do I check raw_input against a list of strings? | [
"",
"python",
"python-2.7",
""
] |
I have an access database containing records pulled in from csv files which are published daily. From time to time, an existing record is updated. My current database is of the form
```
... ID ... Date on which the csv file was created
1 26/05/2013
1 27/05/2013
2 27/0... | Create a `DMax` expression which returns the most recent `creation_date` for each `ID`.
```
DMax("creation_date", "YourTable", "ID=" & <current ID>)
```
Then use that expression in a `SELECT` query to identify the rows which you want discarded.
```
SELECT
y.ID,
y.creation_date,
DMax("creation_date", "You... | If you want to delete all the older records with duplicate IDs at once, you can just execute this SQL.
However, it will require that you have a primary or unique field. I added a field called **RecID** that's just an autonumber field.
```
strSQL = ""
strSQL = strSQL & "DELETE " & vbCrLf
strSQL = strSQL & " t.recid, ... | Delete records if an updated record exists | [
"",
"sql",
"ms-access",
"vba",
""
] |
Is there a built-in function or a very simple way of finding the index of n largest elements in a list or a numpy array?
```
K = [1,2,2,4,5,5,6,10]
```
Find the index of the largest 5 elements?
I count the duplicates more than once, and the output should be a list of the indices of those largest numbers | Maybe something like:
```
>>> K
[4, 5, 1, 6, 2, 5, 2, 10]
>>> sorted(range(len(K)), key=lambda x: K[x])
[2, 4, 6, 0, 1, 5, 3, 7]
>>> sorted(range(len(K)), key=lambda x: K[x])[-5:]
[0, 1, 5, 3, 7]
```
or using `numpy`, you can use `argsort`:
```
>>> np.argsort(K)[-5:]
array([0, 1, 5, 3, 7])
```
`argsort` is also a m... | Consider the following code,
```
N=5
K = [1,10,2,4,5,5,6,2]
#store list in tmp to retrieve index
tmp=list(K)
#sort list so that largest elements are on the far right
K.sort()
#To get the 5 largest elements
print K[-N:]
#To get the 5th largest element
print K[-N]
#get index of the 5th largest element
print ... | How to find the index of n largest elements in a list or np.array, Python | [
"",
"python",
"arrays",
"list",
""
] |
I have a python method which accepts **a date input as a string**.
How do I add a validation to make sure the date string being passed to the method is in the ffg. format:
```
'YYYY-MM-DD'
```
if it's not, method should raise some sort of error | ```
>>> import datetime
>>> def validate(date_text):
try:
datetime.date.fromisoformat(date_text)
except ValueError:
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
>>> validate('2003-12-23')
>>> validate('2003-12-32')
Traceback (most recent call last):
Fi... | The [Python `dateutil`](http://labix.org/python-dateutil) library is designed for this (and more). It will automatically convert this to a `datetime` object for you and raise a `ValueError` if it can't.
As an example:
```
>>> from dateutil.parser import parse
>>> parse("2003-09-25")
datetime.datetime(2003, 9, 25, 0, ... | How do I validate a date string format in python? | [
"",
"python",
"date",
""
] |
I have a situation like the code below. I want to find the index of the first instance of the object A. What is the fastest way I can do that?
I know there are a lot of ways to go through the entire list and find it, but is there a way to stop the search once the first one is found?
```
class A():
def __init__(se... | ```
class A():
def __init__(self):
self.a = 0
def __eq__(self,other): #this overrides the equality check
if isinstance(other,A):
return self.a==other.a
def print(self):
print(self.a)
l = [0, 0, A(), 0, A(), 0]
print(l.index(A()))#now this should work
print A() in l
a1 = ... | You have to test each object; use a list comprehension and [`enumerate()`](http://docs.python.org/3/library/functions.html#enumerate) to get all matching indices:
```
[i for i, ob in enumerate(l) if isinstance(ob, A)]
```
or to get the *first* index, use `next()` and a generator expression:
```
next((i for i, ob in ... | Finding instance of Object type in list | [
"",
"python",
"list",
"search",
""
] |
This must be really basic, but after some searching I haven't found an answer yet.
I'm iterating through a list where some columns have values in them and some are empty. I'd like the code to skip the line if the column is empty. This is what I have:
```
for lines in luku:
split = lines.split("\t")
if "c-sarj... | Calling `int()` on an empty string raises `ValueError`, as you've seen.
Just use a `try/except` block:
```
for lines in luku:
split = lines.split("\t")
if "c-sarja" in split and "F" in split[2]:
try:
age = int(split[8])
except ValueError:
continue # Skip to the... | If you are in a for loop and want to skip the current item, just do `continue` and execution will jump to the next item in the for loop.
(Alternatively, do nothing. Then execution will flow to the start of the next loop through anyway.) | how to skip an empty column with python | [
"",
"python",
""
] |
I have the MySQL query as below -
```
CREATE TABLE city
{
city_id INT AUTO_INCREMENT NOT NULL,
city_name VARCHAR(50) NOT NULL,
state_id int(50) NOT NULL,
PRIMARY KEY (city_id),
FOREIGN KEY(state_id) REFERENCES state(state_id) ON DELETE CASCADE ON UPDATE CASCADE
}
```
what may be the possible err... | This is because you are using clurly braces `{}` instead of round brackets `()`
```
CREATE TABLE city
(
city_id INT AUTO_INCREMENT NOT NULL,
city_name VARCHAR(50) NOT NULL,
state_id int(50) NOT NULL,
PRIMARY KEY (city_id),
FOREIGN KEY(state_id) REFERENCES state(state_id) ON DELETE CASCADE ON ... | You are using the wrong braces...
```
CREATE TABLE city ( city_id INT AUTO_INCREMENT NOT NULL, city_name VARCHAR(50) NOT NULL, state_id int(50) NOT NULL, PRIMARY KEY (city_id), FOREIGN KEY(state_id) REFERENCES state(state_id) ON DELETE CASCADE ON UPDATE CASCADE )
``` | Error in MySQL query for references one column to another table | [
"",
"mysql",
"sql",
"create-table",
""
] |
I have a table "news" with 10 rows and cols (uid, id, registered\_users, ....) Now i have users that can log in to my website (every registered user has a user id). The user can subscribe to a news on my website.
In SQL that means: I need to select the table "news" and the row with the uid (from the news) and insert t... | You should create an additional table to map users to news they have registeres on
like:
```
create table user_news (user_id int, news_id int);
```
that looks like
```
----------------
| News | Users|
----------------
| 5 | 22 |
| 5 | 33 |
| 5 | 45 |
| 7 | 21 |
| ... | ... |
-------------... | It sounds like you are asking to insert a new user, to change a row in `news` from:
```
5 22,33
```
and then user 45 signs up, and you get:
```
5 22,33,45
```
If I don't understand, let me know. The rest of this solution is an excoriation of this approach.
This is a bad, bad, bad way to store data. Relati... | SQL - keep values with UPDATE statement | [
"",
"sql",
"sql-update",
"sql-insert",
""
] |
I have a problem with trying to remove a row of data based on a LIKE match in sql. I'm working with SQL Server 2005.
I have a table (@Containers) which holds information like below:-
```
PMBID DEPT
------ ---------
248057 5,8
249799 5,6,8
249800 5
249941 1,5
249942 1,4,15,16
249943 1,4,5
249945 4
249946 4
... | The commas-in-the-list searching problem. Put commas around `DEPT` and around the values in the string:
```
DELETE FROM @Containers
WHERE (','+Dept+',' LIKE '%,1,%' OR
','+Dept+',' LIKE '%,11,%' OR
','+Dept+',' LIKE '%,23,%' OR
','+Dept+',' LIKE '%,31,%')
``` | It is bad practice to store data in a comma delimited string, but this will work for department 1 as an example:
```
DELETE FROM @Containers
WHERE Dept LIKE '%,1'
OR Dept LIKE '1,%'
OR Dept LIKE '%,1,%'
```
You have to force commas into the criteria to exclude 1 from catching 11 and so on. | Removing a column of data (string) by using LIKE query, there must be a better way | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2005",
""
] |
I wrote following python program
```
#! /usr/bin/python
def checkIndex(key):
if not isinstance(key, (int, long)): raise TypeError
if key<0: raise IndexError
class ArithmeticSequence:
def __init__(self, start=0, step=1):
self.start = start # Store the start value
self.step = step ... | The command that you want to run is:
```
python -i my.py
```
That will parse my.py and define the name `ArithmeticSequence`, and drop you into the Python shell where you can use your objects interactively:
```
>>> s=ArithmeticSequence(1,2)
>>>
``` | Put your file my.py in PYTHONPATH
then
```
from my import ArithmeticSequence
s=ArithmeticSequence(1,2)
``` | How to use script in interactive shell | [
"",
"python",
""
] |
Say we have a string, `'123A......'`. I have a collection of other strings that also begin with `'123A......'` where after the A are other letters of the alphabet, for example, `'123AA.....'` and `'123AB.....'` and `'123ABA....'` and so on.
I want to make a dictionary where the key would be `'123A......'` and the valu... | You should use a quantifier in your regex, like so:
```
baseMatch = re.compile('123A[A-Z]{6}')
baseMatch.findall('123AABCDEFxyz123AAABCDExyz')
['123AABCDEF', '123AAABCDE']
``` | If you know the prefixes (the keys), just do
```
dic = dict()
st = '123AHELLO'
val = st.split('123A')[1]
dic['123A'] = val
```
your question however is not clear. if you want to extract subcollection of suffixes when prefix is `'123A'` then you can do
```
st_lst = ['123AHELLO','123AHALLO','123BHELLO','123AGREAT']
re... | Python Re, need a list of matches | [
"",
"python",
"regex",
""
] |
Given the following dataframe in pandas:
```
import numpy as np
df = pandas.DataFrame({"a": np.random.random(100), "b": np.random.random(100), "id": np.arange(100)})
```
where `id` is an id for each point consisting of an `a` and `b` value, how can I bin `a` and `b` into a specified set of bins (so that I can then ta... | There may be a more efficient way (I have a feeling `pandas.crosstab` would be useful here), but here's how I'd do it:
```
import numpy as np
import pandas
df = pandas.DataFrame({"a": np.random.random(100),
"b": np.random.random(100),
"id": np.arange(100)})
# Bin the dat... | Not 100% sure if this is what you're looking for, but here's what I think you're getting at:
```
In [144]: df = DataFrame({"a": np.random.random(100), "b": np.random.random(100), "id": np.arange(100)})
In [145]: bins = [0, .25, .5, .75, 1]
In [146]: a_bins = df.a.groupby(cut(df.a,bins))
In [147]: b_bins = df.b.gr... | binning a dataframe in pandas in Python | [
"",
"python",
"numpy",
"pandas",
""
] |
I am currently trying to use python to parse the notes file for my kindle so that I can keep them more organized than the chronologically ordered list that the kindle automatically saves notes in. Unfortunately, I'm having trouble using regex to parse the file. Here's my code so far:
```
import re
def parse_file(in_... | When you say `" | Added on "`, you need to escape the `|`.
Replace that string with `" \| Added on "` | You need to escape the `|` in `"- Your " + loc_range_regex + " | Added on " +\`
to: `"- Your " + loc_range_regex + " \| Added on " +\`
`|` is the OR operator in a regex. | Using regex to parse kindle "My Clippings.txt" file | [
"",
"python",
"regex",
""
] |
I'm new to python and writing a program to count lines. the file looks like this:
```
0.86149806
1.8628227
-0.1380086
-1
0.99927421
-1.0007207
0.99927421
0.99926955
-1.0007258
```
And my code attempt is the following:
```
counterPos = 0
counterNeg = 0
counterTot = 0
counterNeu = 0
with open('test.txt'... | Your `line` is a string, but you want to parse it as a `float`. Just use `float(line)`.
It's also better to strip all whitespace from the beginning and end of your line just in case. So:
```
for line in infile:
i = float(line.strip())
# ... count
``` | You are using one extra loop.
Also the data read from the files comes as str with "\n" as endline char. Use strip() to remove "\n" and then convert the data as float.
End code should be like:
```
counterPos = 0
counterNeg = 0
counterTot = 0
counterNeu = 0
with open('temp.txt', 'r') as infile:
counterTot += 1
... | Python count lines with numbers less than, or more than | [
"",
"python",
""
] |
Recently I've been practicing to build a website with flask. Now i encounter a problem.
There is a function which to achieve registration. The code like this:
```
def register():
...
some judgment
...
if true:
sendmail()
return redirect(url_for('onepage'))
```
My ... | What you want is [`threading`](https://docs.python.org/3.8/library/threading.html) rather than the low-level [`thread`](https://docs.python.org/3.8/library/_thread.html) (which has been renamed to `_thread` in Python 3). For a case this simple, there will be no need of subclassing `threading.Thread`, so you could just ... | There are several ways of implementing threading in Python.
One very simple solution for you would be
```
import thread
def register():
...
some judgment
...
if true:
thread.start_new_thread(sendmail,())
return redirect(url_for('onepage'))
```
This will start `s... | threading programming in python | [
"",
"python",
"flask",
""
] |
I've got a structure of the form:
```
>>> items
[([[0, 1], [2, 20]], 'zz', ''), ([[1, 3], [5, 29], [50, 500]], 'a', 'b')]
```
The first item in each tuple is a list of ranges, and I want to make a generator that provides me the ranges in ascending order based on the starting index.
Since the range-lists are already ... | This works:
```
by_index = ([sub_index, list_index] for list_index, list_item in
enumerate(items) for sub_index in list_item[0])
[item[1] for item in sorted(by_index)]
```
Gives:
```
[0, 1, 0, 1, 1]
```
In detail. The generator:
```
by_index = ([sub_index, list_index] for list_index, list_item in
... | ```
from operator import itemgetter
index, element = max(enumerate(items), key=itemgetter(1))
```
Return the index of the biggest element in `items` and the element itself. | Finding the index of the value which is the min or max in Python | [
"",
"python",
""
] |
I make a 2d histogram of some `(x, y)` data and I get an image like this one:

I want a way to get the `(x, y)` coordinates of the point(s) that store the maximum values in `H`. For example, in the case of the image above it would be two points with the aprox coordi... | Here's how you can find first global maximum
```
idx = list(H.flatten()).index(H.max())
x, y = idx / H.shape[1], idx % H.shape[1]
```
Finding coordinate of all maxima *was* left as exercise to the reader...
```
numpy.argwhere(H == H.max())
```
**Edit**
Your code:
```
H, xedges, yedges = np.histogram2d(x, y, range... | The library [`findpeaks`](https://erdogant.github.io/findpeaks/pages/html/Plots.html#two-dimensional-plots) can be of use.
```
pip install findpeaks
```
I do not see your data but let me try another similar example:
```
from findpeaks import findpeaks
```
[](htt... | Find peak of 2d histogram | [
"",
"python",
"numpy",
"matplotlib",
""
] |
I've been struggling on the following.
I have 3 tables: players, players\_clothes, and teams\_clothes.
Table `players`:
```
id user team_id
1 tom 4
2 robo 5
3 bob 4
```
So tom and bob are both on the same team
Table `players_clothes`:
```
id clothes_id p_id
1 13 1
2 ... | I suggest
```
select * from A where team_id = $team_id join B on B.a_id = A.id
where not exists
(
select 1 from C where C.clothes_id = B.clothes_id and team_id = $team_id
)
```
Basically, we find all As who are on their team and for each A join to all clothing they wear, and then only return the row IF we can't f... | This should do the trick:
```
SELECT b.a_id, b.clothes_id
FROM
b INNER JOIN a
ON b.a_id = a.id
LEFT OUTER JOIN c
ON a.team_id = c.team_id
WHERE
c.clothes_id = NULL
```
The thought is to do an outer join on the combination of tables A/B against table C. And then only look for the cases where c.clothes\_... | MySQL query table filtering issue | [
"",
"mysql",
"sql",
""
] |
From the following four records, I want to select the `OwnerId` of second-latest record
```
ItemId OwnerId Date
11477 20981 2013-05-13
11477 1 2013-05-21
11477 21086 2013-05-22 #this is the one I'm talking about
11477 3868 2013-05-24
```
How to go about it? | This needs `ItemID` to be specified,
```
SELECT *
FROM TableName
WHERE ItemID = '11477'
ORDER BY DATE DESC
LIMIT 1,1
```
* [SQLFiddle Demo](http://www.sqlfiddle.com/#!2/898adb/1)
However, if you don't want to specify the `ItemID`, and you want to get all second latest record for every `ItemID`, you can use a co... | ```
select ownerid
from your_table
order by date desc
limit 1, 1
``` | Retrieve the second latest record with same id | [
"",
"mysql",
"sql",
""
] |
I programmed a Trie as a class in python. The search and insert function are clear, but now i tried to programm the python function `__str__`, that i can print it on the screen. But my function doesn't work!
```
class Trie(object):
def __init__(self):
self.children = {}
self.val = None
def __str__... | There are several issues you're running into. The first is that if you have several children at the same level, you'll only be prefixing one of them with the initial part of the string, and just showing the suffix of the others. Another issue is that you're only showing leaf nodes, even though you can have terminal val... | Why not have **str** actually dump out the data in the format that it is stored:
```
def __str__(self):
if self.children == {}:
s = str(self.val)
else:
s = '{'
comma = False
for i in self.children:
if comma:
s = s + ','
else:
... | Implementation of a Trie in Python | [
"",
"python",
"data-structures",
""
] |
I have an array below which consists of repeated strings. I want to find and replace those strings, but each time a match is made I want to change the value of the replace string.
Let me demonstrate.
This Sample Array:
```
SampleArray = ['champ', 'king', 'king', 'mak', 'mak', 'mak']
```
should get changed to:
```
... | I'd use collections.Counter:
```
from collections import Counter
numbers = {
word: iter([""] if count == 1 else xrange(1, count + 1))
for word, count in Counter(sample).items()
}
result = [
word + str(next(numbers[word]))
for word in sample
]
```
This doesn't require the list to be sorted or grou... | `groupby` is a convenient way to group duplicates:
```
>>> from itertools import groupby
>>> FinalArray = []
>>> for k, g in groupby(SampleArray):
# g is an iterator, so get a list of it for further handling
items = list(g)
# If only one item, add it unchanged
if len(items) == 1:
FinalArray.app... | Find and replace duplicates in Array, but replace each nth instance with a different string | [
"",
"python",
""
] |
Here is my set up -
```
project/
__init__.py
prog.py
test/
__init__.py
test_prog.py
```
I would like to be able to run my unit tests by calling a command-line option in *prog.py*. This way, when I deploy my project, I can deploy the ability to run the unit tests at any time.
```
python pr... | Perhaps [this](http://docs.python.org/2/library/unittest.html#load-tests-protocol) is what you're looking for. Implement a `load_tests` function in `test_prog.py` and use the following code in `prog.py` to load and run the tests:
```
import unittest
import test.test_prog
suite = unittest.TestLoader().loadTestsFromModu... | The Python `unittest` module contains its own [test discovery](https://docs.python.org/3/library/unittest.html#test-discovery) function, which you can run from the command line:
```
$ python -m unittest discover
```
To run this command from within your module, you can use the `subprocess` module:
```
#!/usr/bin/env ... | Run unittest from a Python program via a command-line option | [
"",
"python",
"unit-testing",
""
] |
What is a "pythonic" approach to checking to see if an element is in the dictionary before extracting it and using it in a comparison?
For example:
Currently, I do
```
if "key1" in list2 and list2["key1"]=="5":
print "correct"
```
so that it will short-circuit on the first conditional if it fails. However, this l... | This approach is perfectly pythonic. Another, slightly different would be
```
if list2.get("key1", <-1,0 or any sensible default, e.g. None>) == 5:
print "correct"
```
With this approach you employ [`dict.get`](http://docs.python.org/2/library/stdtypes.html#dict.get) method which allows for safe extraction of val... | Nope - try/except is absolutely fine:
```
try:
if list2['key1'] == '5':
# do something
except KeyError:
# key wasn't found
except ValueError:
# most likely value wasn't comparable...
``` | Key in Dictionary Before Extraction [Pythonic Approach] | [
"",
"python",
""
] |
Why does this piece of code throw a SyntaxError?
```
>>> def fun1(a="who is you", b="True", x, y):
... print a,b,x,y
...
File "<stdin>", line 1
SyntaxError: non-default argument follows default argument
```
While the following piece of code runs without visible errors:
```
>>> def fun1(x, y, a="who is you", b... | All required parameters must be placed before any default arguments. Simply because they are mandatory, whereas default arguments are not. Syntactically, it would be *impossible* for the interpreter to decide which values match which arguments if mixed modes were allowed. A `SyntaxError` is raised if the arguments are ... | ```
SyntaxError: non-default argument follows default argument
```
If you were to allow this, the default arguments would be rendered useless because you would never be able to use their default values, since the non-default arguments come **after**.
In Python 3 however, you may do the following:
```
def fun1(a="who... | Why can't non-default arguments follow default arguments? | [
"",
"python",
"keyword-argument",
"positional-argument",
""
] |
I am used to the python byte literal syntax representing bytes as hex values such as `b'\x7a'` is the hex value `0x7a`. I however have run into an issue that I don't know how it is working. I am using the ssl library for the first time and creating random values with `ssl.RAND_bytes(...)` It is returning strings with c... | Byte array notation converts certain values to their textual representation:
```
>>> b'\x12\x41\x42'
b'\x12AB'
```
In this case the hex number 41 is the ASCII value for capital letter A. | If the byte can be represented with a printable ASCII character that character is used instead of a hex escape, here is some code for generating a table of the representation for all byte values (columns are decimal, hex, and byte representation):
```
>>> all_bytes = bytes(range(256))
>>> for i in range(256):
... ... | Python bytes literal has extra characters that aren't hex, but alter the value of the string | [
"",
"python",
"byte",
"python-3.3",
""
] |
I have an excel book with a couple of sheets. Each sheet has two columns with `PersonID` and `LegacyID`. We are basically trying to update some records in the database based on `personid`. This is relatively easy to do TSQL and I might even be able to get it done pretty quick in powershell but since I have been trying ... | Can you turn the LegacyID into ints ?
i[1] = int(i[1])
outFile.write("\nUPDATE PERSON SET LegacyID = " + "'" + str(i[1]) + "'" + " WHERE personid = " + "'" + str(i[0])
+ "'") | try this..
```
# use 'a' if you want to append in your text file
outFile = open(r'D:\Scripts\update.txt', 'a')
for i in myList:
outFile.write("\nUPDATE PERSON SET LegacyID = '%s' WHERE personid = '%s'" %( int(i[1]), str(i[0])))
``` | Reading data from Excel sheets and building SQL statements, writing to output file in Python | [
"",
"python",
"excel",
""
] |
I am trying to solve a problem of how to find the maximum count of consecutive years in a series of records. In the following example:
```
ID Year
1 1993
1 1994
1 1995
1 1995
1 2001
1 2002
2 1993
2 1995
2 1996
2 1996
2 1998
2 1999
2 2000
2 2001
2 2001
```
My result set should look like
```
id count
1 3
2 ... | This will produce your desired result:
```
select
id,
ayear,
byear,
yeardiff
from
(
select
a.id,
a.year ayear,
b.year byear,
(b.year - a.year)+1 yeardiff,
dense_rank() over (partition by a.id order by (b.year - a.year) desc) rank
from
years a
join years b on a.id = b.id
... | Try:
```
with cte as
(select t.id, t.year, d.d, row_number() over (partition by t.id, d.d
order by t.year) rn
from (select -1 d from dual union all select 1 d from dual) d
cross join my_table t
where not exists
(select null
from my_table o
where... | Find the maximum consecutive years for each ID's in a table(Oracle SQL) | [
"",
"sql",
"oracle",
""
] |
I am using a SQL statement to fetch records where name begins with some alphabet
```
SELECT * FROM Music WHERE Title LIKE 'A%' ORDER BY Title
```
Can anyone suggest SQL query which will fetch Title beginning with numbers and symbols? | You can use LIKE with character sets:
```
SELECT * FROM Music WHERE Title LIKE '[^A-Za-z]%' ORDER BY Title
```
Sample:
```
declare @music table(id int identity(1,1) not null primary key, title varchar(10))
insert @music(title)
values
('test1'),
('9test'),
('0test'),
('#test')
SELECT * FROM @Music... | use `PATINDEX`
```
SELECT *
FROM Music
WHERE PATINDEX('[^a-zA-Z]%', Title) = 1
ORDER BY Title
```
* [SQLFiddle Demo](http://www.sqlfiddle.com/#!3/b5df12/2)
* [TSQL Doc: PATINDEX](http://msdn.microsoft.com/en-us/library/ms188395.aspx) | WHERE to check if NVARCHAR record begins with a number or symbol in SQL | [
"",
"sql",
"sql-server",
""
] |
Say I have a list of dictionaries. They mostly have the same keys in each row, but a few don't match and have extra key/value pairs. Is there a fast way to get a set of all the keys in all the rows?
Right now I'm using this loop:
```
def get_all_keys(dictlist):
keys = set()
for row in dictlist:
keys =... | You could try:
```
def all_keys(dictlist):
return set().union(*dictlist)
```
Avoids imports, and will make the most of the underlying implementation of `set`. Will also work with anything iterable. | A fun one which works on python3.x1 relies on `reduce` and the fact the `dict.keys()` now returns a set-like object:
```
>>> from functools import reduce
>>> dicts = [{1:2},{3:4},{5:6}]
>>> reduce(lambda x,y:x | y.keys(),dicts,{})
{1, 3, 5}
```
For what it's worth,
```
>>> reduce(lambda x,y:x | y.keys(),dicts,set())... | Union of all keys from a list of dictionaries | [
"",
"python",
"list",
"dictionary",
""
] |
```
Create table #Tbl
(
ID int not null,
Keyword nvarchar(max)
)
Insert into #Tbl Values ('0','Cryptography')
Insert into #Tbl Values ('1','Cryptography')
Insert into #Tbl Values ('4','Cryptography')
Insert into #Tbl Values ('0','SQL')
Insert into #Tbl Values ('0','SQL')
Insert into #Tbl Values ('3','Cloud Computing')
... | Assuming your IDs start from 0, the below should work
```
select Keyword,COUNT(distinct id) from #Tbl
group by Keyword
having COUNT(distinct id)>1 and MIN(id) = 0
``` | There are many ways to do this, one example:
```
SELECT DISTINCT Keyword
FROM #Tbl T
WHERE EXISTS (SELECT 1 FROM #Tbl WHERE Keyword = T.Keyword
AND ID = 0)
AND EXISTS (SELECT 1 FROM #Tbl WHERE Keyword = T.Keyword
AND ID != 0)
```
[**Here is a sqlfiddle**](http://sqlfiddle.com/#!3/6e099/3) ... | Get records with more than one value and at least one of them is zero | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am used to creating basic queries, so I am stuck on a rather complex one.
```
Order Number Order Line Package Part Number Size Cost Reviewed
0001 1 1 A1 S 22.5 Yes
0001 1 1 B2 M 33.1 Yes
... | This will exclude records with a matching order\_number and order\_line that have a package other than 1:
```
SELECT
ORDER_Number,
ORDER_Line,
Package
FROM
aTABLE
WHERE NOT EXISTS (SELECT 1
FROM atable AS b
WHERE atable.order_number = b.order_number
... | This might be a little hackish and not promising good performance, but I've used something like this before.
```
SELECT ORDERNumber,
ORDERLine
FROM orders
GROUP BY ORDERNumber,
ORDERLine
HAVING SUM(CASE WHEN package = 1 THEN 0 ELSE 1 END)= 0
ORDER BY ordernumber,
orderline
```
**[sqlFiddle](... | Exclude SQL query results - single table | [
"",
"sql",
""
] |
i have to find a way to solve this issue... in a table like that, i would see my column "C" increment his value on each rows, starting from a costant, adding value in column "B" and adding value by the previous value in the same column "C".
Furthermore ... Grouping by User.
For example: (starting point Phil: 350, sta... | SQL Server 2008 doesn't support cumulative sums directly using window functions. You can use a correlated subquery for the same effect.
So, using the same structure as GBN:
```
DECLARE @t TABLE (ID int IDENTITY(1,1), UserName varchar(100), Point int);
INSERT @t (UserName, Point)
VALUES
('Phil', 1000),
('Phil', 150),... | Using windowing. The table declaration is SQL Server but the rest is standard SQL if your RDBMS supports it (SQL Server 2012, PostgreSQL 9.1 etc)
```
DECLARE @t TABLE (ID int IDENTITY(1,1), UserName varchar(100), Point int);
INSERT @t (UserName, Point)
VALUES
('Phil', 1000),
('Phil', 150),
('Phil', 200),
('Mark', 300... | Increment value colum by previous row in select sql statement | [
"",
"sql",
"sql-server",
""
] |
I am struggling to join multiple table in mySQL or SQL Server and keep the performance fast.
I have this table:
table songs
```
songID|songName
---------------
01|diamond
02|goodbye
```
table singersong
```
songID|singerID
---------------
01|15
02|22
```
table singers
```
singerID|singerName|Sex
-------------... | Specify the conditions to join on. Your current query, depending upon the whims of the optimiser, may be producing a cartesian product between all tables and then filtering the result. Also make sure you have indexes and FKs setup properly.
```
SELECT s.songID, s.songName, sr.singerName, sr.Sex
FROM songs s
LEFT JOIN... | Your syntax is not the modern style, but it should work fine. For performance, make sure you have indexes on all the columns used for the join: `songID` and `singerID`. | How to Do Efficient JOIN on multiple table in MySQL or SQL Server? | [
"",
"mysql",
"sql",
""
] |
this is how my table looks like :

Now i want to retrieve Field1 for 'AAA'
I tried something like :
```
select Field1 from table where CommaSeparatedList='AAA'
```
But it didn't work.
So How can I achieve this ?? | ```
select field1
from table
where ',' + replace(commaseparatedlist, ' ', '') + ',' like '%,AAA,%'
``` | I suggest that you try:
```
SELECT Field1 FROM table WHERE CommaSeparatedList LIKE '%AAA%'
``` | Comparing value with comma separated values in select statement | [
"",
"sql",
""
] |
I have a database where `article.cat_id` is linked to `category.id`.
I removed a few rows from `category` and now I want to select or remove all rows from `article` that link to an `id` in `category` that doesn't exist. Unfortunately, I don't exactly know which `id`s have been removed.
Is there an SQL way to check to... | e.g
```
SELECT * FROM Table_1 where Table_1.ID not in (SELECT Table_2.ID FROM Table_2)
```
the inner select it will select all the IDs from Table 2 while the outer select it will base the returned rows where the ID doesn't exist in TABLE 2 | ```
DELETE a.*
FROM article a
LEFT JOIN category c
ON a.cat_id = c.id
WHERE c.id IS NULL
```
Change `DELETE` to `SELECT` first to make sure it's what you want. | Return all rows from a table for which the cat_id cannot be found in another table | [
"",
"mysql",
"sql",
"database",
""
] |
This is surely a duplicate, but say I have a class as follows:
```
class MyObj(object):
def __init__(self, *args, **kwargs):
self._data = [2, 1, 3]
self._more_data = [False, True, False]
```
How can I make it sortable, not against other MyObj objects (which I could do with `__lt__`), but internall... | `sorted()` **never** modifies the original data. To make it work with a custom object you'd have to implement `__iter__` though (returning e.g. `iter(self._data)`) - but that would just give you a sorted version of that object and neither modify your original object nor sort both lists.
What you want is a `sort()` met... | You can't make `sorted` return an instance of your class. `sorted` always returns a list. If you make it [an iterator](https://stackoverflow.com/questions/19151/build-a-basic-python-iterator) you can get `sorted` to return a sorted version of your class's data (as a list). But it's probably simpler to just give your cl... | How to make class data sortable | [
"",
"python",
"sorting",
""
] |
I have been debugging a SQL stored procedure which has to take values (in my code ID and Numb) form table A based on the values (ID) present in the Table C, then square the Numb and store it in Table B i.e. all the things ID, Numb and Square.
I am not able to figure out the problem in the below code
```
DELIMITER $$
... | There are various minor errors;
You need a parameter list, even if empty for the procedure;
```
CREATE PROCEDURE matlab.squaring()
```
The continue handler needs to be right below the other declarations;
```
DECLARE id_cur CURSOR FOR
SELECT ID, Numb FROM A WHERE EXISTS ( SELECT ID FROM c);
DECLARE CONTIN... | * You have missed () after PROCEDURE matlab...
* And ; after END IF
* Also, HANDLER declaration should be before any executable code and
after CURSOR declaration
* Semicolon after SET @square= @Numb \* @Numb is needed
So, query should be like this:
```
DELIMITER $$
CREATE PROCEDURE matlab.squaring ()
BEGIN
... | Stored procedure not working properly in MySql? | [
"",
"mysql",
"sql",
"stored-procedures",
""
] |
how can I change a string to a string of list (as seen in the question header)
I can simply do something like that, but I'm there is a simpler way
```
orig = "bla bla"
final = "["
for i in orig:
final = "%s %d," % (final, i)
final = final[:-1] + "]"
``` | You can also do:
```
>>> orig = "bla bla"
>>> str(map(ord, orig))
'[98, 108, 97, 32, 98, 108, 97]'
>>>
``` | You can use [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) and [ord](http://docs.python.org/2/library/functions.html#ord).
```
>>> nums = str([ord(char) for char in "abc"])
>>> nums
"[97, 98, 99]"
``` | Turn "abc" to "[97, 98 99]" | [
"",
"python",
""
] |
I have 2 tables, Table1 and Table2, where 2 columns in both tables are same
update:type of Table1.col1 same as Table2.col1 and Table1.col2 same as Table2.col2
Trying to fetch the data where table1.col1 not in table2.col1 and table1.col2 not in table2.col2, and this is my query.
```
select * from Table1
where Ta... | This query should do the job, I ran a simple test based on your query and it doesn't produce the desired result
```
SELECT *
FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.col1 = t2.col1 AND t1.col2 = t2.col2
WHERE t2.col1 IS NULL AND t2.col2 IS NULL
```
Given this
```
CREATE TABLE Table1
(
colA VarChar(50),
col1 ... | Use a LEFT JOIN:
```
SELECT Table1.*
FROM Table1
LEFT JOIN Table2
ON Table1.col1 = Table2.col1
AND Table1.col2 = Table2.col2
WHERE Table2.col1 IS NULL
``` | SQL query to fetch the data from two tables with "not in" condition | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"join",
""
] |
I have a list of objects of the same type
```
lis = [<obj>, <obj>, <obj>]
```
that I wish to sort naturally by the object attribute `name`. I have tried
```
sortedlist = sorted(lis, key=lambda x: x.name)
```
However this sorts the list as
```
A1
A10
A2
```
Not in the format that I wanted
```
A1
A2
A10
```
I hav... | ```
sorted(obj, key=lambda x: (x.name[0], int(x.name[1:])))
``` | This way uses groupby, and works for an arbitrary number of swaps between alpha and digits
```
from itertools import groupby
def keyfunc(s):
return [int(''.join(g)) if k else ''.join(g) for k, g in groupby(s, str.isdigit)]
sorted(my_list, key=keyfunc)
```
Demo:
```
>>> my_list =['A1', 'A10', 'A2', 'B0', 'AA11',... | Sort list of objects by attribute alphanumerically | [
"",
"python",
"sorting",
""
] |
I've got django models displaying on a page using a checkbox input that has a label over it like so:
```
{% if recipes_list %}
<table>
{% for r in recipes_list %}
<tr>
<td>
<section class="ac-container">
<div>
<input id="ac-1" type="checkbox" />
<label for="ac-1">{{r.name}}</label>
... | You can write a filter which gets the model name
```
from django import template
register = template.Library()
@register.filter(name='class_name')
def class_name(obj):
return obj.__class__.__name__
```
and in the template:
and in the template, wherever you want the id/classname:
```
<article id={{obj|class_name}... | You can use the [forloop.counter](https://docs.djangoproject.com/en/dev/ref/templates/builtins/) to achieve this:
```
{% if recipes_list %}
<table>
{% for r in recipes_list %}
<tr>
<td>
<section class="ac-container">
<div>
<input id="ac-{{forloop.counter}}" type="checkbox" />
<label for="ac... | Unique HTML element IDs for each model with Django | [
"",
"python",
"html",
"django",
"django-forms",
"django-templates",
""
] |
Why does
```
select 1 as a, 2 as b
union all
select 20 as b, 10 as a
```
returns
```
a b
1 2
20 10
```
instead of
```
a b
1 2
10 20
```
?
Is there a way to make `union` match column names? | I'm not sure if this solves your problem, but you can use subqueries within the `union` to put the columns in the "right" order:
```
(select a, b from (select 1 as a, 2 as b) t)
union all
(select a, b from (select 20 as b, 10 as a) t)
```
I realize the question is tagged MySQL, which doesn't support `full outer join`... | > Is there a way to make union match column names?
Nope, selecting the columns in order is required with `UNION`. | UNION ignores column names? | [
"",
"mysql",
"sql",
"union",
""
] |
If a have a list like:
```
l = [1,2,3,4,5]
```
and I want to have at the end
```
min = 1
max = 5
```
WITHOUT `min(l)` and `max(l)`. | The fastest approach I can think of would be to sort the original list and then pick the first and last elements. This avoids looping multiple times, but it does destroy the original structure of your list. This can be solved by simply copying the list and sorting only the copied list. I was curious if this was slower ... | If you are trying to avoid using two loops, hoping a single loop will be faster, you need to reconsider. Calling two O(N) functions still gives you a O(N) algorithm, all you do is double the constant per-iteration cost. A single Python loop with comparisons can't do better than O(N) either (unless your data is already ... | How can I get the minimum and the maximum element of a list in python | [
"",
"python",
"max",
"min",
""
] |
I have a python list that looks like that:
```
list = [u'a', u'b', u'c']
```
Now I want to encode it in UTF-8. Therefore I though I should use:
```
list = list[0].encode("utf-8")
```
But print list gives only
```
a
```
meaning the first element of the list. Not even a list anymore. What am I doing wrong? | ```
>>> items = [u'a', u'b', u'c']
>>> [x.encode('utf-8') for x in items]
['a', 'b', 'c']
``` | `list[0]` is the first element, not a list. you are reassigning your `list` var to a new value, the utf-8 encoding of the first element.
Also, don't name your variables `list`, as it masks the `list()` function. | Encode Python list to UTF-8 | [
"",
"python",
"list",
"encode",
""
] |
I'm creating a system for keeping track of which type of software, and which version of the software is licensed for each company. Some of the software has version numbers like 1.1.4 or similar with more than one decimal point.
I have tried saving it as a varchar for now, since I couldn't find a numerical data type th... | Assuming that the revision and patch values (in `version.revision.patch`) will have a maximum of two digits, you could store them in an `INT UNSIGNED` (or smaller) column as follows:
```
version * 10000 + revision * 100 + patch
```
With this approach, your search becomes `>= 10102 or <= 20501`. | Not natively, no, as multiple decimal points aren't a common data type.
Your best bet would be saving it as `varchar` like you have done, and then in your app code, splitting the number and doing the comparison by hand. | Using numbers with multiple decimal points (ex. 1.4.4) in MySql, is it possible? | [
"",
"mysql",
"sql",
"decimal",
""
] |
I am using Mac OSX 10.8, previously I used macports, but I switched to brew.
```
Snows-MacBook-Pro:~ Mac$ brew search matplotlib
samueljohn/python/matplotlib
Snows-MacBook-Pro:~ Mac$ pip search matplotlib
matplotlib - Python plotting package
```
So my question is easy.
Should I use brew or pip for ins... | **I recommend using a package manager** (brew, indeed, or MacPorts). Here are a few reasons why:
* If you use your package manager (MacPorts, brew,…) to later install additional programs that depend on **Matplotlib**, the package manager **will install** it **regardless**.
* **If you install a Python package via pip**... | Since you need compile many of these packages, it is not the simplest task on the Mac. I would recommend to use a distribution like [Anaconda](http://continuum.io/downloads.html). It is free, comes with all the things you need and has a simple installer. It will save you a lot of hassle because all components work toge... | Should I use brew or pip for installing matplotlib? | [
"",
"python",
"macos",
"matplotlib",
"homebrew",
""
] |
I have the following string
```
"1206292WS_R0_ws.shp"
```
I am trying to re.sub everything except what is between the second "\_" and ".shp"
Output would be "ws" in this case.
I have managed to remove the .shp but for the life of me cannot figure out how to get rid of everything before the "\_"
```
epass = "120629... | you dont really need a regex for this
```
print epass.split("_")[-1].split(".")[0]
>>> timeit.timeit("epass.split(\"_\")[-1].split(\".\")[0]",setup="from __main__
import epass")
0.57268652953933608
>>> timeit.timeit("regex.findall(epass)",setup="from __main__ import epass,regex
0.59134766185007948
```
speed seems ... | The regular expression you describe is `^[^_]*_[^_]*_(.*)[.]shp$`
```
>>> import re
>>> s="1206292WS_R0_ws.shp"
>>> regex=re.compile(r"^[^_]*_[^_]*_(.*)[.]shp$")
>>> x=re.sub(regex,r"\1",s)
>>> print x
ws
```
Note: this is the regular expression as you describe it, not necessarily the best way to solve the actual pro... | Python re finding string between underscore and ext | [
"",
"python",
"regex",
""
] |
I would like to know how can I sort a string by the number inside.
As example I have:
```
hello = " hola %d" % (number_from_database)
bye = "adios %d" % (number_from_database_again)
```
I want to sort them by the number even if it changes. | You can pass a key to sort:
```
sorted(l, key=lambda x: int(re.sub('\D', '', x)))
```
For example:
```
In [1]: import re
In [2]: l = ['asdas2', 'asdas1', 'asds3ssd']
In [3]: sorted(l, key=lambda x: int(re.sub('\D', '', x)))
Out[3]: ['asdas1', 'asdas2', 'asds3ssd']
```
Where `re.sub('\D', '', x)` replaces [everyth... | Just a little complement to Andy's answer.
If you want to sort set which also contain strings without any number:
```
sorted(l, key=lambda x: int('0'+re.sub('\D', '', x)))
```
, which would put those strings without any number at the very beginning. | sort string by number inside | [
"",
"python",
"string",
"int",
""
] |
I have a python object which includes some decimals. This is causing the json.dumps() to break.
I got the following solution from SO (e.g. [Python JSON serialize a Decimal object](https://stackoverflow.com/questions/1960516/python-json-serialize-a-decimal-object)) but
the recoomended solution still does not work. Pyth... | It is not (no longer) recommended you create a subclass; the `json.dump()` and `json.dumps()` functions take a `default` function:
```
def decimal_default(obj):
if isinstance(obj, decimal.Decimal):
return float(obj)
raise TypeError
json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default)
```... | I can't believe that no one here talked about using simplejson, which supports deserialization of Decimal out of the box.
```
import simplejson
from decimal import Decimal
simplejson.dumps({"salary": Decimal("5000000.00")})
'{"salary": 5000000.00}'
simplejson.dumps({"salary": Decimal("1.1")+Decimal("2.2")-Decimal("3... | Python to JSON Serialization fails on Decimal | [
"",
"python",
"json",
"decimal",
""
] |
I have a >100,000 urls (different domains) in a list that I want to download and save in a database for further processing and tinkering.
Would it be wise to use scrapy instead of python's multiprocessing / multithreading? If yes, how do I write a standalone script to do the same?
Also, feel free to suggest other awe... | Scrapy does not seem relevant here if you know very well the URL to fetch (there's is no crawling involved here).
The easiest way that comes to mind would be to use [`Requests`](http://docs.python-requests.org/en/latest/). However, querying each URL in a sequence and block waiting for answers wouldn't be efficient, so... | Most site owners try to block you crawler if you suddenly create hi-load.
So even if you have fixed list of links you need control timeouts, http answer codes, proxies and etc. on scrapy or [grab](http://docs.grablib.org/) | What is the best way to download <very large> number of pages from a list of urls? | [
"",
"python",
"multithreading",
"multiprocessing",
"scrapy",
"web-crawler",
""
] |
I want to use the LIKE operator to match possible values in a column.
If the value begins with "CU" followed by a digit (e.g. "3") followed by anything else, I would like to return it. There only seems to be a wildcard for any single character using underscore, however I need to make sure it is a digit and not a-z.
I ... | You need to use regexp:
```
select name
from table1
where name regexp binary '^CU[0-9]'
```
The documentation for `regexp` is [here](http://dev.mysql.com/doc/refman/5.5/en/regexp.html).
EDIT: `binary` is required to ensure case-sensitive matching | The [`like` operator](http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html) only have the `%` and `_` wildcards in MySQL, but you can use a regular expression with the [`rlike` operator](http://dev.mysql.com/doc/refman/5.0/en/regexp.html):
```
select name from table1 where name rlike '^CU[0-9]'
``` | wildcard for single digit mysql | [
"",
"mysql",
"sql",
""
] |
I am currently in some truble regarding python and reading files. I have to open a file in a while loop and do some stuff with the values of the file. The results are written into a new file. This new file is then read in the next run of the while loop. But in this second run I get no values out of this file... Here is... | Why to write to a file and then read it ? Moreover you use flush, so you are doing potentially long io. I would do
```
with open(originalpath) as f:
mat = f.read()
while condition :
run += 1
write_mat_run(mat, run)
mat = func(mat)
```
write\_mat\_run may be done in another thread. You should check io ... | I can see nothing wrong with your code. The following concrete example worked on my Linux machine:
```
import os
run = 0
while run < 10:
run += 1
prevrun = run-1
if os.path.isfile("output%d.txt" %prevrun):
matfile = open("output%d.txt" %prevrun, "r")
data = matfile.readlines()
mat... | Python read file in while loop | [
"",
"python",
"file-io",
"while-loop",
""
] |
So I have my Django app running and I just added South. I performed some migrations which worked fine locally, but I am seeing some database errors on my Heroku version. I'd like to view the current schema for my database both locally and on Heroku so I can compare and see exactly what is different. Is there an easy wa... | From the command line you should be able to do `heroku pg:psql` to connect directly via PSQL to your database and from in there `\dt` will show you your tables and `\d <tablename>` will show you your table schema. | locally django provides a [management command](https://docs.djangoproject.com/en/dev/ref/django-admin/#dbshell) that will launch you into your db's shell.
`python manage.py dbshell` | How to View My Postgres DB Schema from Command Line | [
"",
"python",
"django",
"postgresql",
"heroku",
"django-south",
""
] |
i'm trying to get started with evernote SDK , i'm using ubuntu 13.04
i installed the SDK via :
```
pip install evernote
```
but when i want to test it using :
```
python -c 'from evernote.api.client import EvernoteClient'
```
i got this :
```
Traceback (most recent call last):
File "<string>", line 1, in <modul... | This is pretty old already, but I bet more people will hit it, so I'll put the answer here. It seems to be a surprisingly common issue that doesn't have an answer anywhere.
Note how the error complains about api.client but not evernote.
`Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportEr... | Could you check the version of Evernote SDK for Python with:
```
pip freeze
```
If `import evernote` works but `from evernote.api.client import EvernoteClient` doesn't, you might happen to use 1.23.0 version or older since EvernoteClient class was introduced in 1.23.1.
Also please check your site-packages directory ... | unable to import evernote.api.client (evernte sdk) | [
"",
"python",
"sdk",
"evernote",
""
] |
I'm trying to calculate pi with arbitrary precision on Python using one of Ramanujan's formulas: <http://en.wikipedia.org/wiki/Approximations_of_%CF%80#20th_century>. It basically requires lots of factorials and high-precision floating numbers division.
I'm using multiple threads to divide infinite series calculation ... | Threads do not speed things up because of the GIL (Global Interpret Lock). Use [`multiprocessing`](http://docs.python.org/2/library/multiprocessing.html) for this kind of task. Its usage is very similar to threads. | Python has a GIL([Global Interpreter Lock](http://wiki.python.org/moin/GlobalInterpreterLock)) that prevents more than one thread to execute python code at the same time, i.e. you cannot obtain a speed up on CPU-bound tasks using multiple threads. You must use multiple processes. | Calculation of Pi with multiple threads( no acceleration - what to do ) | [
"",
"python",
"multithreading",
"pi",
""
] |
In Python, how do I split on either a space or a hyphen?
Input:
```
You think we did this un-thinkingly?
```
Desired output:
```
["You", "think", "we", "did", "this", "un", "thinkingly"]
```
I can get as far as
```
mystr.split(' ')
```
But I don't know how to split on hyphens as well as spaces [and the Python de... | If your pattern is simple enough for one (or maybe two) `replace`, use it:
```
mystr.replace('-', ' ').split(' ')
```
Otherwise, use RE as suggested by [@jamylak](https://stackoverflow.com/a/16926888/2289509). | ```
>>> import re
>>> text = "You think we did this un-thinkingly?"
>>> re.split(r'\s|-', text)
['You', 'think', 'we', 'did', 'this', 'un', 'thinkingly?']
```
As @larsmans noted, to split by multiple spaces/hyphens (emulating `.split()` with no arguments) used `[...]` for readability:
```
>>> re.split(r'[\s-]+', text... | Split on either a space or a hyphen? | [
"",
"python",
"string",
"formatting",
""
] |
I am implementing a small command line tool in python that needs to ask the user a couple of questions. I use
```
raw_input('Are you male or female?')
```
all the time. Now I would like to be able to deal with dumb users (or those too lazy to read/remember the documentation), so I need to check whether the answer mak... | Necromanting again...
Please have a look at [click](https://click.pocoo.org) if you need a simple helper library for questions. Its main focus are command line options, but it’s a good fit for your use case, I think.
EDIT 3 years later: I’m using [prompt toolkit](https://github.com/prompt-toolkit/python-prompt-toolki... | This question is quite old, but I'm researching it today. The library [pyinputplus](https://pypi.org/project/PyInputPlus/) is recommended by Al Swigert in *[Automate the Boring Stuff With Python](https://automatetheboringstuff.com/2e/chapter8/)* | python library for user input | [
"",
"python",
"user-input",
""
] |
I am performing multiple iterations of the type:
```
masterSet=masterSet.union(setA)
```
As the set grows the length of time taken to perform these operations is growing (as one would expect, I guess).
I expect that the time is taken up checking whether each element of setA is already in masterSet?
My question is t... | You can use `set.update` to update your master set in place. This saves allocating a new set all the time so it should be a little faster than `set.union`...
```
>>> s = set(range(3))
>>> s.update(range(4))
>>> s
set([0, 1, 2, 3])
```
---
Of course, if you're doing this in a loop:
```
masterSet = set()
for setA in ... | As mgilson points out, you can use `update` to update a set in-place from another set. That actually works out slightly quicker:
```
def union():
i = set(range(10000))
j = set(range(5000, 15000))
return i.union(j)
def update():
i = set(range(10000))
j = set(range(5000, 15000))
i.update(j)
... | Quick way to extend a set if we know elements are unique | [
"",
"python",
"set",
"union",
""
] |
I have a table ItemCategory with category listing and this category is assigned with items. It is like the following:
```
+---------+-------------+
| item_id | category_id |
+---------+-------------+
| 1 | 1 |
| 2 | 1 |
| 3 | 0 |
| 3 | 2 |
| 3 | ... | Try this one:
```
SELECT * FROM Table1
WHERE item_id IN (
SELECT item_id FROM Table1
GROUP BY item_id
HAVING MAX(category_id) = 0
)
```
Result:
```
╔═════════╦═════════════╗
║ ITEM_ID ║ CATEGORY_ID ║
╠═════════╬═════════════╣
║ 4 ║ ... | ```
select * from a group by item having count(distinct category)=1 and category=0;
``` | Select value which don't have atleast one association | [
"",
"mysql",
"sql",
""
] |
We have this format Date/Time stored in a varChar column for each row in our table: 2013-05-26 20:22:07.2894.
How can we use this column in a T\_SQL WHERE statement to retrieve the last 1 hour's worth of rows?
We have tried this and it works: WHERE Time\_Stamp > '2013-05-26 18:00:00:0000' however we would like to hav... | Here is a sargable approach (meaning it will use the index):
```
where Time_Stamp > convert(varchar(255), getdate() - 1.0/24, 121)
``` | To convert your `VARCHAR` to a `DATETIME`, just use;
```
CONVERT(DATETIME, SUBSTRING(myDate, 1, 23), 121);
```
...where myDate is your column name. Once it's converted to a datetime, a comparison with `GETDATE()` is simple.
[A very simple SQLfiddle](http://sqlfiddle.com/#!6/63fad/3). | Compare Date/Time in SQL Server T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
We are using jinja2 to create our html but, because of the many loops and other things we do in jinja to produce the html, the html 'looks' ugly....(note: this is just for aesthetics). Is there anything we can do to clean up the html? (Other than the obvious of cleaning up our jinja2 code, which would make our template... | Add '-' to the tags:
```
{%- if 'this'=='this' -%}
{{ blah }}
{%- endif -%}
``` | It looks like someone out there created a library to do just what need. See [this library](https://github.com/cobrateam/django-htmlmin#using-the-html_minify-function) which I found attached to [this question](https://stackoverflow.com/questions/13587531/minify-html-output-from-flask-application-with-jinja2-templates) (... | Is there a way to clean up the html that jinja2 produces? | [
"",
"python",
"jinja2",
""
] |
Is this now possible using Google Drive API or should I just send a multiple requests to accomplish this task?
By the way I'm using Python 2.7 | As far as i know, you'll have to send multiple request to delete multiple files: <https://developers.google.com/drive/v2/reference/files/delete>. As you can see "delete" method receives a "fileId". | You can batch your multiple deletes into a single HTTP request. | How to do a multiple folder removal in Google Drive API? | [
"",
"python",
"google-drive-api",
""
] |
This question is one of style. Since the attributes are not private in python, is it good and common practice to address them directly outside the class using something like `my_obj.attr`? Or, maybe, it is still better to do it via member-functions like `get_attr()` that is an usual practice in c++? | Sounds like you want to use properties:
```
class Foo(object):
def __init__(self, m):
self._m = m
@property
def m(self):
print 'accessed attribute'
return self._m
@m.setter
def m(self, m):
print 'setting attribute'
self._m = m
>>> f = Foo(m=5)
>>> f.m = 6
s... | Create an instance of the class first:
```
myinstance = MyClass()
myinstance.attr
```
Otherwise you'd get an error like `AttributeError: class MyClass has no attribute 'attr'` when trying to do `MyClass.attr` | Style of addressing attributes in python | [
"",
"python",
"coding-style",
""
] |
Is there a way to slice a 2d array in numpy into smaller 2d arrays?
**Example**
```
[[1,2,3,4], -> [[1,2] [3,4]
[5,6,7,8]] [5,6] [7,8]]
```
So I basically want to cut down a 2x4 array into 2 2x2 arrays. Looking for a generic solution to be used on images. | There was [another question](http://stackoverflow.com/a/13990648/190597) a couple of months ago which clued me in to the idea of using `reshape` and `swapaxes`. The `h//nrows` makes sense since this keeps the first block's rows together. It also makes sense that you'll need `nrows` and `ncols` to be part of the shape. ... | It seems to me that this is a task for [`numpy.split`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html) or some variant.
e.g.
```
a = np.arange(30).reshape([5,6]) #a.shape = (5,6)
a1 = np.split(a,3,axis=1)
#'a1' is a list of 3 arrays of shape (5,2)
a2 = np.split(a, [2,4])
#'a2' is a list of thr... | Slice 2d array into smaller 2d arrays | [
"",
"python",
"numpy",
""
] |
I have a list that looks like this:
```
relationShipArray = []
relationShipArray.append([340859419124453377, 340853571828469762])
relationShipArray.append([340859419124453377, 340854579195432961])
relationShipArray.append([340770796777660416, 340824159120654336])
relationShipArray.append([340509588065513473, 34076484... | Use an OrderedDict if you need to keep the order:
```
from collections import OrderedDict
>>> L = [[1, 2], [4, 5], [1,2], [2, 1]]
>>> [[x, y] for x, y in OrderedDict.fromkeys(frozenset(x) for x in L)]
[[1, 2], [4, 5]]
```
**EDIT 1**
If the order is not important you can get away with a set:
```
>>> [[x, y] for x, ... | One liner solution
```
relationShipArray = []
relationShipArray.append([340859419124453377, 340853571828469762])
relationShipArray.append([340859419124453377, 340854579195432961])
relationShipArray.append([340770796777660416, 340824159120654336])
relationShipArray.append([340509588065513473, 340764841658703872])
rela... | Python remove duplicate cases that are in inverted matrix | [
"",
"python",
"deduplication",
""
] |
I have a plain text file that contains user login data:
```
dtrapani HCPD-EPD-3687 Mon 05/13/2013 9:47:01.72
dlibby HCPD-COS-4611 Mon 05/13/2013 9:49:34.55
lmurdoch HCPD-SDDEB-3736 Mon 05/13/2013 9:50:38.48
lpatrick HCPD-WIN7-015 Mon 05/13/2013 9:57:44.57
mlay HCPD-WAR-3744 Mon 05/13/2013 1... | I would go for the new(er) print formatter with this one (assuming your fields are consistent). The print/format statement is pretty easy to use and can be found [here](http://docs.python.org/2/library/string.html#formatstrings). Since your data can be seen as a list, you can do a single call to format and supplying th... | `str.ljust(width, [fillchar=" "])` (<http://docs.python.org/2/library/stdtypes.html#str.ljust>) seems like what you're after.
Left justify each field when printing to the maximum length + a little bit.
For the last field to match your example, you'll want to right justify it instead using rjust. | Align columns in a text file | [
"",
"python",
"python-3.x",
"string-interpolation",
""
] |
I have a quick question about VBNET, I'm currently using VS 2012 Express, and Microsoft Access as my database.
My question is, how do I put my queries in a module instead of put the queries in the form itself?
Let's say I have this function in frmStock :
frmStock :
```
Public Sub FillCategory(ByVal Key As String, By... | In your modified `FillCategory` code you called the following but never saved the result:
```
getCategoryParent.Parameters.AddWithValue("Category_Parent", Key)
```
That created an `OleDbCommand` object but then it is immediately discarded. You then call:
```
Dim dr = getCategoryParent.ExecuteReader
```
Which create... | How about just put your SQL string on your module ..
```
Module queryCollection
Public sCatParent As String = "SELECT * FROM Category WHERE Category_Parent = ?"
End Module
```
And you call it like ..
```
getCategoryParent As New OleDbCommand(sCatParent,conn)
getCategoryParent.Parameters.AddWithValue("Category... | Store all queries inside a module? | [
"",
"sql",
"database",
"vb.net",
"visual-studio-2012",
""
] |
I am just trying to create a function that returns a select statement, but it gives the error:
> A RETURN statement with a return value cannot be used in this context.
This is my code:
```
CREATE FUNCTION [dbo].[Sample] (@SampleValue int)
RETURNS TABLE
AS
BEGIN
RETURN(
SELECT * FROM View_sls
)
```
Please let me kn... | Wrong syntax, that's all. You don't need `BEGIN` when you have an "inline table-valued function"
See [CREATE FUNCTION](http://msdn.microsoft.com/en-us/library/ms186755.aspx) and example B
```
CREATE FUNCTION [dbo].[Sample] (@SampleValue int)
RETURNS TABLE
AS
RETURN
(
SELECT * FROM View_sls
);
GO
``` | Two things:
* you need to **define the structure** of the table you want to return
* you need to add data into that table
*Then* you can call `RETURN;` to return that table's data to the caller.
So you need something like this:
```
CREATE FUNCTION [dbo].[Sample] (@SampleValue int)
RETURNS @returnTable TABLE
... | TSQL Error: A RETURN statement with a return value cannot be used in this context | [
"",
"sql",
"t-sql",
"sql-server-2005",
"sql-function",
""
] |
I'm relative new to sql and I would like some help with this one. Basically, I'm trying to do some calculations in the query because functions were a bit slow. Could you guys improve on this?
```
-- Query to retrive ADA from every school
Select Distinct DY,
DATENAME(MM,DT) as 'Month',
CONVERT(nvarcha... | Try this
```
Select DY,
DATENAME(MM,DT) as 'Month',
CONVERT(nvarchar,DT,101) as 'Date',
@M_stu - (Count(case when sc=1 AND al!='' AND DY=T.DY then 1 else null end)/@M_stu)*100 as 'Merced ADA',
@A_stu - (Count(case when sc=2 AND al!='' AND DY=T.DY then 1 else null end)/@A_stu)*100 as '... | Try this solution:
```
SELECT DISTINCT
t.DY AS DY,
DATENAME(MM,t.DT) AS [Month],
CONVERT(NVARCHAR,t.DT,101) AS [Date],
((@M_stu - d.[1])/@M_stu)*100 AS [Merced ADA],
((@A_stu - d.[2])/@A_stu)*100 AS [Atwater ADA],
((@L... | How can this T-SQL query be optimized? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
With normal Django querysets, if I want to retrieve all the myObjects whose "a" attribute is 1, 2 or 3, I would do the following:
```
myObjects.objects.filter(a_in=[1,2,3])
```
But I would like to do this using the Q objects. How would I write the equivalent query with Q objects? | It should look like this:
```
myObjects.objects.filter(Q(a = 1) | Q( a = 2) | Q( a = 3))
```
I don't know why you want to do that but you can also do
```
myObjects.objects.filter(Q(a__in=[1,2,3])
``` | It works right away.
```
Q(a__in=[1, 2, 3])
```
Probably your issue is that you were using a single underscore instead of two. | How to use Q objects to test list membership? | [
"",
"python",
"django",
"django-q",
""
] |
Why this query:
```
SELECT SQL_CALC_FOUND_ROWS,a.*,(SELECT cy.iso_code
FROM ps_address AS addr, ps_country AS cy
WHERE addr.id_customer=a.id_customer
AND addr.id_country=cy.id_country) iso_code
FROM `ps_customer` a ... | From [the documentation on `SELECT`](http://dev.mysql.com/doc/refman/5.0/en/select.html):
> It is not permissible to refer to a column alias in a `WHERE` clause, because the column value might not yet be determined when the `WHERE` clause is executed. See [Section C.5.5.4, “Problems with Column Aliases”](http://dev.my... | Looks like the iso\_code column comes from the ps\_address table which is only available in the context of the subquery you are making inside the select list of your main query (ps\_customer).
Besides that you don't need this WHERE statement in the main query since you are already restricting the iso\_code values in t... | Unknown column error in WHERE clause | [
"",
"sql",
""
] |
My new site (to read books) actually uses static content to serve the pages: I have the HTML file saved in a folder and, to serve the page, I read it and pass the content to a jinja2 template, to show all together. No database hits except for get the book ID to know the title.
This is working fine and fast, but it is ... | Google app engine has a dedicated service for file uploads, it is called Blobstore.
You can write an administration page that let you upload file and publish them. You will need to use the database only to store meta data about each object: Book name, author, related image...
[Here's some documentation](https://devel... | If you want a "poor man's" implementation, create a folder named 'books' in the top level of your application folder. Inside of that, create one folder for each book, and inside each one of those, create one folder for each chapter. This will give you a tree structure for your library.
Then, inside each book's folder,... | GAE: use static HTML file vs database to serve contents | [
"",
"python",
"google-app-engine",
"app-engine-ndb",
""
] |
I always use fabric to deploy my processes from my local pc to remote servers.
If I have a python script like this:
test.py:
```
import time
while True:
print "Hello world."
time.sleep(1)
```
Obviously, this script is a continuous running script.
And I deploy this script to remote server and execute my fabr... | `sudo("python test.py 2>/dev/null >/dev/null &")`
or redirect the output to some other file instead of /dev/null | Usually for this kind of asynchronous task processing [Celery](http://www.celeryproject.org/) is preferred .
[This](http://nicholaskuechler.com/2012/06/19/auto-scale-rackspace-cloud-servers-with-fabric-and-celery/) explains in detail the use of Celery and Fabric together.
```
from fabric.api import hosts, env, execute... | How to prevent fabric form waiting for the process to return | [
"",
"python",
"fabric",
""
] |
If I have the following database schema

And I wanted to write a query that listed all Bill\_Items, but included a flag that was true if any associated inventory items where marked with the CheckFlag bit, what would be the correct way to do it?
The ... | Try this:
```
select
Bill_items.billcode
,max(cast(CheckFlag as int)) as flagSet
from Bill_items
join Linked_items
on Bill_items.billcode = Linked_items.Bill_Code
join inventoryitems
on Linked_items.Item_code = inventoryitems.ItemCode
group by
Bill_items.billcode
```
If you need to include Bi... | This should work (the inner sub-query shall save you from adding all the columns in the `group by` clause) and would also be faster
```
SELECT
bi.*,
temp.checkflag
FROM
bill_items bi
LEFT JOIN (
SELECT
max(ii.checkflag) as checkflag,
li.bill_code
F... | What is the correct way to find if any item in a one to many relationship has a flag set? | [
"",
"sql",
"sql-server",
""
] |
I have many lists in this format:
```
['1', 'O1', '', '', '', '0.0000', '0.0000', '', '']
['2', 'AP', '', '', '', '35.0000', '105.0000', '', '']
['3', 'EU', '', '', '', '47.0000', '8.0000', '', '']
```
I need to create a dictionary with key as the first element in the list and value as the entire list. None of the ke... | put all your lists in another list and do this:
```
my_dict = {}
for list in lists:
my_dict[list[0]] = list[:]
```
This basically gets the first element and puts it as a key in `my_dict` and put the list as the value. | ```
>>> lists = [['1', 'O1', '', '', '', '0.0000', '0.0000', '', ''],
['2', 'AP', '', '', '', '35.0000', '105.0000', '', ''],
['3', 'EU', '', '', '', '47.0000', '8.0000', '', '']]
>>> {x[0]: x for x in lists}
{'1': ['1', 'O1', '', '', '', '0.0000', '0.0000', '', ''], '3': ['3', 'EU', '', '', '', '47.0000', '8.0000', ''... | Create dictionary from list python | [
"",
"python",
"list",
"dictionary",
""
] |
I have a dictionary in format {'string-value-keys':[list-values]}. For a particular key value, I would like to retrieve the value as a string. Here is the example:
```
>>> simpleDict= {'DDL_TABLE1':['create table bla', ' columns bla bla'], 'DML_TABLE1': ['insert into bla', ' values bla']}
>>> simpleDict
{'DDL_TABLE1':... | Move the join inside:
```
(' '.join(value) for key, value in simpleDict.items() if 'DDL' in key)
```
Test:
```
>>> simpleDict= {'DDL_TABLE1':['create table bla', ' columns bla bla'], 'DML_TABLE1': ['insert into bla', ' values bla']}
>>> list(' '.join(value) for key, value in simpleDict.items() if 'DDL' in key)
['cre... | `" ".join()` expects an iterable of strings and your generator yields lists of strings, so you are ending up with a call like `" ".join([['create table bla', ' columns bla bla']])`.
Since it looks like you only expect a single key to match, you probably don't want a generator for this. I would suggest the following:
... | Joining value(list) from <key, value> in dictionary | [
"",
"python",
"python-2.7",
""
] |
I'm wondering if I can select the value of a column if the column exists and just select null otherwise. In other words I'd like to "lift" the select statement to handle the case when the column doesn't exist.
```
SELECT uniqueId
, columnTwo
, /*WHEN columnThree exists THEN columnThree ELSE NULL END*/ AS col... | You cannot do this with a simple SQL statement. A SQL query will not compile unless all table and column references in the table exist.
You can do this with dynamic SQL if the "subquery" is a table reference or a view.
In dynamic SQL, you would do something like:
```
declare @sql nvarchar(max) = '
SELECT uniqueId, c... | As others already suggested, the sane approach is to have queries that meet your table design.
There is a rather exotic approach to achieve what you want in (pure, not dynamic) SQL though. A similar problem was posted at DBA.SE: [How to select specific rows if a column exists or all rows if a column doesn't](https://d... | Select columnValue if the column exists otherwise null | [
"",
"sql",
"sql-server",
"select",
"exists",
""
] |
I was just wondering if there is a simple way to do this. I have a particular structure that is parsed from a file and the output is a list of a dict of a list of a dict. Currently, I just have a bit of code that looks something like this:
```
for i in xrange(len(data)):
for j, k in data[i].iteritems():
fo... | You *never* need to iterate through `xrange(len(data))`. You iterate either through `data` (for a list) or `data.items()` (or `values()`) (for a dict).
Your code should look like this:
```
for elem in data:
for val in elem.itervalues():
for item in val['data']:
```
which is quite a bit shorter. | Will, if you're looking to decend an arbitrary structure of array/hash thingies then you can create a function to do that based on the `type()` function.
```
def traverse_it(it):
if (isinstance(it, list)):
for item in it:
traverse_it(item)
elif (isinstance(it, dict)):
for key in it.... | Python: How to traverse a List[Dict{List[Dict{}]}] | [
"",
"python",
"list",
"loops",
"dictionary",
"traversal",
""
] |
I have a problem using BeautifulSoup4... (I'm quite a Python/BeautifulSoup newbie, so forgive me if i'm dumb)
Why does the following code:
```
from bs4 import BeautifulSoup
soup_ko = BeautifulSoup('<select><option>foo</option><option>bar & baz</option><option>qux</option></select>')
soup_ok = BeautifulSoup('<select>... | As i said in the edited first post, it was a bug in BeautifulSoup 4.2.0, i downloaded 4.2.1 and the bug is gone. | `&` is used in HTML to input so called *HTML entities*. E.g., `<` is a special symbol in HTML because it starts a tag, so you use `<` instead.
Thus, `&` itself is also a special symbol, and you should use `&` for a literal ampersand. Your HTML was invalid and BeautifulSoup fixed it. | BeautifulSoup4 : Ampersand in text | [
"",
"python",
"html",
"python-2.7",
"beautifulsoup",
""
] |
I am trying to slice different parts of a line into a list of dictionaries using a list comprehension. The code below doesn't work, but it illustrates what I am trying to do. Any help would be much appreciated!
Thanks
```
def getDataElements(self):
return [x for x for line in self.data: {"Number": line[0:9],
... | There are instances where list comprehensions are good, but this is not one of them. Just use a loop and a generator:
```
for line in self.data:
yield {
"Number": line[0:9],
"FullName": line[9:27].rstrip(),
"LastName": line[27:63].rstrip(),
"Area": line[63:65].rstrip(),
"Cit... | You were somewhat clear, but you have to put the dictionary in the beginning...if I fully understand what you want, the following should work:
```
return [{"Number": line[0:9],"FullName": line[9:27].rstrip(),"LastName": line[27:63].rstrip(),"Area": line[63:65].rstrip(),"City": line[65:90].rstrip(),"Status": line[91],"... | parsing a line into a dictionary through a list comprehension | [
"",
"python",
"dictionary",
"list-comprehension",
""
] |
I have a while loop that returns the number of 'rushes' it takes to get up a hill.
The size of the hill is the 'slope height' and the height run up is the 'rush\_height\_gain' minus the 'back\_sliding'.
The code below works for:
```
ans = num_rushes(15, 10, 5)
print(ans)
```
which prints 1
and
```
ans = num_rushes... | If I'm understanding the question properly, I think what you're looking for is:
```
def num_rushes(slope_height, rush_height_gain, back_sliding):
if rush_height_gain < slope_height and rush_height_gain - back_sliding < 1:
raise Exception("this is not going to work very well")
current_height = rushes = ... | I believe the problem is this statement:
```
if current_height == slope_height:
return rushes
```
When `back_sliding` is `0`, then on the tenth iteration, `current_height` goes from `90` to `100`. Then the check returns true, and `9` is returned before it's incremented. | While loops (Python) | [
"",
"python",
"while-loop",
""
] |
I'm using SQL Server 2008.
I have a table with a column of type `VarChar`. It is currently filled with strings which actually represent numbers. Unfortunately, the column must remain `VarChar ('1', '2' ... , '1000' )`.
I wish to query that field for the max number value but since this is a `VarChar` I get the Lexicog... | There is no collation option that will perform a natural sort on numbers.
You can however, cast the value as an integer if all the values are expected to be integers.
Try something like
```
SELECT MAX(CAST (Value as int))
FROM MyTable
``` | Just a note, a third option is to use a persisted computed column - which is the value cast to a numeric
That way it is only cast once - on create or update
```
-- Create Table with computed column
CREATE TABLE [dbo].[CCtest]
(
[myString] [varchar] NULL,
[myInt] AS (cast(myString as int)) PERSISTED
)
GO
```
It's the... | SQL Server - Is there a collation that provides natural order for numbers? | [
"",
"sql",
"sql-server-2008",
"collation",
""
] |
How to copy all even lines from one file to a new file in Python?
The even number is just an illustration when I want a very select though substantive number of lines copied from one file to another, but it should be good as an example.
I use this, but it is very inefficient (it takes around 5 minutes):
```
# foo.tx... | What's taking all the time is searching `list`. In order to figure out whether `i` is in `list`, it has to scan through the entire list to be sure that it's not there. If you really only care about even numbers, you can simply use `if i % 2 == 0`, but if you have a specific group of line numbers you want, you should us... | I'm assuming that your `list` is predefined, and can contain any sequence of possible line indices, not necessarily every Nth line for example.
The first probable bottleneck is that you're doing a O(n) list search (`i in list`) 200000 times. Converting the list to a dictionary should already help:
```
listd = dict.fr... | Efficiently copying specific lines to another file (Python 3.3) | [
"",
"python",
""
] |
I am attempting to draw circle at the location of my mouse whenever I hit the space bar. The goal is to draw this circle around a character that is following my mouse cursor and kill other objects it comes in contact with. Am I on the right track, also how the heck does drawing a circle work
```
import math
import pyg... | There are a few things you need to change to make it work. I've included a somewhat lengthy explanation behind all of these changes, so that you will be able to understand them and apply them correctly in other parts of your game. If you do not need the extra explanation, you can skip to working code at the bottom of t... | With the following line (the last one in your program):
```
var.Attack
```
You aren't calling the `attack` function.
Replace it with
```
var.Attack()
```
and see if that works instead. | Drawing a circle at my mouse location when I hit the space bar (Pygame) | [
"",
"python",
"pygame",
"draw",
""
] |
I'm storing some queries in a table column so I can execute them later passing some parameters.
But it has been really annoying to format the query into an Update sentence, because of the special characters.
For Example:
```
SELECT * FROM MOUNTAINS WHERE MON_NAME='PALMA' AND MON_DESC LIKE '%TRANVULCANIA%'
```
Then I... | Adapting the solution given by @rivarolle
```
DECLARE @QUERY VARCHAR(MAX)
DECLARE @FORMATTED varchar(max)
SELECT @QUERY='SELECT * FROM QUERIES WHERE QUE_NOMBRE='''+'PRUEBA 1'+''''
;WITH TOKENS AS(
SELECT
t.r.value('.', 'varchar(MAX)') AS token
, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Id
FROM (
... | Assuming your token table is Tokens(Token, Id, Position):
```
update Tokens
set position = quotes.row%2
from Tokens
left join (select row_number() over( order by Id asc) as row, a.* FROM (SELECT * from Tokens) a where Token = '''') quotes
on quotes.Id = Tokens.Id
```
The position column will have a value o... | How to generate an update query of a dynamic query (automatically)? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"formatting",
""
] |
I know the title seems crazy, but it is true. Here is my predicament. First, I am still a beginner at Python so please be considerate. I am trying to test if a variable exists. Now the variable comes from a file that is parsed in yaml. Whenever I try this code,
```
if not name['foo']:
print "No name given."
re... | A few things:
* That shouldn't throw an exception! You're doing `name['foo']` in two places and expecting different behavior.
* The `name` doesn't behave like a dictionary, if it did you would NOT get a return of `False` in the first example, you'd get an exception. Try doing this:
```
name = {}
name['foo']
`... | I don't understand why you think it would raise an exception. The key evidently exists, otherwise the first snippet would not work. The value for that key is obviously some false-y value like `False`, `None`, `[]` or `''`. | Python: variable "tricking" try-exception, but works for if statement | [
"",
"python",
"parsing",
"exception",
"if-statement",
""
] |
i have a simple table:
```
CREATE TABLE aaa_has_bbb (
aaa_id integer not null,
bbb_id integer not null,
rank integer not null,
primary key(aaa_id, bbb_id),
uniq(aaa_id, rank)
)
```
I am trying to create a rule which will DELETE and INSERT because that will activate some relevant triggers.
```
C... | I tested and reproduced your problem.
This quote from [the manual on `CREATE RULE`](http://www.postgresql.org/docs/current/interactive/sql-createrule.html) should shed some light on the mystery:
> Within condition and command, the special table names `NEW` and `OLD` can
> be used to refer to values in the referenced... | The below fragment works for the simple case, but fails for the second (batch) update, probably caused by the update not being qualified by a where-clause.
I was not able to get a correctly qualified range table entry into the resulting query plan; without a where-clause, the delete-target RTE remains unqualified in t... | postgres update rule wont insert | [
"",
"sql",
"postgresql",
"triggers",
""
] |
I have a .csv file on my F: drive on Windows 7 64-bit that I'd like to read into pandas and manipulate.
None of the examples I see read from anything other than a simple file name (e.g. 'foo.csv').
When I try this I get error messages that aren't making the problem clear to me:
```
import pandas as pd
trainFile = "... | I cannot promise that this will work, but it's worth a shot:
```
import pandas as pd
import os
trainFile = "F:/Projects/Python/coursera/intro-to-data-science/kaggle/data/train.csv"
pwd = os.getcwd()
os.chdir(os.path.dirname(trainFile))
trainData = pd.read_csv(os.path.basename(trainFile))
os.chdir(pwd)
``` | A better solution is to use literal strings like r'pathname\filename' rather than 'pathname\filename'. See [Lexical Analysis](https://docs.python.org/2/reference/lexical_analysis.html) for more details. | Read a .csv into pandas from F: drive on Windows 7 | [
"",
"python",
"csv",
"pandas",
""
] |
Is there a fast way to do serialization of a DataFrame?
I have a grid system which can run pandas analysis in parallel. In the end, I want to collect all the results (as a DataFrame) from each grid job and aggregate them into a giant DataFrame.
How can I save data frame in a binary format that can be loaded rapidly? | The easiest way is just to use [to\_pickle](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_pickle.html) (as a [pickle](https://docs.python.org/3/library/pickle.html)), see [pickling from the docs api page](https://pandas.pydata.org/pandas-docs/stable/reference/io.html#pickling):
```
df.to_pickle(file... | [DataFrame.to\_msgpack](https://pandas.pydata.org/pandas-docs/version/0.25.0/reference/api/pandas.DataFrame.to_msgpack.html) is experimental and not without some issues e.g. with Unicode, but it is **much faster** than pickling. It serialized a dataframe with 5 million rows that was taking 2-3 Gb of memory in about 2 s... | Serialization of a pandas DataFrame | [
"",
"python",
"pandas",
""
] |
Just for curiosity. Discovered Lambdas a few days ago. I was jus wondering if something like that can be done:
(Tried on the interpret but none of my tries seemed to work)
```
p = lambda x: (lambda x: x%2)/2
```
There's no explicit purpose. I just did'nt find a satisfactory answer. I may have misunderstood Lambdas. | You aren't actually *calling* the inner `lambda`:
```
p = lambda x: (lambda x: x%2)(x)/2
```
Note in Python 2 this example will always return `0` since the remainder from dividing by `2` will be either `0` or `1` and integer-dividing that result by `2` will result in a truncated `0`. | You can use an inner lambda to return another function, based on the outer parameters:
```
mul = lambda x: (lambda y: y * x)
times4 = mul(4)
print times4(2)
``` | Lambda inside lambda | [
"",
"python",
"lambda",
""
] |
As we all know, there's list comprehension, like
```
[i for i in [1, 2, 3, 4]]
```
and there is dictionary comprehension, like
```
{i:j for i, j in {1: 'a', 2: 'b'}.items()}
```
but
```
(i for i in (1, 2, 3))
```
will end up in a generator, not a `tuple` comprehension. Why is that?
My guess is that a `tuple` is ... | You can use a generator expression:
```
tuple(i for i in (1, 2, 3))
```
but parentheses were already taken for … generator expressions. | Raymond Hettinger (one of the Python core developers) had this to say about tuples in a [recent tweet](https://twitter.com/raymondh/status/324664257004322817):
> #python tip: Generally, lists are for looping; tuples for structs. Lists are homogeneous; tuples heterogeneous. Lists for variable length.
This (to me) supp... | Why is there no tuple comprehension in Python? | [
"",
"python",
"tuples",
"list-comprehension",
"dictionary-comprehension",
"set-comprehension",
""
] |
I want to change name and type of column from `BIT(1)` to `INT(1)`.
I am using MySQL Workbench.
I tried this:
```
ALTER TABLE table_name ADD new_column_name INT(1)
update table_name
set new_column_name = convert(INT(1), old_column_name)
ALTER TABLE table_name DROP COLUMN old_column_name
```
But I am getting this ... | ```
ALTER TABLE table_name ADD new_column INT(1);
update table_name
set new_column = case when old_column then 1 else 0 end;
ALTER TABLE table_name DROP COLUMN old_column;
```
or simply use:
```
ALTER TABLE table_name MODIFY COLUMN old_column int;
``` | ```
ALTER TABLE table_name CHANGE old_column_name new_col_name varchar(20) not null;
```
I put varchar as an examaple. you can change to any data type you like. You can also add constraints after that. | Change database column name and its type without losing data | [
"",
"mysql",
"sql",
"database",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.