Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am using sql server 2008, i have the following data
```
sNames sDate
(varchar(MAX)) (date)
========== =============
ALS 10/02/2012
SSP 11/03/2012
MRP 11/05/2012
ALS 14/06/2012
ALS 04/10/2012
ALS 03/11/2012
MRP 05/09/2012... | Using the latest dates for duplicate `sNames` you can do
```
select sNames, max(sDate)
from your_table
group by sNames
order by max(sDate) desc
``` | ```
select sName,sDate From [your_table] order by sDate Desc
``` | Order By and Distinct in same SQL query | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2005",
""
] |
Disclaimer: I'm not sure how to title this question correctly, so I apologize if it has been asked already. The questions I found with similar titles and content did not address my problem.
I have two tables, Issues and Text. Issues and Text both share an ID column that acts as the primary key for Issues. Text uses ID... | ```
SELECT
Issues.ID,
Issues.Column1,
Issues.Column2,
Text.Value Column3,
Text2.Value Column4
FROM
Issues LEFT OUTER JOIN Text ON Text.ID = Issues.ID AND Text.Field = 'A'
LEFT OUTER JOIN Text AS Text2 ON Text2.ID = Issues.ID AND Text2.Field = 'B'
``` | You can also use an aggregate function with a CASE expression to get the result:
```
select i.id,
i.column1,
i.column2,
max(case when t.field='A' then t.value end) Column3,
max(case when t.field='B' then t.value end) Column4
from issues i
left join text t
on i.id = t.id
group by i.id, i.column1, i.column2;
`... | SQL Join with Multiple Rows of a Single Table | [
"",
"sql",
"join",
"netezza",
""
] |
How to find rows whose date column is null without using 'is null' in the query?
```
SELECT * FROM HR_OPERATING_UNITS WHERE date_to IS NULL;
```
In above query I want to use a binding variable which can have null in it.
So, expected query is:
```
SELECT * FROM HR_OPERATING_UNITS WHERE date_to=:P_TO_DATE;
```
But th... | The standard approach is to handle the variable being null separately:
```
SELECT * FROM HR_OPERATING_UNITS
WHERE date_to=:P_TO_DATE
OR (:P_TO_DATE IS NULL AND date_to IS NULL)
```
If you really must only have one reference to the variable:
```
SELECT * FROM HR_OPERATING_UNITS
WHERE COALESCE(date_to, '1900-01-01') =... | If I understood your question you want to filter whenever or bind variable is null, or not. If so, try the following:
```
SELECT * FROM HR_OPERATING_UNITS WHERE (:P_TO_DATE IS NULL AND date_to IS NULL) OR (date_to=:P_TO_DATE);
``` | Without using 'isnull' and find rows which are having null in a particular column | [
"",
"sql",
""
] |
I have a MySQL database with the following tables:
```
items | id, item
items_tags | id, item_name, item_id, tag_name, tag_id
tags | id, tag
```
I'd like to allow the user to search for items with any tag or any combination of tags. Here's some example data to show what I'd like to do:
```
items:
id | it... | if you want the item with any of the two tag then:
```
select distinct item_id, item_name
from items_tags
where tag_name in ('yellow', 'fruit');
```
if you want the item having both tag then:
```
select item_id, item_name
from items_tags
where tag_name in ('yellow', 'fruit')
group by item_id, item_name
having co... | Try this::
```
Select *, count(1) as noOfTags from
items_tags
group by item_id
having tag_name in ('yellow','fruit') and noOfTags=2
``` | MySQL query to search for items with certain tags | [
"",
"mysql",
"sql",
"select",
""
] |
I'm storing currencies in a Decimal. From the client, I could be receiving strings in the following formats:
```
US$1,000.00
€1.000,00
```
So far, I've written:
```
re.sub(r'[^\d\.]', '', 'US$1,000.00')
```
which will return `1000.00` (formatted the way I'd like) for the first example and `1.000` for the second (wh... | I found a module that takes care of alot of the complexities in currency formatting (in particular with respect to periods, commas and a bunch more things). The package is called `Babel`, here is a link to the particular method(s) that could help: <http://babel.edgewall.org/wiki/ApiDocs/babel.numbers#babel.numbers:pars... | You could try splitting and then glueing things back together
```
import re;
z = re.split("[,.]", re.sub([^\d\.\,], '', "$1,000.00"))
''.join(z[0:-2]) + ".".join(z[-2:]) # '1000.00'
``` | Python Regex: Formatting use of commas, periods internationally | [
"",
"python",
"regex",
""
] |
I have two tables: Products and Items. I want to select `distinct` items that belong to a product based on the `condition` column, sorted by `price ASC`.
```
+-------------------+
| id | name |
+-------------------+
| 1 | Mickey Mouse |
+-------------------+
+-------------------------------------+
| id | pro... | Correct PostgreSQL query:
```
SELECT DISTINCT ON (items.condition) items.id, items.condition, items.price, products.name
FROM products
INNER JOIN items ON products.id = items.product_id
WHERE products.id = 1
ORDER BY items.condition, items.price, products.name;
```
> SELECT DISTINCT ON ( expression [, ...] ) keeps on... | There is no `distinct()` function in SQL. Your query is being parsed as
```
SELECT DISTINCT (items.condition), ...
```
which is equivalent to
```
SELECT DISTINCT items.condition, ...
```
`DISTINCT` applies to the whole row - if two or more rows all have the same field values, THEN the "duplicate" row is dropped fro... | Select DISTINCT returning too many records | [
"",
"sql",
"postgresql",
"distinct",
"greatest-n-per-group",
"distinct-on",
""
] |
I have the following table.
```
____________________________________
| carid | changeid | data1 | data2 |
|_______|__________|_______|_______|
| 1 | 1 |a |b |
| 1 | 2 |c |d |
| 1 | 3 |e |f |
| 2 | 3 |g |h |
| 2 | 2 |i ... | You can join the table back to itself
```
SELECT DISTINCT a.*
FROM YourTable a
INNER JOIN YourTable b ON b.carid = a.carid and b.changeid = 1
```
Table a is all the rows you want to output, filtered by table b which limits the set to those with changeid = 1.
This should have excellent performance as everything is do... | For multiple select you mean using IN?
```
SELECT carid, changeid, data1, data2
FROM YourTable
WHERE carid IN (SELECT carid FROM YourTable WHERE changeid = 1)
``` | Multiple selects really needed? | [
"",
"sql",
""
] |
I've got table structure as follows:
```
Field Type
id int(11) AI
user varchar(64)
date timestamp
key int(11)
```
What I need to do, is find rows (from given day), where difference between two successive rows (closest timestamp (for given user) is less than 13... | try this :-
```
select t1.user, t1.date d1,t2.date d2 ,t1.date-t2.date
from (select @val:=@val+1 rowid,user, date
from mytable,(select @val:=0) a
order by user,date) t1,
(select @val1:=@val1+1 rowid,user, date
from mytable,(select @val1:=1) b
order by user,date) t2
w... | DATEDIFF(t.netxdata, t.date) < (1300 / 3600 / 24)
I assumed 1300 in in seconds, so I converted it to days which is what DATEDIFF returns.
Please, be aware that this query will do a full scan of your table, which might be expensive. | Mysql: Find rows, where timestamp difference is less than x | [
"",
"mysql",
"sql",
""
] |
I am gettin a error while running the below code.
```
#!/usr/bin/python
import subprocess
import os
def check_output(*popenargs, **kwargs):
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cm... | Just use :
```
check_output(['./MyFile'])
```
You've defined your own function, it's not an attribute of `subprocess` module(for Python 2.6 and earlier).
You can also assign the function to the imported module object(but that's not necessary):
```
subprocess.check_output = check_output
location = "%s/folder" % (os.... | You *probably* just want to use `check_output`, but, just so you know, there is a method `subprocess.check_output`, but it's not defined until Python 2.7 (<http://docs.python.org/3/library/subprocess.html#subprocess.check_output>)
You might even want this, which defines the function in the module if it's not there (i.... | check_output error in python | [
"",
"python",
"python-2.6",
""
] |
I'm new to Python and am working with Python 3.3.2.. I'm having trouble including data items in strings that I am trying to print. The `%` operator either prints out literally as in:
```
for miles in range (10, 70, 10):
km=miles*1.609
print ("%d miles --> %3.2f kilometers") % (miles, km)
```
produces:
```
%d... | Move `% (miles, km)` inside the `print` function:
`print` function returns `None`, so in your code you're actually trying to do:
```
None % (miles, km)
```
That's why you're getting that error.
**Working code:**
```
>>> for miles in range (10, 70, 10):
... km=miles*1.609
... print ("%d miles --> %3.2f ki... | Try using .format() method on your sting
```
>>> for miles in range(10, 70, 10):
... km = miles*1.609
... print ("{0} miles ---> {1} kilometers".format(miles, km))
``` | Python print function issues | [
"",
"python",
"string",
"function",
"printing",
"formatting",
""
] |
I am writing a code in python for a project that has to accomplish a few things;
1) read in data from an xls file column by column
2) average each row of the columns in groups of three
3) then average the resulting columns
I have accomplished 1 and 2 but can't quite seem to get 3, I think a lot of the trouble I'm havi... | I'm not sure I understand which columns you want to average in 3), but maybe this does what you want:
```
with open("test2.xls") as w:
w.next() # skip over header row
for row in w:
(date, time, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t,
u, LZA, SZA, LAM) = row.split("\t") # ... | You can use the `decimal` module to display the exact numbers.
```
from decimal import *
getcontext().prec = 6 # sets the precision to 6
```
note that floating points are used which means that:
```
print(Decimal(1)/(Decimal(7)) # 0.142857
print(Decimal(100)/(Decimal(7)) # results in 14.2857
```
This means you proba... | Averaging down a column of averaged data | [
"",
"python",
"csv",
"average",
"multiple-columns",
""
] |
```
s="(8+(2+4))"
def checker(n):
if len(n) == 0:
return True
if n[0].isdigit==True:
if n[1].isdigit==True:
return False
else:
checker(n[1:])
else:
checker(n[1:])
```
This is what I have so far. Simple code, trying to see if a string meets the following conditions.
However when i perfor... | When the length of `n` is 0, the `n[0]` part is going to raise an error because the string in empty. You should add a `return` statement there instead of print.
```
def checker(n):
if len(n) < 2:
return True
if n[0] in x:
```
Note that the conditions must be `len(n) < 2` otherwise you'll get an error ... | You should do `return True` after the first if statement, not `print True`. The function continues to run after that statement and hits an error when the input is size 0. | IndexError string index out of range | [
"",
"python",
"wing-ide",
""
] |
I'm trying to make a program that basically has an inputted string and what the program is supposed to do is to output the character that occurs the most and says how many times it occurs. It also outputs the character that occurs the least and says how many times it occurs.
I'm having trouble getting started with thi... | I like a challenge. No complex data structures, just simple loops and ifs. If this is too complex then your teacher has done a bad job!
```
w = "This is the song that doesn't end; yes it goes on and on my friend."
max_letter = w[0]
min_letter = w[0]
max = w.count(w[0])
min = w.count(w[0])
for c in w:
if c is not "... | ```
from collections import Counter
the_string = "This is a string!"
Counter(x for x in the_string if not x.isspace()).most_common()
```
Here is a way to get started without Counters/dicts/etc.
```
>>> the_string = "This is a string!"
>>> A = [0] * 256
>>> for x in the_string:
... if not x.isspace():
... ... | Program that counts most and least common non-space characters | [
"",
"python",
""
] |
I have a function:
```
ALTER FUNCTION [dbo].[func_ParseString] (@list nvarchar(MAX))
RETURNS @tbl TABLE (string VARCHAR(500) NOT NULL) AS
BEGIN
DECLARE @pos int,
@nextpos int,
@valuelen int
SELECT @pos = 0, @nextpos = 1
WHILE @nextpos > 0
BEGIN
SELECT @nextpos =... | Your function is returning a leading blank in front of Andy.
You should use `LTRIM` function to remove it. Either in function, on insert into @tbl:
```
INSERT @tbl (string)
VALUES (LTRIM (substring(@list, @pos + 1, @valuelen)))
```
or when you call function:
```
SELECT LTRIM(string) FROM [dbo].[func_Parse... | I don't remember where I found this function. I implemented it and works nice
```
ALTER FUNCTION [dbo].[StringSplit]
(
@delimited nvarchar(max),
@delimiter nvarchar(100)
) RETURNS @t TABLE
(
-- Id column can be commented out, not required for sql splitting string
id int identity(1,1), -- I use this column for nu... | String Split sql function only returning first word in string | [
"",
"sql",
"sql-server",
"split",
""
] |
I want to create password as password field in views.
**models.py:**
```
class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
```
**forms.py:**
```
class UserForm(ModelForm):
class Meta:
model = User
``` | Use widget as `PasswordInput`
```
from django import forms
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
``` | You should create a `ModelForm` ([docs](https://docs.djangoproject.com/en/dev/topics/forms/modelforms/)), which has a field that uses the `PasswordInput` widget from the forms library.
It would look like this:
## models.py
```
from django import models
class User(models.Model):
username = models.CharField(max_le... | How to create Password Field in Model Django | [
"",
"python",
"django",
"django-models",
"django-forms",
""
] |
I use Scilab, and want to convert an array of booleans into an array of integers:
```
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)
```
In Scilab I can use:
```
>>> bool2s(y)
0. 0. 1. 1.
```
or even just multiply it by 1:
```
>>> 1*y
0. 0. 1. ... | Numpy arrays have an `astype` method. Just do `y.astype(int)`.
Note that it might not even be necessary to do this, depending on what you're using the array for. Bool will be autopromoted to int in many cases, so you can add it to int arrays without having to explicitly convert it:
```
>>> x
array([ True, False, Tru... | The `1*y` method works in Numpy too:
```
>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)
>>> 1*y # Method 1
array([0, 0, 1, 1])
>>> y.astype(int) # Method 2
array([0, 0, 1, 1])
```
If you are asking for a way to... | How to convert a boolean array to an int array | [
"",
"python",
"integer",
"boolean",
"type-conversion",
"scilab",
""
] |
I am trying to add an attachment to my timeline with the multipart encoding. I've been doing something like the following:
```
req = urllib2.Request(url,data={body}, header={header})
resp = urllib2.urlopen(req).read()
```
And it has been working fine for application/json. However, I'm not sure how to format the body ... | This is how I did it and how the python client library does it.
```
from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart
from email.mime.image import MIMEImage
mime_root = MIMEMultipart('related', '===============xxxxxxxxxxxxx==')
headers= {'Content-Type': 'multipart/rel... | There is a working Curl example of a multipart request that uses the streaming video url feature here:
[Previous Streaming Video Answer with Curl example](https://stackoverflow.com/questions/16997932/attaching-video-with-video-vnd-google-glass-stream-url-after-update-xe6/16998808#16998808)
It does exactly what you ar... | Multipart POST request Google Glass | [
"",
"python",
"django",
"google-mirror-api",
""
] |
I was using pyinstaller before to try and get my app with twisted as an executable, but I got this error when executing:
```
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/cx_Freeze/initscripts/Console.py", line 27, in <module>
exec code in m.__dict__
File "client_test.py", lin... | Add `pkg_resources` to your `includes` in your setup.py for cx\_Freeze. | I had the same issue with cx\_freeze. None of the above solutions seemed to work in my case.
For me this solution from [here](http://sourceforge.net/p/cx-freeze/mailman/message/26483012/) worked :
You need to actually create
`zope/__init__.py` as an empty file so that the normal processing
performed by imp.find\_modul... | ImportError with cx_Freeze and pyinstaller | [
"",
"python",
"twisted",
"pyinstaller",
"cx-freeze",
""
] |
How to Create stored proc that gives totals grouped for month and year
sale tablename
```
year week date value
2008 4 2008-01-21 50
2008 5 2008-02-22 25
2008 6 2008-02-23 30
``` | Try this
```
CREATE PROCEDURE dbo.GetTotalAmount
AS
BEGIN
SELECT DATEPART(YEAR, date)as [Year],
MONTH(date) as [Month],
SUM(Value) as [Value]
FROM Sale
GROUP BY DATEPART(YEAR, date), MONTH(date)
END
EXEC dbo.GetTotalAmount
``` | Here is a full stored procedure code with parameters and example on how to run this.
```
CREATE PROCEDURE dbo.GetTotalByDate
(
@StartDate datetime,
@EndDate datetime
)
AS
BEGIN
SELECT S.year as [Year],
MONTH(S.date) as [Month],
SUM(S.Value) as [Value]
FROM Sale S
WHERE S.date BETWEEN @Star... | How to write Stored procedure to get the group data of a month and year | [
"",
"sql",
"sql-server",
""
] |
How to simple format string with decimal number for show it with spaces between every three digits?
I can make something like this:
```
some_result = '12345678,46'
' '.join(re.findall('...?', test[:test.find(',')]))+test[test.find(','):]
```
and result is:
```
'123 456 78,46'
```
but I want:
```
'12 345 678,46'
`... | This is a bit hacky, but:
```
format(12345678.46, ',').replace(',', ' ').replace('.', ',')
```
As described in [Format specification mini-language](http://docs.python.org/2/library/string.html#format-specification-mini-language), in a format\_spec:
> The ',' option signals the use of a comma for a thousands separato... | I think a regex would be much nicer:
```
>>> import re
>>> some_result = '12345678,46'
>>> re.sub(r"\B(?=(?:\d{3})+,)", " ", some_result)
'12 345 678,46'
```
**Explanation:**
```
\B # Assert that we're not at the start of a number
(?= # Assert that the following regex could match from here:
(?: # The... | Format string - spaces between every three digit | [
"",
"python",
""
] |
I have the following database schema for an attendance system:

How would I write an SQL query to generate a good report of entries on day X? I need it to generate a report that has
Employee Name | TimeIn | TimeOut
Bob | 10:00 | 11:00
Sam | 10:30 | 18:00
B... | This works in Oracle (apologies for the non-ANSI style, but you should get the drift)..
```
SELECT FORENAME,SURNAME,L1.TIME IN_TIME,L2.TIME OUT_TIME
FROM EMPLOYEES EMP, LOG L1, LOG L2
WHERE EMP.EMPLOYEE_ID = L1.EMPLOYEE_ID
AND EMP.EMPLOYEE_ID = L2.EMPLOYEE_ID
AND L1.ENTRYTYPE = 1
AND L2.ENTRYTYPE = 0
AND L2.TIME = (SE... | Simply this will work. Try this
```
SELECT FORENAME,SURNAME,LG.IN_TIME,LG.OUT_TIME FROM EMPLOYEES EMP INNER JOIN
(SELECT MIN(TIME) IN_TIME,MAX(TIME) OUT_TIME,EMPLOYEE_ID FROM LOG
GROUP BY EMPLOYEE_ID) LG ON EMP.EMPLOYEE_ID=LG.EMPLOYEE_ID
```
**Note** : I didnt include the entry type because at any time min time will... | Constructing an SQL query for schema | [
"",
"sql",
"database",
"schema",
""
] |
I apologize if this is a question that has already been resolved. I want to get the current directory when running a Python script or within Python. The following will return the full path including the current directory:
```
os.getcwd()
```
I can also get the path all the way up to the current directory:
```
os.pat... | Like this:
```
os.path.split(os.getcwd())[1]
```
Although `os.path.split` returns a tuple, you don't need to unpack it. You can simply select the item that you need and ignore the one that you don't need. | Use [`os.path.split`](http://docs.python.org/2/library/os.path.html#os.path.split):
```
>>> os.path.split(os.getcwd())
('/home/user', 'py')
>>> os.path.split(os.getcwd())[-1]
'py'
```
help on `os.path.split`:
```
>>> print os.path.split.__doc__
Split a pathname. Returns tuple "(head, tail)" where "tail" is
ever... | Getting just the current directory without the full path in python | [
"",
"python",
"os.path",
""
] |
I would like to know how I can get my code to not crash if a user types anything other than a number for input. I thought that my else statement would cover it but I get an error.
> Traceback (most recent call last): File "C:/Python33/Skechers.py",
> line 22, in
> run\_prog = input() File "", line 1, in NameError: nam... | Contrary to what you think, your script is *not* being run in Python 3.x. Somewhere on your system you have Python 2.x installed and the script is running in that, causing it to use 2.x's insecure/inappropriate `input()` instead. | The error message you showed indicates that `input()` tried to evaluate the string typed as a Python expression. This in turn means you're not actually using Python 3; `input` only does that in 2.x. Anyhow, I strongly recommend you do it this way instead, as it makes explicit the kind of input you want.
```
while time... | Getting error if user types a string | [
"",
"python",
"python-3.x",
""
] |
I would like to load the contents of a .txt file as a string and extract a specific piece of information. The information, which has lots of text before and after it's occurence, looks like this:
```
ValueName: 1234
```
But could also look like:
```
ValueName: 123456
```
That is to say, the value is always ... | You can use a regular expression to extract the value following `ValueName:`
```
>>> import re
>>> line = 'some dummy text ValueName: 123456 some dummy text'
>>> m = re.findall(r'ValueName:\s+([0-9]+)',line)
>>> m
['123456']
```
This will find multiple matches if they exist.
```
>>> import re
>>> line = 'blah bl... | Regular expressions will make this simpler, as Brian's answer (among others) shows.
But don't use a regex if you're not willing to understand what it does. If you want to put off the learning curve for now,\* this isn't that hard to do with simple string processing:
```
def numeric_value_names(path):
with open(pa... | Python Extract Values of varying length from Text Files | [
"",
"python",
""
] |
So, I'm hard at work on a text-based RPG game on Python 2.7, but I came across a problem in the character menu. Here's what it looks like:
```
def raceselect(n):
if n==0:
print "(name) the Human."
if n==1:
print "(name) the Dwarf."
if n==2:
... | You need to turn the raw input into a int:
```
n = int(raw_input())
```
Also, you need to call the function, so use `raw_input()` rather than just `raw_input` | `n = raw_input` here will bring nothing to you. You should use `n = int(raw_input())` according to your need. And I think it is better for you to use a `dict` or `list` rather than several `if`:
```
def raceselect(n):
races = {0: 'Human', 1: 'Dwarf', 2: 'Elf', 3: 'Halfing'}
if n in races:
print '(name)... | Text Based RPG Functioning Error? | [
"",
"python",
"text",
"python-2.7",
""
] |
I just deployed my first ever web app and I am curious if there is an easy way to track every time someone visits my website, well I am sure there is but how? | know from myself people are obsessed with traffic, statistics, looking at other sites – tracking their stats and so on. And if there is enough demand, of course there are sites to satisfy You. I wanted to put those sites and tools in one list together, because at least for me this field was really unclear – I didn’t kn... | Easy as pie, use Google Analytics, you just have to include a tiny script in your app's pages
<http://www.google.com/analytics/> | how do I track how many users visit my website | [
"",
"python",
"flask",
"pythonanywhere",
""
] |
I have an object that has optional fields. I have defined my serializer this way:
```
class ProductSerializer(serializers.Serializer):
code = serializers.Field(source="Code")
classification = serializers.CharField(source="Classification", required=False)
```
I [thought](http://django-rest-framework.org/api-gu... | The serializers are deliberately designed to use a fixed set of fields so you wouldn't easily be able to optionally drop out one of the keys.
You could use a [SerializerMethodField](http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield) to either return the field value or `None` if the field doe... | The method describe below did the work for me.
Pretty simple,easy and worked for me.
DRF version used = djangorestframework (3.1.0)
```
class test(serializers.Serializer):
id= serializers.IntegerField()
name=serializers.CharField(required=False,default='some_default_value')
``` | Django REST Framework - Serializing optional fields | [
"",
"python",
"django",
"serialization",
"django-rest-framework",
""
] |
I have the following table layout (for columns):
ID renterID BookID dateOfRental
And I was asked to make a report page where I could see how many books each renterID has rented on a certain date. Now I am not even sure this is possible, but I thought I'd ask you guys for at least a direction or similar snippet from w... | Something like:
```
SELECT
renterID
, COUNT(DISTINCT BookID)
FROM
your_table
WHERE
dateOfRental = 'the_date'
-- or if you want a date period: dateOfRental BETWEEN start_date AND end_date
GROUP BY
renterID
;
``` | I assume that you want this for a particular date:
```
SELECT
COUNT(*) BookCount,
renterId,
dateOfRental
FROM
someTable
WHERE
dateOfRental = [a certain date]
GROUP BY
renterId
``` | Count rows with same colum value for certain date | [
"",
"mysql",
"sql",
"database",
""
] |
Hi I used the django inbult auth urls and views for my project and now have finished the initial user account creation/login/reset password process.
Now, the user can log in and be redirected to the after successful login url accounts/profile/.
I have several doubts on the django login function. For convenience, I've... | After the login, you can access the user info by referring `request.user` in views and just `{{user}}` in templates. All you need to make sure is you're passing the [`RequestContext`](https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext) in the `HttpResponse` for the future reques... | To override this behavior just put following in `settings.py` of your app :
`LOGIN_REDIRECT_URL = "/"`
This will redirect to your home page. You can change this url to preferred url. | Django- why inbuilt auth login function not passing info about user to after successful login url | [
"",
"python",
"django",
"django-authentication",
"django-login",
""
] |
How can I split the following string based on the '-' character?
So if I had this string: `LD-23DSP-1430`
How could I split it into separate columns like this:
```
LD 23DSP 1430
```
Also, is there a way to split each character into a separate field if I needed to (without the '-')? I'm trying to find a... | I wouldn't exactly say it is easy or obvious, but with just two hyphens, you can reverse the string and it is not too hard:
```
with t as (select 'LD-23DSP-1430' as val)
select t.*,
LEFT(val, charindex('-', val) - 1),
SUBSTRING(val, charindex('-', val)+1, len(val) - CHARINDEX('-', reverse(val)) - charindex('... | Here's a little function that will do "NATO encoding" for you:
```
CREATE FUNCTION dbo.NATOEncode (
@String varchar(max)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN (
WITH L1 (N) AS (SELECT 1 UNION ALL SELECT 1),
L2 (N) AS (SELECT 1 FROM L1, L1 B),
L3 (N) AS (SELECT 1 FROM L2, L2 B),
L4 (N) AS (SELECT ... | SQL Server 2005 Using CHARINDEX() To split a string | [
"",
"sql",
"sql-server-2005",
""
] |
It is a basic question. I am trying the following code:
```
class SMS_store:
def __init__(self):
self=[] #probably something is wrong here
def add_new_arrival(self,from_number,time_arrived,text_of_SMS):
self.append([False,from_number,time_arrived,text_of_SMS]) #append list to self list
self[len(sel... | You can subclass `list` like this
```
class SMS_store(list):
def add_new_arrival(self, from_number, time_arrived, text_of_SMS):
self.append((False, from_number, time_arrived, text_of_SMS)) #append tuple to self
def message_count(self):
return len(self)
```
Notice there is no need for `__i... | If you want to inherit from `list`, use the following:
```
class SMS_store(list):
^^^^^^
```
and remove that assignment to `self` from the `__init__` method.
That said, you might want to simply have a named attribute containing the list:
```
class SMS_store(object):
def __init__(self):
self... | Create List Object Class in Python | [
"",
"python",
"list",
"class",
"append",
""
] |
I am trying to visualize graphs generated from networkx, using d3py.
I used the example provided (<https://github.com/mikedewar/d3py/blob/master/examples/d3py_graph.py>) but all I get is the graph without node names, how do I plot node names as well?
Also, how do I change edge and node colors? | *Here is a partial answer, but also read the caveat at the end.*
The easiest thing is changing the node colour. If you run the example you pointed to with
```
with d3py.NetworkXFigure(G, width=500, height=500) as p:
p += d3py.ForceLayout()
p.css['.node'] = {'fill': 'blue', 'stroke': 'magenta'}
p.show()
``... | Just in case anyone ends up here looking around at d3py. I made d3py a couple of years ago now to see what it would feel like to plot d3 graphics from Python. It was fun! But I didn't have the time to do it properly, which was a shame.
However, Rob Story did! He made vincent, which is available at <https://github.com/... | How to plot graphs using networkx and d3py | [
"",
"python",
"d3.js",
"graph",
"networkx",
"d3py",
""
] |
I have two strings like `s1='fly,dream';s2='dream,fly'`
I want the `s1` equals to `s2`.
The code I tried is:
```
def Isequal(m,n):
s1=m.split(',') s2=n.split(',') s1.sort() s2.sort()
if s1 == s2:
print 'Equal'
else:
print s1,s2
```
Note:s1 may be equal to s2.
Then
```
def Isequal(... | Your code splits the two strings by `,` (which returns a `list`) and calls the `sort` method on the `list`. Since the two substrings are identical, sorting the list of the substrings results in equal lists. The best way to know what is happening is printing the stuff out. See the results.
```
>>> s1 = 'fly,dream'
>>> ... | Set would be more elegant here:
```
def Isequal(m, n):
s1 = set(m.split(','))
s2 = set(n.split(','))
if s1 == s2:
print 'Equal'
else:
print s1, s2
```
and should be more efficient too. | python return equal where the string is not actually equal? | [
"",
"python",
""
] |
In c/c++, we could have:
```
maxnum = 10;
double xlist[maxnum];
```
How to set a maximum length for a python list/set? | You don't and do not need to.
Python lists grow and shrink dynamically as needed to fit their contents. Sets are implemented as a hash table, and like Python dictionaries grow and shrink dynamically as needed to fit their contents.
Perhaps you were looking for [`collections.deque`](http://docs.python.org/2/library/co... | Here is extended version of python's `list`. It behaves like `list`, but will raise `BoundExceedError`, if length is exceeded (tried in python 2.7):
```
class BoundExceedError(Exception):
pass
class BoundList(list):
def __init__(self, *args, **kwargs):
self.length = kwargs.pop('length', None)
... | How to set a max length for a python list/set? | [
"",
"python",
"list",
"max",
"maxlength",
""
] |
I have a list of numbers that needs to be calculated from a function. And i need to calculate 2 millions times. I could have done it this way but is there a simpler way:
```
def funcx():
return random.random() # for simplicity we use random
top10 = [] # max len = 10
for i in range(2000000):
j = funcx()
top10.a... | Update: 2013-me was confused, at best, and this is not correct. See <https://stackoverflow.com/a/68587827/1126841> instead.
---
Use a fixed-size heap instead of sorting the list each time:
```
import heapq
top10=[]
for i in range(2000000):
heapq.heappush(top10, funcx())
top10 = top10[:10]
```
Asymptotically... | I would like to show correct solution using fixed size heap ([accepted answer](https://stackoverflow.com/a/17527689/6604502) is incorrect).
Let's say you want 10 smallest elements. Then you can use max heap and after each push perform a pop. The pop will remove the largest element leaving you with array of 10 smallest ... | How do you iterate and keep the top 10 max? Python | [
"",
"python",
""
] |
i am trying to learn python by myself on codeacademy, and i am looking through past lessons, but i can't figure out what i did wrong. i think i copied everything correctly.
the assignment is to check the user input word to see if it contains at least one character. if it does contain more than one character, the progr... | you need to call the `true_function()` for it to be executed
do something like this
```
print "Welcome to the English to Pig Latin translator!"
def true_function():
original = raw_input("tell me your secrets")
if len(original)>= 1:
print(original)
else:
print("empty")
true_function()
```
... | It's because you never call the `true_function()` function.
You can either remove that, and just have:
```
print "Welcome to the English to Pig Latin translator!"
original = raw_input("tell me your secrets")
if len(original)>= 1:
print(original)
else:
print("empty")
```
Or, call the `true_function()` afterwards... | please help me with my else if loop in python ? | [
"",
"python",
""
] |
In numpy is there a fast way of calculating the mean across multiple axis? I am calculating the mean on all but the 0 axis of an n-dimensional array.
I am currently doing this;
```
for i in range(d.ndim - 1):
d = d.mean(axis=1)
```
I'm wondering if there is a solution that doesn't use a python loop. | In numpy 1.7 you can give multiple axis to `np.mean`:
```
d.mean(axis=tuple(range(1, d.ndim)))
```
I am guessing this will perform similarly to the other proposed solutions, unless reshaping the array to flatten all dimensions triggers a copy of the data, in which case this should be much faster. So this is probably ... | My approach would be to reshape the array to flatten all of the higher dimensions and then run the mean on axis 1. Is this what your looking for?
```
In [14]: x = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
In [16]: x.reshape((x.shape[0], -1)).mean(axis=1)
Out[16]: array([ 2.5, 6.5])
```
(step 2 just calculates the pro... | Getting the mean of multiple axis of a numpy array | [
"",
"python",
"numpy",
""
] |
Python noob here. I need to store an array of float arrays. I am doing this but its not working out:
```
distance = [] ##declare my array
distance.append ([]) ##add an empty array to the array
distance[len(distance)-1].append ([0,1,2,3.5,4.2]) ## store array in array[0]
print distance[0][1] ## this doesnt work, the ar... | Use `list.extend` not `list.append`:
The difference between `extend` and `append` is that `append` appends the object passed to it as it is. While `extend` expects that item passed to it to be an iterable(list, tuple,string, etc) and appends it's items to the list.
Using `append` we can append any type of object; i.e... | Use `extend` instead of `append`:
```
distance[-1].extend([0,1,2,3.5,4.2])
```
(Also, note that `distance[len(distance)-1]` can be written `distance[-1]`.) | Nested float arrays in Python | [
"",
"python",
"arrays",
"nested",
""
] |
I have a django project, using django-rest-framework to create api.
Want to use token base authentication system so api call for (put, post, delete) will only execute for authorized user.
I installed 'rest\_framework.authtoken' and created token for each users.
So, now from django.contrib.auth.backends authenticate,... | > "how can I send the token with post request to my api"
From the docs...
For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example:
```
Authorization: Token 9944b09... | To answer the first half of your question:
> how can I send the token with post request to my api
You can use the Python [requests](http://docs.python-requests.org/en/master/user/authentication/) library. For the django-rest-framework TokenAuthentication, the token needs to be passed in the header and prefixed by the... | How to use TokenAuthentication for API in django-rest-framework | [
"",
"python",
"django",
"django-authentication",
"django-rest-framework",
""
] |
Is there a way to create an XML schema from an existing database in SQL Server 2008, SQL Server Management Studio?
I have a DB with ~50 tables. I'm looking to create a "nice" diagram showing the relationship between those tables. Using another application called SQL Designer (<https://code.google.com/p/wwwsqldesigner/... | If you only need the xml schema of tables query them with this:
```
select top 0 * FROM daTable FOR XML AUTO,XMLSCHEMA
```
If you need the table names and columns in order to create a representation of your database and how tables are connected you can use something like this:
```
SELECT
s.name as '@Schema'
,t.name ... | Combined with a cursor running through INFORMATION\_SCHEMA or sysobjects, the following should help you:
```
SELECT * FROM [MyTable] FOR XML AUTO, XMLSCHEMA
```
I'm uncertain as to whether you can simply apply this to a whole database, or what postprocessing effort would be required to combine all the various table s... | how to create XML schema from an existing database in SQL Server 2008 | [
"",
"sql",
"sql-server-2008",
""
] |
After I added `c.category <> 'AGILE'` to the query below, the results set stopped including `NULL` values for `c.category`. How can I get rows with a `NULL` c.category back in my result set, without doing a `UNION`?
```
select
p.number,
p.method
,sum(p.amount) AS amount
... | `NULL` is neither equal to nor unequal to any particular value. If you want to include NULL values, you would want something like
```
and( c.category <> 'AGILE'
or c.category IS NULL)
``` | This simply works:
```
(c.category <> 'AGILE' OR c.category IS NULL)
``` | Why does inequality test eliminate NULL values? | [
"",
"sql",
"oracle",
""
] |
I'm still in the learning phase of SQL statements and I'm hoping someone out there can help.
I have a many-to-many database base relationship.
The table Department can have multiple Jobs associated with it and and Jobs can be related to multiple Departments. So I have this basic relationship type.
```
Job.ID (one-to... | You can use a [`LEFT JOIN`](http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html). The `LEFT JOIN` keyword returns all rows from the left table with the matching rows in the right table. The result is `NULL` in the right side if there is no match. Since you want the jobs without a matching de... | ```
select job
from job
where id not in (select jobId
from jobs)
``` | SQL Statement - Excluding certain data | [
"",
"sql",
"select",
"many-to-many",
"inner-join",
"where-clause",
""
] |
I want to use Spanish instead of English to program in Python. How to define aliases for keywords such as `if` and `for`? | 1. You don't. "if" and "for" are hardcoded parts of Python. You could write your own programming language or a translator but you can't do what you are asking for in real Python (you could in Lisp or in C/C++ using macros).
2. More importantly, [programming is done in English](http://www.catb.org/esr/faqs/hacker-howto.... | If you are fine to have iPython as a dependency, you might have a look at [Custom input transformation — IPython 3.2.1 documentation](https://ipython.org/ipython-doc/3/config/inputtransforms.html).
Basically, ipython is already preprocessing anything that is given to the prompt, and it allows code to specify more tran... | Defining aliases for keywords in Python | [
"",
"python",
""
] |
How can I write a comprehension to extract all values of key='a'?
```
alist=[{'a':'1a', 'b':'1b'},{'a':'2a','b':'2b'}, {'a':'3a','b':'3b'}]
```
The following works but I just hacked until I got what I want. Not a good way to learn.
```
[alist['a'] for alist in alist if 'a' in alist]
```
in the comprehension I have ... | ```
[elem['a'] for elem in alist if 'a' in elem]
```
might be a clearer way of phrasing what you have above.
The "for elem in alist" part will iterate over alist, allowing this to look through each dictionary in alist.
Then, the "if 'a' in elem" will ensure that the key 'a' is in the dictionary before the lookup occ... | You can do:
```
alist=[{'a':'1a', 'b':'1b'},{'a':'2a','b':'2b'}, {'a':'3a','b':'3b'}]
new_list = [a.get('a') for a in alist]
```
If you want to restrict it only to dictionary with a key `a`,
```
new_list = [a.get('a') for a in alist if a.get('a')]
```
Based on gnibbler's suggestion:
```
new_list = [a.get('a') for ... | Create a list from a list of dictionaries using comprehension for specific key value | [
"",
"python",
""
] |
I will count of total area's record where there status will different like 'PENDING','SENT INFO','PTP' with group by and multiple select queries but result not got so plese help me.
My query is:
```
SELECT AREA,
(SELECT COUNT( * ) FROM prospectmaster WHERE ZONE = 'AHMEDABAD' && STATUS = 'PENDING' GROUP BY AREA) AS P... | ```
SELECT AREA,
SUM(CASE WHEN STATUS = 'PENDING' THEN 1 ELSE 0 END) AS PENDING,
SUM(CASE WHEN STATUS = 'SENT INFO.' THEN 1 ELSE 0 END) AS cnt,
SUM(CASE WHEN STATUS = 'PTP' THEN 1 ELSE 0 END) AS PTP
FROM prospectmaster
WHERE ZONE = 'AHMEDABAD'
GROUP BY AREA;
```
If `STATUS` has 'SENT INFO... | ```
SELECT AREA,
SUM(if(STATUS='PENDING',1,0)) AS PENDING,
SUM(if(STATUS='SENT INFO',1,0)) AS "INFO SENT",
SUM(if(STATUS='PTP',1,0)) AS PTP
FROM prospectmaster
WHERE ZONE = 'AHMEDABAD'
GROUP BY AREA;
``` | Query with multiple SELECT and GROUP BY | [
"",
"mysql",
"sql",
""
] |
The NOT IN clause is omitting the ***NULL*** values when checking the condition.
```
INPUT
ID NAME
1 A
2 <null>
3 C
SELECT... FROM...
WHERE NAME NOT IN ('C')
```
is only returning ID value 1. I need both 1 & 2.
Could this be done? | ```
WHERE NAME NOT IN ('C') OR NAME IS NULL
``` | Either you check NULL values
```
select *
from not_in
where name not in ('C') or name is null;
```
or you can convert NULL values in any other character with coalesce. I use ' ' in the sample below.
```
select *
from not_in
where coalesce(name, ' ') not in ('C');
``` | NOT IN clause and NULL value | [
"",
"mysql",
"sql",
"oracle",
""
] |
I'm doing a project involving data collection and logging. I have 2 threads running, a collection thread and a logging thread, both started in main. I'm trying to allow the program to be terminated gracefully when with Ctrl-C.
I'm using a `threading.Event` to signal to the threads to end their respective loops. It wor... | The problem is that your logger is waiting on `d = input_queue.get()` and will not check the event. One solution is to skip the event completely and invent a unique message that tells the logger to stop. When you get a signal, send that message to the queue.
```
import threading
import Queue
import random
import time
... | I'm not an expert in threading, but in your `logData` function the first `d=input_queue.get()` is blocking, i.e., if the queue is empty it will sit an wait forever until a queue message is received. This is likely why the `logData` thread never terminates, it's sitting waiting forever for a queue message.
Refer to the... | How to let a Python thread finish gracefully | [
"",
"python",
"multithreading",
"python-2.7",
""
] |
According to the [documentation](http://dev.mysql.com/doc/refman/5.7/en/comments.html), there are two ways you can comment to the end of a line in MySql:
* `"#"`
* `"-- "`
Is there any difference between these?
If so, when should I use one vs. the other?
If not, does anyone know why both are supported?
Seems stran... | It only really matters if you want your SQL to be portable. For instance `--` comments are OK in Sqlite and Postegresql while `#` are not. Your best bet is to use `--` with a space following. (As far as I can remember I've hardly ever seen anything else) | As the link you provided clearly explain it `--` is the standard SQL "comment separator". Where MySQL departs from standard is in requiring an *space* after `--` to be recognized as a comment. "Standard" SQL does not require this.
To provide an example, in the following code, `--` is recognized as a comment token:
``... | MySql Comment Syntax - What's the difference between "#" and "-- " | [
"",
"mysql",
"sql",
"syntax",
"comments",
""
] |
My question is : Is there a way to do find the last day of a month in Hive, like Oracle SQL function ? :
`LAST_DAY(D_Dernier_Jour)`
Thanks. | You could make use of `last_day(dateString)` UDF provided by Nexr. It returns the last day of the month based on a date string with yyyy-MM-dd HH:mm:ss pattern.
```
Example:
SELECT last_day('2003-03-15 01:22:33') FROM src LIMIT 1;
2003-03-31 00:00:00
```
You need to pull it from their [Github Repository](https://gith... | As of Hive 1.1.0, [`last_day(string date)`](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF) function is available.
`last_day(string date)`
> Returns the **last day of the month** which the date belongs to. date is a string in the format 'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd'. The time part of date... | Find last day of a month in Hive | [
"",
"sql",
"hive",
"hiveql",
""
] |
I have a textfile, let's call it `goodlines.txt` and I want to load it and make a list that contains each line in the text file.
I tried using the `split()` procedure like this:
```
>>> f = open('goodlines.txt')
>>> mylist = f.splitlines()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Attri... | You are using `str` methods on an open file object.
You can read the file as a list of lines by simply calling `list()` on the file object:
```
with open('goodlines.txt') as f:
mylist = list(f)
```
This *does* include the newline characters. You can strip those in a list comprehension:
```
with open('goodlines.... | Try this:
```
>>> f = open('goodlines.txt')
>>> mylist = f.readlines()
```
`open()` function returns a file object. And for file object, there is no method like `splitlines()` or `split()`. You could use `dir(f)` to see all the methods of file object. | Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split' | [
"",
"python",
"python-3.x",
""
] |
I have consumed a bunch of tweets in a mongodb database. I would like to query these tweets using pymongo. For example, I would like to query for screen\_name. However, when I try to do this, python does not return a tweet but a message about pymongo.cursor.Cursor. Here is my code:
```
import sys
import pymongo
from p... | Ok now I see what's your problem:
If you look carefully into your document you will notice that "screen\_name" is inside the subdocument user, so if you want to acess it all you have to do is the following:
```
tweets.find({"user.screen_name": "JoeCatanzarita"}) #for example.
```
Whenever you are in a situation whe... | PyMongo's find() method returns a Cursor. To actually execute the query on the server and retrieve results, iterate the cursor with `list` or a for loop:
```
for doc in tweets.find({'screen_name': 'name'}):
print(doc)
# Or:
docs = list(tweets.find({'screen_name': 'name'}))
```
If `tweets.find({"screen_name": "na... | Why do I get a pymongo.cursor.Cursor when trying to query my mongodb db via pymongo? | [
"",
"python",
"mongodb",
"twitter",
"pymongo",
"database-cursor",
""
] |
Ok so here is my class:
```
class Vec:
"""
A vector has two fields:
D - the domain (a set)
f - a dictionary mapping (some) domain elements to field elements
elements of D not appearing in f are implicitly mapped to zero
"""
def __init__(self, labels, function):
self.D = labels
self.f = function
```
I need... | The method that you are trying to implement has already been done for you. You can use the set equality and the dictionary equality operator. I ask you not to make a function called `equal` and instead use `__eq__` which allows the use of `==` on class instances.
Here's what you can do
```
def __eq__(self, anotherIns... | You can compare the fields:
```
def equal(self, u, v):
return u.D == v.D and u.f == v.f
``` | Find if 2 vectors are equal in python | [
"",
"python",
"class",
"function",
"vector",
"python-3.x",
""
] |
I have a table containing a set of tasks to perform:
```
Task
ID Name
1 Washing Up
2 Hoovering
3 Dusting
```
The user can add one or more Notes to a Note table. Each note is associated with a task:
```
Note
ID ID_Task Completed(%) Date
11 1 25 05/07/2013 14:00
... | If we assume that tasks only become more complete, you can do this with a `left outer join` and aggregation:
```
select t.ID, t.Name, coalesce(max(n.complete), 0)
from tasks t left outer join
notes n
on t.id = n.id_task
group by t.id, t.name
```
If tasks can become "less complete" then you want the one with... | ```
select a.ID,
a.Name,
isnull((select completed
from Note
where ID_Task = b.ID_Task
and Date = b.date),0)
from Task a
LEFT OUTER JOIN (select ID_Task,
max(date) date
from Note
group by I... | Select rows in one table, adding column where MAX(Date) of rows in other, related table | [
"",
"sql",
"sql-server",
"greatest-n-per-group",
""
] |
I'm working with a database where we have a FNN column (Full National Number). In Australia, all FNN's are 10 digits and begin with a 0 followed by the single digit state number and then the 8 digit phone number.
Currently, half the entries only have 9 digits, meaning that the first 0 is excluded, but the other half h... | In your question you mentioned that some of them have 9 digits while the other half have 10 digits, So I suggest instead of looking for rows that has FNN start with 1-9, why dont look for rows that has FNN = 9 digits?
```
UPDATE SUBSCRIBERS
SET FNN=concat('0',FNN)
WHERE CHAR_LENGTH(FNN) = 9;
``` | Probably you can use `not like`:
```
UPDATE SUBSCRIBERS SET FNN=concat('0',FNN) WHERE FNN NOT LIKE '0%';
``` | MySQL - Concatenate 0 to all column values if no 0 to begin with | [
"",
"mysql",
"sql",
"concatenation",
""
] |
I am new to SQL so bear with me. I am returning data from multiple tables. Followed is my SQL (let me know if there is a better approach):
```
SELECT [NonScrumStory].[IncidentNumber], [NonScrumStory].[Description], [DailyTaskHours].[ActivityDate], [Application].[AppName], [SupportCatagory].[Catagory], [DailyTaskHours]... | You could group by the NonScrumStore columns, and then aggregate the other columns like this:
```
SELECT [NonScrumStory].[IncidentNumber],
[NonScrumStory].[Description],
MAX( [DailyTaskHours].[ActivityDate]),
MAX( [Application].[AppName]),
MAX([SupportCatagory].[Catagory]),
MAX(... | From the screenshot it seems DISTINCT should have solved your issue but if not you could use the ROW\_NUMBER function.
```
;WITH CTE AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY [NonScrumStory].[PK_NonScrumStory] ORDER BY [DailyTaskHours].[ActivityDate] DESC) AS RowNum,
[NonScrumStory].[IncidentNumber], [NonScrumStory]... | SELECTing only one copy of a row with a specific key that is coming from multiple tables | [
"",
"sql",
"sql-server",
""
] |
I am working on a project to get information from a web page.
in the html source I have the following:
**Resultado de Busca:** Foram encontrados **264** casais
I need to get the number between "encontrados" and "casais"
is there anyway in Python to do that? what string function should i use? i want o avoid using reg... | I'd recommend using a library such as [Beautiful Soup](https://pypi.python.org/pypi/beautifulsoup4) if it's HTML you want to parse. No need for regex.
**EDIT**
Using the URL you just added, this is the sample code to get the HTML object out:
```
import BeautifulSoup
import re
import urllib
data = urllib.urlopen('ht... | Given that you can't parse html with regular expression, if you treat your file as a bag of text you have to use regex or something like:
```
a = 'Resultado de Busca: Foram encontrados 264 casais' #your page text
num = int(a[a.index("encontrados")+len("encontrados"):a.index("casais")])
``` | search for a string inside html source with python (3.3.1) | [
"",
"python",
"string",
"split",
""
] |
I want to find words that have consecutive letter pairs using regex.
I know for just one consecutive pair like **zoo (oo), puzzle (zz), arrange (rr)**, it can be achieved by `'(\w){2}'`. But how about
* two consecutive pairs: **committee (ttee)**
* three consecutive pairs: **bookkeeper (ookkee)**
edit:
* `'(\w){2}'`... | You can use this pattern:
```
[a-z]*([a-z])\1([a-z])\2[a-z]*
```
the idea is to use backreferences `\1` and `\2` that refer to the capturing groups.
Note that `(\w){2}` matches two word characters but not the same character. | Use [re.finditer](http://docs.python.org/2/library/re.html#re.finditer)
```
>>> [m.group() for m in re.finditer(r'((\w)\2)+', 'zoo')]
['oo']
>>> [m.group() for m in re.finditer(r'((\w)\2)+', 'arrange')]
['rr']
>>> [m.group() for m in re.finditer(r'((\w)\2)+', 'committee')]
['mm', 'ttee']
>>> [m.group() for m in re.fin... | python: how to find consecutive pairs of letters by regex? | [
"",
"python",
"regex",
""
] |
I have an excel workbook that runs some vba on opening which refreshes a pivot table and does some other stuff.
Then I wish to import the results of the pivot table refresh into a dataframe in python for further analysis.
```
import xlrd
wb = xlrd.open_workbook('C:\Users\cb\Machine_Learning\cMap_Joins.xlsm')
```
Th... | You can use pandas' ExcelFile [`parse`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.ExcelFile.parse.html) method to read Excel sheets, see [io docs](http://pandas.pydata.org/pandas-docs/stable/io.html#excel-files):
```
xls = pd.ExcelFile('C:\Users\cb\Machine_Learning\cMap_Joins.xlsm')
df =... | The accepted answer is old (as discussed in comments of the accepted answer).
Now the preferred option is using [pd.read\_excel()](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html). For example:
```
df = pandas.read_excel('C:\Users\cb\Machine_Learning\cMap_Joins.xlsm'), skiprows=[0,1,2,3,4]... | reading excel to a python data frame starting from row 5 and including headers | [
"",
"python",
"excel",
"pandas",
"dataframe",
"import",
""
] |
I'm completely new at SQL and have been at this for 6 hours now, to now avail. I must be missing something simple. In a nutshell: I want to delete a post in a Wordpress database based on a partial matching string in another table in the database.
Here's what I've got so far. It should explain what I'm trying to do:
`... | Your sql syntax is not valid. It has to resemble this:
```
delete from wp_posts
where post_title =
case
when (subquery to get data from option_value table) like '%domain.com%' then 'uniqueId'
else 'XXXXXXX'
end
```
However, it's probably better not to use a case construct here. I would do something like this... | It's hard to give a definitive answer without a bit more context. However, from an initial look at your code, assuming that it needs to adhere to standard SQL syntax, the following line would need updating from
```
option_value FROM wp_options LIKE '%domain.com%'
```
to
```
WHEN EXISTS(SELECT 1 FROM wp_options WHERE... | Deleting a row in Table X based on the existence of a value in Table Y | [
"",
"sql",
"wordpress",
""
] |
It seems that many get this error but each situation is different.
My code:
```
i = 0
def sort(a):
b = len(a)
if(i == b):
print (a)
elif(b == 0):
print ('Error. No value detected...')
elif(b == 1):
print (a)
elif(a[i]>a[i+1]):
a[i], a[i+1] = a[i+1], a[i]
... | Your variable `i` is defined at the global (module) level. See [Short Description of the Scoping Rules?](https://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules)
for info the order in which python looks for your variable. If you only try to reference the variable from within your function, ... | Since you assign to it, your variable `i` is a local variable in your `sort()` function. However, you are trying to use it before you assign anything to it, so you get this error.
If you intend to use the global variable `i` you must include the statement `global i` somewhere in your function. | Error Code: UnboundLocalError: local variable referenced before assignment | [
"",
"python",
"computer-science",
""
] |
I'm with a great difficulty in formulate a SQL for a module of notifications when a new user register.
I have a database of **Notifications**, I set up a notification to be sent. Examples:
* Send notification when a man and blue eyes register;
* Send notification when a woman register;
* Send a notification when a bl... | ```
SELECT *
FROM Notification
inner join User on (
User.Date >= Notification.Date and
(Notification.Gender is null or Notification.Gender = User.Gender) and
(Notification.HairColor is null or Notification.HairColor = User.HairColor) and
(Notification.EyeColor is null Notification.EyeColor = User.EyeCo... | This is the way I would implement this user registration / notification functionality:
1. Three tables: Users, Notif\_type, Notif\_queue.
2. A trigger on insert on table Users which calls a stored procedure SendNotification(user\_id).
3. The stored proc will have the logic which you can change overtime without having ... | SQL design for notification of new registered users | [
"",
"sql",
"database-design",
"mysqli",
""
] |
I tried to implement a simple adjacency matrix to keep track of which nodes are connected to which nodes in an undirected graph. However, my adjacency matrix keeps screwing up by changing entire columns instead of individual cells. Here's my code:
```
def setup_adj_matrix(size, edges):
# initialize matrix with zer... | The lists are all shallow copies of each other, so when you edit one you're actually editing each row. Try this for initializing the matrix:
```
adj_matrix = [[0] * size for i in range(size)]
``` | The multiplication operator with a list and an int returns multiple references to the same list, not multiple copies. Your array contains the same object nine times.
You can create the correct array with a double list comprehension:
```
def init_matrix(x, y):
return [[[0] for i in range(x)] for j in range(y)]
``` | Adjacency Matrix not populating correctly python | [
"",
"python",
""
] |
How do I set up Selenium to work with Python? I just want to write/export scripts in Python, and then run them. Are there any resources for that? I tried googling, but the stuff I found was either referring to an outdated version of Selenium (RC), or an outdated version of Python. | You mean Selenium WebDriver?
Huh....
**Prerequisite**: Install Python based on your OS
Install with following command
```
pip install -U selenium
```
And use this module in your code
```
from selenium import webdriver
```
You can also use many of the following as required
```
from selenium.webdriver.common.by im... | There are a lot of sources for selenium - here is good one for simple use [Selenium](http://selenium-python.readthedocs.io/), and here is a example snippet too [Selenium Examples](https://gist.github.com/hugs/830011)
You can find a lot of good sources to use selenium, it's not too hard to get it set up and start using... | How to use Selenium with Python? | [
"",
"python",
"selenium",
"selenium-webdriver",
"automation",
""
] |
When I type `play`, a random number is assigned to `number1`. It asks me for a prediction and I put in a number, say 5. After putting in 5 I always get the `else` statement and not the `if` statement. I even put a `print()` to find out what number was generated. Sometimes I'm right on or within 1 (The game also allows ... | Use the `elif` statement after the very first statement. At current, your code
```
if lobby == 'back':
altvillagescene()
else:
print('Please type a valid option.')
print('--------------------------------')
altluckyrollgame()
```
is checking if lobby == 'back' and running the el... | Your problem is that you're comparing a string to an integer.
You'll need to first convert the input to an `int`:
```
try:
guess = int(prediction)
except ValueError:
#Handle when a person enters an invalid number here
``` | Condition always evaluates to else branch | [
"",
"python",
""
] |
I have a hash, which I am using for an SQL query
```
:profiles => {:gender => Female, :idea => ''}
```
The way it is setup now, it is looking for profiles with gender female and an empty idea. Meaning the string in the idea column is empty. How do I get this to be the exact opposite. I want to find rows where the ide... | There is no way to express this within the hash itself but you can use one of the other styles of querying e.g.
```
Profile.where("gender = ? and idea != ''", gender)
```
or if you upgrade to Rails 4 you can use the `not` method to invert a condition. e.g.
```
Profile.where.not(idea: '')
```
and you can combine mul... | You may be looking for !string.empty? | How to put "Is not empty" as a hash value? | [
"",
"sql",
"ruby-on-rails",
"ruby",
"ruby-on-rails-3",
""
] |
How can I select like this? Can I create a User defined Aggregate Function
`SELECT Max(A),(SELECT TOP 1 FROM TheGroup Where B=Max(A))` FROM MyTable
where MyTable as Shown Below
```
A B C
--------------
1 2 S
3 4 S
4 5 T
6 7 T
```
I want a Query Like this
```
SELECT MAX(A),(B Where A=M... | Try Following Query :
```
SELECT TABLE1.A , TABLE2.B , TABLE1.C
FROM
(
SELECT MAX(A) AS A,C
FROM MYTable
GROUP BY C
) AS TABLE1
INNER JOIN
(
SELECT *
FROM MYTable
) AS TABLE2 ON TABLE1.A = TABLE2.A
```
[SQLFIDDLE](http://sqlfiddle.com/#!3/ae901/3)
you can do it by simple join query . join query alway... | ```
SELECT A,B,C FROM
(SELECT *, ROW_NUMBER() OVER (PARTITION BY C ORDER BY A DESC) RN FROM MyTable)
WHERE RN = 1
```
(this query will always return only one row per C value)
OR
```
WITH CTE_Group AS
(
SELECT C, MAX(A) AS MaxA
FROM MyTable
GROUP BY C
)
SELECT g.MaxA, t.B, g.C
FROM MyTable t
INNER... | SELECT Row Values WHERE MAX() is Column Value In GROUP BY Query | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Database: Sybase Advantage 11
On my quest to normalize data, I am trying to delete the results I get from this `SELECT` statement:
```
SELECT tableA.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '... | You need to identify the primary key in TableA in order to delete the correct record. The primary key may be a single column or a combination of several columns that uniquely identifies a row in the table. If there is no primary key, then the ROWID pseudo column may be used as the primary key.
```
DELETE FROM tableA
W... | Your second `DELETE` query was nearly correct. Just be sure to **put the table name (or an alias) between `DELETE` and `FROM`** to specify which table you are deleting from. This is simpler than using a nested `SELECT` statement like in the other answers.
## Corrected Query (option 1: using full table name):
```
DELE... | How to write a SQL DELETE statement with a SELECT statement in the WHERE clause? | [
"",
"sql",
"select",
"where-clause",
"advantage-database-server",
"sql-delete",
""
] |
There are two n-length arrays ( `a` and `b` ) consisting of integers > 2.
On every turn I want to remove an integer from each array ( `a[i]` and `b[j]` ) given that a certain condition about them is true (e.g. that they are not co-prime). ( If the condition is not true, I'll try to remove another combination )
After ... | As far as I can tell, to solve this:
* Construct bipartite graph G such that for each Ai and Bj, if GCD(Ai,Bj) > 1, there is an edge (Ai, Bj) in G.
* Find the **maximum matching** of G
* Cardinality of the matching is the solution
I don't see how this could be solved faster. | I know where this problem you took.
And you solution for this problem is wrong because its O(n^2) and greedy. n <= 10^5. 2 > a,b < 10^9 from array
I think in this problem you have to find some trick. And all algorithm for maximum matchings in bipartite graphs will TL. | Find maximum number of valid combinations for elements of two arrays | [
"",
"python",
"algorithm",
"python-3.x",
""
] |
I have a query with results like ID, Value. What I want is to get the values in order of their ids and also calculate the accumulated value in another column. take a look at my simplified code:
```
declare @TempTable Table
(
ID int,
Value int
)
insert into @TempTable values
(1, 10),
(2, -15),
(3, 12),
(4, 18),... | In 2012 version, you can use:
```
SELECT
id,
Value,
AccValue = SUM(Value) OVER (ORDER BY ID
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW)
FROM
@TempTable ;
```
For previous versions of SQL-Server, see my answer in this sim... | You can use recursion:
```
;WITH x AS
(
SELECT
[ID],
[Value],
bal=[Value]
FROM Table1
WHERE [ID] = 1
UNION ALL
SELECT
y.[ID],
y.[Value],
x.bal+(y.[Value]) as bal
FROM x INNER JOIN Table1 AS y
ON y.[ID] = x.[ID] + 1
)
SELECT
[ID],
[V... | Accumulating in SQL | [
"",
"sql",
"sql-server",
"cumulative-sum",
""
] |
I want to count the number of occurrences of each of certain words in a data frame. I currently do it using `str.contains`:
```
a = df2[df2['col1'].str.contains("sample")].groupby('col2').size()
n = a.apply(lambda x: 1).sum()
```
Is there a method to match regular expression and get the count of occurrences? In my ca... | Update: Original answer counts those rows which contain a substring.
To count all the occurrences of a substring you can use [`.str.count`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.count.html):
```
In [21]: df = pd.DataFrame(['hello', 'world', 'hehe'], columns=['words'])
In [22]: df.w... | You can use `value_count` function.
```
import pandas as pd
# URL to .csv file
data_url = 'https://vincentarelbundock.github.io/Rdatasets/csv/carData/Arrests.csv'
# Reading the data
df = pd.read_csv(data_url, index_col=0)
```
[](https://i.stack.imgu... | Count occurrences of each of certain words in pandas dataframe | [
"",
"python",
"pandas",
"dataframe",
""
] |
I'm trying to build a database that will store information on movies.
```
Title
Plot
Genre
Rating
Director
```
The only thing that is bothering me is that most films don't just have one genre and I'm struggling to figure out how to store this on a MySQL Database. At first I was thinking that I'll ... | I would suggest you should follow the following structure:
> tablename: movies
>
> movieid, title, plot, rating, director
```
> sample data:
>
> 1 titanic Bollywood 10 James Cameron
```
> tablename: genres
>
> genreid, genre
```
> sample data:
> 1 Horror
> 2 Thriller
> 3 Action
> 4 Love
```
> t... | What you are looking to model here is called a "many-to-many" relationship, and is very common when modelling "real world" categorisations.
There are many descriptions out there of how to work with such relationships including:
* Praveen's answer here which is specific to your question.
* <http://en.wikipedia.org/wik... | Movie Database, storing multiple genres | [
"",
"mysql",
"sql",
"database-design",
"join",
"many-to-many",
""
] |
I wanted to find the total number of orders placed by a customer till date and the last order date.
**Customer**
```
custome_id customer_name
1 JOHN
2 ALEX
```
**Order**
```
order_id customer_id order_date status
R1 1 06/06/2013 ... | In case you want to get last `Order_ID`, you need to join order table with sub-query like this:
```
SELECT tbl.customer_id, tbl.customer_name, o.order_id, MaxOrderDate, Completed_orders, Total_Order
FROM [ORDER] o
JOIN
( SELECT c.customer_id, c.customer_name, MAX(o.order_date) AS MaxOrderDate
,SUM(CASE WHEN o.st... | ```
select
customer_id,
MAX(order_date) as last_order_date,
count(*) as num_orders
from Order
group by customer_id
``` | select total orders and last order from a customer | [
"",
"sql",
"join",
"count",
"informix",
""
] |
Say we need a program which takes a list of strings and splits them, and appends the first two words, in a tuple, to a list and returns that list; in other words, a program which gives you the first two words of each string.
```
input: ["hello world how are you", "foo bar baz"]
output: [("hello", "world"), ("foo", "ba... | Well, in this particular case:
```
def firstTwoWords(strings):
return [s.split()[:2] for s in strings]
```
Otherwise, though, you can use one generator expression:
```
def firstTwoWords(strings):
return [(s[0], s[1]) for s in (s.split() for s in strings)]
```
And if performance is actually critical, just us... | Writing what comes to mind naturally from English and hoping it's valid syntax rarely works, unfortunately.
The generalized form of what you're trying to do is bind some expression to a name within a comprehension. There's no direct support to that, but since a `for` clause in a comprehension binds a name to each elem... | Eliminating redundant function calls in comprehensions from within the comprehension | [
"",
"python",
"list-comprehension",
""
] |
So i have a list of heights:
```
heights = [1, 2, 3, 5, 7, 8, 8, 13]
```
And im using this function to store each height integer value and its index in the list in a class i called Node.
```
def initializeNodes(heights):
ans = []
for height in heights:
ans.append(Node(heights.index(height), height))
... | Use [`enumerate()`](http://docs.python.org/2/library/functions.html#enumerate) to generate an index:
```
def initializeNodes(heights):
ans = []
for i, height in enumerate(heights):
ans.append(Node(i, height))
return ans
```
You can collapse the four lines into 1 using a list comprehension:
```
de... | The problem with `list.index` is that it'll only return the index of first occurrence of the item.
```
>>> heights = [1, 2, 2, 3, 5, 5, 7, 8, 8, 13]
>>> heights.index(2)
1
>>> heights.index(5)
4
>>> heights.index(8)
7
```
help on `list.index`:
> L.index(value, [start, [stop]]) -> integer -- return first index of
> v... | Python list iteration | [
"",
"python",
"list",
"iteration",
""
] |
I have a database on SQL Server 2012 and am having some problems with a few tables that become slow after a while and the thing that helps is rebuilding the indexes. I was wondering if anyone has advice on what could be wrong in any of them, I will post their structure and indexes below. I have not built this structure... | A great tool that will analyze and, if necessary, rebuild indexes and update statistics is Ola Hallengren's Index and Statistics Maintenance tool/script. We run this thing nightly, along with the Integrity Check, to keep our databases healthy.
<http://ola.hallengren.com/> | One column that sticks out to me is this one:
```
pk_Name (Clustered) [Name, fkID]
```
Clustered keys determine the *physical* order of records in the database table. If `Name` is a string and values are inserted in "random" order (i.e. not always at the end of the table alphabetically) there could be performance pro... | Keep having to reindex sql tables | [
"",
"sql",
"sql-server",
""
] |
I have a table STARTSTOP
```
ACTION DATA ID_PPSTARTSTOPPOZ
0 2013-03-18 08:38:00 10451
1 2013-03-18 09:00:00 10453
0 2013-03-18 09:50:00 10466
1 2013-03-18 10:38:00 10467
0 2013-03-19 11:54:00 10499
1 2013-03-19 12:32:00 10505
```
Action 0 -> START ACTION
Action 1 -> STOP ACTION
DATA i... | ```
select A1.ID_PPSTARTSTOPPOZ as Action_0,
A2.Action_1,
datediff (minute, A1.DATA ,A2.DATA)
from STARTSTOP A1
JOIN
(
select ID_PPSTARTSTOPPOZ as Action_1,
DATA,
(select max(ID_PPSTARTSTOPPOZ)
FROM STARTSTOP
where ID_PPSTARTSTOPPOZ<T.ID_PPSTARTSTOPPOZ
... | It could be done with a single select but algorithmic EXECUTE BLOCK would do much faster:
```
EXECUTE BLOCK
RETURNS (ACTION_1 INTEGER, ACTION_2 INTEGER, DURATION INTEGER)
AS
DECLARE VARIABLE act INTEGER;
DECLARE VARIABLE act_id INTEGER;
DECLARE VARIABLE d TIMESTAMP = NULL;
DECLARE VARIABLE d1 TIMESTAMP = NUL... | firebird - self join on one table | [
"",
"sql",
"join",
"firebird",
"self-join",
""
] |
Another question to do with my minigame. I've received great help on the previous questions and I hope I don't waste your time on such a, most likely foolish, question.
Here's the code:
```
import time
import random
inventory = []
miningskill = 1
fishingskill = 1
gold = 0
rawfish = ["Mackarel", "Cod", "Salmon", "Herri... | Use a `if inventory` condition to check whether `inventory` is empty:
```
def sell_function():
if inventory:
if inventory[0] in rawfish:
#other code
else:
print "Shopkeeper:'You can't sell that.'"
``` | The problem is that your `inventory` list is empty (so there is no 0th element). You can check for this by using `if` statement:
```
def sell_function():
if not inventory:
print "your inventory is empty! You cannot sell anything"
return
if inventory[0] in rawfish:
...
``` | Else not working IndexError: list index out of range | [
"",
"python",
"runtime-error",
""
] |
I built following Select query to get below results
```
SELECT Orders.OrderID, OrderDetails.ProductCode, OrderDetails.Coupon
From Orders, OrderDetails
WHERE Orders.OrderID=OrderDetails.OrderID
```
Results
```
Order ID Product Code Coupon
22 A
22 B XYZ
22 C
23 ... | ```
SELECT
t1.OrderID,
t1.ProductCode,
MAX(ISNULL(t2.Coupon,'')) as CouponCode,
t1.CustomerName
--Here you have select list by using alias 't'
--don't forget it to add in group by clause
FROM
(
select O.OrderID,OD.ProductCode,OD.CouponCode as Coupon,C.CustomerName
--Here add the list of columns
from Order... | This is kind of ugly but does the job:
```
SELECT o.OrderID, od1.ProductCode, COALESCE(od1.Coupon,od2.Coupon)
From
Orders o
inner join
OrderDetails od1
on
o.OrderID=od1.OrderID
left join
(select OrderID,MAX(Coupon) as Coupon from OrderDetails
where Coupon is not null... | SQL Server: fill Null Fields from Not Null Column for multiple rows having same id | [
"",
"sql",
"sql-server",
""
] |
So I have a python application that is being bundled into a .app using py2app. I have some debugging print statements in there that would normally print to stdout if I was running the code in the terminal. If I just open the bundled .app, obviously I don't see any of this output. Is any of this actually being printed s... | It goes to standard output (so in the command line, if you are opening it in command line, or eg. to the log, if you are running it with cron jobs).
For more advanced and flexible usage try using built-in logging support ([`logging` module](http://docs.python.org/2/library/logging.html)). It allows you to direct messa... | Where the stdout and stderr streams are redirect to depends on how you run the application, and on which OSX release you are.
When you run the application from the Terminal ("MyApp.app/Contents/MacOS/MyApp") the output ends up in the terminal window.
When you run the application by double clicking, or using the open(... | Where does stuff "print" to when not running application from terminal? | [
"",
"python",
"macos",
"stdout",
"py2app",
""
] |
I'm having a problem because I have an output of A formatted like so:
```
[0.018801, 0.011839, -3332.980568, 0.009446, -3332.984916, 0.007438, -3332.982958]
[0.020493, 0.015735, -3332.980353, 0.013179, -3332.968465, 0.055135, 0.135461]
[0.020678, 0.018212, -3332.983603, 0.011993, 0.097811, 0.014364, 0.099570]
[0.02075... | You are trying to generate a list of lists. However, you aren't saving each list -- every time you go through the loop you create a new record and then replace it with the next record. This is why a eventually just contains the last record.
The commas aren't relevant -- that's just Python's syntax. The values are not ... | Extrapolating from your [other question](https://stackoverflow.com/questions/17489218/averaging-down-a-column-of-averaged-averages), I think you could do what you want with something like this:
```
def mean(a):
return sum(a) / len(a)
averages = []
with open("test2.xls") as w:
w.next() # skip over header row
... | Separating rows of output by commas and staying in float | [
"",
"python",
"format",
"rows",
""
] |
I have a table with columns similar to below , but with about 30 date columns and 500+ records
```
id | forcast_date | actual_date
1 10/01/2013 12/01/2013
2 03/01/2013 06/01/2013
3 05/01/2013 05/01/2013
4 10/01/2013 09/01/2013
```
and what I need to do is get a query with output... | Just in case someone else comes along with the same question:
Instead of trying to use some amazing query, I ended up creating an array of date\_columns\_names and a loop in the program that was calling this query, and for each date\_column\_name, performing teh asme query. It is a bit slower, but it does work | Try:
```
SELECT WeekInYear, ForecastCount, ActualCount
FROM ( SELECT A.WeekInYear, A.ForecastCount, B.ActualCount FROM (
SELECT weekofyear(forecast_date) as WeekInYear,
COUNT(forecast_date) as ForecastCount, 0 as ActualCount
FROM TableWeeks
GROUP BY weekofyear(forecast_date)
) A
INNER ... | MySQL Group by week num w/ multiple date column | [
"",
"mysql",
"sql",
""
] |
I would like to find all records in Column A where, after sorting Column C in ascending order, Column D begins with a value other than the earliest date.
From the below example, I would want it to return records for Ex2 and Ex3 and not return records for Ex1.
**REVISED UPDATES/REQUIREMENTS:**
1) I would like it grou... | You appear to assume an ordering by [Column B], which you can make explicit in a self join:
```
SELECT t1.[Column A], t1.[Column B], t1.[Column C], t1.[Column D]
FROM YourTableName t1
JOIN YourTableName t2
ON t2.[Column A] = t1.[Column A]
AND t2.[Column B] > t1.[Column B]
WHERE t2.[Column C] > t1.[Column C]
AND t2.[Co... | New answer specifically addressing the following specifications (which seem to comprise the problem now):
> UPDATE: I would like it grouped by Column A and ordered by Column C.
>
> UPDATE #2: I want to return all examples from Column A where the
> "first" value in Column D is not the lowest value.
```
SELECT a.*
FROM... | SQL compare min value in one column with max date in different column | [
"",
"sql",
"sql-server-2008",
""
] |
Why can't i do this?
```
extout = os.path.splitext(args.outputfile)[1].lower()
if extout != (".csv" | ".xml"): # <------- creates error
sys.stderr.write('ERROR: Invalid extension or none found. This program only recognizes .csv or .xml extensions %s\n')
sys.exit(1)
```
This gives me an type error:
`... | Use a tuple and `not in`:
```
if extout not in (".csv", ".xml"):
```
This will return `True` if `extout` doesn't matches any of the tuple items otherwise `False`.
`|` is an Bitwise OR operator in python that's why it is not working on strings. | The easiest way to do what you want is:
```
if extout not in ('.csv', '.xml'):
...
``` | Boolean Operators in Python | [
"",
"python",
""
] |
Here is what I am trying to do:
```
select * from table
where in ('completedDate', 'completedBy', 'cancelDate', 'cancelBy') is not null
```
If the four columns above are not null I need to display the records. I know I would do this with several where/and clauses but trying to learn and make my new stuff cleaner.
Is... | If I understand correctly I guess you want to do that:
```
select *
from table
where completedDate is not null
and completedBy is not null
and cancelDate is not null
and cancelBy is not null
```
Regarding clarity of code I don't see a better way to write it, that's what I would code anyway.
**EDIT**: I would... | ```
-- Under reasonable assumption on data types:
select *
from [table]
where completedBy+cancelBy+DATENAME(yy,completedDate)+ DATENAME(yy,cancelDate)
is not null
``` | Trying to create cleaner sql syntax | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table with a list of dates of datetime format in two columns.
Now what I would like to do is pull each non null date from `Column1`, add one year to each value and then store it into `Column2`.
So below, after the update, `Column2` (the one with the nulls) will show:
```
2014-07-09 00:00:00.000
2013-07-30 ... | ```
UPDATE tbl
SET Column2 = DATEADD(year, 1, Column1)
WHERE Column2 IS NULL AND Column1 IS NOT NULL
```
That's gone to be ok | You can use [DATEADD](http://msdn.microsoft.com/en-us/library/ms186819.aspx)
```
UPDATE YourTable
SET Column2 = DATEADD(YEAR, 1, Column1)
WHERE Column1 IS NOT NULL
``` | SQL update datetime entries | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"t-sql",
""
] |
I have the tables:
* `Candidates`
* `CandidateLanguages`
* `CandidateSkills`
Each candidate may have more than 1 language and more than 1 skill
So for `Candidate` "FRED", his records in `CandidateLanguages` may be
```
FRED - ENGLISH
FRED - FRENCH
```
and his records in `CandidateSkills` may be
```
FRED - RUNNING
... | The problem you are solving is called **Relational Division**.
See this article: **[Divided We Stand: The SQL of Relational Division](https://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division/)** and this question for a few ways to solve it: **[How to filter SQL results in a has... | If you want *all skills* and *all languages*, simply counting the multiplications will be enough.
```
select c.id
from candidate c
join candidateLanguage cl on c.id = cl.candidateId
join language l on cl.languageId = l.id
join candidateSkill cs on c.id = cd.candidateId
join skill s on s.id = cs.skillId
group by c.id
... | Complicated SQL Statement: select that matches on multiple tables | [
"",
"sql",
""
] |
I have a sqlite table with columns x, y, and z. x and y are unique keys and z is the value.
I would like to use R to insert data into this table. If a duplicate record - based on the x and y fields - is being inserted, I would like sqlite to reject the record and continue. In sql, this can be done using "insert or ign... | I found the source where dbWriteTable constructs the sql string and sends it to sqlite. You can use this modified source to allow the "insert or ignore" syntax
<https://gist.github.com/jeffwong/5925000> | Rework of answer from @Karsten W to load all data with same process:
```
library(RSQLite)
# create table
con <- dbConnect(drv=RSQLite::SQLite(), ":memory:")
dbExecute(con, "CREATE TABLE tab1 (a CHAR(6) NOT NULL, b CHAR(6) NOT NULL, PRIMARY KEY (a, b));")
load_data <- function(x) {
# load data
# we want to ad... | RSQLite insert ignore to skip duplicates | [
"",
"sql",
"r",
"sqlite",
""
] |
Ok this is what I get:
> Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)
> Additional information: An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
> CREATE FILE encountered operating system error 5(error not found) whi... | This is a permission issue. The account under which the SQL Server process is running has no write permission to the programs folder. Either you add those permissions to the account running the SQL Server service or you attach your database at a location where the SQL Server service account has read/write rights.
See ... | if you use SSMS try to execute it as Administrator. | Can't attach any database to SQL Server 2012 | [
"",
"sql",
"sql-server-2012",
""
] |
I'm importing flat files through SSIS which then exports them into a SQL table. I need to add an additional column containing a GUID somewhere in the middle so that it can also be exported to the table.
I've made sure there's an additional column ready in the SQL Table for the GUID to be passed into but I'm unsure of ... | You can do this via a Script Component Transformation.
In your data flow task, between source and destination, add the script component.
Under 'Inputs and Outputs' add an output column, name it as you like and in Data Type Properties give it DataType of `unique identifier [DT_GUID]`
Use this script (Make sure ScriptL... | below link should help you .
1. Add a derived transform
2. add a new column
3. get dt\_guid
here the link with more details
<http://microsoft-ssis.blogspot.com/2011/02/create-guid-column-in-ssis.html>
best of luck | How can I add a GUID column in SSIS from a Flat File source before importing to a SQL Table? | [
"",
"sql",
"guid",
"ssis",
"flat-file",
""
] |
I'm proficient in Python but a noob at Scala. I'm about to write some dirty experiment code in Scala, and came across the thought that it would be really handy if Scala had a function like `help()` in Python. For example, if I wanted to see the built-in methods for a Scala `Array` I might want to type something like `h... | I do not know of one built-in but you should use [Scaladocs](http://www.scala-lang.org/api/current/index.html) to find the same information.
Unless you use eclipse which has an auto complete with short explanations. For instance it will give you all the commands for arrays after typing 'array.'. | I think tab completion is the closest thing to Python's help.
There is also a dated but still relevant [post](http://dcsobral.blogspot.com/2011/12/using-scala-api-documentation.html) from @dcsobral on using Scala documentation and [Scalex](http://scalex.org/) which is similar to Hoogle for Haskell.
This is the tab co... | Scala equivalent of Python help() | [
"",
"python",
"scala",
"equivalent",
""
] |
I'm formatting GPS output logs and I need an efficient method to remove x number of lines above the line that contains a 0 and y number of lines below that line.
```
*--------------------------------------*
UTC Time: 000000.00
Latitude: 0000.0000
N/S ind.: N
Longitude: 000... | ```
def remLines(infilepath, outfilepath, delim, above, below):
infile = open(infilepath)
outfile = open(outfilepath, 'w')
buff = []
line = infile.readline()
while line:
if line.strip() == delim:
buff = []
for _ in range(below): # need to error check here, if you're... | You can use a `set` here, iterate over the file and as soon as you see `'Position fix ind: 0'` in a line(say, index of the line is `i`), then add a set of numbers from `i-6` to `i+3`
to a set.
```
f = open('abc')
se = set()
for i,x in enumerate(f):
if 'Position fix ind: 0' in x:
se.update(range(i-6,i+4))
f... | Remove amount of lines above and below a line containing a string | [
"",
"python",
"python-2.5",
""
] |
I have two dates
`06-Jan-2009` and `12-Dec-2010`
I want to calculate the date difference between these two dates.. (basis on the month and year).
I want to get the answer 2 Year.
But if dates is `06-Jan-2009` And `12-Oct-2010`
then I need 10 Months as output. | Try this one:
```
Declare @SDate DateTime ='06-Jan-2009'
Declare @EDate DateTime ='12-Oct-2009'
select case when DateDiff(M,@sDate,@EDate) <=12
then DateDiff(M,@sDate,@EDate)
else Round( ( Convert(Decimal(18,0)
,DateDiff(M,@sDate,@EDate)/12.0)),0) end
``` | ```
declare @Birthdate datetime
declare @AsOnDate datetime
declare @years int
declare @months int
declare @days int
declare @hours int
declare @minutes int
--NOTE: date of birth must be smaller than As on date,
--else it could produce wrong results
set @Birthdate = '1989-11-30 9:27 pm' --birthdate
set @AsOnDate ... | Calculate Duration between two dates (Month and Year will be Considered) | [
"",
"sql",
"sql-server",
"datediff",
""
] |
I've started to use the IPython Notebook and am enjoying it. Sometimes, I write buggy code that takes massive memory requirements or has an infinite loop. I find the "interrupt kernel" option sluggish or unreliable, and sometimes I have to restart the kernel, losing everything in memory.
I also sometimes write scripts... | I could be wrong, but I'm pretty sure that the "interrupt kernel" button just sends a SIGINT signal to the code that you're currently running (this idea is supported by Fernando's comment [here](http://lighthouseinthesky.blogspot.com/2011/09/review-ipython-notebooks.html)), which is the same thing that hitting CTRL+C w... | You can press `I` twice to interrupt the kernel.
This only works if you're in Command mode. If not already enabled, press `Esc` to enable it. | Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running? | [
"",
"python",
"ipython",
"jupyter-notebook",
""
] |
In order to use `random.choice()`, I have to convert my string to a list:
```
>>> x = "hello"
>>> y = list(x)
>>> y
['h', 'e', 'l', 'l', 'o']
```
But trying to do that in reverse yields a string that actually looks like `['h', 'e', 'l', 'l', 'o']` instead of just `hello`. Doing this repeatedly causes an infinite loop... | ```
>>> x = "hello"
>>> y = list(x)
>>> y
['h', 'e', 'l', 'l', 'o']
>>> ''.join(y)
'hello'
``` | `"".join (x)` will do it quite easily. | Converting list to string? | [
"",
"python",
""
] |
Hi below is my sample table "tbltemptransaction" & "tblProduct"
```
tbltemptransaction table
userid pid pname description qty
3 1 HP PROBOOK 4440S Intel Core i5 5
3 1 HP PROBOOK 4440S Intel Core i5 3
3 6 DocuPrint C1110B 16ppm black 2
3 2 iMac 21.5" Intel Core i5 3
tblPr... | When `pid`, `pname` and `description` are the same (like in your example) then `group by` will aggregate those results to one row.
```
select t.pid, t.pname, t.description, sum(t.qty) as qty
from tbltemptransaction t
group by t.pid, t.pname, t.description
```
**Edit**
```
select t.pid, sum(t.qty) as qty
from tbltemp... | ```
select sum(qty) as qty, pid, pname, description from
tbltemptransaction group by pid,pname, description
``` | Sql Distinct & count | [
"",
"sql",
"count",
"distinct",
""
] |
What algorithms are available for size efficient [A dictionary or associative array](http://en.wikipedia.org/wiki/Associative_array)?
For example, with this key/value set, how can one avoid duplication "Alice" in values?
```
{
"Pride and Prejudice": "Alice",
"The Brothers Karamazov": "Pat",
"Wuthering Heig... | As mentioned by [bennofs](https://stackoverflow.com/users/2494803/bennofs) in comments, you could use [`intern()`](http://docs.python.org/2/library/functions.html#intern) to ensure that identical strings are stored only once:
```
class InternDict(dict):
def __setitem__(self, key, value):
if isinstance(val... | One way to improve space efficiency (in addition to sharing values, which (as bennofs points out in the comments) you can probably accomplish efficiently by using sys.intern) is to use [hopscotch hashing](http://mcg.cs.tau.ac.il/projects/hopscotch-hashing-1), which is an open addressing scheme (a variant of linear prob... | size efficient dictionary(associative array) implementation | [
"",
"python",
"algorithm",
"dictionary",
""
] |
So I have a table of aliases linked to record ids. I need to find duplicate aliases with unique record ids. To explain better:
```
ID Alias Record ID
1 000123 4
2 000123 4
3 000234 4
4 000123 6
5 000345 6
6 000345 7
```
The result of a query on this table should be som... | It looks as if you have two requirements:
1. Identify all aliases that have more than one record id, and
2. List the record ids for these aliases horizontally.
The first is a lot easier to do than the second. Here's some SQL that ought to get you where you want with the first:
```
WITH A -- Get a list of unique co... | Perhaps what you want is just the `min()` and `max()` of `RecordId`:
```
select Alias, min(RecordID), max(RecordId)
from yourTable t
group by Alias
having min(RecordId) <> max(RecordId)
```
You can also count the number of distinct values, using `count(distinct)`:
```
select Alias, count(distinct RecordId) as NumRec... | In SQL, find duplicates in one column with unique values for another column | [
"",
"sql",
"sql-server",
""
] |
In a python unit test (actually Django), what is the correct `assert` statement that will tell me if my test result contains a string of my choosing?
```
self.assertContainsTheString(result, {"car" : ["toyota","honda"]})
```
I want to make sure that my `result` contains at least the json object (or string) that I spe... | ```
self.assertContains(result, "abcd")
```
You can modify it to work with json.
Use `self.assertContains` only for `HttpResponse` objects. For other objects, use `self.assertIn`. | To assert if a string is or is not a substring of another, you should use `assertIn` and `assertNotIn`:
```
# Passes
self.assertIn('bcd', 'abcde')
# AssertionError: 'bcd' unexpectedly found in 'abcde'
self.assertNotIn('bcd', 'abcde')
```
These are new since [Python 2.7](https://docs.python.org/2/library/unittest.htm... | Python/Django: how to assert that unit test result contains a certain string? | [
"",
"python",
"json",
"django",
"unit-testing",
"assert",
""
] |
i am having problem with my retrieving of date after the date fall after 12. for example : if i click from the calander extender: 2/7/2013 to 19/july/2013 , is will throw it me with this error : The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.
this is my code.... | try this
```
select CONVERT(varchar,<datecol>,103) --- and will return as dd/mm/yyyy
where convert(date,<datecol>) between '' and ''
``` | If you want to alter the format of a column of a `GridView` from CodeBehind Add a `RowDataBound` to your grid view.
Then in the `GridView_RowDataBound(object sender, GridViewRowEventArgs e)` method, you'll be able to access e which will provide you with access to the individual cells of that row where you can specify ... | string is not supported in calendar System.Globalization.GregorianCalendar | [
"",
"asp.net",
"sql",
"sql-server",
""
] |
I have a table with email addresses. I am trying to fill a `DomainName` column with the domains from the email addresses. The select statement works fine on its own. But when I add it to the update query I get the following:
> Subquery returned more than 1 value. This is not permitted when the subquery follows `=`, `!... | Just drop the subselect.
```
update Table1
set Table1.DomainName= SUBSTRING(Table1.Email,(CHARINDEX('@',Table1.Email)+1),LEN(Table1.Email) - (CHARINDEX('@',Table1.Email)))
FROM Table1
``` | Remove the `SELECT` statement, it should be this way:
```
update Table1
set Table1.DomainName= SUBSTRING(Table1.Email,
(CHARINDEX('@', Table1.Email) + 1),
LEN(Table1.Email) - (CHARINDEX('@',Table1.Email))
``` | SQL Update Query with select statement | [
"",
"sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.