Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
```
print '%d:%02d' % divmod(10,20)
```
results in what I want:
```
0:10
```
However
```
print '%s %d:%02d' % ('hi', divmod(10,20))
```
results in:
```
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print '%s %d:%02d' % ('hi', divmod(10,20))
TypeError: %d format: a number is requ... | You are *nesting* tuples; concatenate instead:
```
print '%s %d:%02d' % (('hi',) + divmod(10,20))
```
Now you create a tuple of 3 elements and the string formatting works.
Demo:
```
>>> print '%s %d:%02d' % (('hi',) + divmod(10,20))
hi 0:10
```
and to illustrate the difference:
```
>>> ('hi', divmod(10,20))
('hi'... | ```
print '%s %d:%02d' % ('hi',divmod(10,20)[0], divmod(10,20)[1])
^ ^ ^
1 2 3
```
Parentheses with commas indicate tuples, parens with concatenation (+) will return strings.
You need a 3-tuple for 3 inputs as shown | python tuple print issue | [
"",
"python",
"tuples",
"string-formatting",
""
] |
What I need is:
```
pro [-a xxx | [-b yyy -c zzz]]
```
I tried this but does not work. Could someone help me out?
```
group= parser.add_argument_group('Model 2')
group_ex = group.add_mutually_exclusive_group()
group_ex.add_argument("-a", type=str, action = "store", default = "", help="test")
group_ex_2 = group_ex.ad... | `add_mutually_exclusive_group` doesn't make an entire group mutually exclusive. It makes options within the group mutually exclusive.
What you're looking for is [subcommands](http://docs.python.org/dev/library/argparse.html#sub-commands). Instead of prog [ -a xxxx | [-b yyy -c zzz]], you'd have:
```
prog
command 1... | While [Jonathan's answer](https://stackoverflow.com/a/17909525/492620) is perfectly fine for complex options, there is a very simple solution which will work for the simple cases, e.g. 1 option excludes 2 other options like in
```
command [- a xxx | [ -b yyy | -c zzz ]]
```
or even as in the original question:
```
p... | Python argparse mutual exclusive group | [
"",
"python",
"argparse",
""
] |
i am passing args like
```
python file.py arg1 arg2 arg3
```
I want to know if there is a way to treat these args as objects not strings for the following code:
```
one = sys.argv[1]
two = sys.argv[2]
three = sys.argv[3]
from one import two
a = two.three()
```
since one two three would be strings. how can they ... | You can use [importlib for Python 2](http://docs.python.org/2/library/importlib.html) or [importlib for Python 3](http://docs.python.org/3/library/importlib.html#importlib.import_module).
```
import importlib
path = importlib.import_module('os.path')
print(path.join('a','b'))
``` | You can use the built-in `__import__` or the `imp` [module](http://docs.python.org/2/library/imp.html) to import object programmatically:
```
# Import 'name' relative to 'path'
module = imp.load_module(name, *imp.find_module(name, [path]))
```
Whenever I've wanted to programmatically import modules, this is how I do ... | python: better workaround for treating argument in bash/cmd line as an object | [
"",
"python",
"python-2.7",
""
] |
Just wondering if it is possible to use both an optional argument in the same function as multiple arguments. I've looked around and I feel as if I just have the vocabulary wrong or something. Example:
```
def pprint(x, sub = False, *Headers):
pass
```
Can I call it still using the multiple headers without having t... | In Python 3, use:
```
def pprint(x, *headers, sub=False):
pass
```
putting the keyword arguments *after* the positionals. This syntax will not work in Python 2.
Demo:
```
>>> def pprint(x, *headers, sub=False):
... print(x, headers, sub)
...
>>> pprint('foo', 'bar', 'baz', sub=True)
foo ('bar', 'baz') True... | I want to say yes because lots of matplotlib (for example) methods have something similar to this...
For example,
`matplotlib.pyplot.xcorr(x, y, normed=True, detrend=<function detrend_none at 0x2523ed8>, usevlines=True, maxlags=10, hold=None, **kwargs)`
When I'm using this I can specify any of the keyword arguments ... | Feasibility of using both optional and multiple arguments | [
"",
"python",
"python-3.3",
""
] |
I have a function that solves a quadratic equation:
```
class QuadEq(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def solve_quad_eq(self):
D = self.b**2-4*self.a*self.c
if D >= 0:
x1 = (-self.b-math.sqrt(D))/2*self.a
x2 ... | The short answer has already been posted. Use an [instance variable](http://docs.python.org/2/tutorial/classes.html#instance-objects) (`self.answer`):
```
class QuadEq(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def solve_quad_eq(self):
self.answer = ... | Make the answer a member of the class. and reference it by `self.answer`.
```
class QuadEq(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
self.answer = []
def solve_quad_eq(self):
D = self.b**2-4*self.a*self.c
if D >= 0:
x1 =... | How to give a function a value from another function in Python | [
"",
"python",
""
] |
I made the original battleship and now I'm looking to upgrade my AI from random guessing to guessing statistically probably locations. I'm having trouble finding algorithms online, so my question is what kinds of algorithms already exist for this application? And how would I implement one?
Ships: 5, 4, 3, 3, 2
Field:... | The ultimate naive solution wold be to go through every possible placement of ships (legal given what information is known) and counting the number of times each square is full.
obviously, in a relatively empty board this will not work as there are too many permutations, but a good start might be:
for each square on ... | Nice question, and I like your idea for statistical approach.
I think I would have tried a [machine learning](http://en.wikipedia.org/wiki/Supervised_learning) approach for this problem as follows:
First model your problem as a [classification problem](http://en.wikipedia.org/wiki/Statistical_classification).
Th... | How to generate statistically probably locations for ships in battleship | [
"",
"python",
"algorithm",
"math",
"statistics",
""
] |
I am implementing an algorithm for Texture Synthesis as outlined [here](http://graphics.cs.cmu.edu/people/efros/research/NPS/alg.html). For this I need to calculate the Sum of Squared Differences, a metric to estimate the error between the `template` and different positions across the `image`. I have a slow working imp... | This is basically an improvement over Warren Weckesser's answer. The way to go is clearly with a multidimensional windowed view of the original array, but you want to keep that view from triggering a copy. If you expand your `sum((a-b)**2)`, you can turn it into `sum(a**2) + sum(b**2) - 2*sum(a*b)`, and this multiply-t... | You can do some amazing things with the `as_strided` function combined with numpy's broadcasting. Here are two versions of your function:
```
import numpy as np
from numpy.lib.stride_tricks import as_strided
def sumsqdiff(input_image, template, valid_mask=None):
if valid_mask is None:
valid_mask = np.one... | Faster way to calculate sum of squared difference between an image (M, N) and a template (3, 3) for template matching? | [
"",
"python",
"image-processing",
"numpy",
"scipy",
"vectorization",
""
] |
So, let say I have 3 different calls called `something`, `something1` and `something2`.
and right now, im calling it like
```
try:
something
something1
something2
except Keyerror as e:
print e
```
Note that in the above code, if something fails, something1 and something2 will not get executed and so on.
... | You could try this, assuming you wrap things in functions:
```
for func in (something, something1, something2):
try:
func()
except Keyerror as e:
print e
``` | Here's a little context manager I've used for similar situations:
```
from contextlib import contextmanager
@contextmanager
def ignoring(*exceptions):
try:
yield
except exceptions or Exception as e:
print e
with ignoring(KeyError):
something()
# you can also put it on the same line if it... | a cleaner way to approach try except in python | [
"",
"python",
"exception",
"try-catch",
""
] |
I'm trying to make a game, and I want to save the position of the player before he moves (oldPosition), so that I can use it later. The problem is that by the time World.UpdateContents() runs, oldPosition is updated along with self.position. How can I keep oldPosition from changing when self.position does?
```
def Mov... | The attribute `position` is a list, when you assign it to `oldPosition` you're creating a reference to that list, but any modification you make on `position` will also be reflected on `oldPosition` - they're pointing to the same object. To solve this problem, make a copy of `position` at the beginning, like this:
```
... | Oscar Lopez is right, and his solution will work. The problem you're facing is due to the fact that lists in python are mutable. What does this mean?
Well, say we have some non-mutable variable, such as an integer. We can do, say,
```
x = 3
y = x
x = x + 1
print "x =", x, "y =", y
```
which, as expected, returns:
`... | Trying to store a class variable for later use | [
"",
"python",
"python-2.7",
""
] |
I have a table of projects and a table of comments. A project can have many comments. I want to get a list of all projects where the comment postedOn is > 30 days OR projects with no comment. What is the best way to accomplish this?
I’ve had many unsuccessful attempts; this is my latest go at it.
```
SELECT p.id,
... | ```
SELECT projects.id FROM projects
LEFT JOIN
(SELECT comments.projectID
FROM comments
GROUP BY comments.projectID
HAVING DATEDIFF(Now(), MAX(comments.postedOn)) < 30) AS C
ON projects.id = C.projectID
WHERE C.projectID IS NULL;
```
<http://sqlfiddle.com/#!2/ec919/14> | ```
SELECT PROJ.id,
PROJ.officialStatus
FROM Projects PROJ
LEFT JOIN
(
SELECT projectid, MAX(posted) AS max_posted
FROM Comments
GROUP BY projectid
) COMMENTS ON PROJ.id = COMMENTS.projectid
WHERE PROJ.officilstatus NOT IN ('Blue', 'Ca... | SQL left join: selecting the last records | [
"",
"sql",
"sql-server-2000",
""
] |
Is there a way to programmatically clean output on command prompt? I want to be able to print each letter of a word than erase them one at a time in the same line. | Something like this?
```
from sys import stdout
from time import sleep
def show(word):
for char in word:
stdout.write(char)
stdout.flush()
sleep(1)
for char in word:
stdout.write('\b \b')
stdout.flush()
sleep(1)
show('hello')
``` | ```
os.system('clear')
```
Works on linux.
You'll have to add:
```
import os
```
And for windows:
```
os.system('CLS')
``` | Is there a way to clean output on command prompt programmatically? | [
"",
"python",
""
] |
what is the difference between below two sql sentences:
1.
```
SELECT pid, config, constants
FROM sys_template
WHERE config LIKE '%code = LIST%'
```
2.
```
SELECT pid, config, constants
FROM sys_template
WHERE config LIKE 'code = LIST'
``` | 1. In your First query it shows all config column data which contains **code = LIST**
2. In your second query it shows all config column data which exact to **code = LIST**
LIKE supports wildcards. Usually it uses the % or \_ character for the wildcard.
For know more about [LIKE](http://dev.mysql.com/doc/refman/5.0/e... | `%` is a *wildcard character* to match any string. The latter matches only exactly `code = LIST` (basically working as `=` here), whereas the former matches `foocode = LISTbar` (for instance) as well.
To match a single arbitrary character, you can use `?` as a wildcard. | sql: what is the difference between LIKE %...% and LIKE? | [
"",
"mysql",
"sql",
""
] |
How do I start a process (another Python script, for example) from a Python script so the "child" process is completely detached from the "parent", so the parent can a) continue on its merry way without waiting for child to finish and b) can be terminated without terminating the child process?
**Parent:**
```
import ... | Answering my own question: I ended up simply using `os.system` with `&` at the end of command as [suggested by @kevinsa](https://stackoverflow.com/questions/17937249/fire-and-forget-a-process-from-a-python-script#comment26211780_17937249). This allows the parent process to be terminated without the child being terminat... | Since you mentioned `os.system`, I think it's worth to mention that you should have used `os.spawn*` with mode `P_NOWAIT` to achieve the "forget" part.
But `subprocess` module provides replacements for `os.system`, `os,spawn*`,etc so you should use that instead like so
```
import subprocess
p = subprocess.Popen("./ch... | "Fire and forget" a process from a Python script | [
"",
"python",
"linux",
"subprocess",
""
] |
What i mean is, how is the syntax defined, i.e. how can i make my own constructs like these?
I realise in a lot of languages, things like this will be built into the compiler / spec, and so it's dealt with by the compiler (at least that how i understand it to work).
But with python, everything i've come across so far... | Well, you have a couple of options for creating your own syntax:
1. Write a higher-order function, like `map` or `reduce`.
2. Modify python at the C level. This is, as you might expect, *relatively* easy as compared with fiddling with many other languages. See this article for an example: <http://eli.thegreenplace.net... | No, you can't, not from within Python. You can't add new syntax to the language. (You'd have to modify the source code of Python itself to make your own custom version of Python.)
Note that the [iterator protocol](http://docs.python.org/2/library/stdtypes.html#iterator-types) allows you to define objects that can be u... | How do the for / while / print *things* work in python? | [
"",
"python",
"loops",
"for-loop",
"syntax",
"while-loop",
""
] |
I have a very large .txt file with hundreds of thousands of email addresses scattered throughout. They all take the format:
```
...<name@domain.com>...
```
What is the best way to have Python to cycle through the entire .txt file looking for a all instances of a certain @domain string, and then grab the entirety of t... | This [code](https://developers.google.com/edu/python/regular-expressions) extracts the email addresses in a string. Use it while reading line by line
```
>>> import re
>>> line = "should we use regex more often? let me know at jdsk@bob.com.lol"
>>> match = re.search(r'[\w.+-]+@[\w-]+\.[\w.-]+', line)
>>> match.group(... | You can also use the following to find all the email addresses in a text and print them in an array or each email on a separate line.
```
import re
line = "why people don't know what regex are? let me know asdfal2@als.com, Users1@gmail.de " \
"Dariush@dasd-asasdsa.com.lo,Dariush.lastName@someDomain.com"
match =... | Extract email sub-strings from large document | [
"",
"python",
"string",
""
] |
Now I have read the other stackoverflow Game of Life questions and also Googled voraciously.I know what to do for my Python implementation of the Game Of Life.I want to keep track of the active cells in the grid.The problem is I'm stuck at how should I code it.
Here's what I thought up but I was kinda at my wit's end... | You have two lists, I'll name them currentState, and newChanges. Here will be the workflow:
1. Iterate over currentState, figuring out which are newly born cells, and which ones are going to die. **Do NOT add these changes to your currentState**. If there is a cell to be born or a death, add it to the newChanges list.... | don't know if it will help you, but here's a quick sketch of Game of Life, with activecells dictionary:
```
from itertools import product
def show(board):
for row in board:
print " ".join(row)
def init(N):
board = []
for x in range(N):
board.append([])
for y in range(N):
... | Game Of Life : How to keep track of active cells | [
"",
"python",
""
] |
Is there a field or a function that would return all ASCII characters in python's standard library? | You can use the [`string`](http://docs.python.org/2/library/string.html#string-constants) module:
```
import string
print string.printable
```
which gives:
```
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
``` | You can make one.
```
ASCII = ''.join(chr(x) for x in range(128))
```
If you need to check for membership, there are other ways to do it:
```
if c in ASCII:
# c is an ASCII character
if c <= '\x7f':
# c is an ASCII character
```
If you want to check that an entire string is ASCII:
```
def is_ascii(s):
... | Is there a list of all ASCII characters in python's standard library? | [
"",
"python",
""
] |
After `E0_copy = list(E0)`, I guess `E0_copy` is a deep copy of `E0` since `id(E0)` is not equal to `id(E0_copy)`. Then I modify `E0_copy` in the loop, but why is `E0` not the same after?
```
E0 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for k in range(3):
E0_copy = list(E0)
E0_copy[k][k] = 0
#print(E0_copy)
prin... | `E0_copy` is not a deep copy. You don't make a deep copy using `list()`. (Both `list(...)` and `testList[:]` are shallow copies, as well as `testList.copy()`.)
You use [`copy.deepcopy(...)`](http://docs.python.org/library/copy.html#copy.deepcopy) for deep copying a list.
> `copy.deepcopy(x[, memo])`
>
> Return a deep... | In Python, there is a module called `copy` with two useful functions:
```
import copy
copy.copy()
copy.deepcopy()
```
`copy()` is a shallow copy function. If the given argument is a compound data structure, for instance a **list**, then Python will create another object of the same type (in this case, a **new list**)... | How to deep copy a list? | [
"",
"python",
"list",
"copy",
"deep-copy",
""
] |
I am getting an error in my Django project, and it looks like it's coming from my `views.py` file:
```
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime
def get_date_time(request):
now = datetime.datetime.now()
return rende... | You need to import [`render`](https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render) from [`django.shortcuts`](https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#module-django.shortcuts) as it is not a built-in function.:
```
from django.shortcuts import render
``` | If you are following the Django tutorial and have this error but already have the import, it could be because the web server needs to be reloaded. The changes in code won't be reflected until `runserver` is ran again. | Django Python: global name 'render' is not defined | [
"",
"python",
"django",
"render",
""
] |
I want to get a data for '20130501'
Following is the query where I put '20130501' for start date, and '20130502' for the end date.
```
SELECT A.NAME, A.GENDER
FROM TABLE A
WHERE
A.DTM >= TO_DATE('20130501','YYYYMMDD')
AND A.DTM <= TO_DATE('20130502','YYYYMMD... | Just add a day to your second date, and use `<` for the comparison;
```
SELECT A.NAME, A.GENDER
FROM A
WHERE A.DTM >= TO_DATE('20130501','YYYYMMDD')
AND A.DTM < TO_DATE('20130501','YYYYMMDD')+1
```
[An SQLfiddle to test with](http://sqlfiddle.com/#!4/b3d95/11). | Instead of using the `>` and `<` for a date range you should use the `BETWEEN` since it is range inclusive:
```
SELECT A.NAME, A.GENDER
FROM TABLE A
WHERE A.DTM BETWEEN TO_DATE('20130501','YYYYMMDD') AND TO_DATE('20130502','YYYYMMDD');
```
<http://www.techonthenet.com/sql/between.php>
Since the solution with `TO_DAT... | Selecting data between two dates | [
"",
"sql",
"oracle",
"date",
""
] |
I want to produce a list of lists that represents all possible combinations of the numbers 0 and 1. The lists have length n.
The output should look like this. For n=1:
```
[ [0], [1] ]
```
For n=2:
```
[ [0,0], [0, 1], [1,0], [1, 1] ]
```
For n=3:
```
[ [0,0,0], [0, 0, 1], [0, 1, 1]... [1, 1, 1] ]
```
I looked a... | You're looking for [`itertools.product(...)`](http://docs.python.org/2/library/itertools.html#itertools.product).
```
>>> from itertools import product
>>> list(product([1, 0], repeat=2))
[(1, 1), (1, 0), (0, 1), (0, 0)]
```
If you want to convert the inner elements to `list` type, use a list comprehension
```
>>> [... | Use [`itertools.product`](http://docs.python.org/3/library/itertools.html#itertools.product), assigning the `repeat` to n.
```
from itertools import product
list(product([0,1], repeat=n))
```
Demo:
```
>>> list(product([0,1], repeat=2))
[(0, 0), (0, 1), (1, 0), (1, 1)]
>>> list(product([0,1], repeat=3))
[(0, 0, 0), ... | How to generate list combinations? | [
"",
"python",
"combinations",
""
] |
I have the following code:
```
Matrix = [[""] for x in range(2)]
for x in range (2):
Matrix[x] = input().title().split(" ")
print(Matrix)
```
When I run it with this input :
```
hEllo wOrld
SecoNd teST
```
I have this output :
```
[['Hello', 'World'], ['Second', 'Test']]
```
I don’t understand why the case o... | The [string function title](http://docs.python.org/2/library/stdtypes.html#string-methods) is the one modifying the case. It is meant to do so :)
Just remove it and you should be fine:
```
Matrix = [[""] for x in range(2)]
for x in range (2):
Matrix[x] = input().split(" ")
print(Matrix)
``` | function `title()` has made such changes. According to Python doc:
> str.title() Return a titlecased version of the string where words
> start with an uppercase character and the remaining characters are
> lowercase. | the case of string is modified when added in a matrix | [
"",
"python",
"string",
""
] |
Well, the title is not very appropriate, please read on (I couldn't get a better one).
Note: Using Python 2.7, but an algorithm will help too.
I'm making a side scroller game, in which I am generating the obstacles on the fly. The trouble I am having is figuring out how to generate the obstacles. o\_O
I have a some... | The following should work fairly well:
```
def find_valid_locations(grid, z, a, b):
check = [(0, 0, 0, 0)]
w = z + b
h = z + a
while check:
x, y, ox, oy = check.pop()
if x + w >= len(grid) or y + h >= len(grid[0]):
continue
for i, row in enumerate(grid[x+ox:x+w+1], x... | You can store the surface in a matrix M, then iterate over the matrix to find a place for the top-left corner of the new rectangle R:
```
for all rows of matrix M
for all columns of matrix M
variable empty = 0
for all numbers from 1 to a
for all numbers from 1 to b
empty ... | Finding an appropriate rectange in a 2-d array | [
"",
"python",
"algorithm",
"logic",
""
] |
Code example:
```
In [171]: A = np.array([1.1, 1.1, 3.3, 3.3, 5.5, 6.6])
In [172]: B = np.array([111, 222, 222, 333, 333, 777])
In [173]: C = randint(10, 99, 6)
In [174]: df = pd.DataFrame(zip(A, B, C), columns=['A', 'B', 'C'])
In [175]: df.set_index(['A', 'B'], inplace=True)
In [176]: df
Out[176]:
C
A... | To query the *df* by the *MultiIndex* values, for example where *(A > 1.7) and (B < 666)*:
```
In [536]: result_df = df.loc[(df.index.get_level_values('A') > 1.7) & (df.index.get_level_values('B') < 666)]
In [537]: result_df
Out[537]:
C
A B
3.3 222 43
333 59
5.5 333 56
```
Hence, to get for... | **For better readability**, we can simply use [the `query()` Method](http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-query-method), to avoid the lengthy `df.index.get_level_values()` and `reset_index`/`set_index` to and fro.
Here is the target `DataFrame`:
```
In [12]: df ... | How to query MultiIndex index columns values in pandas | [
"",
"python",
"pandas",
"indexing",
"slice",
"multi-index",
""
] |
I am installing certificates on a remote server and want to check whether they exist before I overwrite them. The server only allows non-root access via ssh public key. I can `sudo -s` to root once in a shell. Root is required because /etc/ssl is not readable by anyone else. This is being developed in `python fabric`, ... | ```
from fabric.contrib.files import exists
def foo():
if exists('/path/to/remote/file', use_sudo=True):
#command
``` | Maybe not the simplest way, but out of my head, I would suggest
```
ssh user@server 'bash -c "if [ -e /path/to/remote/file ] ; then true ; fi"'
``` | Test if File/Dir exists over SSH/Sudo in Python/Bash | [
"",
"python",
"bash",
"ssh",
"fabric",
""
] |
I have a column name called "PersonNameID"
which contains two values
```
ABCD-GHJI
ABHK-67891
HJKK-HJJJMH-8990
```
I have to extract only the first part of the "PersonNameID" which contains number after "-".Ideally my output should be
```
ABCD-GHJI
ABHK
HJKK-HJJJMH
```
but when I use following code :
```
SELECT T... | I have found the solution to the above situation...
```
DECLARE @Person TABLE(
Person_NAME_Original VARCHAR(500),
Person_NAME_Modified VARCHAR(500)
)
INSERT INTO @Person (Person_NAME_Original,Person_NAME_Modified)
SELECT top 1000 PersonNameID,
CASE WHEN CHARINDEX('-',PersonNameID) = 0
... | Use pattern matching to find the numeric ones and then work out where the numeric
```
SELECT
LEFT(PersonNameID,
CASE WHEN PersonNameID LIKE '%[0-9]%' AND CHARINDEX('-', PersonNameID) > 0
THEN
CHARINDEX('-', PersonNameID)-1
ELSE
LEN(PersonNameID... | Substring in sql server on numbers | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2005",
"sql-server-2008-r2",
""
] |
I am currently reading "Python Programming for the Absolute Beginning 3rd Edition". One of the challenges is:
> Write a Character Creator program for a role-playing game. The
> player should be given a pool of 30 points to spend on four
> attributes: Strength, Health, Wisdom, and Dexterity. The
> player should be able... | To make it short: I would go for the dictionary.
To make it long: This could be a nice example to delve directly into object oriented programming.
```
#! /usr/bin/python3
class Character:
class AbilityScoreOutOfBoundsException (Exception): pass
def __init__ (self, name):
self.name = name... | Dictionaries in Python are implement with hash tables, so efficiency isn't an issue here. Using dictionary of attributes is better because it is more flexible.
For example, if you wanted multiple characters, then you can simply have a list of attribute dictionaries. Using variables in this case isn't maintainable (you... | Dictionary vs Variable | [
"",
"python",
"dictionary",
"python-3.x",
""
] |
I have some list like this
```
[ ['2000-01-01', 1.0], ['2000-02-01', 2.0] ]
[ ['2000-01-01', 2.0], ['2000-02-01', 1.0], ['2000-03-01', 3.0] ]
[ ['2000-01-01', 3.1], ['2000-02-01', 2.0], ['2000-03-01', 1.4] ]
```
how can i merge the datatime and sum the value get a list like this
```
[ ['2000-01-01', 6.1], ['2000-02-... | Use [`collections.defaultdict()`](http://docs.python.org/2/library/collections.html#collections.defaultdict) here. See the snippet.
```
>>> a = [ ['2000-01-01', 1.0], ['2000-02-01', 2.0] ]
>>> b = [ ['2000-01-01', 2.0], ['2000-02-01', 1.0], ['2000-03-01', 3.0] ]
>>> c = [ ['2000-01-01', 3.0], ['2000-02-01', 2.0], ['20... | For all that kind of Excel-like programming, I advise to leverage Pandas as it is made for this.
However if you want to stay with the standard lib, a Counter is good enough. | python sum and merge element of list | [
"",
"python",
"list",
"datetime",
"sum",
""
] |
I need to perform a SQL request to extract some data. I'm not sure if it's possible, and if so, I don't know how to do it. I believe an example is better to demonstrate what I'd like to do.
Lets assume a very simple table:
```
--------------------------
| ID | domain |
--------------------------
| 1 | exa... | this will resolve your problem.
```
select * from table_name where :userParam like CONCAT('%', domain)
```
:userparam will be 'www.example.com' | you could split the user input along the `.`s, and try shorter and shorter sequences.
some pythonlike pseudocode:
```
user_input = "www.stackoverflow.com"
split_domain = user_input.split('.')
query = 'SELECT * FROM table WHERE domain = ' + '.'.join(split_domain)
while db_returns_no_rows(query) and split_domain:
d... | SQL: Finding DB entry that ends a given string | [
"",
"mysql",
"sql",
""
] |
I want to subtract two columns, and then I want to compute the total of the subtracted values.
I am using MS Access 2010.
```
Value1 Value2
100 50
100 80
```
I have applied-
`select value1-value2 as Result from tbl`
it gives the result
```
Result
50
20
```
But I want
```
Result
... | Use the following:
```
select sum(value1-value2) as Result
from tbl
``` | Use this statement:
```
SELECT SUM(Value1- value2) as Result
FROM tbl
``` | SQL Query to Subtract and Sum in same time | [
"",
"sql",
"ms-access-2007",
""
] |
I'm trying to access the corner values of a numpy ndarray. I'm absolutely stumped as for methodology. Any help would be greatly appreciated.
For example, from the below array I'd like a return value of array([1,0,0,5]) or array([[1,0],[0,5]]).
```
array([[ 1., 0., 0., 0.],
[ 0., 1., 0., 0.],
[ 0.,... | To add variety to the answers, you can get a view (not a copy) of the corner items doing:
```
corners = a[::a.shape[0]-1, ::a.shape[1]-1]
```
Or, for a generic n-dimensional array:
```
corners = a[tuple(slice(None, None, j-1) for j in a.shape)]
```
Doing this, you can modify the original array by modifying the view... | How about
```
A[[0,0,-1,-1],[0,-1,0,-1]]
```
where `A` is the array. | Get corner values in Python numpy ndarray | [
"",
"python",
"numpy",
""
] |
In previous version of Nose testing framework, there were several ways to specify only a subset of all tests:
```
nosetests test.module
nosetests another.test:TestCase.test_method
nosetests a.test:TestCase
nosetests /path/to/test/file.py:test_function
```
<http://nose.readthedocs.org/en/latest/usage.html#selecting-te... | I have some tests in dev/tests, for example:
```
dev/tests/test_file.py
```
I am able to run this with:
```
nose2 -s dev tests.test_file
```
Additionally, I'm able to run a specific test method in a test case as follows:
```
nose2 -s dev tests.test_file.TestCase.test_method
```
Does that accomplish what you want? | Works without `-s`, if you have your test in `tests/path/path2/mytest.py`
You can do
`nose2 tests.path.path2.mytest` | How to run specific test in Nose2 | [
"",
"python",
"nosetests",
"unittest2",
"nose2",
""
] |
I am pretty new to python and currenty I am trying to use pylint for checking code quality. I am getting a problem. My pylint doesn't point to virtualenv python interpreter. Here is the output that I get when I run pylint --version
```
$ pylint --version
pylint 0.21.1,
astng 0.20.1, common 0.50.3
Python 2.6.... | A cheap trick is to run (the global) pylint using the virtualenv python. You can do this using `python $(which pylint)` instead of just `pylint`. On zsh, you can also do `python =pylint`. | I am fairly sure that you need to install pylint under your virtual environment and then run that instance of it.
## Update - Make life easier:
I would suggest that anybody working a lot in virtual environments create a batch file, (in a known location or on the path), or bash script with something like the following... | pylint doesn't point to virtualenv python | [
"",
"python",
"virtualenv",
"pylint",
""
] |
Say I define a string in Python like the following:
```
my_string = "something{name1, name2, opt1=2, opt2=text}, something_else{name3, opt1=58}"
```
I would like to parse that string in Python in a way that allows me to index the different structures of the language.
For example, the output could be a dictionary `pa... | I highly recommend **[pyparsing](http://pyparsing.wikispaces.com/)**:
> The pyparsing module is an alternative approach to creating and
> executing simple grammars, vs. the traditional lex/yacc approach, or
> the use of regular expressions.
>
> The Python representation of the grammar is quite
> **readable**, owing to... | Here is a test of regular expression modified to react on `{}` instead of `()`:
```
import re
s = "something{name1, name2, opt1=2, opt2=text}, something_else{name3, opt1=58}"
r = re.compile(r'(?:[^,{]|{[^}]*})+')
print r.findall(s)
```
You'll get a list of separate 'named blocks' as a result:
```
`['something{name... | Parsing a lightweight language in Python | [
"",
"python",
"parsing",
""
] |
At the moment I'm doing my query like this:
`results = Points.where(latitude: (lat_low..lat_high))`
`result = results.where(longitude: (long_low..long_high)).first()`
It works but I can't help but think there should be a better way to pull out that one record. | Try this:
```
Points.where({ latitude: (lat_low..lat_high), longitude: (long_low..long_high) }).first
``` | How about ...
```
result = Points.where(latitude: (lat_low..lat_high)).
where(longitude: (long_low..long_high)).
first
``` | Combine two BETWEEN Rails queries | [
"",
"sql",
"ruby-on-rails",
""
] |

This should be done easy in Excel, however, I would like to have this kind of calculation done via SQL. I could use the `GROUP BY` , `OVER()` to calculate the SUM and % of a single year. But I failed to present the data 3 years at once. Any help will ... | Since you are using SQL Server, if you are using SQL Server 2005+ then you can use the PIVOT function to get the result. This solution implements both an unpivot and a pivot process to get the result. The starting point for this result is to calculate the total percent and total by type:
```
select type, year, total,
... | `SUMIF` can be replicated in SQL with `SUM(case statement)`:
```
SELECT Type
,SUM(CASE WHEN Year = '2010' THEN Total ELSE 0 END)'2010 Total'
,SUM(CASE WHEN Year = '2010' THEN Total ELSE 0 END)*1.0/SUM(SUM(CASE WHEN Year = '2010' THEN Total ELSE 0 END)) OVER () '2010 Percent of Total'
,SUM(CASE WHEN Y... | SUMIFS (Sum if with multiple conditions) with SQL Server | [
"",
"sql",
"sql-server",
""
] |
Im trying to print out all elements in a list, in Python, after I´ve appended one list to another. The problem is that it only prints out every element when I use PRINT instead or RETURN.
If I use print it prints out the whole list in a column with "None" at the end of the list, but return will print out just the first... | When you use a `return` statement, the function *ends*. You are returning just the first value, the loop does not continue nor can you return elements one after another this way.
`print` just writes that value to your terminal and does not end the function. The loop continues.
Build a list, then return *that*:
```
d... | `return` means end of a function. It will only return the first element of the list.
For your `print` version, `a.append(b)` makes `a = [1,2,3,4,[1,2,3]]` so you will see the elements before `None`. And the function returns nothing, so `print union(a, b)` will print a None.
I think you may want:
```
def union(a, b):... | Python: Why "return" won´t print out all list elements in a simple for loop and "print" will do it? | [
"",
"python",
"list",
"return",
""
] |
I have been googling almost an hour and am just stuck.
for a script, stupidadder.py, that adds 2 to the command arg.
e.g. python stupidadder.py 4
prints 6
python stupidadder.py 12
prints 14
I have googled so far:
```
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.ad... | I'm not entirely sure what your goal is. But if that's literally all you have to do, you don't have to get very complicated:
```
import sys
print int(sys.argv[1]) + 2
```
Here is the same but with some nicer error checking:
```
import sys
if len(sys.argv) < 2:
print "Usage: %s <integer>" % sys.argv[0]
sys.e... | Assuming that you are learning how to use the argparse module, you are very close. The parameter is an attribute of the returned args object and is referenced as `x = args.x`.
```
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('x', metavar='x', type=int, narg... | Python Command Args | [
"",
"python",
"parsing",
"arguments",
"args",
""
] |
```
import os
for dirpaths, dirnames, filenames in os.walk(mydir):
print dirpaths
```
gives me *all* (sub)directories in `mydir`. How do I get only the directories at the very bottom of the tree? | This will print out only those directories that have no subdirectories within them
```
for dirpath, dirnames, filenames in os.walk(mydir):
if not dirnames:
print dirpath, "has 0 subdirectories and", len(filenames), "files"
``` | Like this?
```
for dirpaths, dirnames, filenames in os.walk(mydir):
if not dirnames: print dirpaths
``` | How to list only down-most directories in Python? | [
"",
"python",
""
] |
```
print 'a' in 'ab'
```
prints `True`, while
```
print 'a' in 'ab' == True
```
prints `False`.
Any guess why? | [Operator chaining](http://docs.python.org/2/reference/expressions.html#not-in) at work.
```
'a' in 'ab' == True
```
is equivalent to
```
'a' in 'ab' and 'ab' == True
```
Take a look:
```
>>> 'a' in 'ab' == True
False
>>> ('a' in 'ab') == True
True
>>> 'a' in ('ab' == True)
Traceback (most recent call last):
Fil... | ```
>>> 'a' in 'ab' == True
False
>>> ('a' in 'ab') == True
True
```
---
Let's take a look at what the first variant *actually* means:
```
>>> import dis
>>> def f():
... 'a' in 'ab' == True
...
>>> dis.dis(f)
2 0 LOAD_CONST 1 ('a')
3 LOAD_CONST 2 ('ab')
... | Python statement giving unexpected answer | [
"",
"python",
"boolean",
""
] |
I'm trying to create a view using a double join between tables.
I'm working on some travel software, managing holiday bookings. The different items a person pays for can be in different currencies.
I've a table of bookings, and a table of currencies.
There are many different items a person can pay for, all stored in... | For `SQL Server`
This query allows each {`BookingId`, `CurrencyId`} have more than one row in the `Transfer` and `Extras` tables.
since you stated
> I've created a view showing the total owed per payment Item type.
I'm accumulating them by BookinID and CurrencyID
```
SELECT ISNULL(transfers.BookingId, extras.Book... | You should try to use the `full outer join` in joining the two tables: **Transfers** & **Extras**. Assuming you are using MySQL platform, the sql query can be:
```
SELECT t.BookingId,t.CurrencyId,e.TotalExtrasPrice,t.TotalTransfersPrice
FROM transfers as t FULL OUTER JOIN extras as e
ON t.BookingId = e.BookingId AND t... | SQL view using double joins between tables | [
"",
"sql",
""
] |
How do I check in Python, if an item of a list is repetead in another list?
I suppose that I should use a FOR loop, to go and check item by item, but I´m stuck in something like this (which I know it´s not correct):
```
def check(a, b):
for item in b:
for item1 in a:
if b[item] in a[item1]:
... | Assuming that `a` and `b` do not contain duplicate items that need to be preserved *and* the items are all hashable, you can use Python has a built in [`set`](http://docs.python.org/2/library/stdtypes.html#set):
```
c = list(set(b) - set(a))
# c is now a list of everything in b that is not in a
```
This would work fo... | You can use Python's [set](http://docs.python.org/2/library/stdtypes.html#set) operations without the need for loops:
```
>>> a = [1,2]
>>> b = [2]
>>> set(a) - set(b)
set([1])
>>>
``` | Compare with each other, items inside two lists, in a for loop? | [
"",
"python",
"list",
"for-loop",
""
] |
Let's say I have a list of lists of strings (stringList):
```
[['its', 'all', 'ball', 'bearings', 'these', 'days'],
['its', 'all', 'in', 'a', 'days', 'work']]
```
and I also I have a set of strings (stringSet) that are the unique words from stringList:
```
{'its', 'all', 'ball', 'bearings', 'these', 'days', 'in', '... | This seems to work:
```
str_list = [
['its', 'all', 'ball', 'bearings', 'these', 'days'],
['its', 'all', 'in', 'a', 'days', 'work']
]
str_set = set(word for sublist in str_list for word in sublist)
str_dict = {word: set(lindex
for lindex, sublist in enumerate(str_list) if word in sublist)
for wor... | ```
>>> alist = [['its', 'all', 'ball', 'bearings', 'these', 'days'],
... ['its', 'all', 'in', 'a', 'days', 'work']]
>>> aset = {'its', 'all', 'ball', 'bearings', 'these', 'days', 'in', 'a', 'work'}
>>> {x: {alist.index(y) for y in alist if x in y} for x in aset}
{'a': set([1]), 'all': set([0, 1]), 'ball': set([0]), ... | How do I add values to a set in a comprehension? | [
"",
"python",
"list-comprehension",
"dictionary-comprehension",
"set-comprehension",
""
] |
How can I do something like this.
```
index=[[test1,test2,test3],[test4,test5,test6],[test7,test8,test9]]
if test5 is in index:
print True
``` | Using [any](http://docs.python.org/2/library/functions.html#any) + [generator expression](http://docs.python.org/2/howto/functional.html?highlight=generator%20expression#generator-expressions-and-list-comprehensions):
```
if any(test5 in subindex for subindex in index):
print True
``` | Loop over your list of lists, and check for existence in each inner list:
```
for list in list_of_lists:
if needle in list :
print 'Found'
``` | How to search for an item in a list of lists? | [
"",
"python",
"list",
""
] |
I have a dataframe column, `data['time taken']` ;
```
02:08:00
02:05:00
02:55:00
03:42:00
01:12:00
01:46:00
03:22:00
03:36:00
```
How do I get the output in the form of minutes like below?
```
128
125
175
222
72
106
202
216
``` | You could try to convert it to `DatetimeIndex`
```
In [58]: time = pd.DatetimeIndex(df['time taken'])
In [59]: time.hour * 60 + time.minute
Out[59]: array([128, 125, 175, 222, 72, 106, 202, 216], dtype=int32)
``` | Assuming this is a string column you can use the [`str.split`](http://pandas.pydata.org/pandas-docs/dev/basics.html#vectorized-string-methods) method:
```
In [11]: df['time taken'].str.split(':')
Out[11]:
0 [02, 08, 00]
1 [02, 05, 00]
2 [02, 55, 00]
3 [03, 42, 00]
4 [01, 12, 00]
5 [01, 46, 00]
6 [... | Convert hh:mm:ss to minutes using python pandas | [
"",
"python",
"pandas",
""
] |
Let's imagine I have a table named "users". The code for creation:
```
CREATE TABLE IF NOT EXISTS users
(id_user INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(32) COLLATE NOCASE,
passwd_hash VARCHAR(255) NOT NULL DEFAULT '',
passwd_salt VARCHAR(255) NOT NULL DEFAULT '',
email_addr VARCHAR(255) NOT NULL ... | I would create a three-column index: (userid, password\_hash, password\_salt). This can be used as a *covering index* for greater efficiency.
It seems that this is only a minor improvement in SQLite, but the concept is used to greater benefit in other RDBMS implementations that can cache indexes in RAM.
<http://www.s... | When you execute the query:
```
SELECT passwd_hash, passwd_salt
FROM users
WHERE id_user = %d;
```
The SQL engine will use the index to find the right record. It then goes into the table itself to retrieve the data needed for the `select` clause.
If you instead build the index as:
```
CREATE INDEX IF NOT EXISTS idx... | Which columns should be indexed? | [
"",
"sql",
"database",
"sqlite",
"indexing",
""
] |
I wonder how I can mount a SQL as portable as possible to query for all columns of a table for a specific phrase, like:
**Table**
```
ID | Name | text | Date | Author | Status
1 | Augusto Weiand | Test text | 2010-01-01 | Deividi | 1
```
**Query**
```
SELECT *
FROM table
WHERE columns LIKE ... | Here is how you would concatenate the values in dynamic SQL:
```
set @Pattern = '%augusto%';
select @q := concat('select * from Table1 ',
'where concat(', group_concat(column_name), ', "") like "', @Pattern, '"'
)
from information_schema.columns c
where table_name = 'Table1';
pr... | It's doable, although I ***strongly*** suggest you look into full-text search for efficiency;
To avoid looking for all patterns in all fields one by one, you can just concat and search in that;
```
SELECT *
FROM (SELECT id,CONCAT(name,'|',text,'|',date,'|',author,'|',status) txt
FROM Table1) a
WHERE txt LIKE '%... | Mysql query search a string in all columns of a table | [
"",
"mysql",
"sql",
""
] |
This seems to be a gotcha for me, I couldnt figure this out
```
>>> from collections import Counter
>>> tree = [Counter()]*3
>>> tree
[Counter(), Counter(), Counter()]
>>> tree[0][1]+=1
>>> tree
[Counter({1: 1}), Counter({1: 1}), Counter({1: 1})]
```
Why does updating one Counter updates everything? | Using `[x] * 3`, the list references same item(`x`) three times.
```
>>> from collections import Counter
>>> tree = [Counter()] * 3
>>> tree[0] is tree[1]
True
>>> tree[0] is tree[2]
True
>>> another_counter = Counter()
>>> tree[0] is another_counter
False
>>> for counter in tree: print id(counter)
...
40383192
40383... | `[Counter()]*3` produces a list containing the *same* `Counter` instance 3 times. You can use
```
[Counter() for _ in xrange(3)]
```
to create a list of 3 independent `Counter`s.
```
>>> from collections import Counter
>>> tree = [Counter() for _ in xrange(3)]
>>> tree[0][1] += 1
>>> tree
[Counter({1: 1}), Counter()... | Python list simultaneous update | [
"",
"python",
"python-2.7",
""
] |
I have a set of 2D vectors presented in a `n*2` matrix form.
I wish to get the 1st principal component, i.e. the vector that indicates the direction with the largest variance.
I have found [a rather detailed documentation](https://www.clear.rice.edu/comp130/12spring/pca/pca_docs.shtml) on this from Rice University.
... | PCA gives only 2d vecs from 2d data.
Look at the picture in Wikipedia [PCA](http://en.wikipedia.org/wiki/Principal_component_analysis):
starting with a point cloud (dataMatrix) like that, and using `matplotlib.mlab.PCA`,
`myPCA.Wt[0]` is the first PC, the long one in the picture. | Similar question here: [Principal component analysis in Python](https://stackoverflow.com/questions/1730600/principal-component-analysis-in-python)
Or you could have a look at scikit-learn: <https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html> | How to get the 1st Principal Component by PCA using Python? | [
"",
"python",
"pca",
""
] |
Good day everyone. I would like to ask a question regarding my SQL statement. I am using SQL Server 2008 and has a table called Workflow Transaction. In this table, I have 12 records. The picture below is the content of the table.

I have this SQL st... | Your problem is that you're doing an update of ALL records with RequestId = 3. Take into account that your subquery result is `3` so you end up updating all related records.
Your query is equivalent to do
```
UPDATE Workflow_Txn
SET Status = 1
WHERE RequestId = 3
```
Not sure if you have any reason to make your que... | The problem with your query is that the subquery goes into great detail to find the records with order number less than the maximum. And then it chooses everything with the same request -- which would include the maximum order number.
I prefer to fix this using a CTE as follows:
```
with toupdate as (
select t.... | UPDATE using subqueries - Updates more than the needed records | [
"",
"sql",
"sql-server",
""
] |
I've read similar questions to this on Stack Overflow but they have not helped. Here is my code:
```
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Hello World')
pygame.mouse.set_visible(1)
done = False
clock = pygame.time.Clock()
whi... | The problem is that you don't process pygame's event queue. You should simple call `pygame.event.pump()` at the end of your loop and then your code works fine:
```
...
while not done:
clock.tick(60)
keyState = pygame.key.get_pressed()
if keyState[pygame.K_ESCAPE]:
print('\nGame Shuting Down!')
... | May I suggest using an event que instead? It's probably a better idea:
```
while True: #game loop
for event in pygame.event.get(): #loop through all the current events, such as key presses.
if event.type == QUIT:
die()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: ... | pygame.key.get_pressed() is not working | [
"",
"python",
"pygame",
""
] |
I've done some searches, but I'm actually not sure of the way to word what I want to take place, so I started a question. I'm sure its been covered before, so my apologies.
The code below doesn't work, but hopefully it illustrates what I'm trying to do.
```
sieve[i*2::i] *= ((i-1) / i):
```
I want to take a list and... | [NumPy](http://www.numpy.org/) would actually let you do that!
```
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> i = 2
>>> a[i*2::2] *= (i-1.0)/i
>>> a
array([0, 1, 2, 3, 2, 5, 3, 7, 4, 9])
```
If you can't use NumPy or prefer not to, a loop would probably be clearest:
... | You can do:
```
>>> def sieve(L, i):
... temp = L[:i]
... for x, y in zip(L[i::2], L[i+1::2]):
... temp.append(x)
... temp.append(y/2)
... return temp
...
>>> sieve([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
[1, 2, 3, 2, 5, 3, 7, 4, 9, 5]
```
Note that `itself * (2 - 1 ) / 2` is equivale... | changing values in a list while looping through it? | [
"",
"python",
"loops",
""
] |
I need a Mysql query like this SELECT \* FROM table 1 where column value = 1,2 or 3 and unique under a foreign (under one foreign key colum value =1 should have only one entry) find the count of duplicated values under the foreign key | ```
SELECT colValue, count(colValue) as cnt
FROM table1
where colValue in (1,2,3)
group by colValue
having cnt>1
``` | Try this:
```
SELECT
<Table1>.id, COUNT(<Table1>.Id)
FROM <Table1>
INNER JOIN <Table2> ON <Table1>.Id = <Table2>.Id
GROUP BY id
HAVING COUNT(<Table1>.Id) > 1
``` | to find the duplication of values | [
"",
"mysql",
"sql",
""
] |
```
Join = input('Would you like to join me?')
if Join == 'yes' or 'Yes':
print("Great," + myName + '!')
else:
print ("Sorry for asking...")
```
So this is my code. It's longer; just including the problem. I'm asking a yes or no question and when in the console it runs smoothly until you get to it. Whatever you ty... | ```
if Join == 'yes' or 'Yes':
```
This is always true. Python reads it as:
```
if (Join == 'yes') or 'Yes':
```
The second half of the `or`, being a non-empty string, is always true, so the whole expression is always true because anything `or` true is true.
You can fix this by explicitly comparing `Join` to both v... | I answered [this question](https://stackoverflow.com/a/17902498/2502012) yesterday
You can use [`.lower()`](http://docs.python.org/2/library/stdtypes.html#str.lower)
```
Join = input('Would you like to join me?')
if Join.lower() == 'yes':
print("Great," + myName + '!')
else:
print ("Sorry for asking...")
``` | Yes or No output Python | [
"",
"python",
"variables",
""
] |
How do I prepend an integer to the beginning of a list?
```
[1, 2, 3] ⟶ [42, 1, 2, 3]
``` | ```
>>> x = 42
>>> xs = [1, 2, 3]
>>> xs.insert(0, x)
>>> xs
[42, 1, 2, 3]
```
How it works:
`list.insert(index, value)`
Insert an item at a given position. The first argument is the index of the element before which to insert, so `xs.insert(0, x)` inserts at the front of the list, and `xs.insert(len(xs), x)` is equ... | ```
>>> x = 42
>>> xs = [1, 2, 3]
>>> [x] + xs
[42, 1, 2, 3]
```
Note: don't use `list` as a variable name. | Append integer to beginning of list in Python | [
"",
"python",
"list",
"prepend",
""
] |
In a "religious" discussion about formatting of Microsoft T-SQL code, I questioned whether or not the GOTO statement was still available in T-SQL syntax. In 13 years of using T-SQL I have never had occasion to use it, and indeed didn't know if it existed. After a brief search of the documentation and to my consternatio... | I almost never use `GOTO` and can easily live without it.
The one case where I would consider using it is when I have complicated code that does lots of error checking. I might want to take some action when an error returns, and `GOTO` allows me to define a single block of code for the error checking.
You can solve t... | i saw goto a few times in large scripts where people used it to improve readability. sometimes it is better readable but mostly it turns into spaghetti code.
i see just one situation where goto can maybe perform better. its inside a multiple while loop. you can use goto once instead of multiple [breaks](http://msdn.mi... | In what case would the use of a T-SQL GOTO statement be acceptable? | [
"",
"sql",
"t-sql",
"coding-style",
"goto",
""
] |
I'm trying to make a VarDump class, where I can do:
```
vd.attribute = value
```
and
```
print vd.attribute
```
So, this is the code:
```
class VarDump:
def __init__(self):
self.dump={}
def __setattr__(self,item,var):
self.dump[item]=var
def __getattr__(self,item):
if not ite... | `self.dump={}` calls `__setattr__` to set `dump`, which calls `__getattr__` to get the `dump` to put `dump` into, which calls `__getattr__` to get the `dump`, etc. You could resolve this with `object.__setattr__`, but the easier way is to just do this:
```
class Namespace(object):
def __getattr__(self, attr):
... | In Python 3.3, use the new [`types.SimpleNamespace()` type](http://docs.python.org/3/library/types.html#types.SimpleNamespace) instead:
```
>>> from types import SimpleNamespace
>>> vd = SimpleNamespace()
>>> vd.foo = 'bar'
>>> print(vd.foo)
bar
```
The documentation gives you a backwards-compatible version on a plat... | Python: Class as var dump error | [
"",
"python",
"variables",
""
] |
The file my function reads is of the format:
```
Column1 Column2 Column3 Column4
Value2 Value1 Value4 Value3
Value7 Value6 Value5 Value8
Value9 Value10 Value11 Value12
```
I read the file, filter and sort it and am left with a list of lists of the format:
`lines = [[Column1, Column2, Column3, Column4], [Value... | The following code worked for me, the problem I see is that you're not adding a newline after one row has been written.
```
>>> with open('fileName', 'w') as outFile:
for line in lines:
for elem in line:
outFile.write(elem.strip()+'\t')
outFile.write('\n')
```
This gave... | You want the `string.join(list)` function, which concatenates the elements of `list`, separating them by `string`. So you'll want `"\t".join(x.strip() for x in line)`. But this alone doesn't give you the newlines at the end of each string. You could then add the newline afterwards as follows: `"\t".join(x.strip() for x... | Adding a Newline Character at the End of a Line in a Column | [
"",
"python",
"file-io",
""
] |
My problem is when updating a dictonary to a list.
Input:
```
>>> res=[]
>>> my_inital_dict={'aa':1,'bb':1}
>>> for i in range(4):
... my_initial_dict.update({'aa':i+4})
... print my_initial_dict
... res.append(my_initial_dict)
```
Output I got:
```
{'aa': 4, 'bb': 1}
{'aa': 5, 'bb': 1}
{'aa': 6, 'bb': ... | All list items are reference the same dictionary object. Make a copy:
```
res = []
my_initial_dict = {'aa':1,'bb':1}
for i in range(4):
d = my_initial_dict.copy()
d['aa'] = i + 4
print d
res.append(d)
print res
``` | All items in your res list are referencing the **same object**, as said before.
You: Append this **[mutable](http://en.wikipedia.org/wiki/Mutable)** object to a list, change it, and append it again, now show me what that looks like.
Computer: Add object to list, add same object to list, here is your list, it has the ... | Python dictionary update to a list gives wrong output | [
"",
"python",
"python-2.7",
""
] |
When inside a jinja template:
1. How is the string, provided to {%extends xxx\_string%} and {% include xxx\_string%}, resolved?
2. Is this relative to actual filesystem, or a generated namespace (such as when using the Flask.url\_for function)?
Ultimately, I would like to use relative imports when inside my templates... | It seems the most appropriate solution for my "resource bundling" should be handled with Jinja loaders (see [Jinja Docs on Loaders](http://jinja.pocoo.org/docs/api/#loaders "Jinja Loaders")). Right away, `jinja2.PackageLoader`, `jinja2.PrefixLoader`, and jinja2.DictLoader seem like they could be fun.
The accepted answ... | Using folders instead of prefixes makes it a bit more clean in my opinion. Example application structure:
```
yourapplication
|- bp143
|- templates
|- bp143
|- index.jinja
|- quiz.jinja
|- context.jinja
|- templates
|- base.jinja
|- index.jinja
|- bp143
|- context.jin... | Flask - Jinja environment magic in a Blueprint | [
"",
"python",
"flask",
""
] |
I need to count only those order numbers where all products' status is **Active**.
Existing records:
```
OrderNo ProductID Status
1 1 Active
1 2 Active
1 3 Active
2 1 Inactive
2 2 Inactive
3 ... | ```
SELECT COUNT(*)
FROM
(
SELECT OrderNo
FROM products
GROUP BY OrderNo
HAVING MIN(Status) = 'Active' AND MAX(Status) = 'Active'
) AS dt
``` | To get the total orders with active numbers
```
SELECT COUNT(*) FROM
(SELECT * FROM products WHERE OrderNo NOT IN (SELECT * FROM products WHERE Status = 'Inactive' GROUP BY OrderNo)) as tmp_b; OrderNo
```
To get only the order numbers
```
SELECT OrderNo FROM
(SELECT * FROM products WHERE OrderNo NOT IN (SELECT * F... | SQL: Count Records if All Columns Are Equal | [
"",
"sql",
"sql-server",
"count",
""
] |
I created a file using the `write` command, and for some reason when I try to open it with my text editor after, it comes up with this message:
"The document python\_file.rtf could not be opened"
Here's exactly what I did:
```
infile=open("python_file.rtf","w")
infile.write("insert string here")
infile.close()
```
T... | You try to save this to a [RichTextFormated](http://en.wikipedia.org/wiki/Rich_Text_Format) File, but `"insert string here"` is only a character sequence. Try to save it as `python_file.txt` and open it with a notepad application, then you should see the text.
If you want to save RTF files you should check how this fi... | That's because rtf isn't just plain text format. Save it as `python_file.txt` for example or create file that compatibile with rtf format, for example:
```
>>> infile=open("python_file.rtf","w")
>>> infile.write("{\r test \par }")
>>> infile.close()
``` | Python file cannot be opened | [
"",
"python",
"file",
""
] |
Background: I'm working with a device vendor-supplied API module which stores device login data (device hostname, session ID, etc) as a global variable; I'm trying to figure out if it's possible to have multiple instances of the module to represent logins to multiple devices.
So far I've attempted a couple strategies ... | The following seems to work. It uses your `statictest.py` module and a combination of a few of the ideas in other answers to create a context manager which will allow easy switching and use of any of the various instances of the module:
```
from contextlib import contextmanager
import importlib
import random
import sy... | I think it's not possible because Python modules pretty much behave like Singletons (in fact this is a valid method to create a Singleton in Python). [Refer to this SO thread](https://stackoverflow.com/questions/10936709/why-does-a-python-module-act-like-a-singleton) or [this one](https://stackoverflow.com/questions/67... | Multiple instances of a global module variable? | [
"",
"python",
""
] |
My code needs to have an inner class and I want to create the instance of this inner class without creating the instance of outer class.
**How to do so in python?** In java we can define the inner class to be static but I don't know how to make a inner class static in python. I know that for methods we can use `@stat... | The class Inner is defined during the definition of the class Outer and it exists in its class namespace afterwards. So just `Outer.Inner()`. | You don't need to do anything special. Just refer to it directly:
```
instance = Outer.Inner()
``` | Static inner class in python | [
"",
"python",
"oop",
"static",
"inner-classes",
"static-classes",
""
] |
I know this sounds crazy and probably should not be done this way but I need something like this - I have a records from `SELECT [Type], [Total Sales] From Before`
I want to add an extra row at the end to show the SUM at the end of the table (After). Could this be done?
`](http://msdn.microsoft.com/en-us/library/bb522495.aspx "Using GROUP BY with ROLLUP, CUBE, and GROUPING SETS") GROUP BY function:
```
SELECT
Type = ISNULL(Type, 'Total'),
TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;
```
... | This is the more powerful grouping / rollup syntax you'll want to use in SQL Server 2008+. Always useful to specify the version you're using so we don't have to guess.
```
SELECT
[Type] = COALESCE([Type], 'Total'),
[Total Sales] = SUM([Total Sales])
FROM dbo.Before
GROUP BY GROUPING SETS(([Type]),());
```
Craig... | Add a summary row with totals | [
"",
"sql",
"sql-server",
"rollup",
""
] |
I am looking for some code in Python which could return `k` largest numbers from an unsorted list of `n` numbers. First I thought to do this by sorting the list first, but this might turn out to be very bulky.
For example the list from which I want to find `k` largest number be `list1`
```
> list1 = [0.5, 0.7, 0.3, 0... | Python has all batteries included - use [`heapq`](http://docs.python.org/2/library/heapq.html) module :)
```
from heapq import nlargest
data = [0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]
print nlargest(3, data)
```
it's also faster than sorting the whole array, because it's using partial heapsort | It can be done like this:
```
>>> list1
[0.5, 0.7, 0.3, 0.3, 0.3, 0.4, 0.5]
>>> list2 = list1[:] #make a copy of list1
>>> k = 3
>>> result = []
>>> for i in range(k):
result.append(max(list2)) #append largest element to list of results
list2.remove(max(list2)) # remove largest element from old list
>>... | How to find k biggest numbers from a list of n numbers assuming n > k | [
"",
"python",
"list",
"max",
""
] |
I have a class
```
class Foo():
def some_method():
pass
```
And another class **in the same module**:
```
class Bar():
def some_other_method():
class_name = "Foo"
# Can I access the class Foo above using the string "Foo"?
```
I want to be able to access the `Foo` class using the stri... | ```
import sys
getattr(sys.modules[__name__], "Foo")
# or
globals()['Foo']
``` | [You can do it with help of the `sys` module:](http://ideone.com/XXlIzj)
```
import sys
def str2Class(str):
return getattr(sys.modules[__name__], str)
``` | How to get class object from class name string in the same module? | [
"",
"python",
""
] |
I am just wondering how do I make python generate random numbers other than a particular number? For instance, I want it to generate any number from 1 to 5 except 3, so the output would be `1, 2, 4, 5` and `3` will not be counted in the list. What can I do to achieve that?
An example would be like this:
*There are *... | Use `random.choice` on a list, but first remove that particular number from the list:
```
>>> import random
>>> n = 3
>>> end = 5
>>> r = list(range(1,n)) + list(range(n+1, end))
>>> r
[1, 2, 4]
>>> random.choice(r)
2
>>> random.choice(r)
4
```
Or define a function:
```
def func(n, end, start = 1):
return list(... | While other answers are correct. The use of intermediate lists is inefficient.
---
**Alternate Solution**:
Another way you could do this is by choosing randomly from a range of numbers that is n-1 in size. Then adding +1 to any results that are greater than or equal to >= the number you want to skip.
The following f... | Choosing random integers except for a particular number for python? | [
"",
"python",
"random",
""
] |
forms.py
```
class PhoneForm(forms.ModelForm):
number1 = forms.IntegerField(required=False,error_messages={'invalid':'Enter a valid phone number'})
number2 = forms.IntegerField(required=False,error_messages={'invalid':'Enter a valid phone number'})
number3 = forms.IntegerField(required=False,error... | Never save phone numbers as `IntegerFields`. The behaviour you're seeing is normal for integers in any programming language.
```
>> myInt = 00001
>> print myInt
>> 1
```
What should you store it as? Either you a) write your own field, b) choose `CharField` or choose a `RegexField`
When it comes to phonenumbers I usu... | NEVER treat phone numbers as integers! Always use CharFields and maybe do a little bit of validation if necessary. Be sure that you do not only allow digits, but also "-", " " etc.
Your ModelForm might look like this:
```
class PhoneForm(forms.ModelForm):
class Meta:
model = PhoneInfo
fields = ['n... | Integer field prefix zero not displaying | [
"",
"python",
"django",
"django-models",
"django-forms",
"django-templates",
""
] |
How do I convert my Python app to a `.exe`? I made a program with `tkinter` and was wondering how to make it possible for others to use. I use Python 3.3. I searched for a bit but could not find anything. | cx\_Freeze does this but creates a folder with lots of dependencies. [py2exe](http://pypi.python.org/pypi/py2exe/) now does this and, with the --bundle-files 0 option, creates just one EXE, which is probably the best solution to your question.
UPDATE: After encountering third-party modules that py2exe had trouble "fin... | I have found [PyInstaller](http://www.pyinstaller.org/) to work the best.
You have many options for example you can pack everything to a one file exe.
I love to use it together with [Cython](http://cython.org/) for speed. | How do I compile my Python 3 app to an .exe? | [
"",
"python",
"tkinter",
"compilation",
"exe",
"python-3.3",
""
] |
How can I create a loop that prompts for a list of items, with the prompt changing each time.
For example "Input your first item" then "Input your second item" etc... (or 1st, 2nd)
I need to add all of the items to an array:
```
items = []
for i in range(5):
item = input("Input your first thing: ")
items.app... | Slightly altering your code:
```
names = {1: "first", 2: "second", 3: "third" # and so on...
}
items = []
for i in range(5):
item = input("Input your {} thing: ".format(names[i+1])
items.append(item)
print(items)
```
Or a more general version:
def getordinal(n):
if str(n)[-2:] in ("11","12","13"... | Use a list of prompts:
```
prompts = ('first', 'second', 'third', 'fourth', 'fifth')
items = []
for prompt in prompts:
item = input("Input your {} thing: ".format(prompt))
items.append(item)
``` | Change prompt to user with each loop pass | [
"",
"python",
"loops",
""
] |
Suppose I have a table:
```
HH SLOT RN
--------------
1 1 null
1 2 null
1 3 null
--------------
2 1 null
2 2 null
2 3 null
```
I want to set RN to be a random number between 1 and 10. It's ok for the number to repeat across the entire table, but it's *bad* to repeat the number *w... | Well, I couldn't get a slick solution, so I did a hack:
1. Created a new integer field called `rand_inst`.
2. Assign a random number to each empty slot.
3. Update `rand_inst` to be the instance number of that random number within this household. E.g., if I get two 3's, then the second 3 will have `rand_inst` set to 2.... | To get a random number between 1 and the number of rows in the hh, you can use:
```
select hh, slot, row_number() over (partition by hh order by random()) as rn
from t;
```
The larger range of values is a bit more challenging. The following calculates a table (called `randoms`) with numbers and a random position in t... | SQL random number that doesn't repeat within a group | [
"",
"sql",
"algorithm",
"random",
"netezza",
""
] |
If I define a little python program as
```
class a():
def _func(self):
return "asdf"
# Not sure what to resplace __init__ with so that a.func will return asdf
def __init__(self, *args, **kwargs):
setattr(self, 'func', classmethod(self._func))
if __name__ == "__main__":
a.func
```
I ... | You can dynamically add a classmethod to a class by simple assignment to the class object or by setattr on the class object. Here I'm using the python convention that classes start with capital letters to reduce confusion:
```
# define a class object (your class may be more complicated than this...)
class A(object):
... | There are a couple of problems here:
* `__init__` is only run when you create an instance, e.g. `obj = a()`. This means that when you do `a.func`, the `setattr()` call hasn't happened
* You cannot access the attributes of a class directly from within methods of that class, so instead of using just `_func` inside of `_... | How can I dynamically create class methods for a class in python | [
"",
"python",
"class",
"metaprogramming",
"static-methods",
"setattr",
""
] |
Here is example
```
In > int('1.5')
Out > 1
In > int('10.5')
Out > 10
```
But I want to keep values intact. How do you do it? | Integers are only numbers that have no decimals.
```
-4,-3,-2,-1,0,1,2,3,4,...,65535 etc...
```
Floating point numbers or Decimal numbers are allowed to represent fractions and more precise numbers
```
10.5, 4.9999999
```
If you want to take a string and get a numerical type for non-whole numbers, use [`float()`](h... | ```
foo = 10.5
foo2 = int(foo)
print foo, foo2
10.5, 10
``` | How to convert strings to numbers in python while preserving fractional parts | [
"",
"python",
"floating-point",
""
] |
Suppose I create a histogram using scipy/numpy, so I have two arrays: one for the bin counts, and one for the bin edges. If I use the histogram to represent a probability distribution function, how can I efficiently generate random numbers from that distribution? | It's probably what `np.random.choice` does in @Ophion's answer, but you can construct a normalized cumulative density function, then choose based on a uniform random number:
```
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
data = np.random.normal(size=1000)
hist, bins = np.histog... | @Jaime solution is great, but you should consider using the kde (kernel density estimation) of the histogram. A great explanation why it's problematic to do statistics over histogram, and why you should use kde instead can be found [here](http://nbviewer.ipython.org/url/mglerner.com/HistogramsVsKDE.ipynb)
I edited @Ja... | Random Number from Histogram | [
"",
"python",
"numpy",
"scipy",
"montecarlo",
""
] |
For example I have 2 arrays
```
a = array([[0, 1, 2, 3],
[4, 5, 6, 7]])
b = array([[0, 1, 2, 3],
[4, 5, 6, 7]])
```
How can I `zip` `a` and `b` so I get
```
c = array([[(0,0), (1,1), (2,2), (3,3)],
[(4,4), (5,5), (6,6), (7,7)]])
```
? | You can use [dstack](http://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html):
```
>>> np.dstack((a,b))
array([[[0, 0],
[1, 1],
[2, 2],
[3, 3]],
[[4, 4],
[5, 5],
[6, 6],
[7, 7]]])
```
If you must have tuples:
```
>>> np.array(zip(a.ravel(),b.ravel... | ```
np.array([zip(x,y) for x,y in zip(a,b)])
``` | in Numpy, how to zip two 2-D arrays? | [
"",
"python",
"arrays",
"numpy",
"zip",
""
] |
For a documentation project I am writing I need to include a table with date format strings. Now almost everything works fine, but at the end I have this slight problem where I want to print a literal ' quote and two literal quotes (separately and between other quotes). Sphinx changes these to up/down quotes, which usu... | As mentioned by other people in the comments, this process where Sphinx changes plain `"` into curled `“` and so on is called SmartQuotes.
I'm not sure if you specifically wanted the literals at all in the first place, or if they were only a compromise to avoid the SmartQuotes, but there are (at least) two ways to sto... | I just found the answer burried in the documentation:
<http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#inline-markup>
It turns out you can escape space characters by using a backslash "\" before them. So "\ " will be rendered as "". This is useful for instances where you need to use whitespace for ... | How to escape single quotes in reStructuredText when converting to HTML using Sphinx | [
"",
"python",
"python-sphinx",
"restructuredtext",
"docutils",
""
] |
In igraph or networkx, what is the fastest way to find all simple paths of length 4 in a sparse directed graph? One way is to make a graph of a simple path of length 4 and use the subgraph isomorphism vf2 function. Is this the best/fastest way?
I don't have a source node, I would like all simple paths of length 4 that... | Using a function like this:
```
def simple_paths(start, length, visited=[]):
if length==0:
yield(visited + [start])
else:
for child in children(start):
if child not in visited:
for path in simple_paths(child, length-1, visited + [start]):
yield(pa... | At the beginning, let's solve more simpler problem - calculate number of paths of length 4.
1) Let A be an adjacency matrix of the given graph. `A[i][j] = 1` if there exist an edge between vertices I and J and 0 otherwise. `A^N` gives number of paths of length `N` for some fixed length.
2) matrix *squaring* looks lik... | Sub graph isomorphism | [
"",
"python",
"algorithm",
"networkx",
"igraph",
""
] |
I wanted to create a regex which could match the following pattern:
```
5,000
2.5
25
```
This is the regex I have thus far:
```
re.compile('([\d,]+)')
```
How can I adjust for the `.`? | Easiest method would just be this:
```
re.compile('([\d,.]+)')
```
But this will allow inputs like `...`. This might be acceptable, since your original pattern allows `,,,`. However, if you want to allow only a single decimal point you can do this:
```
re.compile('([\d,]+.?\d*)')
```
Note that this won't allow inpu... | I think the perfect regex would be
```
re.compile(r'\d{1,2}[,.]\d{1,3}')
```
This way you match one or two digits followed by a comma or a full stop, and then one to three digits.
You don't need the parentheses if you are not going to use the contents of the match later. Omitting them speeds up the process. | Regex to pick up comma and period Python | [
"",
"python",
"regex",
""
] |
I am wanting to send the user an email whenever a new primary key is generated in Django. My code in **Models.py:**
```
class PurchaseOrder(models.Model):
product = models.CharField(max_length=256)
vendor = models.CharField(max_length=256)
dollar_amount = models.FloatField()
item_number = models.AutoFi... | Use [django signals](https://docs.djangoproject.com/en/dev/topics/signals/).
```
from django.db.models import signals
def send_email_on_new_order(instance, created, raw, **kwargs):
# Fixtures or updates are not interesting.
if not created or raw:
return
# `instance` is your PurchaseOrder instance... | Listen to the `post_save` signal.
```
from django.db.models import signals
from django.dispatch import receiver
@receiver(signals.post_save, sender=PurchaseOrder)
def email_handler(sender, **kwargs):
if kwargs['created']:
email = EmailMessage('Purchase Order System', 'your message here', to=['youremail@gm... | How can I send an email based on a new primary key being generated through Django? | [
"",
"python",
"django",
"email",
"key",
""
] |
Simple table:
```
create table [dbo].[payraisehistory]
(
[id][int] not null,
[payrate][money] not null,
[empid][int] not null
)
```
// Query to return last payrate raise
```
select prh.empid, max(prh.dategrant)
from payraisehistory prh
group by prh.empid
empid (No column name)
2 2013-07-30 00:00:00... | This is a case where you want to use `row_number()`:
```
select prh.empid, prh.payrate, prh.dategrant
from (select prh.*,
row_number() over (partition by prh.empid order by prh.dategrant desc) as seqnum
from payraisehistory prh
) prh
where seqnum = 1;
```
Your query is:
```
select prh.empid, ... | ```
SELECT * FROM
(
select prh.empid, prh.payrate, CASE WHEN prh.dategrant = max(prh.dategrant) over(partition
by prh.empid ORDER BY byprh.empid) THEN 1 ELSE 0 END AS st from payraisehistory prh
) AS T WHERE t.st = 1
``` | How to get salary back from with max(datetime) aggreate? | [
"",
"sql",
"sql-server-2008",
""
] |
If I have two dictionaries:
```
[{u'id': 217110,
u'label': u'Business A',
u'score': 0},
{u'id': 217111,
u'label': u'Business B',
u'score': 0},
{u'id': 217112,
u'label': u'Business Yada Yada',
u'score': 0'}]
```
and
```
[{u'City': u'Damariscotta',
u'EntityType': u'Maine Public',
u'EntityTypeCode': ... | Actually not very interesting puzzle supposing that this two lists are joined by `u'label'` and `u'Name1'` respectively.
Now answering your question I'd say that efficient way would be to create index of elements in second list by `u'Name1'`
```
name_index = {item[u'Name1']: i for i, item in enumerate(list2)}
```
Th... | First, this sounds like homework problem. We all encourage askers to post what they have written so that we can comment on it. Yet you have not shown us what you have done yet.
Second, the way the data is stored is not recommended. If the keys are from a small fixed set, you're better off using namedtuple in dictionar... | Dictionaries: how to compare values and merge if values are the same? | [
"",
"python",
""
] |
I'm trying to create a histogram of a data column and plot it logarithmically (`y-axis`) and I'm not sure why the following code does not work:
```
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('foo.bar')
fig = plt.figure()
ax = fig.add_subplot(111)
plt.hist(data, bins=(23.0, 23.5,24.0,24.5,25.0... | try
```
plt.yscale('log', nonposy='clip')
```
<http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.yscale>
The issue is with the bottom of bars being at y=0 and the default is to mask out in-valid points (`log(0)` -> undefined) when doing the log transformation (there was discussion of changing this, but I d... | The hist constructor accepts the `log` parameter.
You can do this:
```
plt.hist(data, bins=bins, log=True)
``` | Logarithmic y-axis bins in python | [
"",
"python",
"matplotlib",
"histogram",
"logarithm",
""
] |
I created a line that appends an object to a list in the following manner
```
>>> foo = list()
>>> def sum(a, b):
... c = a+b; return c
...
>>> bar_list = [9,8,7,6,5,4,3,2,1,0]
>>> [foo.append(sum(i,x)) for i, x in enumerate(bar_list)]
[None, None, None, None, None, None, None, None, None, None]
>>> foo
[9, 9, 9,... | Yes, this is bad style. A list comprehension is to build a list. You're building a list full of `None`s and then throwing it away. Your actual desired result is a side effect of this effort.
Why not define `foo` using the list comprehension in the first place?
```
foo = [sum(i,x) for i, x in enumerate(bar_list)]
```
... | I think it's generally frowned upon to use list comprehensions just for side-effects, so I would say a for loop is better in this case.
But in any case, couldn't you just do `foo = [sum(i,x) for i, x in enumerate(bar_list)]`? | When to drop list Comprehension and the Pythonic way? | [
"",
"python",
"list-comprehension",
"pylint",
"code-complete",
""
] |
So, basically, I need a program that opens a .dat file, checks each line to see if it meets certain prerequisites, and if they do, copy them into a new csv file.
The prerequisites are that it must 1) contain "$W" or "$S" and 2) have the last value at the end of the line of the DAT say one of a long list of acceptable ... | ```
import os
NewFilePath = "A:\test.txt"
Acceptable_Values = ('Apple','Banana')
#Main
def main():
if os.path.isfile(NewFilePath):
os.remove(NewFilePath)
NewFile = open (NewFilePath, 'w')
NewFile.write('Header 1,','Name Header,','Header 3,','Header 4)
OldFile_Loc=raw_input("Input File for Progra... | There are two parts you need to implement: First, read a file line by line and write lines meeting a specific criteria. This is done by
```
with open('file.dat') as f:
for line in f:
stripped = line.strip() # remove '\n' from the end of the line
if test_line(stripped):
print stripped # ... | Python: Copying lines that meet requirements | [
"",
"python",
""
] |
I am using MySQL
my database created is like this:
```
Create table Author ( Id int , Name nvarchar(max) );
Create table Image ( Id int ,ImagePath nvarchar(max) );
Create table Blog ( Id int ,Name nvarchar(max) ,AuthorId int );
Create table BlogImages ( Id int ,BlogId int ,ImageId int );
```
now when I am trying ... | You have to define `primary keys`:
```
Create table Author
(
Id int ,
Name nvarchar(max),
PRIMARY KEY (id)
);
Create table Image
(
Id int ,
ImagePath nvarchar(max),
PRIMARY KEY (id)
)
Create table Blog
(
Id int ,
Name nvarchar(max) ,
AuthorId int,
PRIMARY KE... | You can add query to create table
```
CREATE TABLE author ( Id int , Name varchar(255) );
```
When you want alter Author table then you can write the below query
```
ALTER TABLE author ADD test varchar(255)
```
When you want to add primary key to id you can put below query
```
ALTER TABLE author ADD Primary key au... | foreign keys not adding instead giving errors | [
"",
"mysql",
"sql",
""
] |
I have an SQL Trigger FOR INSERT, UPDATE I created which basically does the following:
Gets a LineID (PrimaryID for the table) and RegionID From the Inserted table and stores this in INT variables.
It then does a check on joining tables to find what the RegionID should be and if the RegionID is not equal what it shoul... | This has been resolved. I resolved the problem by adding the trigger to another table as the IF @PurchaserRegionID IS NOT NULL was always false. | The major problem with your trigger is that it's written in assumption that you always get only one row in `INSERTED` virtual table.
SQL Server triggers are statement-triggers not row-triggers. You have to take that fact into consideration.
Now if I understand correctly the logic behind this trigger then you need jus... | SQL Insert, Update Trigger - Can you update the inserted table? | [
"",
"sql",
"sql-server",
"triggers",
"insert",
""
] |
I wrote this to calculate the minimum number of bills and coins needed to make change. Can this be done using a loop?
```
def user_change(balance):
twen = int(balance/20)
balance=balance%20
ten = int(balance/10)
balance=balance%10
five = int(balance/5)
balance = balance%... | EDIT: updated answer per roippi@ suggestion:
```
from collections import OrderedDict
_currency_values = [
('twenties',20),
('tens',10),
('fives',5),
('ones',1),
('quarters',0.25),
('dimes',0.10),
('nickels',0.05),
('pennies',0.01),
]
currency_values = OrderedDict(_currency_values)
de... | This is a good time (okay it's *always* a good time) to make things easier on yourself and first think about data structures. You have a list of currency (keys) that, for each key, you want to find one unique amount for (value). k:v pairings mean a `dict`, so fill one up in lieu of just printing the value; you can alwa... | Can this be done by using a loop? Or maybe by using lists? | [
"",
"python",
"loops",
""
] |
I have two numpy boolean arrays (`a` and `b`). I need to find how many of their elements are equal. Currently, I do `len(a) - (a ^ b).sum()`, but the xor operation creates an entirely new numpy array, as I understand. How do I efficiently implement this desired behavior without creating the unnecessary temporary array?... | On my machine this is faster:
```
(a == b).sum()
```
If you don't want to use any extra storage, than I would suggest using numba.
I'm not too familiar with it, but this seems to work well.
I ran into some trouble getting Cython to take a boolean NumPy array.
```
from numba import autojit
def pysumeq(a, b):
tot ... | To start with you can skip then A\*B step:
```
>>> a
array([ True, False, True, False, True], dtype=bool)
>>> b
array([False, True, True, False, True], dtype=bool)
>>> np.sum(~(a^b))
3
```
If you do not mind destroying array a or b, I am not sure you will get faster then this:
```
>>> a^=b #In place xor opera... | Numpy sum of operator results without allocating an unnecessary array | [
"",
"python",
"arrays",
"optimization",
"numpy",
"numexpr",
""
] |
I currently have a django site that is using cookie sessions. Ive noticed that the session is randomly being logged out. When debugging this I found it was due to the logic within my code looking at the age of the session.
However I then noticed that during the periods that there were no issues the correct time showed ... | The Apache logs indicate a very discrete time step of 5 hours so this is unlikely to be an underlying system time adjustment by a time keeping daemon such as ntp. I'd guess that it's almost certain to be related to a timezone setting.
If you're using mod\_wsgi to serve your app in non-daemon mode, there could be share... | This seems an OS/HW misconfiguration.
I suspect that some times your network fails and OS (Operating Sistem) need to get data from hardware clock but ntp.
You should ensure than **BIOS clock UTC configuration match with `/etc/default/rcS` parameters**:
```
# assume that the BIOS clock is set to UTC time (recommended... | Apache Time Issue | [
"",
"python",
"django",
"apache",
""
] |
I have two variables, 1 varchar named `cust_ref`, and 1 int named `associated_ids`. What I'm trying to accomplish is the following:
You provide `cust_ref` with a value which will usually result in between 1+ rows being returned from the `Customer` table. I am concerned with gathering all `customer_id` records for that... | ```
declare @cust_ref varchar(20) = 'ABGR55532' --from your code
DECLARE @result varchar(100)
set @result =
(SELECT distinct (customer_id + ' ')
FROM dbo.Customer
where cust_ref = @cust_ref --from your code
ORDER BY (customer_id + ' ')
FOR XML PATH (''))
SELECT REPLACE(RTRIM(@result),' ',',')
``` | You could try something like this ... obviously, some adjustment will be needed:
```
create table x (id varchar(50),num int)
insert into x (id,num) values ('75458','20')
insert into x (id,num) values ('77397','20')
insert into x (id,num) values ('94955','20')
```
and then,
```
create function GetList (@num as varcha... | SQL - Storing multiple records in a variable separated by commas | [
"",
"sql",
"sql-server-2008",
"t-sql",
"variables",
""
] |
I'm working on a Pivot problem. I came up with some code, but have been unsuccessfull in working out the coding. Please could someone give me some guidance on what I'm doing wrong here?
I have table 1, which is create in code below:
```
create table T1 (
[name] varchar(30)
,[size] int
,[DT] date)
in... | You have unclosed quotation marks, extra unneeded brackets, whole part with STUFF FOR XML inside dynamic sql is not needed (for output described), there was wrong column name...
```
declare @DateList as varchar(max)
declare @dynamic_PQ as varchar(max)
select @DateList =
stuff( (
select DISTINCT
', '+ ... | Your query has multiple errors. This version works:
```
select [name], [01-03-2013], [01-04-2013], [01-05-2013], [01-06-2013]
from ( Select [name], size,
STUFF((SELECT distinct ', ' + cast(a2.size as varchar(10))
from t1 a2
where src.name = a2.name and src.dt = a2.dt
FO... | Pivot Table Code, Need some ideas | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
"pivot",
""
] |
I have the following code in my template:
```
data: [{% for deet in deets %} {{ deet.value*100|round(1) }}{% if not loop.last %},{% endif %} {% endfor %}]
```
I am expecting data rounded to 1 decimal place. However, when I view the page or source, this is the output I'm getting:
```
data: [ 44.2765833818, 44.276583... | Didn't realize the filter operator had precedence over multiplication!
Following up on bernie's comment, I switched
```
{{ deet.value*100|round(1) }}
```
to
```
{{ 100*deet.value|round(1) }}
```
which solved the problem. I agree the processing should happen in the code elsewhere, and that would be better practice. | You can put parens around the value that you want to round. (This works for division as well, contrary to what @sobri wrote.)
```
{{ (deet.value/100)|round }}
```
NOTE: `round` returns a `float` so if you really want the `int` you have to pass the value through that filter as well.
```
{{ (deet.value/100)|round|int ... | Jinja2 round filter not rounding | [
"",
"python",
"flask",
"jinja2",
"template-engine",
""
] |
I have below sample values in a column
```
Abc-123-xyz
Def-456-uvw
Ghi-879-rst-123
Jkl-abc
```
Expected output is the third element split by '-', in case there is no third element, the last element will be retrieve.
See expected output below:
```
Xyz
Uvw
Rst
Abc
```
Thanks ahead for the help. | ```
SELECT initcap(nvl(regexp_substr(word, '[^-]+', 1,3),regexp_substr(word, '[^-]+', 1,2))) FROM your_table;
``` | Another approach:
```
SQL> with t1(col) as(
2 select 'Abc-123-xyz' from dual union all
3 select 'Def-456-uvw' from dual union all
4 select 'Ghi-879-rst-123' from dual union all
5 select 'Jkl-Abc' from dual
6 )
7 select regexp_substr( col
8 , '[^-]+'
9 ... | Oracle SQL : Regexp_substr | [
"",
"sql",
"regex",
"oracle",
""
] |
I have a set of records and I want to sort these records on the basis of the number of items in a group.

I want to arrange the records in such a way that Products with maximum number of items are at the top i.e. the required order is- ... | ```
Select Product_ID, Item_Name, Item_Description, Item_Number
from Product
order by COUNT(1) over (partition by Product_ID) desc
``` | I assume you want to group by the ID only but you want to list all other fields, you don't need to group by at all if you just want to order by:
```
SELECT product_id,
item_name,
item_description,
item_number
FROM product p1
ORDER BY (SELECT Count(product_id)
FROM product p2 ... | Sorting Records on the Basis of Number of Items in a Group- SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I wanted to declare an `if` statement inside a `lambda` function:
Suppose:
```
cells = ['Cat', 'Dog', 'Snake', 'Lion', ...]
result = filter(lambda element: if 'Cat' in element, cells)
```
Is it possible to filter out the 'cat' into `result`? | If you want to filter out all the strings that have `'cat'` in them, then just use
```
>>> cells = ['Cat', 'Dog', 'Snake', 'Lion']
>>> filter(lambda x: not 'cat' in x.lower(), cells)
['Dog', 'Snake', 'Lion']
```
If you want to keep those that have `'cat'` in them, just remove the `not`.
```
>>> filter(lambda x: 'cat... | You don't need `if`, here. Your `lambda` will return a boolean value and [`filter()`](http://docs.python.org/2/library/functions.html#filter) will only return those elements for which the `lambda` returns `True`.
It looks like you are trying to do either:
```
>>> filter(lambda cell: 'Cat' in cell , cells)
['Cat']
```... | If statement in lambdas Python | [
"",
"python",
""
] |
Python 3.4 introduces a new module [`enum`](http://docs.python.org/3.4/library/enum.html), which adds an [enumerated type](http://en.wikipedia.org/wiki/Enumerated_type) to the language. The documentation for `enum.Enum` provides [an example](http://docs.python.org/3.4/library/enum.html#planet) to demonstrate how it can... | This is advanced behavior which will not be needed in 90+% of the enumerations created.
According to the docs:
> The rules for what is allowed are as follows: `_sunder_` names (starting and ending with a single underscore) are reserved by enum and cannot be used; all other attributes defined within an enumeration wil... | The most elegant solution (IMHO) is to use mixins / base class to provide the correct behavior.
* base class to provide the behavior that's needed for all implementation that's common to e.g. `Satellite` and `Planet`.
* [mixins are interesting](https://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-the... | Is it possible to define a class constant inside an Enum? | [
"",
"python",
"python-3.x",
"enums",
"constants",
"class-constants",
""
] |
heya I am new to SQL thing
I am trying to make a Blog
the plan goes like
a single blog can have only one AUTHOR
where a Author can have more than one blog
and a single blog can have multiple images
can any one make me understand how will the relation go with this for the sql mapping?? | ```
Create table Author
(
Id int
, Name nvarchar(max)
);
Create table Image
(
Id int
,ImagePath nvarchar(max)
);
Create table Blog
(
Id int
,Name nvarchar(max)
,AuthorId int
);
Create table BlogImages
(
Id int
,BlogId int
,ImageId int
);
ALTER TABLE Blog
ADD FOREIGN KEY (AuthorId)
REFERENCES Author(Id);
ALTER TABL... | > Author ----> Blogs -------> Images..
So let me explain the plan a little bit.
There will be a table authors having all details of authors. PK being author\_id.
Blog table will be having details of blogs. Blog\_id being the PK and will be having a foreign key author\_id referenced by author table.
Image table will b... | SQL relations between blog and author | [
"",
"mysql",
"sql",
"sqlite",
""
] |
I am working on a program to sensor out words in python.
user input = my email id is harry@hogwarts.com
output = my email id is xxxxx@hogwarts.com
this is what i have so far
```
def main():
message = []
userInput = str(input("Enter the sentence: "))
splitInput = str(list(userInput))
print(splitInput)
... | you could use this function to encode email:
```
>>> def encodeemail(email):
e = email.split("@")
return "@".join(["x" * len(e[0]), e[1]])
>>> encodeemail("harry@hogwarts.com")
xxxxx@hogwarts.com
```
or even
```
>>> def encodeemail(email):
d = email.split(" ")
for i, f in enumerate(d):... | You can use `re` module if the string does not contain email only.
```
>>> s
'my email id is harry@hogwards.com'
>>> re.sub('(?<=\s)\w+(?=@)', lambda y: 'x'*len(y.group()), s)
'my email id is xxxxx@hogwards.com'
``` | Using Lists and String methods to sensor out words in python | [
"",
"python",
""
] |
I am working on to achieve dynamic Highcharts graph – basic column and I need help in making SQL in MySQL. I need results for last the 12 months (irrespective of any data for the month (it can be 0 – but all the 12 months records should be fetched)) from the current month showing how many members (4 types of users) hav... | Try this
```
SELECT month(u.`userRegistredDate`),
sum(CASE WHEN u.`userTypeID`=1 THEN 1 ELSE 0 END) AS agent,
sum(CASE WHEN u.`userTypeID`=2 THEN 1 ELSE 0 END) AS individuals,
sum(CASE WHEN u.`userTypeID`=3 THEN 1 ELSE 0 END) AS builders,
sum(CASE WHEN u.`userTypeID`=4 THEN 1 ELSE 0 END) AS real_estate_companies,
... | This is what you want :
```
SELECT
sum(CASE WHEN u.`userTypeID`=1 THEN 1 ELSE 0 END) AS agent,
sum(CASE WHEN u.`userTypeID`=2 THEN 1 ELSE 0 END) AS individuals,
sum(CASE WHEN u.`userTypeID`=3 THEN 1 ELSE 0 END) AS builders,
sum(CASE WHEN u.`userTypeID`=4 THEN 1 ELSE 0 END) AS real_estate_companies,
u.`userRegistredDa... | SQL query for displaying records on Highcharts graph | [
"",
"mysql",
"sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.