Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I currently have a SQL query that produces a table with around 10M rows. I would like to append this table with another column that has the same entry for all 10M rows.
As an example consider the following toy query
```
SELECT PRODUCT_ID, ORDER_QUANTITY
FROM PRODUCT_TABLE
GROUP BY SALES_DAY
```
And say that is produ... | Like this:
```
SELECT PRODUCT_ID, ORDER_QUANTITY, 999 as USER_VALUE
FROM PRODUCT_TABLE
GROUP BY SALES_DAY
``` | You can pass it in the `SELECT`, for example:
```
SELECT PRODUCT_ID, ORDER_QUANTITY, 999 AS USER_VALUE
FROM PRODUCT_TABLE
GROUP BY SALES_DAY
``` | How to add a user defined column with a single value to a SQL query | [
"",
"sql",
""
] |
I have two tables.
Table 1
```
ID Code1 Code2 Code3
10 1.1 1.2 1.3
```
Table 2
```
Code Group Category
1.1 a cat1
1.2 b cat1
1.3 c cat2
1.4 d cat3
```
Now I need to get the outputs in two different forms from these two tables tables
Output 1
```
ID Group1 Group2 Grou... | First off, I *strongly* suggest you look into an alternative. This will get messy very fast, as you're essentially treating rows as columns. It doesn't help much that `Table1` is already denormalized - though if it really only has 3 columns, it's not that big of a deal to normalize it again.:
```
CREATE VIEW v_Table1 ... | These answers assume that all 3 codes are available in table 2. If not, then you should use OUTER joins instead of INNER.
Output 1 can be achieved like this:
```
select t1.ID,
cd1.Group as Group1,
cd2.Group as Group2,
cd3.Group as Group3
from table1 t1
inner join table2 cd1
on t1.Code1 = cd1.Code... | SQL Server - Setting multiple columns from another table | [
"",
"sql",
"sql-server",
""
] |
I recently started learning python. I have created some basic webapps with Django and wrote some simple scripts. After using VIM as a Python IDE I really fell I love with "Terminal programs" (is there an official term for this?). Right now I am capable of doing simple things like asking someones age and printing it to ... | A true command-line program is something in the vein of `ls` or `grep`; it is started from the command-line, but it's non-interactive and can be used in pipelines and combined with other programs. A typical command-line program has no interactive user experience, instead relying on shell's history and init file for cus... | On a \*nix system (linux/unix),
if you:
```
$ chmod 0744 your_file.py
-rwxr--r-- your_file.py
```
and add the path to python as the first line of `your_file.py`:
```
#!/usr/bin/python
```
or (in my case):
```
#!/usr/local/bin/python
```
Once you do that, instead of running it like this:
```
$ python your_f... | Creating a Terminal Program with Python | [
"",
"python",
"command-line",
""
] |
I'm writing a small API, and wanted to print a list of all available methods along with the corresponding "help text" (from the function's docstring). Starting off from [this answer](https://stackoverflow.com/a/13318415/2511466), I wrote the following:
```
from flask import Flask, jsonify
app = Flask(__name__)
@app.... | There is `app.view_functions`. I think that is exactly what you want.
```
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api', methods = ['GET'])
def this_func():
"""This is a function. It does nothing."""
return jsonify({ 'result': '' })
@app.route('/api/help', methods = ['GET'])
def h... | Here's mine:
```
@app.route("/routes", methods=["GET"])
def getRoutes():
routes = {}
for r in app.url_map._rules:
routes[r.rule] = {}
routes[r.rule]["functionName"] = r.endpoint
routes[r.rule]["methods"] = list(r.methods)
routes.pop("/static/<path:filename>")
return jsonify(ro... | List all available routes in Flask, along with corresponding functions' docstrings | [
"",
"python",
"flask",
""
] |
So I am using the python chain method to combine two querysets (lists) in django like this.
```
results=list(chain(data,tweets[:5]))
```
Where data and tweets are two separate lists. I now have a "results" list with both data and tweet objects that I want ordered in this fashion.
```
results=[data,tweets,data,tweets... | You can use `itertools.chain.from_iterable` and `zip`:
```
>>> data = [1,2,3,4]
>>> tweets = ['a','b','c','d']
>>> list(chain.from_iterable(zip(data,tweets)))
[1, 'a', 2, 'b', 3, 'c', 4, 'd']
```
Use `itertools.izip` for memory efficient solution. | Here's a solution using iterators:
```
from itertools import izip
result = (v for t in izip(data, tweets) for v in t)
``` | Python-Order a list so that X follows Y and Y follows X | [
"",
"python",
"django",
""
] |
I have a column which is called `studentID`, but I have *millions* of records and somehow the application has input some *arbitrary text* in the column.
How do I search:
```
SELECT *
FROM STUDENTS
WHERE STUDENTID CONTAINS TEXT
``` | Leaving database modeling issues aside.
I think you can try
```
SELECT * FROM STUDENTS WHERE ISNUMERIC(STUDENTID) = 0
```
But `ISNUMERIC` returns 1 for any value that seems numeric including things like `-1.0e5`
If you want to exclude digit-only studentids, try something like
```
SELECT * FROM STUDENTS WHERE STUDEN... | Just try below script:
Below code works only if studentid column datatype is varchar
```
SELECT * FROM STUDENTS WHERE STUDENTID like '%Searchstring%'
``` | Check if a column contains text using SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
If I run the following query:
```
select count(*) from all_tab_columns
where column_name = 'foo'
and table_name = 'VIEW0';
```
I get 0 for a result. I expect 1.
But if I run the following query I get many (expected) rows returned:
```
select foo from VIEW0;
```
Why? I'm assuming I'm making some dum... | Probably the reason is that you have case sensitive setting.
Try to add `UPPER` function as below.
```
select count(*) from all_tab_columns
where column_name = upper('foo')
and table_name = 'VIEW0';
``` | [ALL\_TAB\_COLUMNS describes the columns of the tables, views, and clusters **accessible** to the current user.](http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_2094.htm) Check, if user under whom you running this query have access to the desired table. | Oracle SQL: selecting from all_tab_columns does not find existing column | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
""
] |
I always think that the relations between tables are needed to perform cross-table operations, such as join. But I noticed that I can inner join two tables that are not linked at all (hasn't any foreign keys).
**So, my questions:**
1. Are some differences (such as speed) in joining linked and not-linked tables?
2. Wh... | The primary advantage is that foreign key constraints ensure the relational integrity of the data.. ie it stops you from deleting something that has a related entry in another table
You only get a performance advantage if you create an index on your FK | The FK/PK relationship is a logical feature of the data that would exist even if it were not declared in a given database. You include FKs in a table precisely to establish these logical relationships and to make them visible in a way that makes useful inner joins possible. Declaring an FK as referencing a given PK has... | DB: advantages of relations | [
"",
"sql",
"database",
"relational-database",
""
] |
I have python 2.7 installed. I want to use python 2.4 to run python code. Is it possible? | Either directly use the Python 2.4 interpreter to run it, or modify the programs she-bang line to point to the interpreter you wish to use.
Note that there's many things in common use in recent python (`any`/`all`, the `1 if 2 else 3` syntax, as well as major stdlib and language changes) that may cause your program to... | You can install Python 2.4 **as well**. Any of the minor versions, 2.4, 2.5, 2.6, etc. can live side by side.
Code you write for 2.4 will also run on Python 2.7, albeit that you may hit some deprecation warnings. If you are using the 2.7 interpreter to write 2.4 code, you'll need to be careful that you don't use synta... | Running python program using earlier version of python | [
"",
"python",
"backwards-compatibility",
""
] |
I have this scroll-able frame (frame inside canvas actually).
```
import Tkinter as tk
class Scrollbarframe():
def __init__(self, parent,xsize,ysize,xcod,ycod):
def ScrollAll(event):
canvas1.configure(scrollregion=canvas1.bbox("all"),width=xsize,height=ysize,bg='white')
self.parent=... | Perhaps the simplest solution is to make a global binding for the mousewheel. It will then fire no matter what widget is under the mouse or which widget has the keyboard focus. You can then unconditionally scroll the canvas, or you can be smart and figure out which of your windows should scroll.
For example, on window... | Based on @BryanOakley's answer, here is a way to scroll only the focused widget (i.e. the one you have mouse cursor currently over).
Bind to `<Enter>` and `<Leave>` events happening on your scrollable frame which sits inside a canvas, the following way (`scrollframe` is the frame that is inside the canvas):
```
.... | tkinter: binding mousewheel to scrollbar | [
"",
"python",
"binding",
"tkinter",
"scrollbar",
"mousewheel",
""
] |
I need to parse data from a website: <http://www.sarkari-naukri.in/jobs-by-qualification/b-tech/sub-centre-manager.html>
Most of tutorial for BeautifulSoup are for parsing links and not in-depth parsing of required data from a link.
Now i went through some tutorial of BeautifulSoup module of python and wrote this scr... | This solution uses BeautifulSoup
```
import os
import sys
# Import System libraries
import re
import urllib2
# Import Custom libraries
from BeautifulSoup import BeautifulSoup, Tag
job_location = lambda x: x.name == "div" and set([(u"id", u"content")]) <= set(x.attrs)
job_title_location = lambda x: set([(u"class", u... | Your problem lies here: `postdata.findAll('div', {'class': 'scdetail'})`. While you are looking for `div`s, the page has `span`s. Changing it to `postdata.findAll('span', {'class': 'scdetail'})` results in a non-empty result.
Example of one of the values you are wanting to read:
```
<div class="scheading">
"Pay S... | Parse data using BeautifulSoup in python | [
"",
"python",
"parsing",
"web-scraping",
"beautifulsoup",
""
] |
I have a data file that has values in it like this:
> @ DD MM YYYY HH MN SS Hs Hrms Hma x Tz Ts Tc THmax EP S T0 2 Tp Hrms EPS
>
> 29 11 2000 13 17 56 2.44 1.71 3.12 9.12 11.94 5.03 12.74 .83 8.95 15.03 1.80 .86
> 29 11 2000 13 31 16 2.43 1.74 4.16 9.17 11.30 4.96 11.70 .84 8.84 11.86 1.80 .87
I use the following t... | Here's a `pandas` solution for you:
test.csv:
```
29 11 2000 13 17 56 2.44 1.71 3.12 9.12 11.94 5.03 12.74 .83 8.95 15.03 1.80 .86
29 11 2000 13 31 16 2.43 1.74 4.16 9.17 11.30 4.96 11.70 .84 8.84 11.86 1.80 .87
```
`pandas` provide a [read\_csv](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parser... | This is how I would do it:
```
from datetime import datetime
# assuming you have a row of the data in a list like this
# (also works on ndarrays in numpy, but you need to keep track of the row,
# so let's assume you've extracted a row like the one below...)
rowData = [29, 11, 2000, 13, 17, 56, 2.44, 1.71, 3.12, 9.1... | How to interpret values in a .txt data file as a time series | [
"",
"python",
"pandas",
"timestamp",
"python-dateutil",
""
] |
I have this query:
```
SELECT * FROM `employee_activities` a
LEFT JOIN `activity` b ON a.activity_code = b.code
LEFT JOIN `employees` c ON a.employee_code = c.code
WHERE b.type = "Design"
AND c.code NOT IN(
SELECT * FROM `employee_activities` a
LEFT JOIN `activity` b ON a.activity_code = b.code
LEF... | For the not in sub query - it should contain only one column - for example
```
SELECT * FROM `employee_activities` a
LEFT JOIN `activity` b ON a.activity_code = b.code
LEFT JOIN `employees` c ON a.employee_code = c.code
WHERE b.type = "Design"
AND c.code NOT IN(
SELECT b.employee_code FROM `employee_activities` a
... | Your query
```
AND c.code NOT IN(
SELECT * FROM `employee_activities` a
...
```
tries to compare c.code to *all columns in the subquery*. What you want is probably;
```
AND c.code NOT IN(
SELECT c.code FROM `employee_activities` a
```
Also, you have a problem in your `LEFT JOIN`;
```
LEFT JOIN `activity` b ... | Getting an error when using joins in query | [
"",
"mysql",
"sql",
""
] |
I would like to convert stuff from my csv.reader to a dictionary. I implemented the instructions from this post [Add new keys to a dictionary?](https://stackoverflow.com/questions/1024847/add-to-a-dictionary-in-python) but I keep getting `IndexError: list index out of range`. How can I fix this?
```
import wx
import c... | ```
for index, row in enumerate(info):
dict_info[index] = [row[1], row[4]]
``` | import collections
d = collections.OrderedDict()
info = csv.reader(open('report.csv', 'rb'),delimiter=',')
d = {row[0]:row[1].strip() for row in info}
for some1, some2 in d.items():
and than write everything else | add new elements to a dictionary | [
"",
"python",
"csv",
"dictionary",
""
] |
I'd like to modify some characters of a file in-place, without having to copy the entire content of the file in another, or overwrite the existing one. However, it doesn't seem possible to just replace a character by another:
```
>>> f = open("foo", "a+") # file does not exist
>>> f.write("a")
1
>>> f.seek(0)
0
>>> f... | That's because of the mode you're using, in append mode, the file pointer is moved to the end of file before `write`, you should open your file in `w+` mode:
```
f = open("foo", "w+") # file does not exist
f.write("samething")
f.seek(1)
f.write("o")
f.seek(0)
print f.read() # prints "something"
```
If you want to do... | Truncate the file using `file.truncate` first:
```
>>> f = open("foo", "a+")
>>> f.write('a')
>>> f.truncate(0) #truncates the file to 0 bytes
>>> f.write('b')
>>> f.seek(0)
>>> f.read()
'b'
```
Otherwise open the file in `w+`mode as suggested by @Guillaume. | Replace a character by another in a file | [
"",
"python",
"file",
"file-io",
"python-3.x",
""
] |
I've got a table with two columns, `ID` and `Value`. I want to change a part of some strings in the second column.
Example of Table:
```
ID Value
---------------------------------
1 c:\temp\123\abc\111
2 c:\temp\123\abc\222
3 c:\temp\123\abc\333
4 c:\temp\123... | You don't need wildcards in the `REPLACE` - it just finds the string you enter for the second argument, so the following should work:
```
UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=4
```
If the column to replace is type `text` or `ntext` you need to cast it to nvarchar
```
UPDATE dbo.xxx
SET Val... | Try to remove `%` chars as below
```
UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=4
``` | UPDATE and REPLACE part of a string | [
"",
"sql",
"sql-server",
"string",
"sql-server-2008",
"replace",
""
] |
I need to export data from a database with a new random field not present in the database.
Something like:
```
SELECT field1, field2, rand(1,5) as field3 FROM table
```
It is possible? | Yes, `RAND()` returns a value between 0 and 1. Use math to make that number be within the range you want.
[MySQL RAND Documentation](http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand) | Not a MySQL answer, but may be of use: on SQL Server the 'RAND' function requires a seed that must differ between rows. Therefore a simple way may be:
```
SELECT field1, field2, rand(id) as field3 FROM table
```
This is dependant upon an ID being available, and it is also only pseudo-random; the same value for field3... | Generate field in MySQL SELECT with random value | [
"",
"sql",
""
] |
I have a combobox that you can select a location, 1-7, and then a query based on that location is used as a record source for a report. However, I also want to be able to see all... So, I have a line of code like:
```
iif(Forms!ReportCreator.Location.Value>0,Forms!ReportCreator.Location.Value,"")
```
However, I can't... | If you create the SQL command with VBA then it would be:
```
strSQL = "SELECT ... WHERE SampleLocation = " & _
Iif(Forms!ReportCreator.Location.Value > 0, _
Forms!ReportCreator.Location.Value,"SampleLocation")
```
If you want to do it directly in the SQL command it would be:
```
SELECT ...
WHERE ... | One way is to embed the `WHERE` within the iif:
```
iif(Forms!ReportCreator.Location.Value>0," WHERE SampleLocation = " _
& Forms!ReportCreator.Location.Value,"")
```
although it depends how you are constructing your statement. | iif in query expression to return multiple parts | [
"",
"sql",
"ms-access",
"ms-access-2007",
"vba",
""
] |
I'm looking for the best approach for inserting a row into a spreadsheet using openpyxl.
Effectively, I have a spreadsheet (Excel 2007) which has a header row, followed by (at most) a few thousand rows of data. I'm looking to insert the row as the first row of actual data, so after the header. My understanding is that... | Answering this with the code that I'm now using to achieve the desired result. Note that I am manually inserting the row at position 1, but that should be easy enough to adjust for specific needs. You could also easily tweak this to insert more than one row, and simply populate the rest of the data starting at the rele... | == Updated to a fully functional version, based on feedback here: groups.google.com/forum/#!topic/openpyxl-users/wHGecdQg3Iw. ==
As the others have pointed out, `openpyxl` does not provide this functionality, but I have extended the `Worksheet` class as follows to implement inserting rows. Hope this proves useful to o... | Insert row into Excel spreadsheet using openpyxl in Python | [
"",
"python",
"excel",
"xlrd",
"xlwt",
"openpyxl",
""
] |
I am trying to install pymssql on ubuntu 12.04 using pip. This is the error I am getting. Any help would be greatly appreciated as I am completely lost!
Tried googling this but unfortunately to no avail...
```
Downloading pymssql-2.0.0b1-dev-20130403.tar.gz (2.8Mb): 2.8Mb downloaded
Running setup.py egg_info for ... | Make sure you have the `python-dev` package installed (needed to compile packages with native bindings (thanks to @ravihemnani).
Then you'll need to install the FreeTDS development package (`freetds-dev`) before trying to install `pymssql` with pip:
```
$ sudo apt-get install freetds-dev
```
and then, in your *virtu... | Apart from freetds-dev, you need to install python-dev as well as follow.
```
sudo apt-get install python-dev
```
Or else, you will again face some error. | trying to install pymssql on ubuntu 12.04 using pip | [
"",
"python",
"ubuntu",
"ubuntu-12.04",
"pip",
"pymssql",
""
] |
I have two dicts:
```
blocked = {'-5.00': ['121', '381']}
all_odds = {'-5.00': '{"121":[1.85,1.85],"381":[2.18,1.73],"16":[2.18,1.61],"18":\
[2.12,1.79]}'}
```
I want to first check whether the `.keys()` comparision (`==`) returns `True`, here it does (both `-5.00`) then I want to remove all items from `a... | First, make the string a dictionary with [`ast.literal_eval()`](http://docs.python.org/3.4/library/ast.html#ast.literal_eval). [Don't use `eval()`](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html):
```
>>> import ast
>>> all_odds['-5.00'] = ast.literal_eval(all_odds['-5.00'])
```
Then you can use a... | Here's how you can do the same in about 2 lines. I'm not going to use ast, or eval here, but you can add that if you want to use that.
```
>>> blocked = {'-5.00': ['121', '381']}
>>> all_odds = {'-5.00': {'121':[1.85,1.85],'381':[2.18,1.73],'16':[2.18,1.61],'18':\
... [2.12,1.79]}}
>>> bkeys = [k for k in all_odd... | Removing nested dict items with dict comprehension | [
"",
"python",
"python-2.7",
"dictionary",
"compression",
""
] |
I think this may be a common problem that may not have an answer for every tool. Right now we are trying to use amazons Redshift. The only problem we have now is we are trying to do a look up of zip code for an IP address. The table we have that connects IP to city is a range by IP converted to an integer.
Example:
`... | Beginning with PostgreSQL **9.2** you could use one of the new [**range types**](http://www.postgresql.org/docs/current/interactive/rangetypes.html),`int4range` or `int8range`.
```
CREATE TABLE city (
city_id serial PRIMARY KEY
,ip_range int4range
,city text
,zip text
);
```
Then your query could simply be:
`... | Try using `between`, listing the table with the target value *second*:
```
select *
from table1 t1
join table2 t2
on t2.ip between t1.startip and t1.endip
```
And make sure there's an index on `table2.ip`.
It should perform pretty well. | Best way to join on a range? | [
"",
"sql",
"postgresql",
"amazon-redshift",
"range-types",
""
] |
I'm trying to unit test python code which accesses a remote service. I'm using PyUnit with python 2.7.
In the `setUpClass` method, the code prompts the user to enter the password for the service. I want to keep everything modular, so I've created separate unit test classes for each class being tested. These classes al... | Class definition is executed once.
```
import unittest
from getpass import getpass
class TestCommon(unittest.TestCase):
pwd = getpass()
class test_A(TestCommon):
def test_a(self):
self.assertEqual(self.pwd, 'secret')
class test_B(TestCommon):
def test_b(self):
reversed_pwd = self.pwd[::-... | In your `setUpClass()` function, you can save the password as a property of `self`, then make each test a part of your `TestCommon` class.
```
import unittest
from getpass import getpass
class TestCommon(unittest.TestCase):
@classmethod
def setUpClass(self):
self.pwd = getpass()
def test_A(self):... | Python Unit Test with User-Entered Password | [
"",
"python",
"unit-testing",
"python-2.7",
"python-unittest",
""
] |
I am currently writing a SQL query which first creates a lot of temporary tables using the WITH operator along with SELECT statements and then joins all of the temporary statements at the end.
All of my SELECT statements that create temporary tables depend on certain filters... so my query looks something liek
```
... | It depends how you're running your query.
If you're using an interactive client like SQL\*Plus or TOAD you should use substitution variables:
```
WITH
table_1 as (
SELECT product_id
avg(price)
FROM daily_sales
WHERE product_category = &product_cat
AND sell_date BETWE... | Further to APC's answer, in SQL\*Plus or SQL Developer you can also declare variables that you can assign values to in an anonymous PL/SQL block and then reference as bind variables in your plain SQL query:
```
variable v_product_cat number;
variable v_start_date varchar2(10);
variable v_end_date varchar2(10);
begin
... | Declaring and Setting Variables of Different Data Types in Oracle SQL | [
"",
"sql",
"oracle",
""
] |
suppose I have a table in a postgresql database with columns: `time,speed`
Now I've added a column "`distance`" and I want to insert the values of distance by something like:
```
row[time+1].distance = row[time].distance + row[time+1].speed
```
which is the fastest way to update the table?
**UPDATE**
I would li... | So, I made a table:
```
create table whatever ( time_c int4, speed int4, distance int8);
```
and inserted some rows:
```
insert into whatever (time_c, speed) select i, random() * 100 from generate_series(1,10) i;
```
This gave me this data:
```
$ select * from whatever;
time_c | speed | distance
--------+-------... | No need for a loop or even for storing this data. Apparently you want a "running sum" of the "speed" column, which can easily be done using a window function:
(Sample data shamelessly stolen from Depesz's answer)
```
create table whatever
(
time_c int4,
speed int4,
distance int8
);
insert into whatever ... | update rows with incremental value | [
"",
"sql",
"postgresql",
""
] |
Why is the following code true?
```
>>> foo = {}
>>> foo > 1
True
>>> foo < 1
False
>>> foo == 0
False
>>> foo == -1
False
>>> foo == 1
False
```
I understand what I wanted was len(foo) > 1, but as a beginner this surprised me. | From the [docs](http://docs.python.org/release/2.5.2/ref/comparisons.html):
> The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and ar... | rich comparison between incompatible types is based on the name(?) of the type in python2.x and has been disallowed in python3.x.
In any event, in python2.x, the ordering is guaranteed to give the same results for a particular python implementation and version, but the ordering itself is not defined. | Why is an empty dictionary greater than 1? | [
"",
"python",
""
] |
I have a vendor database for a web application with 100 "user defined string" columns. They have a datatype of varchar with a length of 255.
I need to return all the rows that aren't null so that I can find out what is being stored in each one. There's no controlling for what the input has been over the years so userd... | The only improvement to that that I can think of would be to use `COALESCE` in the `WHERE` clause instead of `OR`:
```
SELECT *
FROM userdefinedstringTable
WHERE COALSECE( userdefinedstring1
, userdefinedstring2
...
) IS NOT NULL
```
Depending on your DBMS product, the... | RBarry's COALESCE is a good idea, and you can use this to list out all columns of interest:
```
SELECT c.name ColumnName
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
WHERE t.name = 'varchar'
AND t.max_length = 255
ORDER BY c.OBJECT_ID;
```
Good chance to use EXCEL to craft a query q... | Vendor database contains table with 100 user defined string columns need to find all occurrences in that table that are not null | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have been attending a couple of hackathons. I am beginning to understand that writing code is not enough. The code has to be optimized. That brings me to my question. Here are two questions that I faced.
```
def pairsum(numbers, k)
"""Write a function that returns two values in numbers whose sum is K"""
for ... | Knowing the most efficient Python idioms and also designing code that can reduce iterations and bail out early with an answer is a major part of optimization. Here are a few examples:
List list comprehensions and generators are usually fastest:
With a straightforward nested approach, a generator is faster than a `for... | Your first program is a little vague. I assume `numbers` is a list of tuples or something? Like `[(1,2), (3,4), (5,6)]`? If so, your program is pretty good, from a complexity standpoint - it's O(n). Perhaps you want a little more Pythonic solution? The neatest way to clean this up would be to join your conditions:
```... | Python lists, dictionary optimization | [
"",
"python",
"python-2.7",
""
] |
Let's say I have two classes A and B:
```
Class A:
# A's attributes and methods here
Class B:
# B's attributes and methods here
```
Now I can assess A's properties in object of B class as follows:
```
a_obj = A()
b_obj = B(a_obj)
```
What I need is a two way access.
How do I access A's properties in B and B's... | You need to create pointers either way:
```
class A(object):
parent = None
class B(object):
def __init__(self, child):
self.child = child
child.parent = self
```
Now `A` can refer to `self.parent` (provided it is not `None`), and `B` can refer to `self.child`. If you try to make an instance ... | Why not just plan your objects in a way where this can be taken care of with inheritance.
```
class A(object):
# stuff
class B(A):
# has A methods/properties
class C(B):
# has A and B methods/properties
```
In this case by planing ahead, you could just use `C` for a generalist object, and `A` with `B` a... | Python: accessing attributes and methods of one class in another | [
"",
"python",
"oop",
""
] |
Im kind of stuck on an issue and Ive gone round and round with it until ive confused myself.
What I am trying to do is take a list of words:
```
['About', 'Absolutely', 'After', 'Aint', 'Alabama', 'AlabamaBill', 'All', 'Also', 'Amos', 'And', 'Anyhow', 'Are', 'As', 'At', 'Aunt', 'Aw', 'Bedlam', 'Behind', 'Besides', 'B... | Use [`itertools.groupby()`](http://docs.python.org/2/library/itertools.html#itertools.groupby) to group your input by a specific key, such as the first letter:
```
from itertools import groupby
from operator import itemgetter
for letter, words in groupby(sorted(somelist), key=itemgetter(0)):
print letter
for ... | Instead of using any library imports, or anything fancy.
Here is the logic:
```
def splitLst(x):
dictionary = dict()
for word in x:
f = word[0]
if f in dictionary.keys():
dictionary[f].append(word)
else:
dictionary[f] = [word]
return dictionary
splitLst(['Abou... | Python: Split list based on first character of word | [
"",
"python",
"list",
"sorting",
"split",
"alphabetical",
""
] |
From the [docs](http://docs.python.org/2/library/functions.html#all), `all` is equivalent to:
```
def all(iterable):
for element in iterable:
if not element:
return False
return True
```
Then why do I get this output:
```
# expecting: False
$ python -c "print( all( (isinstance('foo', int... | Arguments are evaluated before calling a function. In this case first you have to create the tuple you pass to `all`.
`all` never had a chance to check them, the exception was thrown before that.
```
>>> int('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal fo... | One (fairly ugly) way to get the behaviour you want is via lambdas:
```
all(f() for f in (lambda: isinstance('foo', int), lambda: int('foo')))
``` | Why doesn't all() stop on the first False element? | [
"",
"python",
""
] |
I have a table called Employee. The EmpId column serves as the primary key. In my scenario, I cannot make it AutoNumber.
What would be the best way of generating the the next EmpId for the new row that I want to insert in the table?
I am using SQL Server 2008 with C#.
Here is the code that i am currently getting, bu... | Using `MAX(id) + 1` is a bad idea both performance and concurrency wise.
Instead you should resort to [sequences](http://msdn.microsoft.com/en-us/library/ff878091.aspx) which were design specifically for this kind of problem.
```
CREATE SEQUENCE EmpIdSeq AS bigint
START WITH 1
INCREMENT BY 1;
```
And to generate... | The above
```
select max(empid) + 1 from employee
```
is the way to get the next number, but if there are multiple user inserting into the database, then context switching might cause two users to get the same value for empid and then add 1 to each and then end up with repeat ids. If you do have multiple users, you m... | Generating the Next Id when Id is non-AutoNumber | [
"",
"sql",
"sql-server",
""
] |
I have this table in my mysql database
```
+-----+----------+------+----------+
| id | group_id | a_id | status |
+-----+----------+------+----------+
| 2 | 144 | 266 | active |
| 7 | 160 | 105 | inactive |
| 8 | 0 | 262 | inactive |
| 11 | 120 | 260 | inactive |
| 12 | 120 ... | ```
SELECT DISTINCT a_id
FROM yourtable
WHERE group_id!=0
GROUP BY a_id, group_id
HAVING SUM(status='inactive')=COUNT(*);
```
Please see fiddle [here](http://sqlfiddle.com/#!2/2798d/6). | you could use it easy like this
```
select a_id from tab_name where group_id<>0 and status="inactive"
group by group_id
```
update:
```
select a_id from tab_name where group_id<>0 and status="active"
and a_id not in (select a_id from tab_name where status ='inactive')
group by group_id
```
[**demo**... | Specific SQL with group by does not work correctly | [
"",
"mysql",
"sql",
""
] |
If I want to replace a pattern in the following statement structure:
```
cat&345;
bat &#hut;
```
I want to replace elements starting from `&` and ending before (not including `;`). What is the best way to do so? | Including or not including the & in the replacement?
```
>>> re.sub(r'&.*?(?=;)','REPL','cat&345;') # including
'catREPL;'
>>> re.sub(r'(?<=&).*?(?=;)','REPL','bat &#hut;') # not including
'bat &REPL;'
```
### Explanation:
* Although not required here, use a `r'raw string'` to prevent having to escape b... | Here is a good regex
`import re
result = re.sub("(?<=\\&).*(?=;)", replacementstr, searchText)`
Basically this will put the replacement in between the `&` and the `;` | Python regex example | [
"",
"python",
""
] |
(Other posts on SO are similar, but none have the specific combination of uwsgi + Flask + virtualenv) ([This one is closest](https://stackoverflow.com/questions/16605048/flasknginxuwsgi-importerror-no-module-named-site))
I installed uwsgi via apt-get. I also tried pip install wsgi. Both gave me the same issue.
Test c... | **See the answer from @JRajan first.**
If you're sure you just want to *suppress* the error and not actually *solve* the underlying issue, you should add `--no-site` to your command or `no-site=true` to your uwsgi.ini file. | The path to your virtual environment is wrong. That's the reason for this error.
I'm using virtualenvwrapper and my virtual environments are set at ~/.virtualenvs. So in my case, the uwsgi call would look something like
```
sudo uwsgi -s /tmp/uwsgi.sock -w myapp:app -H ~/.virtualenvs/myapp
```
Hope this helps next t... | uwsgi + Flask + virtualenv ImportError: no module named site | [
"",
"python",
"flask",
"virtualenv",
"uwsgi",
""
] |
I'm trying to manually create a new user in my table but am finding it impossible to generate a "UniqueIdentifier" type without the code throwing an exception...
Here is my example:
```
DECLARE @id uniqueidentifier
SET @id = NEWID()
INSERT INTO [dbo].[aspnet_Users]
([ApplicationId]
,[UserId]
... | ApplicationId must be of type `UniqueIdentifier`. Your code works fine if you do:
```
DECLARE @TTEST TABLE
(
TEST UNIQUEIDENTIFIER
)
DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();
INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);
SELECT * FROM @TTEST
```
Therefore I would say it is safe to assume that `App... | Kindly check Column ApplicationId datatype in Table aspnet\_Users , ApplicationId column datatype should be uniqueidentifier .
\****Your parameter order is passed wrongly ,
Parameter @id should be passed as first argument, but in your script it is placed in second argument.***.\*
So error is raised..
Please refere s... | How to generate and manually insert a uniqueidentifier in SQL Server? | [
"",
"sql",
"sql-server",
"database",
"t-sql",
"uniqueidentifier",
""
] |
I've had a search around but can't find anything regarding this...
I'm looking for a way to save a dictionary to file and then later be able to load it back into a variable at a later date by reading the file.
The contents of the file don't have to be "human readable" it can be as messy as it wants.
Thanks
- Hyflex
... | A few people have recommended `shelve` - I haven't used it, and I'm not knocking it. I have used pickle/cPickle and I'll offer the following approach:
# How to use Pickle/cPickle (the abridged version)...
There are *many* reasons why you would use Pickle (or its noticable faster variant, cPickle). Put tersely *Pickle... | Python has the `shelve` module for this. It can store many objects in a file that can be opened up later and read in as objects, but it's operating system-dependent.
```
import shelve
dict1 = #dictionary
dict2 = #dictionary
#flags:
# c = create new shelf; this can't overwrite an old one, so delete the old one fir... | Store a dictionary in a file for later retrieval | [
"",
"python",
"python-2.7",
"dictionary",
"load",
"store",
""
] |
I am trying to get the data for the last 6 months.
This is what I have used:
```
WHERE d_date > DATEADD(m, -6, current_timestamp)
```
and I am getting this error.
```
ERROR: CLI prepare error: SQL0206N "M" is not valid in the context where it is used
```
also tried
```
WHERE d_date > current date -180
```
and g... | Based on Andriy's eagle-eyes, here is (I think) the DB2 syntax:
```
WHERE d_date > current_date - 6 MONTHS
```
And [here is a link](https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/dateadd?lang=en) to a pretty good function to mirror DATEADD in DB2.
Also, since you mentioned SAS, here is the S... | In DB2, it should be something like
```
WHERE TIMESTAMPDIFF(64, CAST(CURRENT_TIMESTAMP- d_date AS CHAR(22))) <= 6
```
Remove the SQL-Server tag, that's for MS SQLServer questions. | sql query to get last 6 months of data | [
"",
"sql",
"db2",
"sas",
"enterprise-guide",
""
] |
I'd like to add a couple of things to what the `unittest.TestCase` class does upon being initialized but I can't figure out how to do it.
Right now I'm doing this:
```
#filename test.py
class TestingClass(unittest.TestCase):
def __init__(self):
self.gen_stubs()
def gen_stubs(self):
# Create... | Try this:
```
class TestingClass(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestingClass, self).__init__(*args, **kwargs)
self.gen_stubs()
```
You are overriding the `TestCase`'s `__init__`, so you might want to let the base class handle the arguments for you. | Just wanted to add some clarifications about overriding the init function of
```
unittest.TestCase
```
The function will be called before each method in your test class. Please note that if you want to add some expensive computations that should be performed **once** before running all test methods please use the [Se... | __init__ for unittest.TestCase | [
"",
"python",
"unit-testing",
""
] |
I have the following
```
user_id job_id job_offer_date
------- ------ --------------
1 123 2013-05-10
1 124 2013-07-19
2 127 2013-05-10
3 128 2013-06-15
```
I want to write TWO separate queries here to use in a report:
**QUERY #1 (I have this working already)**
... | The set of relevant first job offers.
```
select user_id, min(job_offer_date) as first_offer
from job
group by user_id
having min(job_offer_date) > '2013-05-10'
and min(job_offer_date) < '2013-07-19'
```
Join on that set to get the users. I'd guess that user data is stored in a user table.
```
select u.*
from use... | If I remember my SQL date stuff correctly, wouldn't it look something like this:
```
SELECT DISTINCT j.* FROM job WHERE j.job_offer_date > '2013-05-10' AND j.job_offer_data < '2013-7-19'
```
EDIT: I misunderstood your question. The above would look for any user with a job between (but not on) the two dates listed. Ol... | SQL get record that matches FIRST date criteria | [
"",
"sql",
"sql-server",
"sql-server-2008",
"date",
""
] |
I'm working on an application writing binary data (ints, doubles, raw bytes) to a file.
Problem is, that the data is not actually written to the file the way I expect it to be:
```
>>> import struct
>>> import io
>>> out = io.open("123.bin", "wb+")
>>> format = "!i"
>>> data = struct.pack(format, 1)
>>> out.write(dat... | Looks like this is an oddity of `hexdump(1)`. Using `xxd(1)`, I get...
```
$ xxd 123.bin
0000000: 0000 0001 ....
```
...which looks correct.
Looks like you have to use the `-C` option to get `hexdump(1)` to output in a sane format...
```
$ hexdump -C 123.bin
00000000 00 00 00 01 ... | The problem here isn't with python, but with hexdump. It's treating the data in the file as 16 bit little endian values. What you need to do is tell hexdump to treat the data as 8 bit values. Without looking it up, I think it's the '-c' option. | Python mangles struct.pack strings written to disk | [
"",
"python",
"bit-packing",
""
] |
I am fairly new to Python.
I have two lists
List A [a, b, c]
List B [c,d,e,f,g,h]
I would like to re.match (or re.search) list A variables in list B. If any variable from list A not present in List B, it should return false.
In above lists, it should return false.
Can I try for loop as below ?
for x in listA: ... | You can use `all`:
```
>>> lis1 = ['a', 'b', 'c']
>>> lis2 = ['c','d','e','f','g','h']
>>> all(x in lis2 for x in lis1)
False
```
If `lis2` is huge convert it to a `set` first, as sets provide `O(1)` lookup:
```
>>> se = set(lis2)
>>> all(x in se for x in lis1)
False
```
Regular expressions don't work on lists. | This sounds like a job for sets, not regular expressions:
```
set(listA) & set(listB) == set(listA)
```
The above is stating: if the intersection of the two sets has the same elements than the first set, then all of the first set's elements are also present in the second set. Or, as Jon points out, a solution based ... | pattern match list a with list b | [
"",
"python",
"pattern-matching",
""
] |
I like to use [collections.OrderedDict](http://docs.python.org/2/library/collections.html#collections.OrderedDict) sometimes when I need an associative array where the order of the keys should be retained. Best example I have of this is in parsing or creating csv files, where it's useful to have the order of columns re... | For your specific use case (writing csv files) an ordered dict is not necessary. Instead, use a [`DictWriter`](http://docs.python.org/2/library/csv.html#csv.DictWriter).
Personally I use `OrderedDict` when I need some LIFO/FIFO access, for which is even has a the `popitem` method. I honestly couldn't think of a good u... | > But I'm worried that this is bad practice, since it seems to me that the whole concept of an associative array is that the order of the keys should never matter,
Nonsense. That's not the "whole concept of an associative array". It's just that the order *rarely* matters and so we default to surrendering the order to ... | Is it bad practice to use collections.OrderedDict? | [
"",
"python",
""
] |
Here is a little script I wrote for making fractals using newton's method.
```
import numpy as np
import matplotlib.pyplot as plt
f = np.poly1d([1,0,0,-1]) # x^3 - 1
fp = np.polyder(f)
def newton(i, guess):
if abs(f(guess)) > .00001:
return newton(i+1, guess - f(guess)/fp(guess))
else:
return... | I worked from Lauritz V. Thaulow's code and was able to get a pretty significant speed-up with the following code:
```
import numpy as np
import matplotlib.pyplot as plt
from itertools import count
def newton_fractal(xmin, xmax, ymin, ymax, xres, yres):
yarr, xarr = np.meshgrid(np.linspace(xmin, xmax, xres), \
... | I vectorized the newton function and got approx. 85 times faster with 200x200 points, 144 times faster with 500x500 points, and 148 times faster with 1000x1000 points:
```
import numpy as np
import matplotlib.pyplot as plt
f = np.poly1d([1,0,0,-1]) # x^3 - 1
fp = np.polyder(f)
def newton(i, guess):
a ... | How do I speed up fractal generation with numpy arrays? | [
"",
"python",
"numpy",
""
] |
I know that to generate a list in Python you can use something like:
```
l = [i**2 for i in range(5)]
```
instead of using for loop like:
```
l = []
for i in range(5):
l.append(i**5)
```
Is there a way to do 2D lists without using for loops like this:
```
map = [[]]
for x in range(10):
row = []
for y ... | Use a list comprehension here too:
```
>>> [ [(x+y)**2 for y in range(10)] for x in range(10)]
[[0, 1, 4, 9, 16, 25, 36, 49, 64, 81], [1, 4, 9, 16, 25, 36, 49, 64, 81, 100], [4, 9, 16, 25, 36, 49, 64, 81, 100, 121], [9, 16, 25, 36, 49, 64, 81, 100, 121, 144], [16, 25, 36, 49, 64, 81, 100, 121, 144, 169], [25, 36, 49, ... | The more efficient way to do that is using numpy.meshgrid(). Here you have an example:
```
i = np.arange(1,10)
I,J = np.meshgrid(i,i)
array = (I+J)**2
```
and array has the desired form.
You could compare the performance between your method and meshgrid. Meshgrid is C-implemented, so it's very fast!
If you need a l... | 2D lists generation Python | [
"",
"python",
"list",
"loops",
""
] |
I am looking for a way to extract lines from a pretty big database in python. I need to retain only those containing one of my keywords.
I thought I could use regex to solve the problem and I've put together the code below. Unfortunately, it gives me some errors (perhaps also due to the fact that my keywords, which are... | Here is my code:
```
import re
data = open('database.txt', 'r')
fileout = open("fileout.txt","w+")
with open('listtosearch.txt', 'r') as f:
keywords = [line.strip() for line in f]
# one big pattern can take time to match, so you have a list of them
patterns = [re.compile(keyword) for keyword in keywords]
for li... | You may want to have a look at the [Aho–Corasick string matching algorithm](http://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algorithm). A working implementation in python can be found [here](http://0x80.pl/proj/pyahocorasick/).
A simple example usage of this module :
```
from pyahocorasick import Tr... | Alternative way to extract lines from text (python-regex) | [
"",
"python",
"regex",
"text",
""
] |
I have confusion regarding what does **request.user** refers to in Django?
Does it refer to **username** field in the **auth\_user** table or does it refer to User model instance?
I had this doubt because I was not able to access email field in the template using `{{request.user.username}}` or `{{user.username}}`.
So... | If your template is receiving [AnonymousUser](https://docs.djangoproject.com/en/1.2/topics/auth/#django.contrib.auth.models.AnonymousUser), the reference to `{{request.user.email}}` will not be found. Previously, you must ask if `{{request.user.is_authenticated }}`.
You must check if it is included `django.core.contex... | `request.user` is User model object.
You cannot access request object in template if you do not pass `request` explicitly.
If you want access user object from template, you should pass it to template or use RequestContext. | What does request.user refer to in Django? | [
"",
"python",
"django",
"email",
"django-templates",
"django-views",
""
] |
In Python you have the `None` singleton, which acts pretty oddly in certain circumstances:
```
>>> a = None
>>> type(a)
<type 'NoneType'>
>>> isinstance(a,None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
``... | You can try:
```
>>> variable = None
>>> isinstance(variable,type(None))
True
>>> variable = True
>>> isinstance(variable,type(None))
False
```
[isinstance](http://docs.python.org/2/library/functions.html#isinstance) takes 2 arguments `isinstance(object, classinfo)` Here, by passing `None` you are setting `classinfo`... | `None` is not a type, it is the singleton instance itself - and the second argument of [`isinstance`](http://docs.python.org/2/library/functions.html#isinstance) must be a type, class or tuple of them. Hence, you need to use `NoneType` from [`types`](http://docs.python.org/2/library/types.html).
```
from types import ... | None Python error/bug? | [
"",
"python",
"python-2.7",
"python-3.x",
"types",
""
] |
I have a program where I need to call another py script from one py script and get a list of dicts from it. I've figured out how to call the other py script and get list as a string from stdout but how do I use it in the second script ?
Here is what the second script outputs.
```
[{'itemkey1': 'item1', 'itemkey2': 'i... | Use `subprocess.check_output` to get the output from that script in a string and then apply `ast.literal_eval` to that string to get the dict object.
```
import ast
import subprocess
ret = subprocess.check_output(['python','some_script.py'])
dic = ast.literal_eval(ret)
```
`ast.literal_eval` demo:
```
>>> ret = ... | `ast.literal_eval` is completely safe
```
>>> import ast
>>> output = "[{'itemkey1': 'item1', 'itemkey2': 'item2'}, {'itemkey1': 'item1', 'itemkey2': 'item2'}]"
>>> ast.literal_eval(output)
[{'itemkey2': 'item2', 'itemkey1': 'item1'}, {'itemkey2': 'item2', 'itemkey1': 'item1'}]
``` | Get list of dicts from another python script? | [
"",
"python",
"stdout",
"ipc",
""
] |
i have 2 lists. First list, `listA` is a list of lists.
```
listA=[[1,2,5,3],[3,1,5],[7,9,2]]
```
Second list, `listB` is a list that i am gonna compare against other lists in listA
```
listB=[1,2,3,4,5,6,7,8,9,10]
```
i want to compare the lists in listA individually and replace with 'T' if the list item exist in ... | You should use [list comprehensions](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions):
```
listC = [ [ ('T' if b in a else b) for b in listB ] for a in listA ]
```
The parentheses are not necessary, but they might make it a bit more readable.
`x if cond else y` is Python's equivalent of the... | Nice and readable :)
```
listC = []
for i in listA:
temp = []
for x in listB:
if x in i:
temp.append('T')
else:
temp.append(x)
listC.append(temp)
print listC
```
Prints:
```
[['T', 'T', 'T', 4, 'T', 6, 7, 8, 9, 10], ['T', 2, 'T', 4, 'T', 6, 7, 8, 9, 10], [1, 'T', ... | python list compare and replace | [
"",
"python",
"list",
""
] |
I am trying to create a form using django form library, yet when viewing the model populated by the form, the values are out of order..for no apparent reason.
Here is my view:
```
def reoccurring_view(request):
if request.method == 'POST':
form = ReoccurringForm(request.POST)
counter = 0
if form.is_valid(... | You can't rely on the ordering of the fields in Django's POST dict I'm afraid - it's essentially a dictionary so there is no set ordering.
If the ordering of the posted data matters, Django provides `request.raw_post_data` to get that. | Python dictionaries are orderless. Because the Django response is a dictionary, it is going to be in an arbitrary order that can not be relied on. | Django Form Ordering is askew | [
"",
"python",
"django",
"forms",
"http",
"post",
""
] |
In Kivy, is there a way to pass image object as a button background, instead of image file name?
`button.background_normal` property accepts only strings. I would like to customize image properties, such as `allow_stretch = False`.
If that succeeds, how can I specify image alignment inside a button, eg. to make it to... | The source is just a property of Button and it is a string as you pointed out. You want a Widget inside a Widget, and that is the basic way Kivy works. So just add the Image as it is. A little bit of positioning would do the rest.
You have to be careful with the positioning. Make sure it is in a visible part and nothi... | In addition to toto\_tico's answer, you can locate the image at the center of the button as:
```
Button:
id: myButton
Image:
source: "./buttonImage.PNG"
center_x: self.parent.center_x
center_y: self.parent.center_y
``` | Passing image object as a button background in Kivy | [
"",
"python",
"kivy",
""
] |
I'm pretty bad at SQL and have been having some troubles doing somewhat of a UNIQUE join of two tables. The SQL structure is somewhat abysmal, but I didn't design it.
I have two tables:
**users**
uid, ufn, uln, ue
*Where users id = uid.*
and
**transactions**
uid, unit, address, start\_date
Basically in the tran... | This will get you close. The problem will be if 2 transactions have the same start date for the same user. But if you don't have that case this should work fine.
```
select u.ufn,
u.uln,
u.ue,
t.unit,
t.address
from users u
inner join (
select uid,
max(star... | Your example SQL has "tenant\_id" but that is not in your tables example?
Are you running this once or 10000 times a day?
Try this:
```
SELECT users.ufn, users.uln, users.ue, transactions.unit, transactions.address
FROM users join transactions on users.uid = transactions.uid
WHERE transactions.UID, transactions.star... | Struggling with a simple SQL JOIN | [
"",
"mysql",
"sql",
"join",
""
] |
need the date in the format yyyy-mm and should be grouped to get
the count but when i give the
```
group by date is says invalid
```
i have found this solution
can anyone help me by providing other solution
```
select
count(*) as count,
Convert(char(10), RH.updated_datetime, 105) as date,
SUM(
datediff(SECOND,... | I think the easiest way to do this is as follows:
```
CONVERT(VARCHAR(7), RH.updated_datetime, 126)
```
However, I have never been a fan of converting dates to strings before the application layer, so if it were me I would keep it as a date format, but convert each date the first of the month using:
```
DATEADD(MONT... | ### Update for SQL Server 2012+
I always find the `CONVERT` magic numbers hard to remember. You can use [`FORMAT`](https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql) instead and provide a formatting pattern string like this:
```
SELECT FORMAT(GetDate(),'yyyy-MM')
```
**See Also**: [Convert da... | need date in the format yyyy-mm in mssql | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am trying to find records which exists in table A but not in table B. If there is only one column to check, then I can use
```
select col_A,col_B,......from A where col_A not in (select Col_A from B).
```
But I have four columns which need to checked.
I did something like this, which works but is not the perfect w... | From Oracle documentation
<http://docs.oracle.com/cd/E11882_01/server.112/e26088/queries004.htm#SQLRF52341>
"MINUS Example The following statement combines results with the MINUS operator, which returns only unique rows returned by the first query but not by the second:"
```
SELECT product_id FROM inventories
MINUS
... | There's an implicit distinct on MINUS that you'd probably want to avoid.
A NOT EXISTS construct would probably be run as a hash anti-join, which would be very efficient.
```
select
col1,
col2,
col3,
... etc
from
table_a a
where
not exists (
select null
from table_b b
where a.col1 = b.col1 a... | Finding records which doesn't exists in other oracle table | [
"",
"sql",
"oracle",
""
] |
Given this list
```
my_lst = ['LAC', 'HOU', '03/03 06:11 PM', '2.13', '1.80', '03/03 03:42 PM']
```
I want to change its `0th` and `1st` values according to the dictionary value:
```
def translate(my_lst):
subs = {
"Houston": "HOU",
"L.A. Clippers": "LAC",
}
```
so the list becomes:
```
[... | If all values are unique then you should reverse the dict first to get an efficient solution:
```
>>> subs = {
... "Houston": "HOU",
... "L.A. Clippers": "LAC",
...
... }
>>> rev_subs = { v:k for k,v in subs.iteritems()}
>>> [rev_subs.get(item,item) for item in my_lst]
['L.A. Clippers', 'Houston... | If the values are unique, then you can flip the dictionary:
```
subs = {v:k for k, v in subs.iteritems()}
```
Then you can use `.get()` to get the value from a dictionary, along with a second parameter incase the key is not in the dictionary:
```
print map(subs.get, my_lst, my_lst)
```
Prints:
```
['L.A. Clippers'... | How to replace elements in a list using dictionary lookup | [
"",
"python",
"list",
"replace",
""
] |
What I am looking to do is merge several rows of data to be displayed as a single row from within either Transact-SQL or SSIS. so for example:
MAKE:
```
REF ID Title Surname Forename DOB Add1 Postcode
---------------------------------------------------------------------------------------... | This will work, but since there is no identity or datetime column - there is no way to find which update row is newer. So if there are more updates on the same column, I just take the first alphabetically/numerically (MIN).
```
WITH CTE AS
(
SELECT ID, REF, MIN(Title) Title, MIN(Surname) Surname, MIN(Forename) Fo... | I added an identity column id2 to make the logic work.
```
declare @t table(id2 int identity(1,1),
REF char(1),
ID int,
Title varchar(10),
Surname varchar(10),
Forename varchar(10),
DOB date,
Add1 varchar(15),
Postcode varchar(10)
)
insert @t values
('D',10, 'MR', 'KINGSTON', NULL, '19750715', '3 WATER SQUARE', NU... | SQL Server : Merging Several Rows of Data into a Single Row | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"ssis",
""
] |
I've got a sql syntax and it gives me the error:
> Msg 8120, Level 16, State 1, Line 1 Column 'VEHICLEMASTR.cconduction'
> is invalid in the select list because it is not contained in either an
> aggregate function or the GROUP BY clause.
Here is the SQL syntax:
```
SELECT A.cplateno,A.cconduction,A.cname,A.cbattery... | The "group by" clause must name every column selected, except those columns that are aggregate functions.
FYI an "aggregate" function is one that returns a single value for many rows, like sum(), count(), etc | a.cconduction needs to be in the group by clause.
When using a `Group By` clause, a column must either have an aggregate function (i.e. COUNT) or be defined in the group by.
A sample group by statement with multiple grouping:
```
SELECT column1_name, column2_name, aggregate_function(column_name3)
FROM table_name
W... | SQL Syntax Error Group By | [
"",
"sql",
"sql-server-2008",
""
] |
I'm new to python coding and I'm trying to create a simple program in emacs.
```
print "Hello World"
def foo():
return "FOO"
def Bar():
return "BAR"
```
In the terminal I have figured out how to run the inicial "HELLO WORLD" but not the methods.
```
$python Test.py #test.py is my file name
Hello World
```
... | From the command line in the same directory.
```
$ python
>> from Test import *
>> foo()
"FOO"
>> Bar()
"BAR"
``` | Inside your Python script, invoke them:
```
print "Hello World"
def foo():
return "FOO"
def Bar():
return "BAR"
print foo();
print Bar();
``` | Beginning Python Emacs & Terminal Setup | [
"",
"python",
""
] |
I do not use dictionary objects often in Python. I've been working on a script that is going to require me to use a dictionary to store dynamically created list'esque information. How can I append a value to a list of values belonging to one key in a dictionary in Python? Is this possible? I would hope to be able to cr... | Use a list as value, list will allow you to append new items:
```
>>> dic = {'PhysicalDrive0': ['0', '1', '2'], 'PhysicalDrive1': ['0', '1']}
>>> dic['PhysicalDrive0'].append('3')
>>> dic['PhysicalDrive1'].append('2')
>>> dic
{'PhysicalDrive1': ['0', '1', '2'], 'PhysicalDrive0': ['0', '1', '2', '3']}
```
To append to... | You should look at `collections.defaultdict` if you can't simply store the value as a list literal...:
```
from collections import defaultdict
dd = defaultdict(list)
dd['Drive1'].append(3)
dd['Drive2'].append(6)
dd['Drive1'].append(2)
# defaultdict(<type 'list'>, {'Drive2': [6], 'Drive1': [3, 2]})
``` | Python 2,7 Dictionary Advice | [
"",
"python",
"dictionary",
""
] |
I wrote a simple little rock, paper, scissors game in python and had some difficulties with an if clause, here's the relevant code:
```
def play():
user = str(input("rock, paper or scissors? Choose one: "))
print("You chose", user)
if user == "paper" or "Paper":
paper()
elif user == "rock" or... | ```
user == "paper" or "Paper"
```
is always true. The `or` operator tests the expressions on either side of itself, and if either is true, the result of the `or` is also true. Your test above checks (up to) two things:
* Is the expression `user == "paper"` true? If so, the whole expression is true, so don't check th... | You can also do this with lists and `in`:
```
if user in ["paper", "Paper"]:
paper()
```
or using regex:
```
import re
user = 'paper'
if re.match('papers?', user):
paper()
elif re.match('[Rr]ock', user):
rock()
```
with regexes you can also do case-insensitive match:
```
import re
user = 'paper'
if re.... | weird behaviour in python if clause | [
"",
"python",
"if-statement",
"clause",
""
] |
Errors are like this:
```
Traceback (most recent call last):
File "NearestCentroid.py", line 53, in <module>
clf.fit(X_train.todense(),y_train)
File "/usr/local/lib/python2.7/dist-packages/scikit_learn-0.13.1-py2.7-linux-i686.egg/sklearn/neighbors/nearest_centroid.py", line 115, in fit
variance = np.array(... | I had a similar problem using the Pystruct `pystruct.learners.OneSlackSSVM`.
It occured because my training labels were floats, in stead of integers. In my case, it was because I initialized the labels with np.ones, without specifying dtype=np.int8. Hope it helps. | It happens quite often that an indexing array should be clearly `integer` type by the way it is created, but in the case of empty list passed, becomes default `float`, a case which might not be considered by the programmer. For example:
```
>>> np.array(xrange(1))
>>> array([0]) #integer type as expecte... | Arrays used as indices must be of integer (or boolean) type | [
"",
"python",
"scikit-learn",
""
] |
I am a novice and learning about dictionaries in python, and spent better part of a day wrapping my head around it, I would appreciate some help!
I would like to create a dictionary of dictionaries:
```
data = [['dog', 'a'], ['mouse', 'a'], ['dog', 'b'], ['mouse', 'c'], ['dog', 'c']]
animals = ['dog', 'mouse']
```
I... | You only really need one loop:
```
data = [['dog', 'a'], ['mouse', 'a'], ['dog', 'b'], ['mouse', 'c'], ['dog', 'c']]
animals = {}
for animal, letter in data:
animals.setdefault(animal, {})[letter] = 0
```
Or if you don't like `setdefault`:
```
for animal, letter in data:
if animal in animals:
animal... | You are setting both `animal_dict['dog']` and `animal_dict['mouse']` to the same `letter_dict` object. Any keys you add to one will be added to the other.
You do not actually need `letter_dict`. Try this instead:
```
for animal in animal_dict:
for d in data:
if d[0] == animal:
animal_dict[anim... | more on creating dictionaries of dictionaries | [
"",
"python",
"loops",
"dictionary",
""
] |
I am searching an XML file generated from Ms word for some phrases. The thing is that any phrase can be interrupted with some XML tags, that can come between words, or even inside words, as you can see in the example:
> `</w:rPr><w:t> To i</w:t></w:r><w:r wsp:rsidRPr="00EC3076"><w:rPr><w:sz w:val="17"/><w:lang w:farea... | Since the situation is *that* complex - don't use regex, just go through your line symbol by symbol:
```
etalone = "String to find"
etalone_length = len(etalone)
counter = 0
for symbol in your_line:
if symbol == etalone[counter]:
counter += 1
if counter == etalone_length:
print("String ... | If I understand the problem correctly, here's a way to tackle the problem without resorting to pathological regular expressions or character-by-character parsing:
```
def do_it(search, text_orig, verbose = False):
# A copy of the text without any "#" markers.
text_clean = text_orig.replace('#', '')
# Star... | Python regex catastrophic backtracking | [
"",
"python",
"regex",
"string",
""
] |
This seems so simple, but I can't seem to figure out how to do it. I have two data sets:
```
SET1
DATE | TOTAL1 | TOTAL2 | TOTAL3
1 Jun 2013 | 0 | 0 | 5
2 Jun 2013 | 0 | 0 | 12
3 Jun 2013 | 0 | 0 | 34
4 Jun 2013 | 0 | 0 | 50
SET2
DATE | TOTAL1 | TOTAL2 | TOTAL3
1 Ju... | ```
SELECT
DATE,
SUM(TOTAL1) AS TOTAL1,
SUM(TOTAL2) AS TOTAL2,
SUM(TOTAL3) AS TOTAL3
FROM
(
SELECT
DATE,
TOTAL1,
TOTAL2,
TOTAL3
FROM
SET1
UNION ALL
SELECT
DATE,
TOTAL1,
TOTAL2,
TOTAL3
... | I'm guessing that you want a `FULL JOIN`:
```
SELECT COALESCE(T1.DATE,T2.DATE) AS DATE,
COALESCE(T1.TOTAL1,0)+COALESCE(T2.TOTAL1,0) AS TOTAL1,
COALESCE(T1.TOTAL2,0)+COALESCE(T2.TOTAL2,0) AS TOTAL2,
COALESCE(T1.TOTAL3,0)+COALESCE(T2.TOTAL3,0) AS TOTAL3
FROM Table1 T1
FULL JOIN Table2 T2
ON ... | Merging SQL data? | [
"",
"sql",
"postgresql",
""
] |
I am using an automation framework and I am getting random error after many iterations which is as follows. Can someone help me understand what this could correspond to !!
```
_os.environ['PATH'] = r'C:\DAL;' + _os.environ['PATH']
File "c:\Python26\lib\os.py", line 420, in __setitem__
putenv(key, item)
OSError: ... | You are creating too long a path and the OS no longer accepts a longer environment variable.
Extend the path only *once*. Test for the presence of the paths you are adding:
```
path = _os.environ['PATH'].split(_os.pathsep)
for extra in (r'C:\Intel\DAL', r'C:\intel\dal', _lakemore_path, plugin_path):
if extra not ... | Add one more `"/"` in the last `"/"` of path for example:
`open('C:\Python34\book.csv')` to `open('C:\Python34\\\book.csv')`
 | Python Error: OSError: [Errno 22] Invalid argument | [
"",
"python",
"error-handling",
""
] |
I am dealing with an issue that involves multiple if and elif conditining..precisely stating, my case goes as follows:
```
if len(g) == 2:
a = 'rea: 300'
b = 'ref: "%s": {"sds": 200},"%s": {"sds": 300}' % (g[0],g[1])
elif len(g) == 3:
a = 'rea: 400'
b = 'ref: "%s": {"sds": 200},"%s": {"sds": 300},"%s": {"... | Maybe something like this:
```
g_len = len(g)
a = "rea: {}".format((g_len + 1) * 100)
b = "ref: "
for i, g_i in enumerate(g):
b += ' "{}": {{"sds": {}}},'.format(g_i, (i+2) * 100)
``` | Try this method:
```
def func(g):
if not 1 < len(g) < 100:
raise ValueError('inadequate length')
d = {x:{'sds':(i+2)*100} for i, x in enumerate(g)}
a = 'rea: %s00' % (len(g)+1)
b = 'ref: %s' % str(d)[1:-1]
return (a, b)
```
I don't know why you are creating a string `b` which looks very mu... | Create if-elif statements using for loop | [
"",
"python",
"if-statement",
"for-loop",
""
] |
I have a database model like this:
```
class RssNewsItem(models.Model):
title = models.CharField(max_length=512)
description = models.TextField()
image_url = models.CharField(max_length=512)
published = models.DateTimeField(auto_now=True)
url = models.CharField(max_length=512, default='')
autho... | ```
from itertools import chain
q1 = RssNewItem.objects.filter(author="author1").order_by("-published")[:3]
q2 = RssNewItem.objects.exclude(author="author1").order_by("-published")[:7]
q = list(chain(q1, q2))
```
P.s. Here's a good SO answer on merging querysets:
[How to combine 2 or more querysets in a Django view?]... | ```
class RssNewsItemManager(models.Manager):
def get_rsslist_with_promoted(self,auth):
prom=self.objects.filter(author=auth).order_by("-published")[:3]
unprom=self.objects.exclude(author=auth).order_by("-published")[:7]
return prom|unprom
class RssNewsItem(models.Model):
title = models... | Django, retrieving database news items promoting a certain author | [
"",
"python",
"django",
"django-models",
""
] |
I have a dictionary with key-value pair. My value contains strings. How can I search if a specific string exists in the dictionary and return the key that correspond to the key that contains the value.
Let's say I want to search if the string 'Mary' exists in the dictionary value and get the key that contains it. This... | I am a bit late, but another way is to use list comprehension and the `any` function, that takes an iterable and returns `True` whenever one element is `True` :
```
# Checking if string 'Mary' exists in the lists of the dictionary values
print any(any('Mary' in s for s in subList) for subList in myDict.values())
```
... | You can do it like this:
```
#Just an example how the dictionary may look like
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}
def search(values, searchFor):
for k in values:
for v in values[k]:
if... | How to search if dictionary value contains certain string with Python | [
"",
"python",
"string",
"dictionary",
"key-value",
""
] |
From what I know, CPython programs are compiled into intermediate bytecode, which is executed by the virtual machine. Then how does one identify without knowing beforehand that CPython is written in C. Isn't there some common DNA for both which can be matched to identify this? | Python isn't written in C. Arguably, Python is written in an esoteric English dialect using BNF.
However, all the following statements are true:
1. *Python is a language, consisting of a language specification and a bunch of standard modules*
2. Python source code is compiled to a bytecode representation
3. this byte... | The **interpreter** is written in C.
It compiles Python code into bytecode, and then an evaluation loop interprets that bytecode to run your code.
You identify what Python is written in by looking at it's source code. See the [source for the evaluation loop](http://hg.python.org/cpython/file/5bc3d8d22a93/Python/ceval... | What does it mean when people say CPython is written in C? | [
"",
"python",
"cpython",
""
] |
I'm trying to fill two forms and login to my banks website.
I can get the first form for the username to fill but I can't seem to get the form for the password to fill.
Here's the code I'm using:
```
from splinter import Browser
username2 = '***'
password2 = '***'
browser2 = Browser()
browser2.visit('http://mijn.i... | Here is the working code:
```
from splinter import Browser
# Define the username and password
username2 = '***'
password2 = '***'
# Choose the browser (default is Firefox)
browser2 = Browser()
# Fill in the url
browser2.visit('https://mijn.ing.nl/internetbankieren/SesamLoginServlet')
# Find the username form ... | The error indicates that you are trying to fill a list of elements. You need to select just one of the elements in the list. You probably want something like:
```
find_by_name('foo').first.fill()
``` | Filling a password form with Splinter | [
"",
"python",
"forms",
"passwords",
"webdriver",
"splinter",
""
] |
I have a table in SQL Server Management Studio with columns containing ranges of numbers as strings. I am trying to find a way to extract the numeric values from the string and insert them into a new table.
For example, in the table I have the value `12.45% - 42.32%` as a string. I'd like to be able to get `12.45` and... | Assuming your data is consistent, this should work fine, and has the added advantage of being easier on the eyes. Also consider decimal if you're going for precision.
```
select
cast(left(r, charindex('%', r) - 1) AS float) as minVal,
cast(replace(right(r, charindex('-', r) - 1), '%', '') as float) AS maxVal
from ... | The function is quite close. You just use numeric and add the point:
```
with C as
(
select cast(substring(S.Value, S1.Pos, S2.L) as decimal(16,2)) as Number,
stuff(s.Value, 1, S1.Pos + S2.L, '') as Value
from (select @String+' ') as S(Value)
cross apply (select patindex('%[0-9,.]%', S.Val... | Extract multiple decimal numbers from string in T-SQL | [
"",
"sql",
"t-sql",
"extract",
"string-matching",
""
] |
i have two tables
TableInitial
```
EnId DateSeen
1 2013-05-01
4 2013-05-06
7 2013-05-01
13 2013-05-09
17 2013-05-09
```
TableFollowup
```
EnId FId DateSeen
1 1 2013-05-04
1 2 2013-05-05
1 3 2013-05-06
4 1 2013-05-09
4 2 2013-05-010
7 1 ... | If Fid is always incrementing, you can use a solution like this:
```
SELECT EnID, MAX(FId), MAX(DateSeen)
FROM (
SELECT EnID, Null AS FId, DateSeen
FROM TableInitial
UNION ALL
SELECT EnId, FId, DateSeen
FROM TableFollowup
) s
GROUP BY EnID
```
Please see fiddle [here](http://sqlfiddle.com/#!2/719e1/1). Or y... | Tunning up your query:
```
select EnId, FId, DateSeen from tableFollowup t1
WHERE DateSeen =(Select MAX(t2.DateSeen) FROM tableFollowup t2 WHERE t2.EnId = t1.EnId)
UNION
select EnId, '' AS FId, DateSeen from tableInitial
Where EnId not in (Select enid from tableFollowup)
GROUP BY EnId
``` | SQL Union to return most recent entry | [
"",
"sql",
"union",
""
] |
I have a matrix of the form,
```
mymatrix=[[1,2,3],[4,5,6],[7,8,9]]
```
I want to the get the index of, say for example, 9 which is at (2,2).
What I have tried to do so far.
```
for i,j in enumerate(mymatrix):
for k,l in enumerate(j):
if l==9:
print i,k
```
Is there a better way of doing the same.... | If you want all of the locations that the value appears at, you can use the following list comprehension with `val` set to whatever you're searching for
```
[(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]
```
for example:
```
>>> mymatrix=[[1,2,9],[4,9,6],[7,8,9]]
>>> val = 9
>>> [(inde... | If you convert mymatrix to a numpy array you can jsut use numpy.where to return the indices:
```
>>> import numpy as np
>>> mymatrix=[[1,2,3],[4,5,6],[7,8,9]]
>>> a = np.array(mymatrix)
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> b = np.where(a==9)
>>> b
(array([2]), array([2]))
>>> mymatrix=[[1,2... | Find indices of a value in 2d matrix | [
"",
"python",
"optimization",
"matrix",
""
] |
I created a `numpy.recarray` from a .csv-Inputfile using the `csv2rec()`-Method. The Inputfile and consequently the recarray have empty rows with no data (resp. `nan`-values). I want to slice this recarray at the `nan`-rows into multiple sub-arrays, excluding the `nan`-rows in the final arrays as shown below.
Original... | For a `2D-array`:
```
a[~np.all(np.isnan(a),axis=1)]
```
For a structured array (recarray) you can do this:
```
def remove_nan(a, split=True):
cols = [i[0] for i in eval(str(a.dtype))]
col = cols[0]
test = ~np.isnan(a[col])
if not split:
new_len = len(a[col][test])
new = np.empty((new... | If you just wish to get rid of the blanks, rather than slice on them, then just compress your array with the selection criteria being a check for not nan. Hint, nan <> nan.
If you really wish to slice at the nans then use a loop of some such to generate a list of the Non-Nan indexes and then use choose to generate the... | Slicing numpy recarray at "empty" rows | [
"",
"python",
"numpy",
"slice",
"recarray",
""
] |
I have a user defined function called `Sync_CheckData` under Scalar-valued functions in Microsoft SQL Server. What it actually does is to check the quantity of issued product and balance quantity are the same. If something is wrong, returns an `ErrorStr nvarchar(255)`.
Output Example:
```
Balance Stock Error for Prod... | Try this
```
DECLARE @STR AS VARCHAR(1000)
SELECT @STR='Balance Stock Error for Product ID : 4'
SELECT substring(@STR,charINDEX(':',@STR)+1,LEN(@STR)-charINDEX(':',@STR)+1)
``` | I'd use `RIGHT` for this:
```
declare @response varchar(100)
set @response = 'Balance Stock Error for Product ID : 4'
select right(@response, len(@response) - charindex(':', @response))
```
Sample fiddle: <http://sqlfiddle.com/#!3/d41d8/16397> (altered from above) | Query to return substring from string in SQL Server | [
"",
"sql",
"sql-server",
"substring",
"user-defined-functions",
""
] |
Can anyone explain what causes this for better understanding of the environment?
emacs, unix
input:
```
with open("example.txt", "r") as f:
for files in f:
print files
split = files.split()
print split
```
output:
```
Hello world
['Hello', 'world']
Hello wörld
['Hello', 'w\xf6rld']
``` | Python is printing the string representation, which includes a non-printable byte. Non-printable bytes (anything outside the ASCII range or a control character) is displayed as an escape sequence.
The point is that you can copy that representation and paste it into Python code or into the interpreter, producing the ex... | In python, lists are simply printed using unicode encoding. Basically printing a list makes the list calls `__repr__` on each element (which results in a unicode print for strings). If you print each element by itself (in which case a strings `__str__` method is used, rather than the list's) you get what you expect.
`... | Python lists with scandinavic letters | [
"",
"python",
"list",
"encoding",
""
] |
I am trying to write a short program that looks through a directory, takes the filenames of image files, and appends them to match the name of their directory and renumbers and sorts them for processing later. So far I can get the name of the folder, and replace a specific part of the filename with it, using the follow... | Use this simple function:
```
import re
def get_name_and_number(text):
return re.match(r'(\D+)(\d+).*', text).groups()
```
Example:
```
>>> get_name_and_number('storm000045.tiff')
('storm', '000045')
```
---
Or this one:
```
def extract_numbers(text):
return ''.join([x for x in text if x.isdigit()])
```
... | Using [re](http://docs.python.org/2/library/re.html):
```
>>> import re
>>> re.split('(\d+)', 'torm000045.tiff')
['torm', '000045', '.tiff']
>>> re.split('(\d+)', 'torm000_045.tiff')
['torm', '000', '_', '045', '.tiff']
>>> re.split('(\d+)', 'torm000_045.tiff')[1::2]
['000', '045']
```
2nd, 4th, 6th elements are numb... | How can I separate the numeric parts of filenames using Python? | [
"",
"python",
"split",
"filenames",
""
] |
I have a Python project that is hosted on both Github and PyPI.
On Github: <https://github.com/sloria/TextBlob/blob/master/README.rst>
On PyPi: <https://pypi.python.org/pypi/textblob>
**My README.rst doesn't seem to be formatting correctly on PyPI, but it looks fine on Github.**
I have already read [this](https://s... | **Historical note**: *this answer covered a release of PyPI that is no longer used, as it has since been replaced by a new server called [Warehouse](https://github.com/pypa/warehouse), which has been tracking docutils releases as they come out (which at the time of this note, was 0.16). If you are having issues with Re... | For a [package I uploaded recently](https://pypi.python.org/pypi/TaarifaAPI), the issue was a relative link (not an in-page link) in the `README.rst` to our contribution guidelines, which [renders fine on GitHub](https://github.com/blog/1395-relative-links-in-markup-files), but trips up rendering on PyPI.
To fix this,... | reStructuredText: README.rst not parsing on PyPI | [
"",
"python",
"restructuredtext",
"pypi",
""
] |
I have a large nested list and each list within the nested list contains a list of numbers that are formatted as floats. However every individual list in the nested list is the same except for a few exceptions. I want to extract the numbers that are common to all of the lists in the nested list. A simple example of my ... | You can use `reduce` and `set.intersection`:
```
>>> reduce(set.intersection, map(set, nested_list))
set([2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0])
```
Use `itertools.imap` for memory efficient solution.
# Timing Comparisons:
```
>>> lis = [[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0... | Try this, it's the simplest solution:
```
set.intersection(*map(set, nested_list))
```
Or if you prefer to use generator expressions, which should be a more efficient solution in terms of memory usage:
```
set.intersection(*(set(e) for e in nested_list))
``` | How to find elements that are common to all lists in a nested list? | [
"",
"python",
"overlap",
"nested-lists",
""
] |
I have a sql `Table` `Messages`
it has **4 columns** which are
```
1. sno
2. sender_id
3. reciever_id
4. message
```
i hv to make a `SELECT` statement which is a `unique combination` of **sender\_id** and **reciever\_id** when either of them is equal to 1.
Also i want that if a combination of **(1,3)** is include... | SQL that works in most RDBMS:
```
SELECT DISTINCT
CASE WHEN sender_id > reciever_id THEN reciever_id ELSE sender_id END,
CASE WHEN sender_id > reciever_id THEN sender_id ELSE reciever_id END
FROM
MyTable;
```
MySQL SQL dialect (and ANSI SQL):
```
SELECT DISTINCT
LEAST(sender_id, reciever_id)
GREA... | create table #temp(sno int , sender\_id int, reciever\_id int)
insert into #temp
select '1','1','1'
union all
select '2','2','2'
union all
select '3','3','3'
union all
select '1','1','1'
union all
select '2','2','2'
union all
select '3','3','3'
union all
select '3','3','3'
union all
select '1','1','3'
... | sql select statement to display distinct combination of two columns | [
"",
"mysql",
"sql",
""
] |
I have a simple query that selects one field and only one row, thus one value.
Is there any way to make it return NULL if the query results in an empty set? Instead of returning zero rows?
I think I need to use something with NOT EXISTS, THEN NULL but not certain about it. | ```
select
(Your entire current Select statement goes here) as Alias
from
dual
```
`dual` is a built in table with a single row that can be used for purposes like this. In Oracle this was mandatory until 23c. [MySQL supports it](https://dev.mysql.com/doc/refman/8.0/en/select.html), but you can also just select a ... | An easy way to do this is with aggregation:
```
select max(col)
from t
where <your condition here>
```
This always returns one row. If there is no match, it returns `NULL`. | How to return NULL when result is empty? | [
"",
"mysql",
"sql",
""
] |
How do I get the probability of a string being similar to another string in Python?
I want to get a decimal value like 0.9 (meaning 90%) etc. Preferably with standard Python and library.
e.g.
```
similar("Apple","Appel") #would have a high prob.
similar("Apple","Mango") #would have a lower prob.
``` | There is a built in.
```
from difflib import SequenceMatcher
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
```
Using it:
```
>>> similar("Apple","Appel")
0.8
>>> similar("Apple","Mango")
0.0
``` | # Solution #1: Python builtin
use [SequenceMatcher](https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher) from [difflib](https://docs.python.org/3/library/difflib.html)
**pros**:
built-in python library, no need extra package.
**cons**: too limited, there are so many other good algorithms for stri... | Find the similarity metric between two strings | [
"",
"python",
"probability",
"similarity",
"metric",
""
] |
I am somewhat new to Python and have a seemingly simple question.
I have a python script that interacts with an API (RHN Satellite if you're curious). This API returns a date in the form of a string and it always trims leading 0's. For example, 6/1/13 or 10/9/12. I need to convert this string to a date and determine t... | I think you just have a typo, use `%y` instead of `$y`:
```
date = datetime.datetime.strptime(var, '%m/%d/%y')
``` | This code works for me, provided you change `$y` to `%y` in the format code. | Python: trouble converting string into date | [
"",
"python",
"datetime",
""
] |
This is my table of a train time table I want a solution for train between stations
```
Train Code
15609 ABC
15609 XYZ
15609 PQR
15609 ADI
15609 QWE
15609 XPM
15609 IND
15680 ABC
15680 XYZ
15680 PQR
15680 ADI
15680 QWE
15680 XPM
15680 IND
```
For the output the user will give two i... | This should do the trick. It also should perform well--no JOIN is needed.
```
SELECT
Train
FROM
dbo.TrainTime
WHERE
Code IN ('ABC', 'XYZ')
GROUP BY
Train
HAVING
Count(DISTINCT Code) = 2
;
``` | I think what you want is something like this
```
select Train from mytable where Code = 'ABC'
intersect
select Train from mytable where Code = 'XYZ'
```
[**SQL FIDDLE EXAMPLE**](http://sqlfiddle.com/#!6/fb99b/2) | SQL Query To find Train between stations | [
"",
"asp.net",
"sql",
"sql-server",
""
] |
I need create a query for postgresql that shows requests made within 100 milliseconds. The postgresql table request has request id (request\_id) and timestamp(create\_stamp).
Mu query below works but very slowly.
```
select
b1.create_stamp as st1,
b2.create_stamp as st2,
b1.request_id as b1_id,
b2.req... | Consider the following query:
```
SELECT Q.*
FROM (
SELECT *, lag (create_stamp, 1) OVER (ORDER BY request_id) prev
FROM request
) Q
WHERE
create_stamp - prev <= interval '00:00:00.1';
```
[[SQL Fiddle]](http://sqlfiddle.com/#!12/4192e/46)
It will return all rows such that there is a previous1 row within... | You want to use `lag()`/`lead()` to check previous and next values. This should be much faster than a self-join:
```
select r.*
from (select r.*,
lag(create_stamp) over (order by request_id) as prevcs,
lead(create_stamp) over (order by request_id) as nextcs
from request r
) r
where... | How to optimize a SQL query showing 2 adjacent rows with closed in values timestamps? | [
"",
"sql",
"postgresql",
""
] |
I am looking for a different way to get a string list from a tuple of tuples. This is how I do right now:
```
x = (('a',1), (2,3), (4,), (), (None,))
op_list = []
for item in x:
if item and item[0]:
op_list.append(str(item[0]))
print op_list
```
Output: ['a', '2', '4']
I cannot think of any other way to ... | ```
>>> x = (('a',1), (2,3), (4,))
>>> [str(item[0]) for item in x if item and item[0]]
['a', '2', '4']
``` | Maybe using [`map`](http://docs.python.org/2/library/functions.html#map) and [`lambda`](http://docs.python.org/2/reference/expressions.html#lambda) functions gives you the easiest and more compact way to do it:
```
>>> x = (('a',1), (2,3), (4,), (None,), ())
>>> filter(None, map(lambda i: str(i[0]) if len(i) > 0 and i... | Create a list from a tuple of tuples | [
"",
"python",
"list",
"tuples",
""
] |
So I have the following datasource ("/" represents tab delimited locales), and I want to get it into a JSON format. The data have no headers, and I'd like to be able to insert one for the name, the degree, the area (CEP), the phone number, the email, and the url. Not sure if this will be possible for the first column w... | First make sure that delimiter is really what you think. You can check this by opening the file using openoffice or writing a python function to detect the delimiter using regular expressions (re module). Also make sure that lines are ending with "/n" or windows style (additional r).
Header is nothing more than the fi... | To do this in python you can try and read each line (fixing the data as you go) and then write a fixed Tab Separated Value file with headers like so:
```
import csv
rows = []
with open('rawdata.txt') as f:
row = ['']
for line in f.readlines():
data = line.rstrip().split('\t')
if len(data) > 1:... | How to insert headers into a tab delimited file? | [
"",
"python",
""
] |
I am trying to retrieve last record from database table. My query is as below:
```
Select AppointmentDate from tbAppointment where MID=@MID
```
MID is employee id code and primary key is ID.
Since primary key(in my case) is integer and auto incremented on each record insertion, I am trying to get last record on the... | ```
SELECT TOP 1 AppointmentDate
FROM tbAppointment
WHERE MID = @MID
ORDER BY ID DESC
``` | ```
Select Top 1
AppointmentDate from tbAppointment
where MID=@MID
Order By ID Desc
```
This worked for me, It helped me to retrieve last row inserted into database table. Thanks to James :) | Select last record from database on the basis of primary key | [
"",
"sql",
"sql-server-2008",
""
] |
Suppose I'm designing a database for an insurance company with the following two tables:
**Customers**
```
CustomerID, CustomerName
```
**Policies**
```
PolicyID, CustomerID, EffectiveDate, ExpirationDate
```
A customer is considered "Active" if it has a policy such that the expiration date of the policy is after ... | As duskwuff says, this is a common practice.
However, denormalization has some costs - you have to come up with an alternative way to keep the "active" column up to date, and that process will introduce more code and therefore opportunities for failure.
In general, I strongly recommend only denormalizing if you know ... | What you are describing is what's known as a *denormalized* database schema. It's a perfectly valid technique to use to improve performance, so long as you can ensure that data remains consistent.
Further reading at: <https://en.wikipedia.org/wiki/Database_normalization> | Is it okay to design a database with columns that could possibly contradict each other | [
"",
"sql",
"database",
"database-design",
""
] |
I am creating a screenshot module using only pure python (ctypes), no big lib like win32, wx, QT, ... It has to manage multi-screens (what PIL and Pillow cannot).
Where I am blocking is when calling CreateDCFromHandle, ctypes.windll.gdi32 does not know this function. I looked at win32 source code to being inspired, bu... | Edit, I found my mystake! This is the code that works:
```
srcdc = ctypes.windll.user32.GetWindowDC(0)
memdc = ctypes.windll.gdi32.CreateCompatibleDC(srcdc)
bmp = ctypes.windll.gdi32.CreateCompatibleBitmap(srcdc, width, height)
ctypes.windll.gdi32.SelectObject(memdc, bmp)
ctypes.windll.gdi32.BitBlt(memdc, 0, 0, width,... | Looking at [the source](http://pywin32.hg.sourceforge.net/hgweb/pywin32/pywin32/file/ed400a27739f/Pythonwin/win32dc.cpp#l138) for [`pywin32`](http://starship.python.net/crew/mhammond/win32/), `CreateDCFromHandle` is a fabrication. It does not exist in the Windows API; it is simply a bridge converting a Windows API thin... | Screenshot [ctypes.windll CreateDCFromHandle] | [
"",
"python",
"ctypes",
"python-mss",
""
] |
I have created a set of 6 random integers and I wish to write 500 of them into a text file so it looks like this inside the text file:
x, x, xx, x, xx, x \n
x, x, x, xx, x, x ....etc
(where x is an integer)
```
from random import shuffle, randint
def rn():
return randint(1,49);
print "Random numbers are: " , r... | How about this:
```
print "Random numbers are: "
for _ in xrange(500):
print rn(), rn(), rn(), rn(), rn(), rn()
```
If you want to write to text file:
```
with open('Output.txt', 'w') as f:
f.write("Random numbers are: \n")
for _ in xrange(500):
f.write("%s,%s,%s,%s,%s,%s\n" % (rn(), rn(), rn(), ... | Iterate over a sufficiently-large generator.
```
for linenum in xrange(500):
...
``` | Write multiple values into text file in Python? | [
"",
"python",
""
] |
This question seems to come up regularly both on StackOverflow and elsewhere, yet I wasn't able to find a completely satisfactory solution anywhere.
There seem to be two types of common solutions. The first one (from e.g. <http://article.gmane.org/gmane.comp.python.general/630549>) uses a function decorator:
```
clas... | I think the metaclass' `__prepare__` method can be used for this by injecting a decorator that knows about the class hierarchy:
```
def log_docstring(fn):
print('docstring for %r is %r' % (fn, fn.__doc__))
return fn
class InheritableDocstrings(type):
def __prepare__(name, bases):
classdict = dict(... | Starting in Python 3.5, [`inspect.getdoc`](https://docs.python.org/3/library/inspect.html#inspect.getdoc) searches the inheritance tree for a docstring. So if you leave the docstring for the child empty, it will retrieve it from the parent. That avoids the need for code repetition, and automatic code generators like sp... | Python 3 - Method docstring inheritance without breaking decorators or violating DRY | [
"",
"python",
"python-3.x",
"inheritance",
"docstring",
""
] |
I'm trying to parse a `.txt` file with regex:
```
#file = '22 test 333'
with open('file.txt', 'r') as f:
pattern = '\d\d(?=\s)' # should match 22
data = re.compile(pattern)
print f.read() # prints '22 test 333'
print data.findall(f.read()) # outputs an empty list []
```
Regex is corre... | You read the file *already*. The file pointer is now at the end and you won't read any more data.
Store the file data once:
```
contents = f.read()
print contents # prints '22 test 333'
print data.findall(contents) # outputs ['22']
```
Alternatively, seek back to the start:
```
print f.read() ... | You are reading the file which is already read. If you omit the "print f.read()" line, everything should work. Alternatively, after printing file, you can do "f.seek(0)", and that should return the cursor in file to the first position. | Parsing text in a file with regex | [
"",
"python",
"regex",
"file",
""
] |
I have a pandas dataframe/csv of the form
```
date Country Type Val
2013-01-01 USA x 23
2013-01-01 USA y 13
2013-01-01 MX x 11
2013-01-01 MX y 14
2013-01-02 USA x 20
2013-01-02 USA y 19
2013-01-02 MX x ... | Probably not the most elegant way possible, but using [unstack](http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-stacking-and-unstacking):
```
>>> df
date Country Type Val
0 2013-01-01 USA x 23
1 2013-01-01 USA y 13
2 2013-01-01 MX x 11
3 2013-01-01 ... | I cooked up my own pivot based solution to the same problem before finding Dougal's answer, thought I would post it for posterity since I find it more readable:
```
>>> pd.__version__
'0.15.0'
>>> df
date Country Type Val
0 2013-01-01 USA x 23
1 2013-01-01 USA y 13
2 2013-01-01 MX ... | Pandas DataFrame: transforming frame using unique values of a column | [
"",
"python",
"csv",
"pandas",
""
] |
I have a table for e.g.
```
Merchant(
id (PK,char(15),not null),
name (varchar(22),null),
city(varchar(10),null),
location(varchar(10),null),
state_code(int,null),
country_code(int,null)
)
```
Where `city` is always `NULL` and `name` is also `NULL`.
Someone updated these fields as the *string... | You can fix the problematic rows like so:
```
UPDATE Merchant
SET city = NULL
WHERE city = 'NULL';
UPDATE Merchant
SET name = NULL
WHERE name = 'NULL';
```
---
To simply find the rows with the *string* `"NULL"`:
```
SELECT * FROM Merchant
WHERE city = 'NULL'
OR name = 'NULL';
```
Or to find real `NULL`s:
```
SEL... | You can try something like
```
SELECT *
FROM Merchant
WHERE city = 'NULL'
OR name = 'NULL'
```
This should return all rows where either column city or column name is set to the string NULL.
```
SELECT *
FROM Merchant
WHERE city IS NULL
OR name IS NULL
```
Will return all rows where either column city or column na... | How to locate the difference in default NULL and NULL string value | [
"",
"sql",
""
] |
I am making an program that simulates the roll of a dice 100 times. Now I want to sort the output of the random numbers that are given by the program. How do I have to do that?
```
import random
def roll() :
print('The computer will now simulate the roll of a dice 100 times')
list1 = print([random.randint(1,6... | You do not *have* a list. The `print()` function returns `None`, not whatever it just printed to your terminal or IDE.
Store the random values, *then* print:
```
list1 = [random.randint(1,6) for _ in range(100)]
print(list1)
```
Now you can just sort the list:
```
list1 = [random.randint(1,6) for _ in range(100)]
l... | The above problem can also be solved using **for loop** as follows -
```
>>> import random
>>> mylist = []
>>> for i in range(100):
mylist.append(random.randint(1,6))
>>> print(mylist)
```
To sort the list, issue the following commands -
```
>>> sortedlist = []
>>> sortedlist = sorted(mylist)
>>> print(s... | Python: how to sort random numbers in list | [
"",
"python",
"sorting",
"python-3.x",
""
] |
How can I construct a SQL statement that will always return a start date of July 1 of the previous year, and an end date of June 30 of the current year based on GETDATE()? Right now I have
```
Dateadd(yy, Datediff(yy,1,GETDATE())-1,0) AS StartDate,
DateAdd(dd,-1,Dateadd(yy, Datediff(yy,0,GETDATE()),0)) AS EndDate
... | You could just add another DATEADD() to your current script:
```
SELECT DATEADD(month,6,DATEADD(yy, DATEDIFF(yy,1,GETDATE())-1,0)) AS StartDate
,DATEADD(month,6,DATEADD(dd,-1,DATEADD(yy, DATEDIFF(yy,0,GETDATE()),0))) AS EndDate
``` | This seems like an odd request. One way of doing it is by constructing date strings and parsing them:
```
select cast(cast(year(GETDATE()) - 1 as varchar(255))+'-07-01' as DATE) as StartDate,
cast(cast(year(GETDATE()) as varchar(255))+'-06-30' as DATE) as EndDate
```
This constructs the strings in the format `... | Creating a dynamic date range in SQL | [
"",
"sql",
"sql-server",
"date",
"date-range",
""
] |
When I try to run the following code...
```
from telnetsrvlib import *
if __name__ == '__main__':
"Testing - Accept a single connection"
class TNS(SocketServer.TCPServer):
allow_reuse_address = True
class TNH(TelnetHandler):
def cmdECHO(self, params):
""" [<arg> ...]
Echo parameters
E... | Install the UniCurses module from here: <https://pypi.python.org/pypi/UniCurses>
You may need to alter some of your code in order to use it, as it provides the functionality of NCurses, not the vanilla curses library.
Unfortunately, no direct Python for Windows port of curses exists. | You could also look into installing the curses module from here:
<http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses>.
It allows python's native curses to be used on Windows, so all your standard python curses code can be used. | Error no module named curses | [
"",
"python",
"windows",
"python-2.7",
"telnet",
"curses",
""
] |
```
def shuffle(self, x, random=None, int=int):
"""x, random=random.random -> shuffle list x in place; return None.
Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.
"""
randbelow = self._randbelow
for i in reversed(ran... | Clearly you're passing in `d.keys()` to your `shuffle` function. Probably this was written with python2.x (when `d.keys()` returned a list). With python3.x, `d.keys()` returns a `dict_keys` object which behaves a lot more like a `set` than a `list`. As such, it can't be indexed.
The solution is to pass `list(d.keys())... | You're passing the result of `somedict.keys()` to the function. In Python 3, `dict.keys` doesn't return a list, but a set-like object that represents a view of the dictionary's keys and (being set-like) doesn't support indexing.
To fix the problem, use `list(somedict.keys())` to collect the keys, and work with that. | TypeError: 'dict_keys' object does not support indexing | [
"",
"python",
"python-3.x",
"dictionary",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.