Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
If scipy.weave.inline is called inside a massive parallel MPI-enabled application that is run on a cluster with a home-directory that is common to all nodes, every instance accesses the same catalog for compiled code: $HOME/.pythonxx\_compiled. This is bad for obvious reasons and leads to many error messages. How can t... | My previous thoughts about this problem:
Either scipy.weave.catalog has to be enhanced with a proper locking mechanism in order to serialize access to the catalog, or every instance has to use its own catalog.
I chose the latter. The `scipy.weave.inline` function uses a catalog which is bound to the module-level name... | As per [the scipy docs](http://docs.scipy.org/doc/scipy/reference/tutorial/weave.html#catalog-search-paths-and-the-pythoncompiled-variable), you could store your compiled data in a directory that isn't on the NFS share (such as /tmp or /scratch or whatever is available for your system). Then you wouldn't have to worry ... | How can scipy.weave.inline be used in a MPI-enabled application on a cluster? | [
"",
"python",
"scipy",
"cluster-computing",
"mpi",
""
] |
I wanted to know if the functionality i am trying to implement in python is possible.
I have a global hash called Creatures. Creatures contain sub-hashes called mammals, amphibians, birds, insects.
Mammals have sub-hashes called whales, elephants. Amphibians have sub-hashes called frogs, larvae. Birds have sub-hashes... | If you just have to "count" things -- and assuming the data file contains all the required level of "hashes" -- that will do the trick:
```
import collections
result = collections.defaultdict(int)
with open("beast","rt") as f:
for line in f:
hashes = line.split()
key = '-'.join(hashes)
re... | The value assigned to a key in a dictionary can itself be another dictionary
```
creatures = dict()
creatures['birds'] = dict()
creatures['birds']['eagle'] = dict()
creatures['birds']['eagle']['female'] = 0
creatures['birds']['eagle']['female'] += 1
```
You need to explicitly create each dictionary, though. Unlike Pe... | Multiple levels of keys and values in Python | [
"",
"python",
"python-2.7",
"dictionary",
""
] |
I have images such as the one below from which I need to count the prominent white spots. Unfortunately my object counting algorithm is becoming confused due to those "fuzzy" white areas. It can sometimes see hundreds of objects there.

So what I'm wondering is whe... | I ended up using G'MIC's Bilateral Filtering, it was the perfect tool for the job. | Increase the [contrast](http://docs.gimp.org/en/gimp-tool-brightness-contrast.html) in GIMP. | Exaggerating colors in GIMP/Python | [
"",
"python",
"image-processing",
"python-imaging-library",
"gimp",
""
] |
What's wrong with this python snippet:
```
for zhszam in pontok.keys():
s = 0
for p in pontok[zhszam]:
if p.isdigit():
s += int(p)
print s
pontok[zhszam] = s
return pontok
```
where *pontok* is `{1: ['10', ' 5', ' 3', ' 10', ' 7'], 2: ['10', ' 5', ' 3', ' 10']}`.
It gives t... | Every string except the first `'10'` has a leading space, which isn't a digit. Thus it's not being processed at all.
Try:
```
for p in pontok[zhszam]:
p = p.strip()
# ...
``` | You should not use `str.isdigit`, it can break very easily. Better use a try-except block with `int()`.
```
>>> dic = {1: ['10', ' 5', ' 3', ' 10', ' 7'], 2: ['10', ' 5', ' 3', ' 10']}
for k,v in dic.iteritems():
s = 0
for x in v:
try:
s += int(x) #raises Error if the item is not a vali... | Cannot convert string to int in Python | [
"",
"python",
"arrays",
"hash",
"sum",
"type-conversion",
""
] |
I have a table with user\_ids, and other table with user\_ids and other data(empty).
I want to insert all the ids into the empty table.
I know I can just do it with i.e. php script or even create copy\paste script with
```
insert into tableB values(x),(y),(z);
```
what I m interested in, though, is can i somehow us... | Have a look st
[INSERT ... SELECT Syntax](http://dev.mysql.com/doc/refman/5.0/en/insert-select.html)
> With INSERT ... SELECT, you can quickly insert many rows into a table
> from one or many tables.
Syntax
```
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ... | ```
insert into tableB select x from tableA
``` | insert all rows from table into other table, single query | [
"",
"mysql",
"sql",
"insert",
""
] |
How can I check if my installed version of numpy is compiled with SSE/SSE2 instruction set?
I know that some parts of numpy is using BLAS, how to check BLAS too? | Take a look at:
```
import numpy.distutils.system_info as sysinfo
sysinfo.show_all()
```
This will print out all of the information about what numpy was compiled against. | I think that one way is to use objdump on a numpy.so file if you are under linux, and grep for instruction that are specific to sse.
for SSE3 (<http://en.wikipedia.org/wiki/SSE3>) :
```
objdump -d /usr/lib/pyshared/python2.7/numpy/core/*.so | grep -i MOVDDUP
```
for SSE2 (<http://fr.wikipedia.org/wiki/Jeu_d%27instr... | How can I check if my installed numpy is compiled with SSE/SSE2 instruction set? | [
"",
"python",
"numpy",
"sse",
""
] |
Can someone tell me why when you copy dictionaries they both point to the same directory, so that a change to one effects the other, but this is not the case for lists?
I am interested in the logic behind why they would set up the dictionary one way, and lists another. It's confusing and if I know the reason behind it... | Some code with similar intent to yours will show that changes to one list do affect other references.
```
>>> list = ['one' , 'two' , 'three']
>>> newlist = list
>>> list.append('four')
>>> print newlist
['one', 'two', 'three', 'four']
```
That is the closest analogy to your dictionary code. You call a method on the ... | Your two cases are doing different things to the objects you're copying, that's why you're seeing different results.
First off, you're not really copying them. Your simply making new "references" or (in more Pythonic terms) binding new names to the same objects.
With the dictionary, you're calling `dict.clear`, which... | Why do copied dictionaries point to the same directory but lists don't? | [
"",
"python",
"list",
"dictionary",
""
] |
I have an input list like `[2,3,4,"5cm", 6,"2.5km"]` and I would like to have a result:
`[2,3,4,5,6,2.5]`
I would like to start in this way
```
for element in inputList:
``` | Here is a solution that does not use `regex`: :
```
my_list = [2,3,4,"5cm", 6,"2.5km"]
def get_digits(s):
return ''.join(ele for ele in s if not ele.isalpha())
def convert_to_nums(my_list):
result = []
for ele in my_list:
if isinstance(ele, (int, float)):
result.append(ele)
e... | You can use `regex`:
```
>>> import re
>>> lis = [2,3,4,"5cm", 6,"2.5km"]
>>> r = re.compile(r'\d+(.\d+)?')
>>> [float(r.search(x).group(0)) if isinstance(x,str) else x for x in lis]
[2, 3, 4, 5.0, 6, 2.5]
```
Use `ast.literal_eval` instead of `float` to get `5.0` as `5`:
```
>>> from ast import literal_eval
>>> [l... | how to convert string like "5cm" into an integer | [
"",
"python",
"string",
"list",
""
] |
I'm making a program that deals cards and assigns 5 random cards to each player, and it works up until I try to print the hands of each player (showHand function). I am trying to print the cards the given player has but it's telling me "cards" isn't a global attribute. I know it isn't, but I don't know how to print the... | First of all your `assignCard` function doesn't modify the global variable (I assume that is what you actually wont to do)
so you have to add a line there like `global cardLoc`
having modified this global variable you can print your cards with the following code
```
for i in range(NUMCARDS-1):
if cardLoc[i] == str... | I think you need a global cards object that gets initialized and contains the label. Similar to what you do in `showDeck`. It could be just an array of `NUMCARDS`. Then in `showHand` you iterate through cardLoc and print only the ones given to the user:
```
for i in NUMCARDS:
if cardLoc[i] == str:
print ca... | Dealing Cards in Python? | [
"",
"python",
"arrays",
"loops",
"for-loop",
""
] |
All I have what seems to be a pretty straight forward question, that I haven't been able to figure out. For example, if I have a text string like `T6L 7H5`. Using SQL I need to remove the inner white space from this string so that it displays like `T6L7H5`.
Things to consider:
* Teradata (v.13.10) is my RDBMS, so `RE... | For single white space you can use `POSITION()` and `SUBSTRING()`. You have to offset for the whitespace location that is returned by the `POSITION()` function.
```
WITH CTE(FieldName) AS
(SELECT 'TB7 TCH' AS FieldName)
SELECT SUBSTRING(FieldName FROM 1 FOR (POSITION(' ' IN FieldName) - 1))
|| ... | Can't test this, so spit-balling, but you should be able to leverage Substring and Position:
```
SELECT SUBSTRING('T6L 7H5', 1, POSITION (' ' IN 'T6L 7H5')-1) || SUBSTRING('T6L 7H5', POSITION (' ' IN 'T6L 7H5')+1, CHARACTER_LENGTH('T6L 7H5') - POSITION (' ' IN 'T6L 7H5') )
```
If the field is consistently formatted... | Remove inner white spaces in text data with SQL | [
"",
"sql",
"whitespace",
"teradata",
""
] |
I have a field that is build like this "1;2;3;4;8;9;11;"
If I want to search if a number is in this range I do it like this:
```
SELECT * FROM table WHERE [id] LIKE '[number];%' OR '%;[number];%'
```
Is there another more easy way where i can split the string?
Many thanks | If you are storing the values in a string, the best way to use `like` is as:
```
SELECT *
FROM table
WHERE concat(';', @numbers) like concat('%;', [id], ';%')
```
MySQL also offers `find_in_set()` when the delimiter is a comma:
```
SELECT *
FROM table
WHERE find_in_set(id, replace(@numers, ';', ',')
``` | Use [`IN()`](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_in) with a comma delimited string of IDs
```
SELECT * FROM table WHERE id IN(1,2,3,4,8,9,11)
``` | MYSQL explode search | [
"",
"mysql",
"sql",
""
] |
This is a follow-up question on [Get age from the birthday field with type date using SQL](https://stackoverflow.com/q/17146119/1544337). I have a `date` field in a MySQL database for the birthday of a user and get the age using this query:
```
SELECT
ROUND(DATEDIFF(
Cast((SELECT NOW()) as Date),
... | ```
select AgeGroup
, count(*)
from (
select case
when age between 13 and 17 then 1
when age between 18 and 21 then 2
...
end as AgeGroup
from (
SELECT ROUND(DATEDIFF(Cast(NOW() as Date),
... | Another possible solution:-
```
SELECT AgeRange.MinAge, AgeRange.MaxAge, COUNT(*)
FROM
(
SELECT 13 AS MinAge, 17 AS MaxAge
UNION SELECT 18, 21
UNION SELECT 22, 25
UNION SELECT 26, 35
UNION SELECT 36, 50
UNION SELECT 51, 9999
) AgeRange
INNER JOIN YourTable
ON ROUND(DATEDIFF(CAST(NOW() as D... | Selecting age groups using SQL | [
"",
"mysql",
"sql",
"database",
""
] |
I have some questions about Defaultdict and Counter. I have a situation where I have a text file with one sentence per line. I want to split up the sentence into two (at first space) and store them into a dictionary with the first substring as the key and the second substring as the value. The reason for doing this is ... | Using `collections.Counter` to "get a total number of sentences that share the same key."
```
from collections import Counter
with openFileObject as infile:
print Counter(x.split()[0] for x in infile)
```
will print
```
Counter({'id1': 2, 'id4': 1, 'id3': 1})
```
If you want to store a list of all the lines, yo... | `dict.get(key, 0)` return current accumulated count. If key was not in dict, return 0.
```
classDict = {}
with open('text.txt') as infile:
for line in infile:
key = line.split(' ' , 1)[0]
classDict[key] = classDict.get(key, 0) + 1
print(len(classDict))
for key in classDict:
print(... | Splitting a sentence into two and storing them into a defaultdict as key and value in Python | [
"",
"python",
"list",
"dictionary",
"counter",
"split",
""
] |
Maybe this is a 4am bug, but I *think* I'm doing everything right, but it doesn't appear as though DST is translating from the UTC timestamp to the localized datetime.
```
>>> from datetime import datetime
>>> import pytz
>>> eastern = pytz.timezone("US/Eastern")
>>> utc = pytz.utc
>>> local_now = eastern.localize(dat... | ```
o------------o
| | DT.datetime.utcfromtimestamp (*)
| |<-----------------------------------o
| | |
| datetime | |
| | DT... | You should avoid `datetime.now` if you want to write portable code, as it always uses the local timezone, so `local_now = eastern.localize(datetime.now())` will only work if the timezone on the local machine *is* eastern. Always try to use `utcnow`, and for the same reason `utcfromtimestamp`.
Also, using `strftime("%s... | Losing DST information using pytz and UTC conversions | [
"",
"python",
"datetime",
"timezone",
"utc",
"pytz",
""
] |
```
mylist = [{'a':1,'b':2},{'a':3,'b':'10'},.....]
I want to do some special operations for the last itemin loop (iterarale), what to do?
for item in mylist:
do some operations for all items
#I want to execute the next statement only for last item
last_b = item[b]
last_b
```
What is the best method to d... | `item` remains in scope at the end of the loop, and conveniently is the last item, so you just need to dedent that line
```
for item in mylist:
# do some operations for all items
last_b = item[b]
``` | Try this:
```
for i in range(len(my_list)-1):
#do stuff till last before element, where i will be the index of the list
my_list[last]=#something
```
This will do seperate iteration only for the last element in the list | Do an extra work for the last iteration | [
"",
"python",
""
] |
I have a column in my DB which is currently defined as `NOT NULL`.
I would like to update this column to allow `NULLs`.
I have the following script to do this however I would like to check first if the column is already `NULL` (or `NOT NULL`), as it may have been changed previously.
```
ALTER TABLE [dbo].[aud]
ALTE... | Use **COLUMNPROPERTY** to get column property . You may write something like
```
SELECT COLUMNPROPERTY(OBJECT_ID('dbo.aud'),'actname','AllowsNull') AS 'AllowsNull';
```
For more information please visit this [link](http://msdn.microsoft.com/en-us/library/ms174968.aspx) | ```
select is_nullable from sys.columns c inner join sys.tables t on
t.object_id = c.object_id where t.name = 'aud' and c.name = 'actname'
```
Will give you a `BIT` representing whether it is nullable or not.
So you could switch on this like
```
IF EXISTS(SELECT * from sys.columns c inner join sys.tables t on
t.... | Finding out if a column is NOT NULL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
### Problem
I've segmented a long-running task into logical subtasks, so I can report the results of each subtask as it completes. However, I'm trying to report the results of a task that will effectively never complete (instead yielding values as it goes), and am struggling to do so with my existing solution.
### Ba... | In order for Celery to know what the current state of the task is, it sets some metadata in whatever result backend you have. You can piggy-back on that to store other kinds of metadata.
```
def yielder():
for i in range(2**100):
yield i
@task
def report_progress():
for progress in yielder():
... | Paul's answer is great. As an alternative to using `mark_as_started` you can use `Task`'s `update_state` method. They ultimately do the same thing, but the name "update\_state" is a little more appropriate for what you're trying to do. You can optionally define a [custom state](http://celery.readthedocs.org/en/latest/u... | Reporting yielded results of long-running Celery task | [
"",
"python",
"django",
"celery",
""
] |
I'm looking to write an update statement something like below:
```
update table set
comments = NVL (null, acknowledgement_status),
acknowledgement_status = 'Acknowledge',
alert_updated_time = sysdate,
acknowledged_by = 'Allen'
where alert_id = 8;
```
Actually, the values need to be updated from a JSP page. If a user ... | Here is one way, if you want to pass the values only once:
```
UPDATE tableX t
SET
(comments, acknowledgement_status, alert_updated_time, acknowledged_by)
=
( SELECT
COALESCE(com, ack_st), ack_st, sd, ack_by
FROM
( SELECT
textbox.value AS com,
dropdown.value AS ack_st,
... | Try the following
```
update table set comments =
case when (comments is null) then acknowledgement_status else comments end,
acknowledgement_status = 'Acknowledge',
alert_updated_time = sysdate,
acknowledged_by = 'Allen'
where alert_id = 8;
```
Trigger approach
```
CREATE OR REPLACE TRIGGER test
B... | How to update a column dynamically with the current value of another column? | [
"",
"sql",
"oracle",
"oracle10g",
""
] |
I was trying to install `autoclose.vim` to Vim. I noticed I didn't have a `~/.vim/plugin` folder, so I accidentally made a `~/.vim/plugins` folder (notice the extra 's' in plugins). I then added `au FileType python set rtp += ~/.vim/plugins` to my .vimrc, because from what I've read, that will allow me to automatically... | [:help load-plugins](http://vimdoc.sourceforge.net/htmldoc/starting.html#load-plugins) outlines how plugins are loaded.
Adding a folder to your `rtp` alone does not suffice; it must have a `plugin` subdirectory. For example, given `:set rtp+=/tmp/foo`, a file `/tmp/foo/plugin/bar.vim` would be detected and loaded, but... | You are on the right track with `set rtp+=...` but there's a bit more to it (`rtp` is non-recursive, help indexing, many corner cases) than what meets the eye so it is not a very good idea to do it by yourself. Unless you are ready for a months-long drop in productivity.
If you want to store all your plugins in a spec... | Vim plugins don't always load? | [
"",
"python",
"vim",
"plugins",
""
] |
I am trying to perform a SQL Select query based on the user input from a Checked List Box. I was able to find some code, but the solution doesn't seem to be working. On the debug, it keeps crapping out on line 3 and I have no idea why.
Any help would be grateful.
```
Dim DistrictString As StringBuilder = New StringBu... | Thank you to everyone who helped, this is the solution that I implemented
Learned a lot from this little exercise.
```
Dim DistrictW As String
Dim DistrictX As String
Dim DistrictString As StringBuilder = New StringBuilder
For h = 0 To Me.District.CheckedItems.Count - 1
DistrictString.Append(Me.District.C... | ```
If Me.District.CheckedItems.Items(h).Selected Then
DistrictString.Append(Me.District.CheckedItems.Items(h).Value & ",")
End If
```
Use CheckboxList.Items | CheckedListBox items to SQL Select Statement | [
"",
"sql",
"vb.net",
""
] |
If I have:
```
dicts = [{'a': 4,'b': 7,'c': 9},
{'a': 2,'b': 1,'c': 10},
{'a': 11,'b': 3,'c': 2}]
```
How can I get the maximum keys only, like this:
```
{'a': 11,'c': 10,'b': 7}
``` | Use [`collection.Counter()` objects](http://docs.python.org/2/library/collections.html#counter-objects) instead, or convert your dictionaries:
```
from collections import Counter
result = Counter()
for d in dicts:
result |= Counter(d)
```
or even:
```
from collections import Counter
from operator import or_
re... | ```
>>> dicts = [{'a': 4,'b': 7,'c': 9},
... {'a': 2,'b': 1,'c': 10},
... {'a': 11,'b': 3,'c': 2}]
>>> {letter: max(d[letter] for d in dicts) for letter in dicts[0]}
{'a': 11, 'c': 10, 'b': 7}
``` | Get max keys of a list of dictionaries | [
"",
"python",
"list",
"dictionary",
""
] |
There are tables with clients and festivals. Every festival happens every year (like New Year). But not every client is invited on any festival.
I need to get woman clients, that were invited on festival1 at this moment, but weren't invited on festival2.
```
Table "clients"
+-----+--------------+-----------+---------... | You can use `NOT EXISTS` to eliminate results from your query:
```
SELECT *
FROM Clients
INNER JOIN Invitations
ON Invitations.Client = Clients.ID
INNER JOIN Festivals
ON Festivals.ID = Invitations.Festival
WHERE Festivals.Name = 'Festival1'
AND Clients.Sex = 'W'
AND ... | ```
SELECT c.name
FROM clients c
INNER JOIN invitations i ON c.id = i.client
INNER JOIN festivals f ON f.id = i.festival
WHERE c.sex = 'w'
AND i.year = 2013
group by c.name
having sum(case when f.name='festival1' then 1 else 0 end) > 0
and sum(case when f.name='festival2' then 1 else 0 end) = 0
``` | Multiple sql table select | [
"",
"sql",
"select",
"join",
"multiple-tables",
"multiple-select",
""
] |
I searched for a while but didn't find anything that explained exactly what I'm trying to do.
Basically I have a list of string "labels", e.g. ["brown", "black", "blue", "brown", "brown", "black"] etc. What I want to do is convert this into a list of integers where each label corresponds to an integer, so
```
["brown... | You have non-unique labels; you can use a `defaultdict` to generate numbers on first access, combined with a counter:
```
from collections import defaultdict
from itertools import count
from functools import partial
label_to_number = defaultdict(partial(next, count(1)))
[(label_to_number[label], label) for label in l... | You could first create a dictionary like:
```
dict = {"brown":1 , "black": 2, "blue": 3 }
```
And then:
```
li = ["brown", "black", "blue", "brown", "brown", "black"]
[dict[i] for i in li]
``` | Python: Enumerate a list of string 'keys' into ints | [
"",
"python",
"string",
"int",
"enumerate",
""
] |
```
SELECT
RESVID, VEHTYPE
FROM
(SELECT
dbo.T_VEH_VEHRESERVATION.RESVID,
TABLEVEHICLE.VEHTYPE, TABLEVEHICLE.VEHREGID
FROM
(SELECT
dbo.T_VEH_VEHCATEGORY.VEHBRANDNAME + N' ' + dbo.T_VEH_VEHCLASS.VEHCLASSNAME AS VEHTYPE,
dbo.T_VEH_VE... | Try like this....
```
Select Distinct RESVID ,Stuff((Select ','+VEHTYPE from TabelName A where A.RESVID =B.RESVID
For Xml Path('')),1,1,'') as VEHTYPE from TabelName B
``` | Try with STUFF()
```
SELECT RESVID ,
STUFF((
SELECT ','+ VEHTYPE
FROM TABLERESV b
WHERE a.RESVID = b.RESVID
FOR XML PATH('')
)
,1,1,'') AS VEHTYPE
FROM TABLERESV a
GROUP BY a.RESVID
``` | Concatenate multiple row into single row | [
"",
"sql",
"sql-server",
""
] |
I want to have the x-tick date labels centered between the tick marks, instead of centered about the tick marks as shown in the photo below.
I have read the documentation but to no avail - does anyone know a way to do this?

Here is everything that ... | One way to do it is to use the minor ticks. The idea is that you set the minor ticks so that they are located halfway between the major ticks, and you manually specify the labels.
For example:
```
import matplotlib.ticker as ticker
# a is an axes object, e.g. from figure.get_axes()
# Hide major tick labels
a.xaxis.... | Here's an alternative to using Locators and Formatters. It can be used for any spacings between labels:
```
# tick_limit: the last tick position without centering (16 in your example)
# offset: how many steps between each tick (1 in your example)
# myticklabels: string labels, optional (range(1,16) in your example)
#... | Centering x-tick labels between tick marks in matplotlib | [
"",
"python",
"matplotlib",
"pandas",
""
] |
I have a table with a column named X509 , i have used this function for know how
many characters have the stored values :
```
select distinct LEN (x509certificate) from ctrc
```
this statment have return me these values :
```
2112
2732
2748
2800
```
I need to save in this column values from 2112(min) to ... | You could do this:
```
ALTER TABLE ctrc ADD [cert_length] as LEN (x509certificate);
```
SQL Server will use a suitable size for the column.
If you talk about the certificate, then NVARCHAR(MAX) is fine. SQL Server will store even `(N)VARCHAR(max)` columns in row, if you didn't change any table options and there is s... | If you mean what is the best column type for storing the certs themselves, there is no fixed length for an X509 cert, using nvarchar is exactly the right thing to go for and nvarchar(MAX) or e.g. nvarchar(maxlength \* 2) will have essentially zero performance impact on your database compared to trying to get the exact ... | Best SQL type for 2000 characters | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I'm trying to parse a csv file using the built in python csv reader as follows:
```
sms_prices_list_url = "http://www.twilio.com/resources/rates/international-sms-rates.csv"
sms_prices_list = requests.get(sms_prices_list_url)
reader = csv.reader(sms_prices_list.text)
for row in reader:
print row
```
however when ... | Since you are passing it the raw text, it is splitting on each character as it iterates over it. Use `StringIO` to get around this:
```
import StringIO
import csv
import requests
r = requests.get('http://www.twilio.com/resources/rates/international-sms-rates.csv')
reader = csv.DictReader(StringIO.StringIO(r.text))
ro... | `csv.reader` expects its argument to yield one line of text at a time. You are iterating over a string, which yields one character at a time. Change it to:
```
reader = csv.reader(sms_prices_list.iter_lines())
```
Note that this won't give you a list of dictionaries, but an iterable of lists, since that's what `csv.r... | Why does the parsing of csv file not break things into their 'logical' order? | [
"",
"python",
"python-2.7",
""
] |
I was playing around in python. I used the following code in IDLE:
```
p = [1, 2]
p[1:1] = [p]
print p
```
The output was:
```
[1, [...], 2]
```
What is this `[…]`? Interestingly I could now use this as a list of list of list up to infinity i.e.
```
p[1][1][1]....
```
I could write the above as long as I wanted ... | It means that you created an infinite list nested inside itself, which can not be printed. `p` contains `p` which contains `p` ... and so on. The `[...]` notation is a way to let you know this, and to inform that it can't be represented! Take a look at @6502's answer to see a nice picture showing what's happening.
Now... | This is what your code created
[](https://i.stack.imgur.com/xprQS.png)
It's a list where the first and last elements are pointing to two numbers (1 and 2) and where the middle element is pointing to the list itself.
In Common Lisp when printing circ... | What do ellipsis [...] mean in a list? | [
"",
"python",
"list",
"ellipsis",
""
] |
So I'm kind of stumped here, I have a table setup like this
```
+-----------+------+
| Timestamp | Size |
+-----------+------+
| 1-1-13 + 10.3 +
+-----------+------+
| 1-3-13 + 6.7 +
+-----------+------+
| 1-5-13 + 3.0 +
+-----------+------+
| 1-9-13 + 11.4 +
+-----------+------+
```
And I'm wondering i... | You want to add a running total, and limit based on that, the following should work:
```
SET @runtot:=0;
SELECT
q1.t,
q1.s,
(@runtot := @runtot + q1.s) AS rt
FROM
(SELECT Date AS t,
SIZE AS s
FROM Table1
ORDER BY Date
) AS q1
WHERE @runtot + q1.s <= 20
```
Edit: Demo here - [... | ```
SELECT * FROM ints ORDER BY i;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+
SELECT x.* ,SUM(y.i) FROM ints x JOIN ints y ON y.i <= x.i GROUP BY x.i;
+---+----------+
| i | SUM(y.i) |
+---+----------+
| 0 | 0 |
| 1 | 1 |
| 2 | 3 |
| ... | Limit SQL by the sum of the row's value | [
"",
"mysql",
"sql",
"database",
""
] |
I want to obtain fig1 exactly of 4 by 3 inch sized, and in tiff format correcting the program below:
```
import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
plt.plot(list1, list2)
plt.savefig('fig1.png', dpi = 300)
plt.close()
``` | You can set the figure size if you explicitly create the figure with
```
plt.figure(figsize=(3,4))
```
You need to set figure size before calling `plt.plot()`
To change the format of the saved figure just change the extension in the file name. However, I don't know if any of matplotlib backends support tiff | You can change the size of the plot by adding this before you create the figure.
```
plt.rcParams["figure.figsize"] = [16,9]
``` | Change figure size and figure format in matplotlib | [
"",
"python",
"python-2.7",
"python-3.x",
"matplotlib",
""
] |
Let's say I have two tables. One for containers of fruit, and one for the fruit. Like this:
```
CREATE TABLE Containers
(
ContainerID int,
ContainedFruit int
)
CREATE TABLE Fruit
(
FruitID int,
Name VARCHAR(16)
)
INSERT INTO Fruit VALUES ( 1, 'Apple' )
INSERT INTO Fruit VALUES ( 2, 'Banana' )
INSERT INTO Fruit VALUE... | You can do this with an aggregation and `having` clause:
```
select ContainerId
from Containers
group by ContainerId
having count(distinct ContainedFruit) = 1
```
A slightly more efficient form of this is:
```
select ContainerId
from Containers
group by ContainerId
having min(ContainedFruit) = max(ContainedFruit)
``... | This should do it:
```
SELECT ContainerID
FROM Cointainers
GROUP BY ContainerID
HAVING COUNT(DISTINCT ContainedFruit) = 1
``` | Homogenous Containers with GROUP BY | [
"",
"sql",
"sql-server",
"group-by",
""
] |
Here we have the piece:
I am not sure, if I am doing it properly, one line is broken up after "+",
the next one is artificially braced by "( )" to be able to break it up.
The idea behind the code itself is py.test checking, if the folder is properly ready and if the files are also existing... to be sure that the testi... | imho, you don't need the parenthesis at all.
```
class TestFilewise():
def setup(self):
import os
self.fixture_dir = os.path.abspath(os.path.dirname(__file__)) \
+ "/fixtures/"
assert os.access( self.fixture_dir, os.F_OK ), \
"Oops! the fixture dir should be here "... | ```
import os
class TestFilewise():
def setup(self):
self.fixture_dir = (os.path.abspath(os.path.dirname(__file__)) +
"/fixtures/")
assert os.access(self.fixture_dir, os.F_OK), \
"Oops! the fixture dir should be here " + self.fixture_dir
assert os.... | how to break up lines most reasonably, staying "within 80 chars" in python? | [
"",
"python",
"unit-testing",
"coding-style",
""
] |
I am trying to build a **playback loop option for an OpenCV video**. My program uses Python multiprocessing, and has a button send `loopswitch` calls through `queue4` to enable or disable the loop option. My specific problem is that my video freezes on the last frame, and **I would like to know if the line `vidFile.set... | I partially solved it by replacing vidFile.set `(cv2.cv.CV_CAP_PROP_POS_FRAMES, 1)` by `vidFile.set(cv2.cv.CV_CAP_PROP_POS_AVI_RATIO, 0)`, although this works for .avi files only. | For python3, opencv3.1.0, raspberry pi 3
```
import numpy as np
import cv2
cap = cv2.VideoCapture('intro.mp4')
while(cap.isOpened()):
ret, frame = cap.read()
#cv2.namedWindow("window", cv2.WND_PROP_FULLSCREEN)
#cv2.setWindowProperty("window",cv2.WND_PROP_FULLSCREEN,cv2.WINDOW_FULLSCREEN)
if ... | Playback loop option in OpenCV videos | [
"",
"python",
"opencv",
"video-capture",
""
] |
I want to be able to grab sections of strings with a function. Here is an example:
```
def get_sec(s1,s2,first='{',last='}'):
start = s2.index(first)
end = -(len(s2) - s2.index(last)) + 1
a = "".join(s2.split(first + last))
b = s1[:start] + s1[end:]
print a
print b
if a == b:
return... | You probably want to use the standard python [regex](http://docs.python.org/2/howto/regex.html) library
```
import re
a = re.search('con(.*)tent(.*)more(.*)','contwotentonemorethree')
print a.groups()
# ('two', 'one', 'three')
```
or
print re.findall('con(.*)tent(.*)more(.\*)','contwotentonemorethree')
# [('two', 'on... | It is not just "use regex". you are trying to actually *implement* regex. well, the easiest way for implemeting regex will be using the `re` library. of course. | Find specific string sections in python | [
"",
"python",
"string",
"indexing",
""
] |
I have a file with the following format:
```
/* No comment provided by engineer. */
"Logout Successful!" = "Logout Successful!";
/* No comment provided by engineer. */
"London" = "London";
/* No comment provided by engineer. */
"Low Balance" = "Low Balance";
/* No comment provided by engineer. */
"Low-Cost Call" = ... | It ended up being an encoding issue. The file was UTF-16. Once I added:
```
with codecs.open(file_name, 'r', 'utf-16') as f:
```
the regex works fine. | It seems to me that what you are trying to achieve can be done more easily with string methods instead of regular expressions:
```
>>> s = '"A Key With \"quotes\" in it" = " Another Value "'
>>> l,r = [v.strip().strip('"').strip() for v in s.split('=')]
>>> l,r
('A Key With "quotes" in it', 'Another Value')
```
The ... | Why wont this regex match? | [
"",
"python",
"regex",
""
] |
I'm having some bad time with pymysql and python operators.
I don't know much about python operator though.
I want to insert into the database some values. The code:
```
import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/Applications/MAMP/tmp/mysql/mysql.sock', user='root', passwd='root', db='db2',... | According to the [source code](https://github.com/petehunt/PyMySQL/blob/master/pymysql/__init__.py#L49), the [`paramstyle`](http://www.python.org/dev/peps/pep-0249/#paramstyle) is `format`, so you'll need to change...
```
cur.execute("INSERT INTO ... VALUES (?,?,?,?,?,?)", v)
```
...to...
```
cur.execute("INSERT INT... | i think the mistake is in the data structure of v . it should be list not tuple | Python operators pymysql | [
"",
"python",
"mysql",
"operators",
"pymysql",
""
] |
Is it possible to force virtualenv to use the latest setuptools and pip available from pypi? Essentially, I'm looking for the ***opposite*** of the `--never-download` flag.
Currently, when I make a new virtualenv, it uses the local (old) versions that come bundled with virtualenv.
```
$ v.mk testvenv
New python execu... | It's not supported for security reasons.
> Using virtualenv.py as an isolated script (i.e. without an associated
> virtualenv\_support directory) is no longer supported for security
> reasons and will fail with an error. Along with this, --never-download
> is now always pinned to True, and is only being maintained in ... | You can upgrade pip after installing your virtualenv by using `pip install -U pip`.
I'm sure you could write a bootstrap-script to automate this step. | How to force virtualenv to install latest setuptools and pip from pypi? | [
"",
"python",
"virtualenv",
"pip",
"setuptools",
"virtualenvwrapper",
""
] |
```
I have a table with logs:
LOGGING (300 rows):
- id
- type_id
- timestamp
- notes
And a table with logging types:
LOGGING_TYPES (4 rows):
- id
- typename
```
The field logging.type\_id links to logging\_types.id.
Now I have made this query:
```
SELECT logging.*,logging.types.tyopename
FROM logging, logging_type... | Your choice of using `INNER JOIN` is correct. The problem is that you mixing comma and `JOIN` syntaxes for joining tables. Use only one at a time. Try
```
SELECT l.*,
t.typename
FROM logging l JOIN logging_types t
ON l.type_id = t.id
```
Here is **[SQLFiddle](http://sqlfiddle.com/#!2/697ec/1)** demo. | You need to use [`LEFT JOIN`](http://dev.mysql.com/doc/refman/5.0/en/left-join-optimization.html) like this:
```
SELECT l.*, lt.typename FROM Logging l
LEFT JOIN Logging_Types lt
ON l.type_id = lt.id
```
### See [this SQLFiddle](http://sqlfiddle.com/#!2/0aba2/9) with sample data | Getting name from other table with joins | [
"",
"mysql",
"sql",
"join",
""
] |
Can somebody help write a SQL script that can delete all the tables, and all the data from the database?
I know I can do `DROP tableName` but I want a script that could work across any Database and completely clean it.
NOTE: I do not want to delete the database itself, just empty all the tables and delete all the tab... | Maybe this could help you ?
<http://www.cyberciti.biz/faq/how-do-i-empty-mysql-database/> | There seems to be a stored procedure in SQL Server that can be used for dropping all the tables in a database, like this:
```
EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"
```
([source](http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/a512be8a-376f-4fc9-8243-78dbdbe59e55/)) | SQL-script to clean out a database completely? | [
"",
"sql",
""
] |
I have some code as shown below, but the timezone %Z is returning: 01:04:48 GMT Daylight Time
I need it return: 01:04:48 GMT
```
import time
timenew = time.strftime('%H:%M:%S %Z')
print timenew
```
Anyone have any idea how I can fix/do this? | Lazy way:
```
time.strftime('%H:%M:%S %Z')[:13]
``` | The problem is that `%Z` isn't [documented](http://docs.python.org/3/library/time.html#time.strftime) to give you any specific format at all; it just gives you:
> Time zone name (no characters if no time zone exists).
With CPython 2.7 or 3.3 on POSIX platforms, it will *usually* give you something in the format `EST`... | Strip down %Z to only return the timezone not daylight savings in python | [
"",
"python",
"python-2.7",
"time",
"timezone",
"strftime",
""
] |
I have this code but what it does is when someone types "goodmorning" or "morning" it prints "good morning" but if i were to type "hello goodmorning" it will not print good morning it will print test.
code:
```
dicmorning = "goodmorning" + "morning"
string = raw_input("test: ")
if string in dicmorning:
print "good... | You need to check each token in the input string separately. A reasonably efficient way might be to create a set of the desired tokens, and intersect it with the input tokens...
```
dicmorning = {"goodmorning", "morning"}
raw_string = raw_input("test: ")
tokens = raw_string.split()
if dicmorning.intersection(tokens):
... | Any raw input is a string, even if a number is entered (e.g. "2") | Check for a string in the user inout | [
"",
"python",
"string",
"user-input",
""
] |
I have a csv file named `data.csv` such as
```
TS;val
10:00;0.1
10:05;0.2
10:10;0.3
10:15;0.4
```
I read this csv file using this script
```
#!/usr/bin/env python
import pandas as pd
if __name__ == "__main__":
yyyy = 2013
mm = 2
dd = 1
df = pd.read_csv('data.csv', sep=';', parse_dates=[0], index_co... | Timestamps have a `replace` method (just like datetimes):
```
In [11]: df.index.map(lambda t: t.replace(year=2013, month=2, day=1))
Out[11]:
array([Timestamp('2013-02-01 10:00:00', tz=None),
Timestamp('2013-02-01 10:05:00', tz=None),
Timestamp('2013-02-01 10:10:00', tz=None),
Timestamp('2013-02-01... | provide a `date_parser`
```
In [50]: pd.read_csv(StringIO(data), sep=';', parse_dates=[0],
index_col=0, date_parser=lambda x: Timestamp('20130201 %s' % x))
Out[50]:
val
TS
2013-02-01 10:00:00 0.1
2013-02-01 10:05:00 0.2
2013-02-01 10:10:00 0.3
2013-0... | Change date of a DateTimeIndex | [
"",
"python",
"pandas",
""
] |
```
a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']
```
the above list have words like history, members which do not have numbers in them, so i want to delete them
```
# output would be
a = ['in 1978 by', 'June 4th, 1979'... | Keep the ones you want:
```
a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']
new = [el for el in a if any(ch.isdigit() for ch in el)]
# ['in 1978 by', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 19... | Here's a shorter alternative, using `any()` and `string.digits`:
```
from string import digits
a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979',
'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']
[x for x in a if any(y in x for y in digits)]
=> ['in 1978 by', 'June 4th... | What is the way to delete words in Python list which does not have numbers? | [
"",
"python",
"regex",
""
] |
I am writing a Pythonic tool which validates the correctness of a certain system. Each validation is written as a Python [`unittest`](http://docs.python.org/2/library/unittest.html), and the report looks like:
```
test_exclude_list_not_empty (__main__.TestRepoLists)
Assert the the exclude list is not empty ... ok
test... | This is not exactly what you are asking, but there are several options for having a readable test output there:
* [HTMLTestRunner](http://tungwaiyip.info/software/HTMLTestRunner.html) generates easy to use HTML test reports in a tabular form. [Here](http://tungwaiyip.info/software/sample_test_report.html)'s a sample r... | I would like to add my information as a comment into alecxe's answer, but I do not have enough reputation for that.
In case of someone still looking for an answer, I forked HTMLTestRunner into a simple TestRunner, which has a tabular, colored, terminal-friendly output.
This is a sample of its output:
[ | Just delete the name that is masking the builtin:
```
>>> set = 'oops'
>>> set
'oops'
>>> del set
>>> set
<type 'set'>
```
You can always still access the original built-in through the [`builtins`](https://docs.python.org/3/library/builtins.html) module ([`__builtin__`](https://docs.python.org/2/library/__builtin__.h... | You can use [`builtins`](https://docs.python.org/3/library/builtins.html):
```
>>> import builtins
>>> builtins.set
<class 'set'>
```
---
For Python 2, you can use [`__builtin__`](https://docs.python.org/2/library/__builtin__.html):
```
>>> import __builtin__
>>> __builtin__.set
<type 'set'>
```
or simply(no impor... | How to restore a builtin that I overwrote by accident? | [
"",
"python",
"built-in",
""
] |
I am wanting to extract the last part of the name of the file that is delimited by a constant prefix and '.csv'
Name of the file might look like:
> constant\_prefix\_**my file name**.csv
or
> constant\_prefix\_**myfilename**.csv
I would like to extract the values marked in bold into a variable.
Please advise. | Script:
```
import re
name1 = 'constant_prefix_my file name.csv'
name2 = 'constant_prefix_myfilename.csv'
def get_name(string):
return re.findall(r'constant_prefix_(my.*)\.csv', string)[0]
```
Demo:
```
print get_name(name1)
print get_name(name2)
```
Output:
```
my file name
myfilename
```
Or you can do thi... | use `str.split` and `os.path.splitext`:
```
>>> import os
>>> prefix = 'constant_prefix'
# if your prefix includes the trailing `_` then don't use `_` in `str.split`
# i.e just use this : `strs.split(prefix)[-1]`
>>> name, ext = os.path.splitext(strs.split(prefix + '_')[-1])
>>> name
'myfilename'
>>> strs = "consta... | Extracting part of a string with irregular delimiters in python | [
"",
"python",
"regex",
""
] |
I am using python and XMLBuilder, a module I downloaded off the internet (pypi). It returns an object, that works like a string (I can do print(x)) but when I use file.write(x) it crashes and throws an error in the XMLBuilder module.
I am just wondering how I can convert the object it returns into a string?
I have co... | ```
file.write(str(x))
```
will likely work for you.
Background information: Most types have a function [`__str__`](http://docs.python.org/2/reference/datamodel.html#object.__str__) or [`__repr__`](http://docs.python.org/2/reference/datamodel.html#object.__repr__) (or both) defined. If you pass an object of such a ty... | The Library has `__str__` defined:
```
def __str__(self):
return tostring(~self, self.__document()['encoding'])
```
So you just need to use `str(x)`:
```
file.write(str(x))
``` | Converting a string-like object into a string in python | [
"",
"python",
"string",
"types",
"type-conversion",
""
] |
I'm having some trouble with a Django project I'm working on. I now have two applications, which require a fair bit of overlap. I've really only started the second project (called `workflow`) and I'm trying to make my first form for that application. My first application is called `po`. In the `workflow` application I ... | Firstly, you can try reduce code to:
> ```
> def new2(request, number):
> po=PurcchaseOrder.objects.get(pk=number)
>
> form = WorkflowForm(request.POST or None)
> if form.is_valid():
> new_flow = form.save()
> return HttpResponse('Good')
> else:
> return render(request, 'new-wor... | I had a similar problem and was able to resolve this by declaring all my modelForm classes below all my class models in my models.py file. This way the model classes were loaded before the modelForm classes. | Django: ValueError: Cannot create form field because its related model has not been loaded yet | [
"",
"python",
"django",
"forms",
""
] |
I think I have a relatively simply question but am not able to locate an appropriate answer to solve the coding problem.
I have a pandas column of string:
`df1['tweet'].head(1)
0 besides food,
Name: tweet`
I need to extract the text and push it into a Python str object, of this format:
`test_messages = ["line1",
"li... | Use `list` convert a Series (column) into a python list:
```
list(df1["tweet"])
``` | 1. Get the Series `head()`, then access the first value:
`df1['tweet'].head(1).item()`
2. or: Use the Series `tolist()` method, then slice the 0'th element:
`df.height.tolist()
[94, 170]
df.height.tolist()[0]
94`
(Note that Python indexing is 0-based, but `head()` is 1-based) | Get first element of Pandas Series of string | [
"",
"python",
"string",
"pandas",
"series",
""
] |
Boy, it feels like I've tried EVERYTHING here, and I just can't get this form to render properly (e.g. with a subset of fields). Here's the relevant items (extra items removed):
models.py:
```
class Response(models.Model):
public = models.BooleanField(default=False)
question = models.CharField(max_length=255,... | It looks like you need to specify `form_class` on your view:
```
class ResponseCreate(CreateView):
model = Response
form_class = ResponseForm
``` | Just I want to mention that you don't really need a ModelForm to be created separately.
> Generic views really shine when working with models. These generic
> views will automatically create aModelForm, so long as they can work
> out which model class to use
You can just use this.
```
class Response(models.Model):
... | Excluding Fields in Django Class Based Views Not Working | [
"",
"python",
"django",
"django-forms",
""
] |
I'm trying upload my project (in python) that uses Psycopg2 for Amazon Elastic Beanstalk. I'm doing this with a zip file containing my project and an requirements.txt file.
But I'm receiving this error:
> Downloading/unpacking psycopg2>=2.4.6 (from -r
> /opt/python/ondeck/app/requirements.txt (line 3)) Running setup.... | Need postgresql-devel in your container.
Create a file '.ebextensions/packages.config' with the contents:
```
packages:
yum:
postgresql94-devel: []
```
Replace `94` in `postgresql94-devel` with whatever version of postgres you need. For example, `postgresql93-devel` for postgres 9.3.
<http://docs.aws.amazon.co... | Tried to comment on the accepted answer but don't have the reputation to do so. Recent forum posts from AWS support indicate that the package name is "postgresql93-devel". postgresql-devel does not work in the 2014.09 AMIs. | Psycopg2 on Amazon Elastic Beanstalk | [
"",
"python",
"amazon-web-services",
"psycopg2",
"amazon-elastic-beanstalk",
""
] |
Win7 x64, Python3.3 32bit, Visual Studio 2010/2012 (same behavior). The following code compiles and runs just fine (i.e. prints current date):
```
extern "C"{ // not having it doesn't make any difference either
#include <Python.h>
}
int main() {
Py_Initialize();
PyRun_SimpleString("from time import time,ctime... | So the problem seems to have been the following: I was linking with `python3.lib` but since the string functions were completely overworked with Python3.3 there seemed to have been some problem with correctly linking them. (can't really explain why this would be so, since `PyUnicode_FromString` existed obviously in ear... | I think this could be for 2 reasons, but I'm pretty sure its this one:
<http://docs.python.org/2/c-api/unicode.html>
You need to null terminate y our constant string "test" by making it "test\0". If that doesn't work, it might have to do with the fact that c files are ansi and not utf8. | Embedding Python into C | [
"",
"python",
"c",
"windows",
""
] |
Suppose I wanted to write a function similar to [range](http://docs.python.org/2/library/functions.html#range)
Recall that range has a one argument and 2/3 argument form:
```
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
```
If I wanted the method or function to h... | Not much to suggest here, but one alternative could be using optional arguments and swapping the first two if only one were provided:
```
def range_like(start, stop=None, step=1):
if stop is None:
start, stop = 0, start
...
``` | i would write this as:
```
def range_like(start=None, stop=None, step=1):
if stop is None:
start, stop = stop, start
...
```
if that does what you want?
[update] you can also add:
```
if stop is start is None:
raise ValueError()
```
also, to use sentinel objects instead of None (this is... | Function definition like range | [
"",
"python",
"function",
"python-3.x",
""
] |
I have a database that was exported with pg\_dump, but now when I'm trying to import it again with:
```
psql -d databasename < mydump.sql
```
It fails trying to grant roles to people that don't exist. (error says 'Role "xxx" does not exist')
Is there a way to import and set all the roles automatically to my user? | The default behavior of the import is that it replaces all roles it does not know with the role you are doing the import with. So depending on what you need the database for, you might just be fine with importing it and with ignoring the error messages.
Quoting from <http://www.postgresql.org/docs/9.2/static/backup-du... | The answer that you might be looking for is adding the `--no-owner` to the `pg_restore` command. Unlike the accepted answer at the moment, the command should create every object with the current user even if the role in the dump don't exist in the database.
So no element will get skipped by pg\_restore but if some ele... | Import postgres database without roles | [
"",
"sql",
"database",
"postgresql",
"import",
"psql",
""
] |
For example, I have a basic method that will return a list of permutations.
```
import itertools
def perms(elements, set_length=elements):
data=[]
for x in range(elements):
data.append(x+1)
return list(itertools.permutations(data, set_length))
```
Now I understand, that in its current state this c... | No, function keyword parameter defaults are determined when the function is *defined*, not when the function is executed.
Set the default to `None` and detect that:
```
def perms(elements, setLength=None):
if setLength is None:
setLength = elements
```
If you need to be able to specify `None` as a argume... | Because of the way Python handles bindings and default parameters...
The standard way is:
```
def perms(elements, setLength=None):
if setLength is None:
setLength = elements
```
And another option is:
```
def perms(elements, **kwargs):
setLength = kwargs.pop('setLength', elements)
```
Although this... | Is there a way to set a default parameter equal to another parameter value? | [
"",
"python",
"python-3.x",
""
] |
I'm looking for a clean way to migrate numpy arrays to latex bmatrix. It should work for both 2d arrays and horizontal and vertical 1d array.
**Example**
```
A = array([[12, 5, 2],
[20, 4, 8],
[ 2, 4, 3],
[ 7, 1,10]])
print A #2d array
print A[0] #horizontal ar... | The `__str__` method of the numpy array already does most of the formatting for you. Let's exploit that;
```
import numpy as np
def bmatrix(a):
"""Returns a LaTeX bmatrix
:a: numpy array
:returns: LaTeX bmatrix as a string
"""
if len(a.shape) > 2:
raise ValueError('bmatrix can at most dis... | Try `array_to_latex (pip install)`. I wrote it for this very reason. Please provide your feedback where it falls short.
It has defaults, but also lets you customize formats (exponential, number of decimal places) and handles complex numbers as well and can "pop" the results right into your clipboard (no need to copy t... | Numpy 2d and 1d array to latex bmatrix | [
"",
"python",
"numpy",
"latex",
""
] |
Python has an elegant way of automatically generating a counter variable in `for` loops: the `enumerate` function. This saves the need of initializing and incrementing a counter variable. Counter variables are also ugly because they are often useless once the loop is finished, yet their scope is not the scope of the lo... | Improvement (in readability, I'd say) to Ignacio's answer:
```
x = 0
for c in itertools.takewhile(lambda c: x < 10, itertools.count()):
x = int(raw_input())
print x, c
```
Advantages:
* Only the while loop condition is in the loop header, not the side-effect raw\_input.
* The loop condition can depend on any... | Again with the [`itertools`](http://docs.python.org/2/library/itertools.html)...
```
import itertools
for c, x in enumerate(
itertools.takewhile(lambda v: v < 10,
(int(raw_input()) for z in itertools.count())
)
):
print c, x
``` | Pythonic enumeration of while loop | [
"",
"python",
"while-loop",
""
] |
I am attempting to determine if an algorithm that I wrote operates in polynomial time and, at the moment I can't figure out how count to this function that it uses
```
def combo(list, size):
if size == 0 or not list: # order doesn't matter
return [list[:0]] ... | You've got an algorithm for "k-combinations": given n items, select k of them, treating ordering as irrelevant. From the ancients, we know how many combinations to expect:
```
n!
-----------
(n - k)! k!
```
For a given n (for example, 10), that expression is maximized when k equals half of n (5). As either n or k... | Take a look at the Run Snake Run profile viewer. It takes a profile output and creates a nice visualization of the function calls.
You run your program with the cProfile module and then send the output log to Run Snake Run:
```
python -m cProfile -o profile.log your_program.py
runsnake profile.log
```
That example i... | Determine computational complexity of recursive algorithm | [
"",
"python",
"combinations",
"time-complexity",
""
] |
## I want to do the following:
I have a class which should provide several functions, which need different inputs. And I would like to use these functions from within other scripts, or solely from commandline.
e.g. I have the class "test". It has a function "quicktest" (which basically justs prints something). (From ... | try the following (note that the different indentation, the `if __name__` part is **not** part of class `test` anymore):
```
class test:
def quicktest(params):
pprint(params)
if __name__ == '__main__':
if sys.argv[1] == "quicktest":
testObj = test()
testObj.quicktest(sys.argv)
els... | The `if __name__ == '__main__':` block needs to be at the top level:
```
class Test(object): # Python class names are capitalized and should inherit from object
def __init__(self, *args):
# parse args here so you can import and call with options too
self.args = args
def quicktest(self):
... | Access function from within scripts and from commandline | [
"",
"python",
""
] |
I have data with a time-stamp in UTC. I'd like to convert the timezone of this timestamp to 'US/Pacific' and add it as a hierarchical index to a pandas DataFrame. I've been able to convert the timestamp as an Index, but it loses the timezone formatting when I try to add it back into the DataFrame, either as a column or... | By now this has been fixed. For example, you can now call:
```
dataframe.tz_localize('UTC', level=0)
```
You'll have to call it twice for the given example, though. (I.e., once for each level.) | If you set it as the index, it's automatically converted to an Index:
```
In [11]: dat.index = pd.to_datetime(dat.pop('datetime'), utc=True)
In [12]: dat
Out[12]:
label value
datetime
2011-07-19 07:00:00 a 0
2011-07-19 08:00:00 a 1
2011-07-19 09:00:00 a 2
2011-07-19 07:... | Change timezone of date-time column in pandas and add as hierarchical index | [
"",
"python",
"timezone",
"dataframe",
"pandas",
"multi-index",
""
] |
I need to search a dhcpd file for host entires, their MAC and IP, and print it in one line. I am able to locate the hostname and IP address but cannot figure out how to get the variables out of the `if` statement to put in one line.
The code is below:
```
#!/usr/bin/python
import sys
import re
#check for arguments
... | There are a number of ways that you could go about this. The simplest is probably to initialize an empty string before the if statements. Then, instead of printing split[1] and ip[2], concatenate them to the empty string and print that afterwards. So it would look something like this:
```
printstr = ""
if re.s... | In the general case, you can give comma-separated values to print() to print them all on one line:
```
entries = ["192.168.1.1", "supercomputer"]
print "Host:", entries[0], "H/W:", entries[1]
```
In your particular case, how about adding the relevant entries to a list and then printing that list at the end?
```
entr... | Print results from multiple "if" statements in one line | [
"",
"python",
"python-2.x",
""
] |
While looking for a pythonic way to rotate a matrix, I came across [this](https://stackoverflow.com/a/496056/140367) answer. However there is no explanation attached to it. I copied the snippet here:
```
rotated = zip(*original[::-1])
```
How does it work? | ```
>>> lis = [[1,2,3], [4,5,6], [7,8,9]]
```
`[::-1]` reverses the list :
```
>>> rev = lis[::-1]
>>> rev
[[7, 8, 9], [4, 5, 6], [1, 2, 3]]
```
now we use `zip` on all items of the rev, and append each returned tuple to rotated:
```
>>> rotated = []
>>> for item in zip(rev[0],rev[1],rev[2]):
... rotated.append... | Complementary to the explanations by Ashwini and HennyH, here's a little figure to illustrate the process.

1. First, the `[::-1]` slice operator reverses the list of list, taking the entire list (thus the first two arguments can be omitted) and usin... | How does this code snippet rotating a matrix work? | [
"",
"python",
""
] |
This is the table I've created and some initial values.
```
/*Make the table*/
CREATE TABLE PEOPLE(
ID int PRIMARY KEY,
NAME varchar(100) NOT NULL,
SUPERIOR_NAME varchar(100)
);
/*Give it some initial values*/
INSERT INTO PEOPLE VALUES(1, 'A',NULL), (2, 'B', 'E'), (3, 'C', 'A'),
(4, 'D', 'A'), (5, 'E',NULL), (6, '... | Use a self-referencing common-table expression and retain the top level manager (Boss) in your selection:
```
WITH OrganisationChart (Id, [Name], [Level], superior_name, [Boss])
AS
(
SELECT
Id, [Name], 0 AS [Level], superior_name, name
FROM
dbo.people
WHERE
super... | Try this
```
CREATE PROCEDURE USP_GETSUBS
(
@NAME VARCHAR(100)
) -- USP_GETSUBS 'A'
AS
BEGIN
IF EXISTS (SELECT SUPERIOR_NAME FROM PEOPLE WHERE Name=@NAME)
BEGIN
WITH Subordinates AS
(
SELECT p.ID, p.Name, p.SUPERIOR_NAME
FROM PEOPLE AS p
WHERE p.Name = @NA... | How do I make an SQL procedure that will take entries of a column as input one by one? | [
"",
"sql",
"sql-server",
""
] |
I have the following rows in a table:
```
user_id school_id graduation_date
------- --------- ---------------
1 123 2006-05-19
1 123 2008-05-19
2 123 2006-05-19
2 123 2008-05-19
```
I have the following query:
```
SELECT * FROM user_school us, [us... | Given the constraints you gave about the TOP and ORDER BY, you can't do these in one swoop.
You can find the most recent graduation date, then go find the row with it.
```
SELECT *
FROM (
SELECT user_id,
school_id,
row_number() over (partition by user_id order by graduation_date desc) position
F... | The simplest way to do this is using `row_number()`:
```
select *
from (SELECT *,
row_number() over (partition by us.user_id
order by graduation_date desc) as seqnum
FROM user_school us join
[user] u
on us.user_id = u.user_id
where us.schoo... | SQL return the row ONLY with the later date | [
"",
"sql",
"sql-server",
"sql-server-2008",
"greatest-n-per-group",
""
] |
I have the following code in my template:
```
{% include "entry_table/cell.html" with data_items = data_fields class="entry_table_title" only%}
```
Which gives me the following error:
```
"with" in 'include' tag needs at least one keyword argument.
```
I've tried replacing data\_field (which is a variable I passed ... | Looks like Django is quite picky about whitespace in this instance. If I change...
```
{% include "entry_table/cell.html" with data_items = data_fields class="entry_table_title" only%}
```
...to...
```
{% include "entry_table/cell.html" with data_items=data_fields class="entry_table_title" only%}
```
...it works fo... | I had a very similar problem. Only I was using dashes, which apparently aren't permitted in variable names.
I know this is an older question and it has already been sufficiently answered, but this is closely related, and comes up with a search, so for the sake of posterity ...
```
{% include "partials/forum-panel-hea... | Django `with` tag not recognizing keyword argument | [
"",
"python",
"django",
""
] |
I am using django 1.4 and I have a many2many field, so when creating the admin site I wanted to add this field as an inline, here is some code:
```
class SummaryInline(admin.TabularInline):
model = ParserError.summaries.through
class MyClassAdmin(admin.ModelAdmin):
list_display = ('classifier', 'name', 'err_... | After a while of trying to find the name I figured out thanks to [this answer](https://stackoverflow.com/questions/13817525/django-admin-make-all-fields-readonly), so I checked the names at `self.opts.local_fields` and found the name of the middle table and added it to [`readonly_fields`](https://docs.djangoproject.com... | Additionally, if you do not want the ability to add/delete the rows, you can add these definitions.
```
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
``` | How to add readonly inline on django admin | [
"",
"python",
"django",
"admin",
""
] |
My main app file is currently a series of method definitions, each attached to a route. I've got 3 distinct parts to my app (main, admin, api). I'm trying to split out methods into external files for better maintenance but I like Flask's simplicity in using route decorators for my application's URLs.
One of my routes ... | Like stated in the other comment, you can call `app.route('/')(api.view_home())` or use Flask's `app.add_url_rule()` <http://flask.pocoo.org/docs/api/#flask.Flask.add_url_rule>
Flask's `@app.route()` code:
```
def route(self, rule, **options):
def decorator(f):
endpoint = options.pop('endpoint', None)
... | A decorator is just a special function.
```
routed_galleries = application.route('/api/galleries')(api.get_galleries)
```
And in fact, depending on what the decorator does you may not need to keep the result around at all.
```
application.route('/api/galleries')(api.get_galleries)
``` | Can I use external methods as route decorators in Python/Flask? | [
"",
"python",
"flask",
""
] |
I am trying to use `ForAll` quantifier on `b`, so formula `a * b == b` with every `b` would give me `a == 1` as result. I implemented this in the code below (Z3 python):
```
from z3 import *
a, b, a1 = BitVecs('a b a1', 32)
f = True
f = And(f, a1 == a * b)
f = And(f, a1 == b)
s = Solver()
s.add(ForAll(b, f))
if s.... | What do you think about this:
```
a, b, a1 = BitVecs('a b a1', 32)
f = True
f = And(f, a1 == a * b)
g= True
g = And(f, a1 == b)
s = Solver()
s.add(ForAll(b, ForAll(a1,f == g)))
if s.check() == sat:
print 'a =', s.model()[a]
else:
print 'Unsat
```
output:
```
a = 1
```
Other form:
```
a, b, a1 = BitVecs(... | You are asking Z3 (among other things) to find a single *a1* that is equal to *b* for all values of *b*. This is not possible. Your problem is not with Z3 but with basic logic. | Code produces wrong result with ForAll, why? | [
"",
"python",
"z3",
"z3py",
""
] |
We're running into a problem (which is described <http://wiki.python.org/moin/UnicodeDecodeError>) -- read the second paragraph '...Paradoxically...'.
Specifically, we're trying to up-convert a string to unicode and we are receiving a UnicodeDecodeError.
Example:
```
>>> unicode('\xab')
Traceback (most recent ... | ```
for fname in files:
filename = unicode(fname)
```
The second line will complaint if `fname` is not ASCII. If you want to convert the string to Unicode, instead of `unicode(fname)` you should do `fname.decode('<the encoding here>')`.
I would suggest the encoding but you don't tell us what does `\xab` is in you... | I think you're confusing Unicode strings and Unicode encodings (like UTF-8).
`os.walk(".")` returns the filenames (and directory names etc.) as strings that are *encoded* in the current codepage. It will silently *remove* characters that are not present in your current codepage ([see this question for a striking examp... | UnicodeDecodeError during encode? | [
"",
"python",
"unicode",
""
] |
This is a MWE of what I'm after, adapted from [this question](https://stackoverflow.com/questions/458209/is-there-a-way-to-detach-matplotlib-plots-so-that-the-computation-can-continue):
```
from matplotlib.pyplot import plot, draw, show
def make_plot():
plot([1,2,3])
draw()
print 'continue computation'
p... | You may use `plt.show(block=False)`, which gets rid of the blocking directly.
For your example, this could read
```
from matplotlib.pyplot import plot, show
def make_plot():
plot([1,2,3])
show(block=False)
print('continue computation')
print('Do something before plotting.')
# Now display plot in a windo... | None of the presented solutions work for me. I tested them with three different IDEs [PyCharm](https://www.jetbrains.com/pycharm/), [Spyder](https://pythonhosted.org/spyder/) and [Pyzo](http://www.pyzo.org/), using the (currently) latest Matplotlib 2.1 under Python 3.6.
What works for me, although not optimal, is to u... | Matplotlib - Force plot display and then return to main code | [
"",
"python",
"matplotlib",
"enthought",
""
] |
I would like to obtain the index of the nearest value in a numpy array which is greater than my search value. Example: `findNearestAbove(np.array([0.,1.,1.4,2.]), 1.5)` should return 3 (the index of 2.).
I know that I can get the nearest index with `np.abs(a-value).argmin()`, and I found out that `min(a[np.where(a-val... | Here is one way (I am assuming that by nearest you mean in terms of value not location)
```
import numpy as np
def find_nearest_above(my_array, target):
diff = my_array - target
mask = np.ma.less_equal(diff, 0)
# We need to mask the negative differences and zero
# since we are looking for values above... | I believe you can use [`np.searchsorted`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html) for this:
```
In [15]: np.searchsorted(a,[1.5,],side='right')[0]
Out[15]: 3
```
assuming `a` is in ascending order.
This method also won't work for multi-dimensional arrays, but I'm not sure exactly... | How to find nearest value that is greater in numpy array? | [
"",
"python",
"numpy",
"indexing",
""
] |
As the Django Documentation says, [`select_for_update`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-for-update) returns a `Queryset`. But `get` does not. Now I have a query which I am sure is going to return only one tuple. But I also need to acquire locks for this transaction. So I am doing some... | Just call `get`, slice it, etc. and save as usual. The lock is in place through the transaction.
```
ob = MyModel.objects.select_for_update().get(pk=1)
```
Any changes are committed at the end of the transaction (which by default through 1.5 is per-request) | You [can](https://stackoverflow.com/a/6624655/538284) also use `select_for_update` with `get_object_or_404` function:
```
from django.db import transaction
from django.shortcuts import get_object_or_404
with transaction.atomic():
obj = get_object_or_404(MyModel.objects.select_for_update(), pk=pk)
# do some st... | How to use "select_for_update()" to get an object in Django? | [
"",
"python",
"python-3.x",
"django",
"django-queryset",
"select-for-update",
""
] |
I have the following code in a function
```
CREATE OR REPLACE FUNCTION my_func (
v_dt events.raised_date%TYPE
)
RETURN SYS_REFCURSOR
IS
p_events SYS_REFCURSOR;
OPEN p_events FOR
SELECT event_id
FROM events
... | It is not good idea to check it inside of the function. You are missing why the cursor is returned. Instead do it outside of the function.
```
DECLARE
l_rc SYS_REFCURSOR := my_func();
TYPE events_ntt IS TABLE OF NUMBER;
l_events events_ntt;
l_lookup events_ntt := events_ntt(100);
l_diff even... | A ref cursor is just a pointer to query. There is nothing "in" it. So the only way to find out whether the result set identified by the ref cursor contains a specific record - or indeed any records - is to fetch the cursor and read through the records.
Bear in mind that a ref cursor is a one-shot thang. We cannot fetc... | Check Values in sys_refcursor | [
"",
"sql",
"oracle",
"plsql",
"oracle10g",
"sys-refcursor",
""
] |
Given a (simplified) table called Answers like
```
Id Person Answer Priority
1 Tom France Low
2 Tom Germany High
3 Fred England Low
4 Amy Italy High
```
I would like to write a SQL query that returns one row per person indicating... | Here's one way of doing it:
```
with priorityRank as
(
select *
, priorityRank = row_number() over (partition by Person
order by case Priority when 'High' then 1 when 'Low' then 2 end
, Id)
from
Answers
)
select Id
, Person
, Answer
, Priority
from priorityRank
where priorityRank = 1
... | You can use a common table expression with the `ROW_NUMBER` window function:
```
WITH cte
AS (SELECT [id],
[person],
[answer],
[priority],
RN = Row_number()
OVER (
partition BY person
... | Query to Return One Row per Person | [
"",
"sql",
"sql-server",
""
] |
I've generated some fake data for a database i've created using PowerAMC. This database as some filed with timedate format. But when i'm running the file in SQL server (Express edition), i've the following :
```
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
```
The l... | Datetime only goes back to 1753. Use datetime2 instead, datetime2 was introduced in sql server 2008
example
```
select CONVERT(DATETIME2,'0345-12-9 3:23:52')
``` | In transact SQL `datetime`'s range starts from 1753 jan. 1.
You should Use `datetime2` | Datetime conversion issue with SQL server | [
"",
"sql",
"database",
"sql-server-2008",
"powerdesigner",
""
] |
I have this class that consists of 3 functions. Each function is in charge of one part of the whole process.
`.load()` loads up two files, re-formats their content and writes them to two new files.
`.compare()` takes two files and prints out their differences in a specific format.
`.final()` takes the result of `.co... | There are a couple of ways to do this, but I would write a master function that calls the other three in sequence. Something like:
```
def load_and_compare(self, input_file1, input_file2, output_file1, output_file2, result_file):
self.load(input_file1, input_file2, output_file1, output_file2)
self.compare(outp... | Do you mean call with the name of the two files? Well you defined a class, so you can just do:
```
def load(self, fileIn1, fileIn2, fileOut1, fileOut2):
... // do stuff here
// when done
self.compare( fileOut1, fileOut2 )
```
And so on. | Passing values and calling functions from other functions | [
"",
"python",
"python-2.7",
""
] |
I was looking for an elegant (short!) way to return the first element of a list that matches a certain criteria without necessarily having to evaluate the criteria for every element of the list. Eventually I came up with:
```
(e for e in mylist if my_criteria(e)).next()
```
Is there a better way to do it?
To be more... | Nope - looks fine. I would be tempted to re-write possibly as:
```
from itertools import ifilter
next(ifilter(my_criteria, e))
```
Or at least break out the computation into a generator, and then use that:
```
blah = (my_function(e) for e in whatever)
next(blah) # possibly use a default value
```
Another approach, ... | How about:
```
next((e for e in mylist if my_criteria(e)), None)
``` | Finding the first list element for which a condition is true | [
"",
"python",
"python-2.7",
""
] |
Recently I think about the best practices with storing historical data in MySQL database. For now, each versionable table has two columns - `valid_from` and `valid_to`, both `DATETIME` type. Records with current data has `valid_from` filled with its creation day. When I update this row, I fill `valid_to` with update da... | It's a common mistake to worry about "large" tables and performance. If you can use indexes to access your data, it doesn't really matter if you have 1000 of 1000000 records - at least not so as you'd be able to measure. The design you mention is commonly used; it's a great design where time is a key part of the busine... | I'm nearing completion of an application which does exactly this. Most of my indexes index by key fields first and then the `valid_to` field which is set to `NULL` for current records thereby allowing current records to be found easily and instantly. Since most of my application deals with real time operations, the ind... | Best practices with historical data in MySQL database | [
"",
"mysql",
"sql",
""
] |
I'm new to python and I'm trying to use a library. It raises an exception, and I am trying to identify which one. This is what I am trying:
```
except tweepy.TweepError as e:
print e
print type(e)
print e.__dict__
print e.reason
print type(e.reason)
```
This is what I am getting:
```
[{u'message'... | How about this?
```
except tweepy.TweepError as e:
print e.message[0]['code'] # prints 34
print e.args[0][0]['code'] # prints 34
``` | Every well-behaved exception derived from the base Exception class [has](https://docs.python.org/3/library/exceptions.html#BaseException.args) an `args` attribute (of type `tuple`) that contains arguments passed to that exception. Most of the time only one argument is passed to an exception and can be accessed using `a... | Get the error code from tweepy exception instance | [
"",
"python",
"python-2.7",
"twitter",
"tweepy",
""
] |
I run a python script on a linux server with nohup like that:
```
nohup python3 ./myscript.py > ./mylog.log &
```
It works and the script writes the log file but the problem is that python error messages / thrown exceptions don't seem to get written into the log file. How could I achieve this?
Has this something to ... | I have found the reason. It really was the buffering problem (see my edit above). :)
```
nohup python3 -u ./myscript.py > ./mylog.log &
```
With the python -u parameter it works. It disables buffering.
Now I can go bug hunting... | You are only redirecting stdout. Error messages are given on stderr. Rerun your script like this:
```
nohup python3 ./myscript.py &> ./mylog.log &
```
The `&>` redirects all output (stdout and stderr) to your log file. | no error messages with nohup and python? | [
"",
"python",
"debugging",
"exception",
"stderr",
"nohup",
""
] |
so I was working with paramiko for some basic SSH testing and I'm not getting any output into stdout. Heres my code.
```
import paramiko
client=paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
com="ls ~/desktop"
client.connect('MyIPAddress',MyPortNumber, username='username', password='... | You have closed the connection before reading lines:
```
import paramiko
client=paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
com="ls ~/desktop"
client.connect('MyIPAddress',MyPortNumber, username='username', password='password')
output=""
stdin, stdout, stderr = client.exec_command... | The code in the accepted answer may hang, if the command produces also an error output. See [Paramiko ssh die/hang with big output](https://stackoverflow.com/q/31625788/850848).
An easy solution, if you do not mind merging `stdout` and `stderr`, is to combine them into one stream using [`Channel.set_combine_stderr`](h... | Paramiko: read from standard output of remotely executed command | [
"",
"python",
"ssh",
"paramiko",
""
] |
So given this function as an example.
```
def spaced_word(s):
i= 0
t = s[i] + ' '
while i < len(s) - 2:
t = t + s[i + 1] + ' '
i = i + 1
t= t + s[len(s) - 1]
return t
```
This function gives back the string inputted with a space between each character.
(e.g. `spaced_word('hello')`... | Your question seems to be about why you need to maintain a separate `t` variable to hold the string as you build it up in your loop, rather than directly changing its values.
The reason is that Python's strings are immutable. You can't insert a space in between two letters of an existing string, because you can't modi... | I didn't look at your code in detail, but there is a *much* easier way to write the function you're talking about:
```
def spaced_word( s ):
return ' '.join( s )
print spaced_word( 'abcde' )
```
prints:
```
a b c d e
```
Edit: OK, now I looked at your code to see if I can answer your immediate question, and th... | While loop statement- differing answers | [
"",
"python",
"python-3.x",
"while-loop",
""
] |
I'm working on a text based adventure game. One of the things that I want to do, is build the game using classes, have the main data classes in a separate file, and then have the actual main loop that calls all the classes and functions, in a separate file. This is what I have so far my main loop in calling the main cl... | You've defined `playerPrefs()` as an instance method, rather than a class method (since it has `self` as its first argument). Therefore, you need to create an instance before you call it, e.g.:
```
p = playerPrefs()
p.createNew()
```
Also, your code as written shouldn't run at all, since you haven't indented the defi... | Try
```
from className import *
```
or
```
from className import playerPrefs
``` | Importing functions from classes outside original file | [
"",
"python",
"class",
"function",
"object",
""
] |
I am having trouble with using a key binding to change the value of a label or any parameter.
This is my code:
```
from tkinter import*
class MyGUI:
def __init__(self):
self.__mainWindow = Tk()
#self.fram1 = Frame(self.__mainWindow)
self.labelText = 'Enter amount to deposit'
self.depositLabel = Labe... | ```
self.labelText = 'change the value'
```
The above sentence makes labelText change the value, but not change depositLabel's text.
To change depositLabel's text, use one of following setences:
```
self.depositLabel['text'] = 'change the value'
```
OR
```
self.depositLabel.config(text='change the value')
``` | You can also define a `textvariable` when creating the Label, and change the textvariable to update the text in the label.
Here's an example:
```
labelText = StringVar()
depositLabel = Label(self, textvariable=labelText)
depositLabel.grid()
def updateDepositLabel(txt) # you may have to use *args in some cases
lab... | Changing the text on a label | [
"",
"python",
"tkinter",
""
] |
I just want to make sure that I understand `PRIMARY` and `FOREIGN` key relation before searching for some finished answers on the internet.
Let's say this:
We have table `CITY(ID-PK,CODE,NAME)` and we have table `PERSON(ID-PK,NAME,LASTNAME,CITY_ID-FK)`
I'm confused, if in this case user needs to enter a foreign key ... | I'm not entirely sure what you mean by 'wrong ID input', but I'll assume you mean an ID that that isn't valid, rather than just a mistake (like saying someone is in a different city to where they really are).
The foreign key constraint means that the value they enter in the `person` table for `city_id` **has** to exis... | With whis code you could add a constraint on the Person table to have the foreign key of the City table
```
alter table PERSON
add constraint CONSTR_PERSON_CITY
foreign key (CITY_ID-FK)
references CITY (ID-PK);
``` | how to insert foreign key in a table | [
"",
"sql",
"oracle",
"foreign-keys",
"primary-key",
""
] |
In my android application, I have a SQLite database containing a table with an id column with AUTOINCREMENT. I'm using an INSERT statement to add a new row but I need to immediately access this row so I can refer to it by the ID. So does anyone know of a way to get the ID of this newly added row?
Thanks! | `SQLiteDatabase.insert` returns the id of the newly created row.
So, you would get the row like so:
```
long row = mDatabase.insert(MY_TABLE, "id", values);
```
(above of course is just an example)
See here: [SQliteDatabase.insert](http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#... | I think you can use [**`last_insert_rowid()`**](http://www.sqlite.org/lang_corefunc.html#last_insert_rowid) function
From documentation
> The last\_insert\_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last\_insert\_rowid() SQL function is a wra... | Get newly added row in SQLite table | [
"",
"android",
"sql",
"sqlite",
""
] |
Anyone know why the following is returning `8`? I'm expecting 8 hours 30 minutes, or 8.5?
```
declare @start_day datetime;
declare @end_day datetime;
declare @start_time datetime;
declare @end_time datetime;
set @start_day = '2014-06-18';
set @end_day = '2014-06-18';
set @start_time = '09:00';
set @end_time = '17:30'... | Try this, CAST your DATEDIFF of the minutes to float then divide by 60 to get the hours.
```
declare @start_day datetime;
declare @end_day datetime;
declare @start_time datetime;
declare @end_time datetime;
set dateformat ymd
set @start_day = '2014-06-18';
set @end_day = '2014-06-18';
set @start_time = '09:00';
set ... | Try this :
```
print cast(datediff(mi,@start_day + @start_time, @end_day + @end_time)
as decimal(10,2))/60;
``` | datediff not returning what I'm expecting | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"datetime",
""
] |
I have a table like this...
```
oid id
35 1
43 1
46 1
43 2
49 2
```
I have **id=1** now I want pnly those records which belong to only 1 not any other ids.
i.e o/p - 35,46
I dont need oid = 43 bcz it is belonging to 2 also.
I dont know how to write my question in table on... | Try below:
```
SELECT * FROM `table`
WHERE id = 1 AND oid NOT IN (SELECT oid FROM `table` where id != 1)
``` | here's another way,
```
SELECT oid
FROM tableName
GROUP BY oid
HAVING COUNT(DISTINCT id) = 1 AND -- counts the number of ID for OID
MAX(ID) = 1 -- checks if the value of ID is equal to 1
```
* [SQLFiddle Demo](http://www.sqlfiddle.com/#!2/e876c/1)
OUTPUT
```
╔═════╗
║ OID ║
╠═════╣
║... | Fetch records of single id only not of any other | [
"",
"mysql",
"sql",
""
] |
I'm trying to create a simple script upon which I can build using the boto module in python. I want to define a few functions that would allow me to create and terminate instances. I'm having trouble getting an instance ID, which is needed for the terminate portion. I can get reservation IDs from the get\_all\_instance... | The first point I would make is that a reservation can have more than one instance associated with it. It's not always a one-to-one mapping. If you call `run_instances` and request more than one instance to be created, all of them will be associated to the same reservation.
You say you are using the `get_all_instances... | This is probably not what the op wants - but, an easier way might be to create an instance object when you start the instance. e.g.
```
import boto.ec2
conn = boto.ec2.connect_to_region("us-east-1")
ins1 = conn.run_instances('ami-0axxxxxx', key_name='default', instance_type='t2.micro', security_group_ids=['sg-0c0000... | How to get instance ID from reservation ID in boto | [
"",
"python",
"amazon-ec2",
"boto",
""
] |
I have a table for the football clubs of a country. The fields are "teamName", "playerName", and "country".
> I'd like to count the clubs that all their players are foreigners
. I tried the following query but I think it's not working since it seems that it counts when we have at least one foreigner but I want it to ... | One way would be:
```
SELECT COUNT(DISTINCT teamName)
FROM teams T1
WHERE NOT EXISTS
( select * from teams T2
WHERE T1.teamName=T2.teamName and T2.country like '%England%')
``` | **Quick and dirty answer,** and it does only one pass through the data, no subquery. This selects teams that are all foreign. You can play with the `CASE` expression if that is not what you want.
```
SELECT team_name
FROM teams
GROUP BY team_name
HAVING COUNT(country)=
SUM(CASE country != 'England' WHEN TRUE TH... | How to count the teams with no foreign players | [
"",
"mysql",
"sql",
""
] |
```
While @@Fetch_Status = 0
Begin
INSERT INTO [server].MyDatabase.dbo.Mytabletobeinserted (
UPC,
Sale_date)
VALUES(
@UPC,
@Sale_date)
'Inserting the error trapping here'
IF (@@ERROR <> 0)
BEGIN
ROLLBACK TRANSACTION;
RETURN;
END
Update t_sale_from_pos
... | You could try [begin distributed transaction](http://msdn.microsoft.com/en-us/library/ms188386.aspx). [Distributed transaction](http://msdn.microsoft.com/en-us/library/ms191440%28v=sql.105%29.aspx) is a perfect fit in this case as distributed transactions were designed to span two or more servers. With transaction, eve... | If I understand you correctly. TRY/CATCH should help you -
```
WHILE @@FETCH_STATUS = 0 BEGIN
BEGIN TRY
INSERT INTO [server].MyDatabase.dbo.Mytabletobeinserted (UPC, Sale_date)
SELECT @UPC, @Sale_date
UPDATE dbo.t_sale_from_pos
SET been_sent = 'y'
WHERE UPC ... | How will this affect the data using Loops with rollback transaction | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
"rollback",
""
] |
I have a temporary file with some content and a python script generating some output to this file. I want this to repeat N times, so I need to reuse that file (actually array of files). I'm deleting the whole content, so the temp file will be empty in the next cycle. For deleting content I use this code:
```
def delet... | > How to delete only the content of file in python
There are several ways of setting the logical size of a file to 0, depending how you access that file:
To empty an open file:
```
def deleteContent(pfile):
pfile.seek(0)
pfile.truncate()
```
---
To empty an open file whose file descriptor is known:
```
de... | I think the easiest is to simply open the file in write mode and then close it. For example, if your file `myfile.dat` contains:
```
"This is the original content"
```
Then you can simply write:
```
f = open('myfile.dat', 'w')
f.close()
```
This would erase all the content. Then you can write the new content to the... | How to delete only the content of file in python | [
"",
"python",
"file-io",
"seek",
""
] |
I want to convert num1 and num2 to a list and print it,any inputs on how this can be done?
```
num1 = 12345
num2 = 34266 73628
print num1
print num2
EXPECTED OUTPUT:-
['12345']
['34266','73628']
``` | I'm going to assume that `num1` and `num2` are both strings (otherwise you have a syntax error). You can use [`str.split()`](http://docs.python.org/2/library/stdtypes.html#str.split):
```
>>> num1 = '12345'
>>> num2 = '34266 73628'
>>> num1.split()
['12345']
>>> num2.split()
['34266', '73628']
``` | ```
num1 = '12345'
num2 = '12345 67890'
#Note: Both must be strings
#Option 1(Recommended)
print num1.split()
print num2.split()
#Option 2
import shlex
print shlex.split(num2)
#Option 3
import re
print re.split(' ', num2)
#If the array needs to be of ints:
result1 = [int(item) for item in num1.split()]
result2 = [i... | print list as output | [
"",
"python",
""
] |
I got a list of 40 words which i took out of a txt file. I've found the duplicates, and replaced them with the same word but then with "\*" infront and behind. The code looks like this:
```
def show(self, list1):
a = [x for x in list1 if list1.count(x) > 1]
lista2 = ["*"+s+"*" if s in a else s for s in list1]
... | ```
def show(self, list1):
new_list, seen = [], set()
for x in list1:
if x in seen:
new_list.append('*{0}*'.format(x))
else:
new_list.append(x)
seen.add(x)
print new_list
``` | Use a `set` to keep a track of seen items:
```
>>> seen = set()
>>> new_lis = []
for x in lis:
if x in seen: #if item is present in the set `seen` then add the `*`'s
new_lis.append('*' + x + '*')
else:
seen.add(x) #item seen for the first time, add it to the set and the list
... | How to find duplicates in a list, but ignore the first time it appears? | [
"",
"python",
"list",
""
] |
I have the following function,
```
def facebooktest(request):
fb_value = ast.literal_eval(request.body)
fb_foodies = Foodie.objects.filter(facebook_id__in = fb_value.values())
for fb_foodie in fb_foodies:
state = request.user.relationships.following().filter(username = fb_foodie.user.username).exis... | ```
def facebooktest(request):
fb_value = ast.literal_eval(request.body)
fb_foodies = Foodie.objects.filter(facebook_id__in = fb_value.values())
response = []
for fb_foodie in fb_foodies:
state = request.user.relationships.following().filter(username = fb_foodie.user.username).exists()
u... | There is a function in the django.forms.models package for that: model\_to\_dict
```
from django.forms.models import model_to_dict
model_to_dict(your_model, fields=[], exclude=[])
```
From the help:
```
model_to_dict(instance, fields=None, exclude=None)
Returns a dict containing the data in ``instance`` suitabl... | How to take a dictionary and send a JSON Response | [
"",
"python",
"django",
"json",
"dictionary",
""
] |
I have a sql statement as
```
select t.name, t.company from company t inner join employee e
on t.id = e.emp_id
where t.name not in(select t.name from table1 where t.id='x')
```
This above query returns no rows.
However, when I remove the sub query, and just use
```
select t.name, t.company from company t inner join... | this is because `NOT IN (NULL)` is **always false**
```
select t.name, t.company from company t inner join employee e
on t.id = e.emp_id
where t.name not in(select null from dual)
```
would be the same.
Use `NOT EXISTS` instead:
```
select t.name, t.company
from company t
join employee e on t.id = e.emp_id
wh... | A common cause is `NULL` values in the subquery. But you have a different problem. Here is your query:
```
select t.name, t.company
from company t inner join employee e
on t.id = e.emp_id
where t.name not in(select t.name from table1 where t.id='x')
```
The `t.name` in the subquery refers to the "t" for `company... | SQL query with NOT IN returning no rows | [
"",
"sql",
"plsql",
""
] |
Is it possible to use SQL to select every piece of data in a row where the first column in the row is equal to something?
Thanks | If I'm understanding your question, it's just a simple SELECT statement.
Try this:
```
SELECT * from MyTable WHERE Field1 = 'MatchThis'
``` | ```
SELECT T.* FROM dbo.TableName T WHERE FirstColumn = @Something
``` | Use SQL to select all data in row where first column equals something | [
"",
"sql",
""
] |
I have this model
```
name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(max_length=50, unique=True)
```
I want that the user should not be able to use any other characters than alphanumerics in both fields.
Is there any way? | You would use a [validator](https://docs.djangoproject.com/en/stable/ref/validators/) to limit what the field accepts. A [`RegexValidator`](https://docs.djangoproject.com/en/stable/ref/validators/#regexvalidator) would do the trick here:
```
from django.core.validators import RegexValidator
alphanumeric = RegexValida... | Instead of RegexValidator, give validation in forms attributes only like...
```
class StaffDetailsForm(forms.ModelForm):
first_name = forms.CharField(required=True,widget=forms.TextInput(attrs={'class':'form-control' , 'autocomplete': 'off','pattern':'[A-Za-z ]+', 'title':'Enter Characters Only '}... | How can I make a Django form field contain only alphanumeric characters | [
"",
"python",
"django",
""
] |
I want to fetch function with function name string
eg.
```
class test(object):
def fetch_function():
print "Function is call"
#now i want to fetch function using string
"fetch_function()"
```
Result should be: Function is call | Use `eval()`:
```
eval("fetch_function()")
``` | If you would leave the `()` from `fetch_function()` you could use `getattr` which is in my opinion safer than `eval`:
```
class Test(object):
def fetch_function():
print "Function is called"
test_instance = Test()
my_func = getattr(test_instance, 'fetch_function')
# now you can call my_func just like a ... | How to Fetch function using string? | [
"",
"python",
""
] |
I have a list like this:
```
[['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]
```
I want to convert this list into dictionary like this:
```
{'ok.txt' : ['10', 'first_one', 'done'], 'hello' : ['20', 'second_one', 'pending']}
```
How to do something like this? | You can make use of the built-in zip function to perform this easily like this:
```
list_of_list = [['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]
dict_from_list = dict(zip(list_of_list[0], zip(*list_of_list[1:])))
```
In this, the interior zip(\*list\_of\_list[1:]) will convert the ... | Try this:
```
dict(zip(xs[0], zip(*xs[1:])))
```
For lists as values of the dict:
```
dict(zip(xs[0], map(list, zip(*xs[1:]))))
``` | How to convert the following lists into dictionary? | [
"",
"python",
"list",
"dictionary",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.