Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Folks - I have two lists
```
list1=['a','b']
list2=['y','z']
```
I would like to send the variables to a function like below:
```
associate_address(list1[0],list2[0])
associate_address(list1[1],list2[1])
```
my script:
```
for l in list1:
for i in list2:
conn.associate_address(i,l)
```
I receive the below ou... | Use the [`zip`](http://docs.python.org/2/library/functions.html#zip) function, like this:
```
list1=['a','b']
list2=['y','z']
for i, j in zip(list1, list2):
print(i, j)
```
Output:
```
('a', 'y')
('b', 'z')
``` | Why do you suppose this is?
```
>>> for x in [1,2]:
... for y in ['a','b']:
... print x,y
...
1 a
1 b
2 a
2 b
```
Nested loops will be performed for each iteration in their parent loop. Think about truth tables:
```
p q
0 0
0 1
1 0
1 1
```
Or combinations:
```
Choose an element from a set of two e... | nested for loops in python with lists | [
"",
"python",
"loops",
"nested",
""
] |
I've hit a wall and needed some help or advice to get me through.
I want to append certain strings always apppend to the end of a list.
So we have
```
List1 = ["sony","cant recall","samsung","dont know","apple","no answer", "toshiba"]
```
Next we have another list
```
List2 = ["dont know", "cant recall","no answer... | You can do your algorithm like:
```
list1 = [x for x in list1 if not x in list2] + [x for x in list1 if x in list2]
```
which will result in:
```
['sony', 'samsung', 'apple', 'toshiba', 'cant recall', 'dont know', 'no answer']
``` | ```
lst_result = set(lst1) | set(lst2)
```
Removes duplicates from the lists as a side effect. Not sure if you want it, but looks like it's assumed.
To keep the ordering:
```
lst1 = ["sony","cant recall","samsung","dont know","apple", "toshiba"]
lst2 = ["dont know", "cant recall","no answer"]
stripped = list(filter... | Python - Always append certain strings to the end of a list | [
"",
"python",
"list",
""
] |
I want to create a RSS Feed generator. The generator is supposed to read data from my database and generate RSS feeds for them. I want to write a script that would automatically generate the `xml` file for validation.
So if a typical `xml` file for RSS feed looks like this:
```
<item>
<title>Entry Title</title>
... | Since this is python. Its good to be using `PyRSS2Gen`. Its easy to use and generates the xml really nicely. <https://pypi.python.org/pypi/PyRSS2Gen> | What have you tried so far?
A very basic approach would be to use the [Python DB API](http://docs.python.org/2/library/sqlite3.html#module-sqlite3) to query the database and perform some simple formatting using [`str.format`](http://docs.python.org/2/library/stdtypes.html#str.format) (I type directly in SO -- so bewar... | How to dynamically generate XML file for RSS Feed? | [
"",
"python",
"rss",
""
] |
I'm new to mysql so I don't know yet how to make queries joining multiple tables so I need some help making this query.
So I have these tables:
Products
```
| id | category | description | brand |
|:-----------|------------:|:------------:|:------------:|
| 1 | desktops | Hp example... | ```
select products.category, products.description, products.brand, stores.brands, stores.location, products_stores.price
from products_stores
inner join stores on stores.id = products_stores.stores_id
inner join products on products.id = products_stores.products_id
```
[sql fiddle](http://sqlfiddle.com/#!2/a1ae2/2) | Simply use [joins](http://dev.mysql.com/doc/refman/5.0/en/join.html) (more particularly `INNER JOIN` and make sure that the `store` column isn't called `Brands(physical stores)` though. If it's called `brands`, then simply change it in the query:
```
SELECT
pr.category,
pr.description,
pr.brand,
st.sto... | Multiple table query - SQL | [
"",
"mysql",
"sql",
""
] |
In a list of list of dicts:
```
A = [
[{'x': 1, 'y': 0}, {'x': 2, 'y': 3}, {'x': 3, 'y': 4}, {'x': 4, 'y': 7}],
[{'x': 1, 'y': 0}, {'x': 2, 'y': 2}, {'x': 3, 'y': 13}, {'x': 4, 'y': 0}],
[{'x': 1, 'y': 20}, {'x': 2, 'y': 4}, {'x': 3, 'y': 0}, {'x': 4, 'y': 8}]
]
```
I need to retrieve th... | `max` accept optional `key` parameter.
```
A = [
[{'x': 1, 'y': 0}, {'x': 2, 'y': 3}, {'x': 3, 'y': 4}, {'x': 4, 'y': 7}],
[{'x': 1, 'y': 0}, {'x': 2, 'y': 2}, {'x': 3, 'y': 13}, {'x': 4, 'y': 0}],
[{'x': 1, 'y': 20}, {'x': 2, 'y': 4}, {'x': 3, 'y': 0}, {'x': 4, 'y': 8}]
]
Z = []
for a in A:
d = max(a... | I'd use `itemgetter` and `max`'s `key` argument:
```
from operator import itemgetter
pair_getter = itemgetter('x', 'y')
[pair_getter(max(d, key=itemgetter('y'))) for d in A]
``` | Select highest value from python list of dicts | [
"",
"python",
"list",
"numpy",
""
] |
I'm trying to insert a python variable into a MySQL table within a python script but it is not working. Here is my code
```
add_results=("INSERT INTO account_cancel_predictions"
"(account_id,21_day_probability,flagged)"
"Values(%(account_id)s,%(21_day_probability)s,%(flagged)s)")
data_result={... | Assuming you are using `mysql.connector` (I think you are), define your own converter class:
```
class NumpyMySQLConverter(mysql.connector.conversion.MySQLConverter):
""" A mysql.connector Converter that handles Numpy types """
def _float32_to_mysql(self, value):
return float(value)
def _float64_... | One of your passed values could be of type `numpy.float64` which is not recognized by the MySQL connector. Cast it to a genuine python `float` on populating the dict. | MySQL Connector/Python - insert python variable to MySQL table | [
"",
"python",
"mysql",
"insert",
"mysql-connector-python",
""
] |
I have a table which contains, apart from other, such fields: `id integer, status_id integer, add_date date`.
I would like to execute a query similar to this:
`update table set status_id = new_status_id where status_id = old_status_id`
but one that would only update a given percent of values, say 50%. Moreover, the ... | ```
update table
set status_id = new_status_id
where
status_id = old_status_id
and random() < 0.5
``` | This query will give you `id` of the rows, you want to update:
```
SELECT *
FROM
(SELECT id,
count(id) OVER (PARTITION BY add_date) cnt,
row_num() OVER (PARTITION BY add_date ORDER BY id) rn
FROM table
WHERE status_id = old_status_id) sub
WHERE rn <= cnt * 0.5 -- your percentage
-- WHERE rn <= cnt * ... | How to update only a certain percent of matching values | [
"",
"sql",
"postgresql",
"sql-update",
""
] |
Is there any efficient way using any Python module like `PyWind32` to interact with already existing Native OS dialog boxes like 'Save As' boxes?
I tried searching on Google but no help.
**EDIT:**
1: The Save As dialog box is triggered when user clicks on a Save As dialog box on a web application.
2: Any suggestion... | While looking for a possible solution for this I came across several solutions on SO and otherwise.
Some of them were using `AutoIT`, or editing browsers profile to make it store the file directly without a prompt.
I found all this solution too specific like you can overcome the issue for Save As dialog by editing the... | There is a Python module called win32ui. Its found in the [Python for Windows extensions](http://sourceforge.net/projects/pywin32/ "Python for Windows extensions") package. You want the CreateFileDialog function.
[Documentation](http://timgolden.me.uk/pywin32-docs/win32ui__CreateFileDialog_meth.html "Documentation")
... | Which is the best way to interact with already open native OS dialog boxes like (Save AS) using Python? | [
"",
"python",
"windows",
"winapi",
"selenium",
"pywin32",
""
] |
I have some experimental data which looks like this - <http://paste2.org/YzJL4e1b> (too long to post here). The blocks which are separated by field name lines are different trials of the same experiment - I would like to read everything in a pandas dataframe but have it bin together certain trials (for instance 0,1,6,7... | You should use [`read_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html) rather than `from_csv`\*:
```
tracker_data = pd.read_csv(bhpath+i+'_wmet.tsv', sep='\t', header=4)
```
If you want to join a list of DataFrames like this you could use concat:
```
trackers = (pd.read_cs... | I haven't quite got it working, but I think that's because of how I copy/pasted the data. Try this, let me know if it doesn't work.
Using some inspiration from [this question](https://stackoverflow.com/questions/11020935/splitting-one-file-into-two-files-with-python)
```
pat = "TimeStamp\tGazePointXLeft\tGazePointYLe... | iteratively read (tsv) file for Pandas DataFrame | [
"",
"python",
"pandas",
"dataframe",
"eye-tracking",
""
] |
I am trying to run the following:
```
CREATE TABLE IF NOT EXISTS table_name (
user_id int(11) NOT NULL,
other_id int(11) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (other_id) REFERENCES other_table(id),
PRIMARY KEY (user_id, other_id)
);
```
and getting the following error:
```
#1005 - Can't c... | Take a look at this [SO question](https://stackoverflow.com/questions/1085001/mysql-creating-table-with-fk-error-errno-150).
Note the correct answer. *Check column types* They need to match. May be your problem.
In general, Here is the authoritative guide to [FK in Mysql](http://dev.mysql.com/doc/refman/5.1/en/innodb... | Does `users` and `other_table` exist?
You can't have the foreign key references to non-existant tables.
You can add the references afterwards with `alter table`. | I am getting an error trying to create table in phpmyadmin | [
"",
"mysql",
"sql",
"database",
"phpmyadmin",
""
] |
I am learning python, step-by-step. Today is about Object Oriented Programming. I know how to create and use simple classes, but something bugs me. Most of the objects I use in python do not require to call a constructor
How can this works? Or is the constructor called implicitly? Example:
```
>>> import xml.etree.El... | In this case, what's happening is that the `etree.parse()` function is creating the `ElementTree` object for you, and returning it. That's why you don't have to call a constructor yourself; it's wrapped up in the `parse` function. That function creates an `ElementTree` instance, parses the data and modifies the new obj... | `etree.parse` is a Factory function. Their purpose is mainly to be convenient ways of constructing objects (instances). As you can easily verify by [looking at the source](http://hg.python.org/cpython/file/2.7/Lib/xml/etree/ElementTree.py#l1180), the `parse` function does almost exactly as you do in your second example... | Using a python class without calling __init__ method? | [
"",
"python",
"class",
"object",
""
] |
so I built a sentence tokenizer, that splits paragraphs into sentences, words, and characters... each of these being a data type. but the sentence system is a two stage system, because things like '. . .' throw it off, sense it goes one letter at a time, but it works fine if it's '...' with no spaces.
So the output is... | Ok, here's some working code. Is this roughly what you need?
I'm not too happy with it yet, it looks a bit ugly imho but I want to know if it's the right direction.
```
words = '''Some sentence that is spliced...
and has a continuation.
this cannot be confused by U.S.A.
In that
last sentence...
an abbreviation ended ... | This 'algorithm' tries to makes sense of the input without relying on line endings, so that it *should* work correctly with some input like
```
born in the U.
S.A.
```
The code lends itself to being integrated into a state machine - the loop only remembers its current phrase and "pushes" finished phrases off onto a l... | How can I merge together sentence objects? | [
"",
"python",
"algorithm",
"object",
"append",
""
] |
Suppose I have a dataframe with columns `a`, `b` and `c`. I want to sort the dataframe by column `b` in ascending order, and by column `c` in descending order. How do I do this? | As of the 0.17.0 release, the [`sort`](http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.sort.html) method was deprecated in favor of [`sort_values`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html). `sort` was completely removed in the 0.20.0 release... | As of pandas 0.17.0, `DataFrame.sort()` is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is `DataFrame.sort_values`
As such, the answer to your question would now be
```
df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)
``` | How to sort a pandas dataFrame by two or more columns? | [
"",
"python",
"pandas",
"python-2.7",
"sorting",
"data-analysis",
""
] |
I need little help with TSql :)
```
SELECT TOP (100) PERCENT HSW, NAZWA, COUNT(HSW) AS TEST
FROM _Katalogi.dbo.ZBIOR_NAZW
WHERE hsw = '3768917680'
GROUP BY HSW, NAZWA
```
Now I get this results
```
3768917680 PODKŁADKA UTWARDŹ. 1
3768917680 ŚRUBA SAMOZABEZPIECZJĄCA 1
3768917680 PODKŁADKA ... | ```
SELECT *
FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY HSW ORDER BY CNT DESC) rn
, *
FROM (
SELECT COUNT(*) OVER (PARTITION BY HSW, NAZWA) as CNT
, *
FROM FROM _Katalogi.dbo.ZBIOR_NAZW
) as SubQuery1
... | Something like this?
```
SELECT HSW, NAZWA, COUNT(HSW) AS TEST
FROM _Katalogi.dbo.ZBIOR_NAZW
WHERE hsw = '3768917680'
GROUP BY HSW, NAZWA
HAVING COUNT(HSW) =
(
SELECT TOP 1 COUNT(HSW) AS TEST
FROM _Katalogi.dbo.ZBIOR_NAZW
WHERE hsw = '3768917680'
GROUP BY HSW, NAZWA
ORDER BY COUNT(HSW) DESC... | Take max from SubQuery | [
"",
"sql",
"t-sql",
""
] |
I am trying to edit some text files I have in order to add value to one of the columns. I would like to add two new digit to the second column of my files where are separated with space. The first column would ended on the 13 character, then there is two space and then add the new two digits and the other columns would... | ```
with open('infile.txt', 'rb') as infile, open('outfile.txt', 'wb') as outfile:
outfile.writelines(line[:15] + '32' + line[15:] for line in infile)
``` | Use `str.split`:
```
col = 2
#just pass filenames to your function and use `with` statement for handling files.
with open(infile) as f, open(outfile, 'w') as out:
for line in f:
spl = line.split(None, col)
spl[col -1] = '32' + spl[col -1]
out.write(" ".join(spl))
...
399299.855212 ... | add new digits to a column of a text file in Python | [
"",
"python",
"text-files",
"edit",
""
] |
I have a question about command line methods of searching. Here is my situation.
1. I have a data file which contains a bunch (~36,000) of objects' identification numbers, which looks like this:
```
# ID
85000213
85000234
85000246
85000247
85000249
85000250
...
```
2. I also have a direc... | This is pretty easy in python:
```
import os.path
with open('idfile') as fin:
header = next(fin) #read the `#ID` comment header line. Don't use it.
for line in fin:
fname = 'datafileID{0}.csv'.format(line.strip())
if not os.path.exists(fname):
print fname
``` | From `bash`:
```
{
# Read the header into a variable, but ignore it
read -r hdrLine
while read -r fileID; do
[[ -f $DIRECTORY/datafileID$fileID.csv ]] || echo "$fileID not found"
done
} < id_list.txt
```
Everything in `{...}` reads from the file `id_list.txt`. The first `read` statement reads and di... | Checking That All Files Are Present | [
"",
"python",
"bash",
"csv",
"diff",
""
] |
I have the following bottleneck and am wondering if anyone can suggest ways to speed it up.
I have three lists `x,y,z` of length `N`. and I apply the following [summation](http://en.wikipedia.org/wiki/Correlation_sum).
```
def abs_val_diff(x1, x2, x3, y1, y2, y3):
""" Find the absolute value of the difference bet... | I believe you can utilize numpy a little more efficiently by doing something like the following. Make a small modification to your function to use the numpy.sqrt:
```
import numpy as np
def abs_val_diff(x1, x2, x3, y1, y2, y3):
""" Find the absolute value of the difference between x and y """
return np.sqrt((... | Is there any reason you actually need to take the square root in your function? If all you do with the result is to compare it against a limit why not just square both sides of the comparison?
```
def abs_val_diff_squared(x1, x2, x3, y1, y2, y3):
""" Find the square of the absolute value of the difference between ... | Speeding up summation for loop in python | [
"",
"python",
"numpy",
"scipy",
""
] |
I have a string which can contain any number of words separated by a space. I am sending this string as a parameter from vb to sql via sqlCommand. How can i split this into an array in sql or send it as array from vb altogether to search the table.
The sql search must return all those rows in which each row contains a... | ```
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand("sp_GetCustomerByIDS", connection)
command.CommandType = System.Data.CommandType.StoredProcedure
'Here is how you pass in YourString seperated with comma's
command.Parameters.AddWithValue("@CustomerIDS", YourString... | Besides using table parameters, you can parse the string into a table variable. This is what the pseudocode would be like:
```
Declare a table variable with one VARCHAR column
While the string is not empty
Grab everything up to the first space and insert it into the table variable
Remove the first word from th... | How to search by an array in a stored procedure? | [
"",
"sql",
"vb.net",
""
] |
For debugging purpose I want to create pseudo "result set" in order to join them, like:
```
with tmp_tbl as ( select v from dual where v in ('cat', 'dog', 'fish') )
select read_tbl.* from tmp_tbl
left outer join read_tbl on real_tbl.id = tmp_tbl.id;
```
I understand that above expression is invalid and can be trans... | I'm still not quite sure what you're trying to do, but it looks to me like you want a dummy table with fixed values. If so you can select multiple dummy values from `dual` and `union all` the results, which will give you multiple rows. You can then use that as a sub-select, or if you're effectively masking a real table... | For this purpose you can use [subquery factoring](http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_10002.htm#i2077142), also known as “the with clause”
```
with t as
( select v from dial where v in ('cat','dog','fish') )
Select * from t
```
Oracle may decide to materialize this result set internally o... | How to create temporary result set from selected set of data in SQL? | [
"",
"sql",
"oracle",
""
] |
I've been working with Tornado and have gotten very used to it's overall style and syntax. Currently, I would like to write a website (in Python) that does not require the asynchronous, non-blocking capabilities of Tornado. Obviously, I can use frameworks like Django or Pylons, but I was wondering if there was a partic... | My favorite "minimal" frameworks are:
Flask <http://flask.pocoo.org/docs/> and Pyramid <http://www.pylonsproject.org/>.
Big difference to tornado is that they are WSGI (hence blocking) and have lots of web-site-like plugins for the things you need to do deploying web-sites.
Flask has lots of examples around and is re... | Turbo gears 2 looks promising as it has been built on top of the experience of several next generation web frameworks including TurboGears 1, Django, and Rails
[Turbo gears 2](http://turbogears.org/#the-next-generation-web-framework-that-scales-with-you) | A blocking equivalent to Tornado? | [
"",
"python",
"django",
"tornado",
""
] |
I have this code:
```
def save_to_gcs(self, img, img_obj):
'''
Image data, Image metadata object -> Blob Key
Given an image and image metadata, stores it in a GCS bucket
'''
bucket = '/foo'
filename = bucket + '/' + str(img_obj['filename'])
self.tmp_filenames_to_clean_up = []
logging.... | Same thing happened to me and it baffled me. I got it working by following the steps on [this page](https://developers.google.com/appengine/docs/python/googlestorage/) under the Prerequisites section. A couple notes though:
* For number 2, make sure you go to the [APIs Console](https://code.google.com/apis/console) an... | The documentation is confusing for granting access to your app engine app (which is most likely your problem). Here is what worked for me in the latest [Google Cloud Console](https://cloud.google.com/console):
1. In the Google Cloud Console, click your project, then "APIs & auth". Turn on "Google Cloud Storage" and "G... | ForbiddenError when attempting to write file to GCS from GAE python App | [
"",
"python",
"google-app-engine",
"google-cloud-storage",
""
] |
I have a **table** which looks like this
```
col1, col2
a,C
a,D
a,C
a,D
```
I want to find out that for **a** in `col1`, what is the (Number of rows with **C** - Number of rows with **D**).
If I were to find the two numbers it will simply be
```
SELECT COUNT(1) FROM mytable where COL1='a' and COL2='C'
SELECT COUNT(... | Thanks folks for the quick responses. For me, the following code snippet worked.
```
SUM( CASEWHEN (COL2='D', 1, -1))
```
And a slightly fuller version of this is
```
SUM( CASE WHEN COL2='C' THEN -1 WHEN COL2='D' THEN 1 ELSE 0 END)
```
I would recommend the fuller version. | Here is one way:
```
SELECT SUM(CASE WHEN col2 = 'C' THEN 1 ELSE 0 END) Col2C,
SUM(CASE WHEN col2 = 'D' THEN 1 ELSE 0 END) Col2D,
SUM(CASE WHEN col2 = 'C' THEN 1 WHEN col2 = 'D' THEN -1 ELSE 0 END) [Col2C-Col2D]
FROM myTable
WHERE col1 = 'a'
``` | Case when to find the difference in the number of counts of particular kind of rows. | [
"",
"sql",
""
] |
I am trying to use bash functions inside my python script to allow me to locate a specific directory and then grep a given file inside the directory. The catch is that I only have part of the directory name, so I need to use the bash function find to get the rest of the directory name (names are unique and will only ev... | Have you tried using the [glob](http://pymotw.com/2/glob/) module as opposed to find?
```
import glob
glob.glob("/path/to/directory/*/SomeDir/path/*")
```
You can look past multiple dirctories using \*\*:
```
glob.glob("/path/**/SomeDir/path/*")
```
and that would match /path/to/your/SomeDir/path/file. | evidently `p1.communicate()[0].strip('\n')` is returning an empty string. are you really using the hardcoded value `"/path/to/directory"` as in your example? | Different results when running in python interpreter vs. script file | [
"",
"python",
"bash",
"grep",
"subprocess",
""
] |
How can I get the full name of the current view (my\_app.views.index) in a template in Django 1.5?
With forms, I have an object called "view" in the template which I read using a template tag.
But with DetailViews I doesn't see anything similar.
Is there a way using a custom template processor?
Thanks
**EDIT**
Sit... | Just [set attribute](https://docs.python.org/2/library/functions.html#setattr) to request object in view:
```
setattr(request, 'view', 'app.views.func')
```
and check this in template:
```
{% if request.view == 'app.views.func' %}
do something
{% endif %}
```
It worked for me. | Type just in view
```
{% with request.resolver_match.view_name as view_name %}
...
{{ view_name }}
...
{% endwith %}
``` | Django get current view in template | [
"",
"python",
"django",
"django-templates",
"django-views",
""
] |
Suppose I have a list of functions
```
f1(x,y),f2(x,y),....
```
How can I define the function below:
```
z(x,y)=f1(x,y)+f2(x,y)+...
```
I want to be able to specify x later. So if somebody puts the y=c value, I want the z function to become a function of x! In the simple case when you you have one function, f, and ... | Tweaking the previous answers, we can throw in `functools.partial` to create the desired behavior.
We can do a partial function call (similar to the haskell construct) to produce new functions from incompletely applied functions. Check it out:
```
from functools import partial
funcs = [lambda x, y: x + y] * 10 # a l... | Can be useful for 10s of functions:
```
def z(x,y,functions):
return sum(F(x,y) for F in functions)
```
So you can use it like:
```
z(x,y,(f,g,h))
```
Or if the number of functions comes from a list:
```
z(x,y,list_of_functions)
``` | How to define sum of multiple arbitrary functions? | [
"",
"python",
"function",
""
] |
I've done some searching and can't figure out how to filter a dataframe by
```
df["col"].str.contains(word)
```
however I'm wondering if there is a way to do the reverse: filter a dataframe by that set's compliment. eg: to the effect of
```
!(df["col"].str.contains(word))
```
Can this be done through a `DataFrame` ... | You can use the invert (~) operator (which acts like a not for boolean data):
```
new_df = df[~df["col"].str.contains(word)]
```
where `new_df` is the copy returned by RHS.
*contains also accepts a regular expression...*
---
If the above throws a ValueError or TypeError, the reason is likely because you have mixed... | I was having trouble with the not (~) symbol as well, so here's another way from another [StackOverflow thread](https://stackoverflow.com/questions/11350770/pandas-dataframe-select-by-partial-string):
```
df[df["col"].str.contains('this|that')==False]
``` | Search for "does-not-contain" on a DataFrame in pandas | [
"",
"python",
"pandas",
"contains",
""
] |
I want to put all my `link` tags in `<head>`.
However, I don't know how to render all the `link` tags in the `head` of my DOM when I include shared templates via the built in `include` tag. So my `link` tags are rendered wherever I happen to include my shared templates. I've added code below to better illustrate my pr... | I found a hacky way to do this. I'm not super pleased with it. I found that I can use simple `if` blocks to toggle which sections of my template I want to render with the `include` tag. This allows me to include my references and content separately. (Note, I could solve this problem by separating my references and cont... | I think you are lookig for `{{block.super}}`
for example Layout.html:
```
<html>
<head>
{% load staticfiles %}
{% block references %}
<link rel="stylesheet" href="{% static "mySharedTemplateStylesheet.css" %}" type="text/css">
{% endblock %}
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
```... | static files and django templates | [
"",
"python",
"css",
"django",
"dom",
"django-templates",
""
] |
I have a requirement in which i have to force the sql not to use a particular index which exists on a table.
for example,
```
create table t1(id varhcar2(10),data1 varchar2(3000));
create table t2(id varhcar2(10),data2 varchar2(3000));
create index id1 on t1(id);
select * from t1,t2 where t1.id=t2.id;
```
I cannot... | Try using [NO\_INDEX](https://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements006.htm#BABHJBIB) hint
For instance
```
SELECT /*+ NO_INDEX(t1 id1) */
FROM t1,
t2
WHERE t1.id = t2.id;
``` | There's a general principle that for every query for which you want to specify the execution plan, you need something like two or three hints per table.
In this case, you're probably looking for a hash join resulting from two full table scans, which is fairly simple so the hint block would be something like:
```
sele... | How to force oracle to not to use an index | [
"",
"sql",
"oracle",
"query-performance",
"hints",
""
] |
I am creating an adaptor to custom data from a client. I cannot change their schema or modify the values in their tables, though I can suggest new indices. The approach is to use CTEs to join and reformat the custom data to use our column names, enumerated values, etc. Once the data is reformatted, our standard CTEs ca... | It looks like you already are building your query dynamically so when you get a value from your tool that needs to be filtered on you could build a query with a where clause that looks something like this.
[SQL Fiddle](http://sqlfiddle.com/#!3/d4a82/2)
**MS SQL Server 2008 Schema Setup**:
```
create table YourTable
... | You said you can't change the schema, but I'm thinking outside the box here. You could add a new database that has views that look into the existing database. For example:
```
use NewViewDb
GO
CREATE VIEW dbo.[T1T2View]
AS
SELECT field1, field2, COALESCE(field3, 'default value'), ...
FROM RealDb.dbo.Table1 t1 LEFT JO... | Need SARGABLE way to filter records and also specify a default value for NULLs | [
"",
"sql",
"sql-server",
"performance",
""
] |
I have the following code:
```
scores = [matrix[i][i] / sum(matrix[i]) for (i, scores) in enumerate(matrix)]
```
My problem is that `sum(matrix[i])` could be 0 in some cases, resulting in a `ZeroDivisionError`. But because `matrix[i][i]` is also 0 in that case, I solved this as follows:
```
scores = [divide(matrix[i... | Yes, in Python it's called the [conditional expression](http://docs.python.org/reference/expressions.html#conditional-expressions):
```
[matrix[i][i] / sum(matrix[i]) if sum(matrix[i]) != 0 else 0
for (i, scores) in enumerate(matrix)]
``` | ```
[(lambda x, y: 0 if y == 0 else x/y)(row[i], sum(row))
for i, row in enumerate(matrix)]
``` | Preventing dividing by zero in list comprehensions | [
"",
"python",
"list-comprehension",
"divide-by-zero",
""
] |
I have a python script which has a `while(1)` condition , takes input from a table in database
processes it and writes something to `stdout` but I am unable to redirect its output to a file.I tried all standard methods and found maybe because the script never stops and I have to
stop it with `Ctrl-Z` it is unbale to ap... | I'm guessing that it never writes a newline? If that's true, you need to `sys.stdout.flush()` occasionally. | You could also disable I/O buffering with the `-u` option: `python -u yourscript.py`. (This can diminish performance in some cases.) | Redirection of output in infinetely running python script | [
"",
"python",
""
] |
I am writing documentation for a project and I would like to make sure I did not miss any method. The code is written in Python and I am using PyCharm as an IDE.
Basically, I would need a REGEX to match something like:
```
def method_name(with, parameters):
someVar = something()
...
```
but it should NOT mat... | I don't know python, but I do know my regex.
And your regex has issues. First of all, as comments have mentioned, you may have to escape the closing parenthesis. Secondly, you don't match the new line following the function declaration. Finally, you look for single or double quotations at the START of a line, yet the ... | You mentioned you were using PyCharm: there is an inspection "Missing, empty, or incorrect docstring" that you can enable and will do that for you.
Note that you can then change the severity for it to show up more or less prominently.
 | How to find undocumented methods in my code? | [
"",
"python",
"pycharm",
""
] |
I have an `ActiveRecord` model with the standard `created_at`, `updated_at` timestamps. I want to run a query to find all records created or updated in a time range.
It possible to do this in a single ActiveRecord query?
The following works great for a single clause (just querying on `created_at`, for example).
```
... | You'll have to write your own statement if you want to `OR` two conditions together:
```
Item.where("(created_at BETWEEN ? AND ?) or (updated_at BETWEEN ? and ?)", 2.weeks ago, 1.week ago, 2.weeks_ago, 1.week_ago)
``` | You overcomplicate your code by searching for `created_at` AND `updated_at`. You only need to search for `updated_at` because that gets set at a create too. So the solution for your problem is:
```
range = 2.weeks.ago .. 1.week.ago
Item.where(:updated_at => range)
``` | Find ActiveRecord objects created or updated in a time range | [
"",
"sql",
"ruby-on-rails",
"activerecord",
""
] |
So I'm a bit curious about why this doesn't work.
How come code like:
```
for a in range(10) and b in range(10):
print a + b
```
generates an error that says 'b is not defined'?
Also, code like:
```
for a,b in range(10):
print a + b
```
generates an error: 'int objects are not iterable'.
Why? I haven't estab... | ```
for a,b in zip(range(10),range(10)):
print a + b
```
should work great... assuming I understood your question properly
if not then
```
for a in range(10):
for b in range(10):
print a+b
```
or even `[a+b for a in range(10) for b in range(10)]` | Other answers explained the right way to do it, but nobody explained what was wrong with what you did yet.
```
for a in range(10) and b in range(10):
print a + b
```
That's a cute idea of some intuitive syntax, but Python doesn't know that one. The precedence of what you programmed actually works out like this:
``... | Using the 'And' Operator in a For-Loop in Python | [
"",
"python",
"for-loop",
"typeerror",
""
] |
How to get last Thursday of every month in a year 2013 in oracle? i need to update this date into my table.
i need a output like
```
Last Thursday in a year 2013
----------------------
31.01.2013
28.02.2013
28.03.2013
24.04.2013
30.05.2013
27.06.2013
25.07.2013
29.08.2013
26.09.2013
31.10.2013
28.11.2013
26.12.2013
... | This will do it:
```
select next_day (last_day (add_months(date '2013-01-01', rownum-1))-7, 'THU') as thurs
from dual
connect by level <= 12;
THURS
---------
31-JAN-13
28-FEB-13
28-MAR-13
25-APR-13
30-MAY-13
27-JUN-13
25-JUL-13
29-AUG-13
26-SEP-13
31-OCT-13
28-NOV-13
26-DEC-13
12 rows selected.
```
Explanation:
1)... | I'd go with `dbms_scheduler`:
```
declare
start_dt date := date '2013-01-01';
months_last_thursday date;
begin
loop
dbms_scheduler.evaluate_calendar_string (
calendar_string => 'FREQ=MONTHLY;BYDAY=-1 THU',
start_date => start_dt,
return_date_after => start_dt... | How to get last thursday of every month in a year 2013 in oracle? | [
"",
"sql",
"oracle",
""
] |
Suppose i have two tables.
```
table one:
| col1 |
- - - - -
| do |
| big |
| gone |
table two
| col1 | col2 | col3 | col4 |
- - - - - - - - - - - - - - -
| do | blah | blah | big |
| big | do | blah | gone |
| blah | blah | blah | blah |
```
how do i search from `table two` such that rows which are displ... | Nasty problem...
```
SELECT two.*
FROM two
WHERE (SELECT COUNT(*) FROM one) =
(CASE WHEN col1 IN (SELECT * FROM one) THEN 1 ELSE 0 END +
CASE WHEN col2 IN (SELECT * FROM one) THEN 1 ELSE 0 END +
CASE WHEN col3 IN (SELECT * FROM one) THEN 1 ELSE 0 END +
CASE WHEN col4 IN (SELECT * FROM... | Perhaps the trickiest part of this is guaranteeing that *all* the columns are covered in the second table. It is not enough just to count them, you also have be sure that all are the set:
```
select t.*
from two t left outer join
one o1
on o1.col1 = t.col1 left outer join
one o2
on o2.col1 = t.col2... | Search from a table using values of a column of another table | [
"",
"sql",
""
] |
I have 2 tables
```
TBL_HEADER
----------
HEADER_ID
COST_CENTER
TBL_RESULTS
-----------
WEEK_NO
COST_CENTER
HEADER_ID_FK
```
I have a requirement to copy all of the COST\_CENTER\_CODES from TBL\_HEADER into TBL\_RESULTS
joining on the HEADER\_ID > HEADER\_ID\_FK.
I tried this but the subquery is returning multi... | You want a correlated subquery, not a subquery with a join:
```
UPDATE TBL_RESULTS
SET COST_CENTRE = (SELECT H.COST_CENTRE
FROM TBL_HEADER H
WHERE H.HEADER_ID = TBL_RESULTS.HEADER_ID_FK
)
```
The extra reference to `tbl_results` was causing problems. | ```
UPDATE
TBL_RESULTS R
SET
COST_CENTRE = (
SELECT
H.COST_CENTRE
FROM
TBL_HEADER H
WHERE
H.HEADER_ID = R.HEADER_ID_FK
)
``` | Update multiple rows on second table based on first table data | [
"",
"sql",
"oracle10g",
""
] |
im making a pygame and im trying to make the game progessively harder by speeding up thee enemies every ten seconds
here is the method Im trying:
```
def time_pass(self):
#timer for main game play
self.time_passed = time.clock()
if self.time_passed == (self.start_time + 10):
self.str_spd1 += 2
... | Python 2.x does not have a reliable way to count seconds since launch.
`time.clock()` is very wrong—on any platform other than Windows, it's counting CPU time instead of wall clock time.
`time.time()` is closer, in that it's wall clock on every platform. It's not guaranteed to have sub-second precision, but when you'... | in `__init__`: `self.i = 0`
```
if self.time_passed >= (self.start_time + 10 * self.i):
self.i += 1
...
``` | Changing variables after a certain amount of time | [
"",
"python",
"variables",
"time",
"pygame",
""
] |
I have a table called fields that looks like this:
```
Name | Table
---------------+----------------
DateFound | Table1
DateUpdate | Table2
DateCharge | Table3
DateLost | Table4
DateDismissed | Table5
```
And what I want to do is change the year for all of those fields in their specified... | Try with cursor and dynamic sql, something like this.
```
DECLARE @changeYear datetime
SET @changeYear = '2013-01-01'
DECLARE @tableName varchar(50), @columnName varchar(50)
Declare updateTime_Cursor Cursor FOR
select name, table from fields
OPEN updateTime_Cursor
FETCH NEXT FROM updateTime_Cursor
INTO @column... | I have not tested this, but I think you can run this for each table/field it will do the trick.
```
UPDATE Table1
SET DateFound = DATEADD(YY, DATEDIFF(YY, DateFound, getdate()), DateFound)
``` | Updating data from multiple tables based on a row in another table | [
"",
"sql",
"sql-server",
"select",
""
] |
I have a program that recursively goes through 2 directories and puts the filename:sha256hash into 2 dicts, folder1 and folder2.
What I want to do is a comparison of the hashes and if the hashes match but the key is different, pub the key into a new list called "renamed". I have the logic in place to account for delet... | You can flip your `files1` and `files2` dicts:
```
name_from_hash1 = {v:k for k, v in file1.items()}
name_from_hash2 = {v:k for k, v in file2.items()}
```
(The flipping idiom I found on [this SO answer](https://stackoverflow.com/a/483833/400793).)
Then,
```
renamed = []
for h in name_from_hash1:
if h in name_... | I've got a simple solution for you: rather than having the filenames as keys and hashes as values, have the hashes as keys and filenames as values (after all, you want the keys to be unique, not the values). You'd simply have to adjust the rest of your program to account for that. (Oops, looks like Bitwise already ment... | Comparing 2 dicts, if values are the same, but key is different, add key to a new list in python | [
"",
"python",
"dictionary",
"comparison",
""
] |
Why am I getting duplicates? Seems simple but it isn't getting though my thick skull.
```
SELECT MOPACTIVITY.MOPID STRICT,
TO_CHAR(MOPNOTES.MOPNOTEDATE,
'yyyy-mm-dd hh24:mi') "MOPNOTEDATE"
FROM MOPUSER.MOPACTIVITY
INNER JOIN MOPUSER.MOPNOTES
ON MOPACTIVITY.MOPID=MOPNOTES.MOPID
```
How do... | Try grouping, and using a maximum:
```
SELECT MOPACTIVITY.MOPID STRICT,
TO_CHAR(max(MOPNOTES.MOPNOTEDATE), 'yyyy-mm-dd hh24:mi') "MOPNOTEDATE"
FROM MOPUSER.MOPACTIVITY
INNER JOIN MOPUSER.MOPNOTES ON MOPACTIVITY.MOPID=MOPNOTES.MOPID
GROUP BY MOPACTIVITY.MOPID
``` | If you only need those columns from `MOPNOTES`, then this should do:
```
SELECT MOPACTIVITY.MOPID STRICT,
TO_CHAR(MN.MOPNOTEDATE,
'yyyy-mm-dd hh24:mi') "MOPNOTEDATE"
FROM MOPUSER.MOPACTIVITY
INNER JOIN (SELECT MOPID, MAX(MOPNOTEDATE) AS "MOPNOTEDATE"
FROM MOPUSER.MOPNOTES
... | Why Duplicates in my join | [
"",
"sql",
"oracle",
"select",
"join",
""
] |
I am trying to get a list with a specific output from an index in another list,
for example:
```
L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10,...etc), (...etc)]
multiple_index = [entry[0, 3, 4] for entry in L]
#----> I know this specific code is wrong
```
I would love it if the above code could output:
```
[(0, 3, 4), ... | Use [`operator.itemgetter()`](http://docs.python.org/2/library/operator.html#operator.itemgetter):
```
from operator import itemgetter
multiple_index = map(itemgetter(0, 3, 4), L)
```
or in a list comprehension:
```
multiple_index = [itemgetter(0, 3, 4)(i) for i in L]
``` | Here is one option:
```
L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11), (11, 12, 13, 14, 15, 16)]
multiple_index = [(entry[0], entry[3], entry[4]) for entry in L]
```
Or using [`operator.itemgetter()`](http://docs.python.org/2/library/operator.html#operator.itemgetter):
```
from operator import itemgetter
indices = i... | Python list comprehension with multiple variables | [
"",
"python",
"list",
"list-comprehension",
""
] |
I have the following query
```
SELECT dbo.tblRegion.RegionName,
dbo.tblDistributionLocation.DistributionLocationName,
dbo.tblTSA.TSAName,
TEmailInfo.EmailCM,
COUNT(*) AS EmailCount
FROM dbo.tblArea
INNER JOIN dbo.tblTerritory
ON dbo.tblArea.AreaID = dbo.tblTerritory.AreaID... | Performance tuning is not just flipping a magic switch - it's hard work.
So start with the most obvious : try to reduce your query to the absolute minimum.
E.g.
* why are you selecting `SELECT *` in your inner queries, when you're only ever using a single (or two) columns from that data? Only select what you **reall... | As marc\_s points out, optimization is not a quick thing to do, nor is it a one-trick-fixes-all solution. Your best bet is to read up on the topic (see <http://beginner-sql-tutorial.com/sql-query-tuning.htm> for some starter tips).
You should also read up on the EXPLAIN PLAN tool (or equivalent variation for your DB) ... | Query execution takes too much time | [
"",
"sql",
"sql-server-2008",
""
] |
I'm looking for way to remove every lines before line which contains specific string in multiline string like this:
```
string1
string2
string3
==== bump
string4
string5
string6
==== bump
```
But only first matching one...
At the end I would like to have this as an output:
```
==== bump
string4
string5
string6
===... | ```
import re
text = '''\
string1
string2
string3
==== bump
string4
string5
string6
==== bump'''
print(re.split(r'(=== bump)', text, maxsplit=1)[-1])
```
yields
```
string4
string5
string6
==== bump
``` | ## Alternative Language: Use Perl's Flip-Flop Operator
Assuming that you've stored your text in */tmp/corpus*, you could use the following Perl one-liner:
```
perl -ne 'print if /\A==== bump/ ... /\A==== bump/' /tmp/corpus
```
This leverages the power of Perl's [range operator](http://perldoc.perl.org/perlop.html#Ra... | How to find line with regex and remove any preceding lines | [
"",
"python",
"regex",
""
] |
I am using time.sleep(10) in my program. Can display the countdown in the shell when I run my program?
```
>>>run_my_program()
tasks done, now sleeping for 10 seconds
```
and then I want it to do 10,9,8,7....
is this possible? | you could always do
```
#do some stuff
print 'tasks done, now sleeping for 10 seconds'
for i in xrange(10,0,-1):
time.sleep(1)
print i
```
This snippet has the slightly annoying feature that each number gets printed out on a newline. To avoid this, you can
```
import sys
import time
for i in xrange(10,0,-1):... | This is the best way to display a timer in the console for Python 3.x:
```
import time
import sys
for remaining in range(10, 0, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds remaining.".format(remaining))
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\rComplete! \n")
```... | Display a countdown for the python sleep function | [
"",
"python",
"time",
"sleep",
"stopwatch",
"countdowntimer",
""
] |
I have 3 lists-of-lists.
The sub-lists' field 1 is a name, field 2 is a number, and field 3 is a number. This format is always the same, and doesn't change. There are always the same names in the 3 lists; however, the **order may not be the same**.
```
a = [['jane', '1', '120'], ['bob', '3', '35'], ['joe', '5', '70']... | To illustrate why using the right data structures makes things a lot easier…
Let's say that `a`, `b`, and `c` were actually `dict`s, and your numbers were actually `int`s instead of `str`s. After all, the whole point of a `dict` is to look things up by name, and the whole point of an `int` is to be able to do arithmet... | This seems to give what you want using more pythonic list comprehensions.
```
>>> [[e[0][0], sum(int(r[1]) for r in e), sum(int(r[2]) for r in e)]
for e in zip(a, b, c)]
[['jane', 8, 405], ['bob', 4, 47], ['joe', 8, 200]]
```
If you want it to work with out of order names, you could do something like this
`... | How do I sum multiple lists-of-lists on certain sub-list's fields? | [
"",
"python",
"python-3.x",
""
] |
I have some models and tables in EF that you can see one of those here:

Now when I want to generate database from model it adds 's' to name of tables in generated sql:
```
CREATE TABLE [dbo].[Options] (
[Id] int IDENTITY(1,1) NOT NULL,
[Name] nvarchar(50) NOT NUL... | Just override the OnModelCreating method and remove that “PluralizingTableNameConvention” convention. So you are telling Entity Framework not to pluralise table names, simply add
Updated
```
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTa... | You Should uncheck pluralize tick when you are creating EDMX file | EF pluralize table's name on generating database from model | [
"",
"sql",
"visual-studio-2010",
"entity-framework",
"ef-model-first",
"pluralize",
""
] |
I have two tables which have the same structure, let’s say TA and TB. Most records in TA and TB are the same. There are some records in TA not in TB and some in TB are not in TA. I just want get all the records from TA and TB without duplicity:
```
Select * from TA
Union
Select * from TB
```
This query does give me t... | You could use a `NOT EXISTS` + `UNION ALL`:
```
Select * from TA
UNION ALL
Select * from TB where not exists (select * from TA where TA.KEY_ID = TB.KEY_ID)
```
This gets you all data in `TA` and non-duplicates from `TB`. | Try:
```
SELECT COALESCE(A.ID,B.ID), COALESCE(A.field2,B.field2), etc.
FROM A
FULL JOIN B
ON A.Id = B.ID
``` | rewrite a union query | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I have a list of over 100000 values and I am iterating over these values and checking if each one is contained in another list of random values (of the same size).
I am doing this by using `if item[x] in randomList`.
How efficient is this? Does python do some sort of hashing for each container or is it internally doin... | `in` is implemented by the `__contains__` magic method of the object it applies to, so the efficiency is dependent upon that. For instance, `set`, `dict` and `frozenset` will be hash based lookups, while `list` will require a linear search. However, `xrange` (or `range` in Python 3.x) has a `__contains__` method that d... | You will want to pre-convert your list to a set, where hashing can be used for O(1) lookup.
See <http://wiki.python.org/moin/TimeComplexity>
(Normally, you have to search every element in a 'classical' list to tell if something is in it (unless your data structure also keeps a set of all elements, but that would add ... | How efficient is Python's 'in' or 'not in' operators, for large lists? | [
"",
"python",
"iteration",
"complexity-theory",
""
] |
SQL Server 2008 R2(SP2) 10.50.4263
I have application number in col1 and an indicator (0 or 1) for first time buyers(ftb) in col2. Each application can have 1 or 2 applicants. For applications with two applicants, I get two entries for application as so:
```
application ftb
----------- ---
1234 0
12345 ... | ```
SELECT
application,
MAX(ftb) AS ftb
FROM
yourTable
GROUP BY application
```
I understood your question like you want to have only the rows presented in your desired output in the table and delete the others, right? The simplest way to achieve this, is to use a temporary table.
```
SELECT
application,
MAX(ftb) AS ... | To return the sequence number of a row within a partition of column "application", use the ranking function [ROW\_NUMBER](http://msdn.microsoft.com/en-us/library/ms186734.aspx) with the ORDER BY clause on column "ftb". So you can delete all the duplicate rows
```
;WITH cte AS
(
SELECT ROW_NUMBER() OVER(PARTITION B... | Remove duplicates from col1 when condition in col2 is met | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I'm setting up Travis-CI for the first time. I install scipy in what I believe is the standard way:
```
language: python
python:
- "2.7"
# command to install dependencies
before_install:
- sudo apt-get -qq update
- sudo apt-get -qq install python-numpy python-scipy python-opencv
- sudo apt-get -qq install libh... | I found two ways around this difficulty:
1. As @unutbu suggested, build your own virtual environment and install everything using pip inside that environment. I got the build to pass, but installing scipy from source this way is very slow.
2. Following the approach used by the pandas project in [this .travis.yml file ... | This is covered in the official conda documentation: [Using conda with Travis CI](http://conda.pydata.org/docs/travis.html#using-conda-with-travis-ci).
---
> ## The `.travis.yml` file
>
> The following shows how to modify the `.travis.yml` file to use [Miniconda](http://conda.pydata.org/miniconda.html) for a project ... | scipy ImportError on travis-ci | [
"",
"python",
"scipy",
"travis-ci",
""
] |
I want to separate code in different class and put them to different files. However those class are dependent on each other.
**main.py:**
```
from lib import A, B
def main():
a = A()
b = B()
a.hello()
b.hello()
if __name__ == '__main__':
main()
```
**lib/\_*init*\_.py**:
```
from a import A
fr... | Instead of importing the modules on top, you could import the other module within the hello function.
```
class B():
def __init__(self):
print "B"
def hello(self):
from lib import A
print "hello B"
a = A()
``` | When you have two classes depending on each other usually means that either they really belong to the same module or that you have a too tight coupling that should be resolved using dependency injection.
Now there are indeed a couple corner cases where importing from within the function is the "least worst" solution b... | Simple cross import in python | [
"",
"python",
"import",
"cross-reference",
""
] |
I'm trying to draw an arbitrary quadrilateral over an image using the polylines function in opencv. When I do I get the following error
> OpenCV Error: Assertion failed (p.checkVector(2, CV\_32S) >= 0) in
> polylines, file
> /tmp/buildd/ros-fuerte-opencv2-2.4.2-1precise-20130312-1306/modules/core/src/d
> rawing.cpp, l... | The problem in my case was that `numpy.array` created `int64`-bit numbers by default. So I had to explicitly convert it to `int32`:
```
points = np.array([[910, 641], [206, 632], [696, 488], [458, 485]])
# points.dtype => 'int64'
cv2.polylines(img, np.int32([points]), 1, (255,255,255))
```
(Looks like a bug in cv2 py... | This function is not enough well documented and the error are also not very useful. In any case, [`cv2.polylines`](http://docs.opencv.org/modules/core/doc/drawing_functions.html#polylines) expects a list of points, just change your line to this:
```
import cv2
import numpy as np
img = np.zeros((768, 1024, 3), dtype='... | Opencv polylines function in python throws exception | [
"",
"python",
"opencv",
"numpy",
"points",
""
] |
Let's say I have a string that looks something like:
```
first_string = "(white cats || 'dogs) && ($1,000 || $500-$900' || 1,000+)"
```
And I replace each word with the text "replace" by doing:
```
new_string = re.sub(r'[\w$\-+,][\w$\-+,\t ]*[\w$\-+,]|[\w$\-+,],', "replace", first_string, flags=re.IGNORECASE)
```
A... | You can check your string structure with this pattern:
```
^(?:(?:^|\s*[&|]{2}\s*)\([^|)]+(?:\s*\|\|\s*[^|)]+)*\))*$
```
if `&&` can be inside parenthesis too, you can use:
```
^(?:(?:^|\s*[&|]{2}\s*)\([^&|)]+(?:\s*[&|]{2}\s*[^&|)]+)*\))*$
```
If your replacement pattern is good you don't need to check if the paren... | Not used regex.
```
def is_valid(s):
def surrounded_by_parens(s, next_validation):
s = s.strip()
return s.startswith('(') and s.endswith(')') and next_validation(s[1:-1])
def separated_by_bars(s):
return all(x.strip() == 'replace' for x in s.split('||'))
return all(surrounded_by_par... | How to Use a Regex to Validate the Format of a String | [
"",
"python",
"regex",
""
] |
I have a table I am trying to clean up so I just need the first address in the table for each `ClientId`
Table `Addresses` has these columns
```
Pk[Id]
[ClientId]
[AddressLine1]
[AddressLine2]
```
Query I use:
```
SELECT *
FROM Addresses
ORDER BY ClientId
```
result =
```
1 1 foo bar
2 1 foo2 bar2
... | SQL Server requires that when using a GROUP BY you need to either use an aggregate function on the columns in the select list or add them to the GROUP BY.
Your original query could be changed to use the following:
```
select a.id, a.clientid, a.address1, a.address2
from addresses a
inner join
(
select clientid, M... | You are getting multiple lines because you're selecting a field you don't want to be grouping by. If you just want the first entry for each clientID you can use an analytic function like ROW\_NUMBER
Try:
```
SELECT *
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY clientid ORDER BY ID) as RowRank
FROM Addresses)s... | MS SQL Server 2008 error on GROUP BY | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
In my stored procedure I need to select based on the user input
The query would be like this
```
SELECT A,B FROM MYTABLE WHERE B=array[0] OR B=array[1] OR B=array[2]
```
The number of items in array is unknown to me. The user selection will decide the number of elements in the array.
How can I achieve this? If I co... | Instead of array you can create an [User Defined Table type](http://msdn.microsoft.com/en-us/library/bb522526%28v=sql.105%29.aspx)
```
CREATE TYPE dbo.type_name AS TABLE
(
column1 INT NOT NULL
)
```
Pass a single columned `DataTable` from page as parameter (values are same as in that array) .
And in procedure y... | You could have a look at [Use Table-Valued Parameters (Database Engine)](http://msdn.microsoft.com/en-us/library/bb510489.aspx)
> Table-valued parameters are declared by using user-defined table
> types. You can use table-valued parameters to send multiple rows of
> data to a Transact-SQL statement or a routine, such ... | How can I pass and use array in a stored procedure? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"ado.net",
""
] |
I'm certain this has been asked a million times, but it's difficult to search for something when you don't know the correct terminology :(
I'm attempting (again... I've *never* understood OO, since I got taught it very badly 8 years ago, and avoid it as much as possible, to the horror of every other programmer I know ... | After talking to some much cleverer people than me, the short answer is that what I was trying to do is seemingly impossible. Once an `action` has been defined, it is not possible to change any attribute of it.
At the moment, my knowledge of python isn't great enough to understand exactly why this is (or how I could h... | > 'QToolBar' object has no attribute 'addFile'
Hmm, since you called addFile on self.exitIcon, it looks like you have the wrong kind of object in the self.exitIcon variable. It seems you want it to be a QtGui.QIcon type, but instead it's a QToolBar type.
You should look at where you are making assignments to self.exi... | Very basic OO: changing attribute of a method | [
"",
"python",
"pyqt",
""
] |
If I have the following code:
```
conn = sqlite3.connect('abc.db')
```
.. it will create DB fle called `abc.db` if it doesn't already exist. What do I do if I don't want to create a new file and only want the connection to succeed if the file already exists? | You can check if the file already exists or not:
```
import os
if not os.path.exists('abc.db'):
conn = sqlite3.connect('abc.db')
``` | Use sqlite3\_open\_v2() with either SQLITE\_OPEN\_READONLY or SQLITE\_OPEN\_READWRITE.
As described here:
<http://www.sqlite.org/c3ref/open.html> | Don't want to create a new database if it doesn't already exists | [
"",
"python",
"sqlite",
""
] |
I feel like I'm missing something obvious, but there it is... I would like to go from:
```
lst = [[0, 1, 3, 7, 8, 11, 12], [8, 0, 1, 2, 3, 14], 2]
```
to:
```
output = [0, 1, 3, 7, 8, 11, 12, 8, 0, 1, 2, 3, 14, 2]
```
I can do this with a for loop such as:
```
output = []
for l in lst:
if hasattr(l, '__iter__'... | Here is a pretty straightforward approach that uses a list comprehension:
```
>>> data = [[0, 1, 3, 7, 8, 11, 12], [8, 0, 1, 2, 3, 14], 2]
>>> [a for x in data for a in (x if isinstance(x, list) else [x])]
[0, 1, 3, 7, 8, 11, 12, 8, 0, 1, 2, 3, 14, 2]
```
Here are timing comparisons, it looks like my version is sligh... | You can use `itertools.chain` like this:
```
>>> from itertools import chain
>>> from collections import Iterable
>>> lis = [[0, 1, 3, 7, 8, 11, 12], [8, 0, 1, 2, 3, 14], 2]
def solve(lis):
for x in lis:
if isinstance(x, Iterable) and not isinstance(x, basestring):
yield x
else:
... | Concatenation of inner lists or ints | [
"",
"python",
"numpy",
"concatenation",
"flatten",
""
] |
Here is the table structure:
```
ID
FIELD_A
FIELD_B
DATE_FIELD
VALUE_FIELD
```
The ID field is just a number that increments with each record. We get 2 "sets" of records in a day where FIELD\_A, FIELD\_B, DATE\_FIELD are exactly the same but the VALUE\_FIELD can be different. We get a morning set and an evening set. ... | You would use the analytic function `row_number()`:
```
create view vw_afternoon as
select id, field_a, field_b, date_field, value_field
from (select t.*,
row_number() over (partition by field_a, field_b, date_field
order by id desc
... | If anyone needs an answer that works in SQL environments that don't support partition\_by, I think you can also use:
```
create view my_view as SELECT * FROM my_table WHERE id IN
(SELECT max(id) FROM my_table GROUP BY field_a, field_b, date_field)
``` | oracle sql 2 records per day per unique fields, how to get the latest | [
"",
"sql",
"oracle",
""
] |
I am trying to use the values of a 1-dim array to slice/return the rows and columns from a 2-dim array in Numpy. For example, say I have the following one dim array:
[1,3,5)]
and the following 2 dim array:
```
array([[1, 0, 0, 0, 0, 0],
[0, 4, 0, 0, 0, 1],
[0, 0, 3, 0, 0, 0],
[0, 1, 0, 7, 0, 10],
... | Is this what you want?
```
>>> a = array([[1, 0, 0, 0, 0, 0],
... [0, 4, 0, 0, 0, 1],
... [0, 0, 3, 0, 0, 0],
... [0, 1, 0, 7, 0, 10],
... [0, 0, 0, 0, 8, 0],
... [0, 2, 0, 0, 0, 9]])
>>>
>>> a[1::2,1::2]
array([[ 4, 0, 1],
[ 1, 7, 10],
[ 2, 0, 9]])
```
Since you... | Maybe could be useful the routine np.meshgrid():
```
a = array([[1, 0, 0, 0, 0, 0],
[0, 4, 0, 0, 0, 1],
[0, 0, 3, 0, 0, 0],
[0, 1, 0, 7, 0, 10],
[0, 0, 0, 0, 8, 0],
[0, 2, 0, 0, 0, 9]])
b = np.array([1, 3, 5])
B = np.meshgrid(b,b)
print a[B].T
Out: [[ 4 0 1]
[ 1 7 10]
[ 2 0 9]]
```
... | Return rows and columns from a 2d array using values from a 1d array in Numpy | [
"",
"python",
"arrays",
"numpy",
""
] |
If I have a dictionary {key : [a b c c d]} and I want to print only the unique values corresponding to each key (In this case, (a,b,d)) what is the most efficient way to do this apart from just looping through each element and keeping a count of it? | If elements are sorted as in your example; you could use [`itertools.groupby()`](http://docs.python.org/2/library/itertools.html#itertools.groupby):
```
from itertools import groupby
print " ".join([k for k, group in groupby(d['key']) if len(list(group)) == 1])
# -> a b d
``` | One option, use [collections.Counter](http://docs.python.org/2/library/collections.html#collections.Counter)
```
from collections import Counter
d = {'k': ['a', 'b', 'c', 'c', 'd']}
c = Counter(d['k'])
print [k for k in c if c[k] == 1]
['a', 'b', 'd']
``` | how to print elements which occur only once in a list, without counting | [
"",
"python",
""
] |
Alright here the question
**Table 1**:
```
Id1, Id2
```
**Table 2**
```
Id, Username
```
Now this `Table 1 Id1` and `Id2` variables are unique keys in `Table 2`
I want to select `Table 1` all values as this
```
Username1, Username2
```
So how can I write this query ?
Full example
**Table 1**
```
1,3
3,5
```
... | ```
SELECT table2_1.Username AS Username1, table2_2.Username AS Username2
FROM table1
JOIN table2 AS table2_1 ON table1.Id1 = table2_1.Id
JOIN table2 AS table2_2 ON table1.Id2 = table2_2.Id
``` | Try this
here is <http://www.sqlfiddle.com/#!2/e10b7/2/0>
```
CREATE TABLE table1
(
Id1 int primary key,
Id2 int
);
INSERT INTO table1
VALUES (1, 3),
(3, 5);
CREATE TABLE table2
(
Id int primary key,
Username varchar(255)
);
INSERT INTO table2
VALUES (1, 'Furkan'),
(3, 'Obama'... | How to select 2 variables from another table SQL server query | [
"",
"sql",
"sql-server",
"t-sql",
"join",
"sql-server-2012",
""
] |
I'm opening files in multiple functions, and it seems a bit messy/superfluous to keep 'gracefully' handling potential IOErrors:
```
try:
fileHandle = open(file, 'r')
except:
print "Error: failed to open file %s" % (file)
sys.exit(2)
```
In what contexts is it acceptable to just:
```
fileHandle = ... | This is the principle of exceptions as implemented in Python and other languages. The exception handling in not necessary *local* to the function that raise the exception.
If some local processing is meaningful, do it. If you can't do anything useful, just let the exception go up in the call stack until a proper excep... | Use the 'with' keyword.
```
with open(file, 'r') as fileHandle:
do_whatever()
```
This code is more-or-less equivalent to
```
try:
fileHandle = open(file, 'r')
except IOError:
pass
else:
do_whatever()
finally:
fileHandle.close()
```
Basically, it makes sure that you open and close your files co... | Python: Necessary to catch open() exceptions? | [
"",
"python",
"coding-style",
""
] |
I have these different lines with values in a text file
```
sample1:1
sample2:1
sample3:0
sample4:15
sample5:500
```
and I want the number after the ":" to be updated sometimes
I know I can split the name by ":" and get a list with 2 values.
```
f = open("test.txt","r")
lines = f.readlines()
lineSplit = lines[0].spl... | You can use the `fileinput` module, if you're trying to modify the same file:
```
>>> strs = "sample4:15"
```
Take the advantage of sequence unpacking to store the results in variables after splitting.
```
>>> sample, value = strs.split(':')
>>> sample
'sample4'
>>> value
'15'
```
Code:
```
import fileinput
for li... | Strings are immutable, meaning, you can't assign new values inside them by index.
But you can split up the whole file into a list of lines, and change individual lines (strings) entirely. This is what you're doing in lineSplit[1] = A\_NEW\_INTEGER
```
with open(filename, 'r') as f:
lines = f.read().splitlines()
fo... | Replace character in line inside a file | [
"",
"python",
"file",
""
] |
Every time I enter 4, 6 or 12 it doesn't accept it. Why? The code looks fine to me. Please tell me how to correct or what to change.
```
import random
def roll_the_dice():
print("Roll The Dice")
print()
repeat = True
while repeat:
number_of_sides = input("Please select a dice with 4, 6 or 12 ... | Haidro gave you the reason, but here is a different way to approach your problem:
```
def get_dice_size():
dice_size = input('Enter the number of sides on the dice: ')
while dice_size not in ['4','6','12']:
print 'Sorry, please enter one of 4, 6 or 12:'
dice_size = input('Enter the number of side... | In Python 3, when using `input()`, it returns a *string*. Thus, you would have something like `"4"`. And `"4" is not 4`.
So in your script, specifically at the `if number_of_sides in [4,6,12]`, it will always be `False`, because you are really saying `if "4" in [4,6,12]` (I'm just doing 4 as an example).
Convert the ... | What is wrong with this Python code? Refuses input | [
"",
"python",
""
] |
I have the following query which will return the number of users in table transactions who have earned between $100 and $200
```
SELECT COUNT(users.id)
FROM transactions
LEFT JOIN users ON users.id = transactions.user_id
WHERE transactions.amount > 100 AND transactions.amount < 200
```
The above query returns the cor... | You can use a CASE expression inside of your aggregate function which will get the result in columns:
```
SELECT
COUNT(case when amount >= 0 and amount <= 100 then users.id end) Amt0_100,
COUNT(case when amount >= 101 and amount <= 200 then users.id end) Amt101_200,
COUNT(case when amount >= 201 and amount <= 3... | One way to do this would be to use a case/when statement in your group by.
```
SELECT
-- NB this must match your group by statement exactly
-- otherwise you will get an error
CASE
WHEN amount <= 100
THEN '0-100'
WHEN amount <= 200
THEN '100-200'
ELSE '201+'
END Amount,
COUNT(*)
FROM
transac... | SQL Group By Number Of Users Within Range | [
"",
"mysql",
"sql",
""
] |
I want to have a map from objects of a class called MyObject to integers. I read some stuff [here](https://stackoverflow.com/questions/4901815/object-as-a-dictionary-key), but didn't understand anything and that doesn't seem to be quite the thing I want. Hash function
can only be used for collision. What I want to do i... | I don't completely understand yor question. My interpretation is that you want to use objects to index some integers. If that is the intent, you can use a `dict`.
```
class MyClass:
# your code here
c1 = MyClass()
c2 = MyClass()
D = dict({c1:1,c2:2})
D[c1] # will return 1
D[c2] # will return 2
``` | You seem to be talking about the id() function. From the [manual](http://docs.python.org/2/library/functions.html#id): Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes ma... | How to map objects to integers in python? | [
"",
"python",
"oop",
"hash",
"dictionary",
""
] |
---
## Situation:
I am tentatively considering a situation to use Django to
1. serve HTML (by Django's template)
2. serve all the static files like CSS, JS from the Django project
and my intent to use Django stops here. After the javascript files are downloaded to client side, they communicates with a Flask backend... | If I were you I would take the Django templates from the designer and convert them to Jinja2, then build the application 100% in Flask. But since you asked...
> is this doable? or does this sound a crazy idea?
Yes to both :)
> Can you kindly give some guidance?
Here is a simple way:
You write the two applications,... | I am a little late to the party but [Application Dispatching](http://flask.pocoo.org/docs/latest/patterns/appdispatch/) should help with this. According to the intro in the documentation this is how it goes:
> Application dispatching is the process of combining multiple Flask
> applications on the WSGI level. You can ... | Using Django along with Flask | [
"",
"python",
"flask",
""
] |
I wish to use the Python `all()` function to help me compute something, but this something could take substantially longer if the `all()` does not evaluate as soon as it hits a `False`. I'm thinking it probably is short-circuit evaluated, but I just wanted to make sure. Also, is there a way to tell in Python how the fu... | Yes, it short-circuits:
```
>>> def test():
... yield True
... print('one')
... yield False
... print('two')
... yield True
... print('three')
...
>>> all(test())
one
False
```
From the [docs](http://docs.python.org/2/library/functions.html#all):
> Return `True` if all elements of the *iterab... | Yes, `all` does use short-circuit evaluation. For example:
```
all(1.0/x < 0.5 for x in [4, 8, 1, 0])
=> False
```
The above stops when `x` reaches `1` in the list, when the condition becomes false. If `all` weren't short-circuiting, we'd get a division by zero when `x` reached `0`. | Does Python's `all` function use short circuit evaluation? | [
"",
"python",
"evaluation",
"short-circuiting",
""
] |
I've been asked to write a query to get all the automatic entries that were placed 1 day before the current day. However, the problem is that the date is in this format and I cannot alter the database.
E.g. 20130329.134405990
I'm not sure how I would do this. I was thinking I trim it to the first 8 digits and then mi... | You can use this to get one day before your current date (SQL SERVER):
```
SELECT DATEADD(day,-1,GETDATE())
```
I think it would be:
```
SELECT *
FROM Table
WHERE LEFT(CAST(datefield AS VARCHAR(25)),8) = CAST(DATEADD(day,-1,GETDATE()) AS VARCHAR(25))
```
Update, wasn't comparing to today as you requested. | Just off the top of my head:
You could run the following query:
```
SELECT * FROM JnlDB WHERE UserCode = 'Automation' AND
SUBSTR(ENTEREDDATE,1,8)=TO_CHAR(SYSDATE-1,'YYYYMMDD');
```
This will work on Oracle.
In SQL Server though:
```
SELECT * FROM JnlDB WHERE UserCode = 'Automation' AND
CONVERT(VARCHAR,L... | Query for Trimming the date in SQL | [
"",
"sql",
"date",
"trim",
""
] |
In a table that contains the Employee ID of every employee, the login time and the logout time for each employee, I need to extract the minimum from login time and maximum from logout time for each day. The problem is that every day an employee can login and logout multiple times. So, we have sample data that looks som... | ```
SELECT username, TRUNC(login_time), min(login_time), max(logout_time)
FROM table_name
GROUP BY username, TRUNC(login_time)
ORDER BY username, TRUNC(login_time);
``` | It could be as simple as:
```
SELECT TRUNC(LOGIN_TIME]),NAME, EMPID, MIN(LOGIN_TIME), MAX(LOGOUT_TIME)
FROM Table_Name
GROUP BY TRUNC(LOGIN_TIME),NAME, EMPID
ORDER BY EMPID, TRUNC(LOGIN_TIME)
```
That will return one line per employee/day, earliest login and latest logout for that employee/day. | How to extract minimum and maximum time from a table in Oracle? | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
""
] |
I use "$ipython notebook --pylab inline" to start the ipython notebook. The display matplotlib figure size is too big for me, and I have to adjust it manually. How to set the default size for the figure displayed in cell? | I believe the following work in version 0.11 and above. To check the version:
```
$ ipython --version
```
It may be worth adding this information to your question.
Solution:
You need to find the file `ipython_notebook_config.py`. Depending on your installation process this should be in somewhere like
```
.config/i... | Worked liked a charm for me:
```
matplotlib.rcParams['figure.figsize'] = (20, 10)
``` | How to set the matplotlib figure default size in ipython notebook? | [
"",
"python",
"matplotlib",
"jupyter-notebook",
""
] |
What I'm trying to do is have a dict that goes like
```
((category1: subcategory1, sub2, sub3), (cat2: sub12, sub22...))
```
However, I also want the subcategories to have their own values as well:
```
((subcat1: subitem1, subitem2), (subcat2: subitem12, subitem22)...)
```
I want to be able to reference the subitem... | You probably want a tree data structure. Have a look at [this github gist](https://gist.github.com/hrldcpr/2012250) for an example of how you implement one with dictionaries in python. | You could store it like this:
```
categories = {
'category1': {
'subcat1': ['subitem1', 'subitem2'],
'subcat2': ['subitem12', 'subitem22']
},
'category2': {
# ...
}
}
``` | Can I use a value as a key for another dict? | [
"",
"python",
"dictionary",
"key",
""
] |
I have one understanding probem:
I want to create user profile for my page, which will have many attributes. But since I am new to User Model of django's auth, i dont know if i can extend that model with new coming attributes that i set for user profile. e.g. address, age, ...
if not, why is User Model there? is it o... | I shall try to explain in the perspective of pre-django 1.5
The django's auth models provides a set of "convenience" methods like login, logout, password reset, etc for you which work seamlessly. It is a very common scenario to have more fields - so One approach would be to create a userprofile model, which either `in... | Since Django 1.5 you can create your own User Model with your custom fields. And tell Django to use that model for auth.
Link to documentation: [Custom User Model](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model)
**Update:**
If you are using Django 1.4, then [django-prima... | django user model - when do i need it? | [
"",
"python",
"django",
"django-models",
"django-users",
""
] |
Given two CIDR addresses say 192.168.2.0/14 and 192.168.2.0/32
How do I check if two ip addresses overlap in "python2.6"??
I have gone through netaddr and it allows to check if
192.168.2.0 is in CIDR address 192.168.2.0/14 by
```
from netaddr import IPNetwork, IPAddress
bool = IPAddress("192.168.2.0") in IPNetwork("... | Using [ipaddr](https://pypi.python.org/pypi/ipaddr):
```
>>> import ipaddr
>>> n1 = ipaddr.IPNetwork('192.168.1.0/24')
>>> n2 = ipaddr.IPNetwork('192.168.2.0/24')
>>> n3 = ipaddr.IPNetwork('192.168.2.0/25')
>>> n1.overlaps(n2)
False
>>> n1.overlaps(n3)
False
>>> n2.overlaps(n3)
True
>>> n2.overlaps(n1)
False
``` | I'll assume you actually want both CIDRs to represent ranges, even though in your example, 192.168.2.0/32 represents only one address. Also note that in 192.168.2.0/14, the .2. is meaningless, because the 14-bit prefix doesn't reach the third octet.
Anyway, there are a several ways to do this. You could notice that fo... | Check if two CIDR addresses intersect? | [
"",
"python",
"ip-address",
"cidr",
""
] |
I have a dictionary of dictionaries, and I'm trying to output the information within them in a certain way so that it will be usable for downstream analysis. Note: All the keys in `dict` are in also in `list`.
```
for item in list:
for key, value in dict[item].items():
print item, key, value
```
This is t... | First, if I understand your structure, the list is just a way of ordering the keys for the outer dictionary, and a lot of your complexity is trying to use these two together to simulate an ordered dictionary. If so, there's a much easier way to do that: use [`collections.OrderedDict`](http://docs.python.org/3/library/c... | To store objects in Python so that you can re-use them later, you can you use the `shelve` module. This a module that lets you write objects to a shelf file and re-open it and retrieve the objects later, but it's operating system-dependent, so it won't work if say you made it on a Mac and later you want to open it on a... | How do I write the contents of nested dictionaries to a file in a certain format? | [
"",
"python",
"output",
"output-formatting",
""
] |
I have two tables Project and Comptes i want dispalay Project and his chef in one Query
so did like this
```
Query q=se.createQuery("SELECT p.idpro,p.IdProjet,p.NomProjet,p.DateDeb,p.DateFin,p.nomimg (SELECT c.Nom,c.Prenom FROM Compte u WHERE u.Id = p.IdChef group by u.id) FROM Projets p ");
listPrj=... | An immediate cause of your problem is in the inner query:
```
SELECT c.Nom, -- <-- Aggregate (min, max, sum etc.) expected here
c.Prenom -- <-- Aggregate (min, max, sum etc.) expected here
FROM Compte u
WHERE u.Id = p.IdChef
GROUP BY u.id
```
when GROUP BY is used, all fields within SELECT sho... | ```
SELECT p.idpro,p.IdProjet,p.NomProjet,p.DateDeb,p.DateFin,p.nomimg,c.Nom,c.Prenom
from projects p,Compte c
where c.Id=p-IdChef
group by c.uid
``` | aggregate function expected before ( in SELECT with subquery | [
"",
"mysql",
"sql",
"hibernate",
"aggregate",
""
] |
I am attempting to use matplotlib to plot some figures for a paper I am working on. I have two sets of data in 2D numpy arrays: An ascii hillshade raster which I can happily plot and tweak using:
```
import matplotlib.pyplot as pp
import numpy as np
hillshade = np.genfromtxt('hs.asc', delimiter=' ', skip_header=6)[:,... | Just [mask](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.masked_where.html) your "river" array.
e.g.
```
rivers = np.ma.masked_where(rivers == 0, rivers)
```
As a quick example of overlaying two plots in this manner:
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
... | An alternate way to do this with out using masked arrays is to set how the color map deals with clipping values below the minimum of `clim` (shamelessly using Joe Kington's example):
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
# Generate some data...
gray_data = np.arange(10000).... | Setting Transparency Based on Pixel Values in Matplotlib | [
"",
"python",
"matplotlib",
"python-imaging-library",
""
] |
I was curious if there was any indication of which of `operator.itemgetter(0)` or `lambda x:x[0]` is better to use, specifically in `sorted()` as the `key` keyword argument as that's the use that springs to mind first. Are there any known performance differences? Are there any PEP related preferences or guidance on the... | According to my benchmark on a list of 1000 tuples, using `itemgetter` is almost twice as quick as the plain `lambda` method. The following is my code:
```
In [1]: a = list(range(1000))
In [2]: b = list(range(1000))
In [3]: import random
In [4]: random.shuffle(a)
In [5]: random.shuffle(b)
In [6]: c = list(zip(a, ... | The performance of itemgetter is slightly better:
```
>>> f1 = lambda: sorted(w, key=lambda x: x[1])
>>> f2 = lambda: sorted(w, key=itemgetter(1))
>>> timeit(f1)
21.33667682500527
>>> timeit(f2)
16.99106214600033
``` | operator.itemgetter or lambda | [
"",
"python",
"python-2.7",
"python-3.x",
""
] |
A table in my database holds values as below,
```
TBLFlow
FlowId FlowName ProcessId
------------------------------------------------
F00 Flow1 PID01-PID02-PID03
F01 Flow2 PID01-PID03-PID02
```
The Name of the process are listed in another table... | I imagined such a monster
```
DECLARE @TBLFlow table (FlowId varchar(20), FlowName varchar(100), ProcessId varchar(1000))
DECLARE @TBLProcess table (ProcessId varchar(20), ProcessName varchar(100))
insert into @TBLFlow values ('F00','Flow1','PID01-PID02-PID03'), ('F01','Flow2','PID01-PID03-PID02')
insert into @TBLProc... | You can try this
```
SELECT F.*,ISNULL(P1.ProcessName,'') + '-' + ISNULL(P2.ProcessName,'') + '-' +
ISNULL(P3.ProcessName,'')
FROM TBLFlow AS F
LEFT JOIN TBLProcess AS P1
ON SUBSTRING(F.ProcessId,0,CHARINDEX('-',F.ProcessId)) = P1.ProcessId
LEFT JOIN TBLProcess AS P2
ON LEFT(RIGHT(F.ProcessId,LEN(F.ProcessId)-CHAR... | Split values by hyphen that exist in the same row and integrate with a INNER JOIN? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I'm creating a simple blog on Flask and I'm trying to implement Flask-Admin to manage my posts. If I go to the admin area I can see a list of all my post from the DB but when I try to create a new one I got the next error:
```
Failed to create model. __init__() takes exactly 4 arguments (1 given)
```
This is my post ... | Take a look at the relevant part in the source code for Flask-Admin [here](https://github.com/mrjoes/flask-admin/blob/08a4de5781bc55b431f406b8ac9230363ad6e9d5/flask_admin/contrib/sqla/view.py#L887).
The model is created without passing any arguments:
```
model = self.model()
```
So you should support a construct... | So, this is how I've implemented a Post class in my application:
```
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.Unicode(80))
body = db.Column(db.UnicodeText)
create_date = db.Column(db.DateTime, default=datetime.utcnow())
update_date = db.Column(db.DateT... | Unable to create models on Flask-admin | [
"",
"python",
"flask",
"flask-sqlalchemy",
"flask-admin",
""
] |
```
import copy
a = "deepak"
b = 1, 2, 3, 4
c = [1, 2, 3, 4]
d = {1: 10, 2: 20, 3: 30}
a1 = copy.copy(a)
b1 = copy.copy(b)
c1 = copy.copy(c)
d1 = copy.copy(d)
print("immutable - id(a)==id(a1)", id(a) == id(a1))
print("immutable - id(b)==id(b1)", id(b) == id(b1))
print("mutable - id(c)==id(c1)", id(c) == id(c1))
pri... | Normal assignment operations will simply point the new variable towards the existing object. The [docs](http://docs.python.org/2/library/copy.html) explain the difference between shallow and deep copies:
> The difference between shallow and deep copying is only relevant for
> compound objects (objects that contain oth... | For immutable objects, there is no need for copying because the data will never change, so Python uses the same data; ids are always the same. For mutable objects, since they can potentially change, [shallow] copy creates a new object.
Deep copy is related to nested structures. If you have list of lists, then deepcopy... | What is the difference between shallow copy, deepcopy and normal assignment operation? | [
"",
"python",
"copy",
"variable-assignment",
"immutability",
"deep-copy",
""
] |
The below code gives error:
```
Traceback (most recent call last):
File "pdf.py", line 14, in <module>
create_pdf(render_template('templates.htm'))
File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 123, in render_template
ctx.app.update_template_context(context)
AttributeError: 'NoneT... | From the code, I can see that you want to allow user to download pdf.
```
from xhtml2pdf import pisa
from StringIO import StringIO
from flask import render_template,Flask, Response
app=Flask(__name__)
app.debug=True
@app.route("/")
def create_pdf(pdf_data):
filename= "file.pdf"
pdf=pisa.CreatePDF( St... | Martin's answer gives a good explanation of *why* this error occurs.
The accepted answer fixes the problem posed but it's certainly not the only way. In my case I had something more like:
```
import threading
from flask import Flask, render_template
app = Flask("myapp")
app.route('/')
def get_thing(thing_id):
... | AttributeError: 'NoneType' object has no attribute 'app' | [
"",
"python",
"flask",
"xhtml2pdf",
""
] |
My 'Location' table contains 6 columns. (ID, Name, Alias, Area, X, Y)
Example of some entries from the 'Name' column:
```
Blackwood Highschool, Paris, France
Hilltop Market, Barcelona, Spain
Roundwell Plaza, Melbourne, Australia
Rurk Mount, Moscow, Russia(mountain)
History Museum, Prague, Czech Republic
Narrow R... | If you only have 8 variations, and this is a one time thing, you could do it with a replace.
```
update location
set name = replace(name , '(river)','')
where name like '%(river)%';
``` | You can do this with brute force string operations:
```
select concat(left(name, instr(name, '(') - 1),
right(name, length(name) - instr(val, ')'))
)
```
Actually, you want this in an `update` statement:
```
update location
set name = concat(left(name, instr(name, '(') - 1),
... | MySQL - Remove substring from an entry | [
"",
"mysql",
"sql",
"substring",
"sql-like",
""
] |
I try to get select from two tables and put some data from one to other with ussing WHERE
(PL/SQL)
I have two tables like those:
table1
```
ID NAME COLOR COMPANY_SHORT_NR
1 a Green 1
2 b Red 23
3 c Blue null
4 a Green null
5 g Green 1
```
table2
```
ID SHORT COMP_NAME
1 ... | you neen OUTER JOIN for that
```
select ID
,NAME
,COLOR
,COMPANY_SHORT_NR
from table1
LEFT OUTER JOIN table2 ON ( COMPANY_SHORT_NR = SHORT )
``` | You have to use `left join` as below
```
select ID
,NAME
,COLOR
,COMPANY_SHORT_NR
from table1 t1
left join table2 T2 on t1.COMPANY_SHORT_NR = t2.SHORT
``` | One select on two tables with NULL and not null | [
"",
"sql",
"oracle",
"select",
"plsql",
"isnull",
""
] |
```
SqlConnection con = new SqlConnection("My path");
SqlCommand cmd;
SqlDataReader dr;
Label1.Text = Session["name"].ToString();
con.Open();
cmd = new SqlCommand("Select '"+Session["name"]+"' from table1",con);
dr = cmd.ExecuteReader();
while(dr.read()){
Dropdownlist1.Items.Add(); ------->Stuck here
}
```
I a... | Base on your question you are passing Session["name"] which is your table Column Name to your select query.
There is also need to change on your code:
Lets say your Session["name"] value is **SKY**
```
"Select '"+Session["name"]+"' from tableA" --session["name"] is treated here as a string
```
this will be rendered... | Have you tried?
```
while (dr.read()){
Dropdownlist1.Items.Add(dr["Name"].ToString());
}
```
If you want to go get only once and without also having to specify the column name then you could use GetString(0) like:
```
while (dr.read()){
Dropdownlist1.Items.Add(dr.GetString(0));
break;
}
``` | Not able to display column entries using Data Reader | [
"",
"asp.net",
"sql",
"sql-server",
"c#-4.0",
""
] |
Say I have two lists one longer than the other, `x = [1,2,3,4,5,6,7,8]` and `y = [a,b,c]` and I want to merge each element in y to every 3rd index in x so the resulting list z would look like: `z = [1,2,a,3,4,b,5,6,c,7,8]`
What would be the best way of going about this in python? | Here is an adapted version of the roundrobin recipe from the [itertools documentation](http://docs.python.org/2/library/itertools.html#recipes) that should do what you want:
```
from itertools import cycle, islice
def merge(a, b, pos):
"merge('ABCDEF', [1,2,3], 3) --> A B 1 C D 2 E F 3"
iterables = [iter(a)]*... | Here's another way:
```
x = range(1, 9)
y = list('abc')
from itertools import count, izip
from operator import itemgetter
from heapq import merge
print map(itemgetter(1), merge(enumerate(x), izip(count(1, 2), y)))
# [1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8]
```
This keeps it all lazy before building the new list, and... | Merge 2 lists at every x position | [
"",
"python",
""
] |
In pandas, how can I add a new column which enumerates rows based on a given grouping?
For instance, assume the following DataFrame:
```
import pandas as pd
import numpy as np
a_list = ['A', 'B', 'C', 'A', 'A', 'C', 'B', 'B', 'A', 'C']
df = pd.DataFrame({'col_a': a_list, 'col_b': range(10)})
df
```
```
col_a col... | There's [cumcount](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html), for precisely this case:
```
df['col_c'] = g.cumcount()
```
As it says in the docs:
> Number each item in each group from 0 to the length of that group - 1.
---
*Original answer (before cumcount was... | The given answers both involve calling a python function for each group, and if you have many groups a vectorized approach should be faster (I havent checked).
Here is my pure numpy suggestion:
```
In [5]: df.sort(['col_a', 'col_b'], inplace=True, ascending=(False, False))
In [6]: sizes = df.groupby('col_a', sort=Fal... | Enumerate each row for each group in a DataFrame | [
"",
"python",
"pandas",
"dataframe",
"running-count",
""
] |
The deeper i dive in mysql the more i lost and now i'm completed lost.
So i have some tables:
MainTable
```
id|message|name
-----------------
1 |test |OP
2 |test2 |jim
3 |test3 |ted
```
Table1
```
id|likes
---------
2 | 1
3 | 0
```
Table2
```
id|likes
---------
2 | 1
```
Table3
```
id|likes
---------
1 | 1
... | I am guessing you are looking for one of these...
```
SELECT
id
,SUM(Table1.likes)
,SUM(Table2.likes)
,SUM(Table3.likes)
FROM MainTable
LEFT JOIN Table1 ON MainTable.id = Table1.id
LEFT JOIN Table2 ON MainTable.id = Table2.id
LEFT JOIN Table3 ON MainTable.id = Table3.id
GROUP BY MainTable.id
SELECT
... | Here is the query, counting non-zero likes for every row in MainTable:
```
SELECT
MainTable.id,
MainTable.name,
MainTable.message,
COUNT(Table1.likes) + COUNT(Table2.likes)
+ COUNT(Table3.likes) AS n_likes
FROM
MainTable
LEFT JOIN
Table1 ON MainTable.id = Table1.id
AND
Table1.likes=... | SQL get the sum of entries from join tables | [
"",
"mysql",
"sql",
"join",
""
] |
Working on a webpage I used the next line:
```
Model.select(:column).where("column IS NOT NULL")
```
I was wondering if there was a more Rails-ish way to do this, like using a hash for example
```
Model.select(:column).where(column: !nil)
``` | The [Squeel](https://github.com/ernie/squeel) gem will allow you to use != nil type syntax, but natively rails will not.
Example: `Model.where{column != nil}` | I would prefer to use a scope as its more readable as well as its more manageable later (like merging with other scopes)
```
class Model < ActiveRecord::Base
scope :not_null, lambda { |column|
{:select => column,
:conditions => "#{column} NOT NULL"
}
}
end
```
then use
```
Model.not_null("column_name"... | Rails - Simplify WHERE condition IS NOT NULL | [
"",
"sql",
"ruby-on-rails",
"activerecord",
""
] |
I'm selecting data from two different rows in the same table using a single sql.
```
"id" "borrowMax" "holder" "category" "country"
"1" "2" "0" "3" "US"
"2" "0" "1" "10" "US"
```
What I'm trying to do works out to this.
```
select id, holder from mytable ... | I would make use of nested select statements for a use case like yours. There is no JOIN operation being used, just a select query over a already filtered set of results and a logically more coherent code.
```
SELECT borrowmax, holder, id FROM mytable WHERE
id = (SELECT holder FROM mytable WHERE id = 2 )
AND ca... | You can also use table alias for this.
```
select t1.id, t1.holder, t2.borrowMax from mytable t1, mytable t2 where t1.id = t2.holder
``` | Selecting data from different rows in the same table with a single statement | [
"",
"mysql",
"sql",
""
] |
My Payment Schedule holds a row for a payment schedule that gets run on a specific day, based on an 'effective date'.
```
CREATE TABLE [dbo].[PaymentSchedule] (
[PaymentScheduleId] INT IDENTITY (1, 1) NOT NULL,
[EffectiveDate] DATE NOT NULL,
[EffectiveDays] INT NOT NULL,
CONSTRAINT [pk_Paymen... | Your description of the problem is wrong. If the first payment is on Jan 1, the subsequent payments would be on the Jan 8, Jan 15 and so on.
The answer to your question about the current date is `datediff()` along with the modulus operator. To see if today is a payment date, take the difference and see if it is an exa... | You can use the method DATEDIFF(datepart, startdate, enddate) setting as datepart "dayofyear" to the result of this method will give you the number of days between the two dates, and divide as Modulo (%) this result by the EffectiveDays and if the result is 0 there is payment day; and if not you will have the days pass... | Table driven payment schedule | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a question about dealing with m2m / through models and their presentation in django rest framework. Let's take a classic example:
models.py:
```
from django.db import models
class Member(models.Model):
name = models.CharField(max_length = 20)
groups = models.ManyToManyField('Group', through = 'Members... | How about.....
On your MemberSerializer, define a field on it like:
```
groups = MembershipSerializer(source='membership_set', many=True)
```
and then on your membership serializer you can create this:
```
class MembershipSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.Field(source='group.... | I was facing this problem and my solution (using DRF 3.6) was to use SerializerMethodField on the object and explicitly query the Membership table like so:
```
class MembershipSerializer(serializers.ModelSerializer):
"""Used as a nested serializer by MemberSerializer"""
class Meta:
model = Membership
... | Include intermediary (through model) in responses in Django Rest Framework | [
"",
"python",
"django",
"django-rest-framework",
""
] |
I am wanting to search and count the number of times a string comes up in a webscrape. However I want to search between x and y within the webscrape.
Can anyone tell me the easiest method to count SEA BASS between MAIN FISHERMAN and SECONDARY FISHERMAN in the following example webscrape.
```
<p style="color: #555555;... | Do it in two steps:
1. Extract the substring between MAIN FISHERMAN and SECONDARY FISHERMAN.
2. Count SEA BASS
Like this:
```
relevant = re.search(r"MAIN FISHERMAN(.*)SECONDARY FISHERMAN", html, re.DOTALL).group(1)
found = relevant.count("SEA BASS")
``` | If you want to use `'MAIN FISHERMAN'` and `'SECONDARY FISHERMAN'` as markers to find `<div>` elements to count `'SEA BASS'` within:
```
import re
from bs4 import BeautifulSoup # $ pip install beautifulsoup4
soup = BeautifulSoup(html)
inbetween = False
count = 0
for div in soup.find_all('div', ["post-bodycopy", "clear... | Restricting the area of text that is searched by python | [
"",
"python",
"regex",
"python-2.7",
"web-scraping",
"urllib",
""
] |
I have a very large dataset were I want to replace strings with numbers. I would like to operate on the dataset without typing a mapping function for each key (column) in the dataset. (similar to the fillna method, but replace specific string with assosiated value).
Is there anyway to do this?
Here is an example of my... | Use [replace](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.replace.html)
```
In [126]: df.replace(['very bad', 'bad', 'poor', 'good', 'very good'],
[1, 2, 3, 4, 5])
Out[126]:
resp A B C
0 1 3 3 4
1 2 4 3 4
2 3 5 5 5
3 4 2 3 ... | Considering `data` is your `pandas DataFrame` you can also use:
```
data.replace({'very bad': 1, 'bad': 2, 'poor': 3, 'good': 4, 'very good': 5}, inplace=True)
``` | Replace string/value in entire DataFrame | [
"",
"python",
"replace",
"dataframe",
"pandas",
""
] |
I have tried the Sequence Generator like Lambda, List comprehension and others but it seems that I am not able to get what I really want. My final goal is to print sequence of words from a string like *string[1:3]*
What I am looking for :
```
a = [0,13,26,39]
b = [12,25,38,51]
str = 'If you are done with the file, m... | Use `zip`:
```
>>> a = [0,13,26,39]
>>> b = [12,25,38,51]
>>> strs = 'If you are done with the file, move to the command area across from the file name in the RL screen and type'
>>> spl = strs.split()
>>> for x,y in zip(a,b):
... print spl[x:y]
...
['If', 'you', 'are', 'done', 'with', 'the', 'file,', 'move',... | Do you mean:
```
>>> [read[i:j] for i, j in zip(a,b)]
[['If', 'you', 'are', 'done', 'with', 'the', 'file,', 'move', 'to', 'the',
'command', 'area'], ['from', 'the', 'file', 'name', 'in', 'the', 'RL',
'screen', 'and', 'type'], [], []]
```
or
```
>>> ' '.join[read[i:j] for i, j in zip(a,b)][0])
'If you are done wi... | Sequence Generation with Number applied to string | [
"",
"python",
"string",
"python-2.7",
""
] |
I've declared a list of tuples that I would like to manipulate. I have a function that returns an option from the user. I would like to see if the user has entered any one of the keys 'A', 'W', 'K'. With a dictionary, I would say this: `while option not in author.items() option = get_option()`. How can I accomplish thi... | ```
authors = [('A', "Aho"), ('W', "Weinberger"), ('K', "Kernighan")]
option = get_option()
while option not in (x[0] for x in authors):
option = get_option()
```
How this works :
`(x[0] for x in authors)` is an generator expression, this yield the `[0]th` element of each item one by one from authors list, and th... | How about something like
```
option in zip(*authors)[0]
```
We are using [`zip`](http://docs.python.org/2/library/functions.html#zip) to essentially separate the letters from the words. Nevertheless, since we are dealing with a *list* of tuples, we must [unpack](http://docs.python.org/2/tutorial/controlflow.html#unpa... | Python - input from list of tuples | [
"",
"python",
""
] |
How can I check if there's another record in the table with the same unique ID (the column name is `ID`), then and if one exists not do anything, otherwise insert the record?
Do I need to index the `ID` column and set it as unique/primary key? | One option is to use `INSERT IGNORE`. As the name implies it will INSERT rows that do not exist, and it will do nothing with duplicate rows.
```
CREATE TABLE Table1 (
`id` int NOT NULL PRIMARY KEY,
`foo` varchar(20)
);
INSERT IGNORE INTO Table1
(`id`, `foo`)
VALUES
(1, 'a'),
(2, 'a'),
(3, 'a'),
... | You may use `REPLACE` as `INSERT OR UPDATE` for that | Check if a record with the same unique ID exists in SQL table before insert | [
"",
"mysql",
"sql",
""
] |
I am trying to write a program that will write a list of info in a text file. Here's an example of what I have so far
```
f.open('blah.txt','w')
x = input('put something here')
y = input('put something here')
z = input('put something here')
info = [x,y,z]
a = info[0]
b = info[1]
c = info[2]
f.write(a)
f.write(b)
f.wri... | Format a string and write it:
```
s = ','.join(info)
f.write(s + '\n')
``` | Try this:
```
f.open('blah.txt','a') # append mode, if you want to re-write to the same file
x = input('put something here')
y = input('put something here')
z = input('put something here')
f.write('%d,%d,%d\n' %(x,y,z))
f.close()
``` | Python write to file in list format | [
"",
"python",
"python-3.x",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.