Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am trying to add a new column that will be a foreign key. I have been able to add the column and the foreign key constraint using two separate `ALTER TABLE` commands:
```
ALTER TABLE one
ADD two_id integer;
ALTER TABLE one
ADD FOREIGN KEY (two_id) REFERENCES two(id);
```
Is there a way to do this with one ALTER TA... | As so often with SQL-related question, it depends on the DBMS. Some DBMS allow you to combine `ALTER TABLE` operations separated by commas. For example...
**[Informix](https://www.ibm.com/support/knowledgecenter/SSGU8G_12.1.0/com.ibm.sqls.doc/ids_sqs_0290.htm)** syntax:
```
ALTER TABLE one
ADD two_id INTEGER,
... | In MS-SQLServer:
```
ALTER TABLE one
ADD two_id integer CONSTRAINT fk FOREIGN KEY (two_id) REFERENCES two(id)
``` | Add new column with foreign key constraint in one command | [
"",
"sql",
""
] |
I've a very simple question about python and lists.
I need to cycle trough a list and get sublists of a fixed lenght, spanning from the beginning to the end. To be more clear:
```
def get_sublists( length ):
# sublist routine
list = [ 1, 2, 3, 4, 5, 6, 7 ]
sublist_len = 3
print get_subl... | Use a loop and yield slices:
```
def get_sublists(length):
for i in range(len(lst) - length + 1)
yield lst[i:i + length]
```
or, if you must return a list:
```
def get_sublists(length):
return [lst[i:i + length] for i in range(len(lst) - length + 1)]
``` | ```
[alist[i:i+3] for i in range(len(alist)-2)]
``` | Python get sublists | [
"",
"python",
""
] |
I am trying to subset hierarchical data that has two row ids.
Say I have data in `hdf`
```
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
['one', 'two', 'three']],
labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
[0, 1, ... | ```
In [125]: hdf[hdf.index.get_level_values(0).isin(['foo', 'qux']) & (hdf.index.get_level_values(1) == 'two')][['A', 'C']]
Out[125]:
A C
foo two -0.113320 -1.215848
qux two 0.953584 0.134363
```
Much more complicated, but it would be better if you have many different values you want to cho... | Doesn't look the nicest, but use tuples to get the rows you want and then squares brackets to select the columns.
```
In [36]: hdf.loc[[('foo', 'two'), ('qux', 'two')]][['A', 'C']]
Out[36]:
A C
foo two -0.356165 0.565022
qux two -0.701186 0.026532
```
`loc` could be swapped out for `ix` her... | subsetting hierarchical data in pandas | [
"",
"python",
"pandas",
""
] |
I have this script that does a word search in text. The search goes pretty good and results work as expected. What I'm trying to achieve is extract `n` words close to the match. For example:
> The world is a small place, we should try to take care of it.
Suppose I'm looking for `place` and I need to extract the 3 wor... | ```
def search(text,n):
'''Searches for text, and retrieves n words either side of the text, which are retuned seperatly'''
word = r"\W*([\w]+)"
groups = re.search(r'{}\W*{}{}'.format(word*n,'place',word*n), text).groups()
return groups[:n],groups[n:]
```
This allows you to specify how many words eithe... | While regex would work, I think it's overkill for this problem. You're better off with two list comprehensions:
```
sentence = 'The world is a small place, we should try to take care of it.'.split()
indices = (i for i,word in enumerate(sentence) if word=="place")
neighbors = []
for ind in indices:
neighbors.append... | Extract words surrounding a search word | [
"",
"python",
"regex",
"find",
"text-processing",
""
] |
The `lda.show_topics` module from the following code only prints the distribution of the top 10 words for each topic, how do i print out the full distribution of all the words in the corpus?
```
from gensim import corpora, models
documents = ["Human machine interface for lab abc computer applications",
"A survey of u... | There is a variable call `topn` in `show_topics()` where you can specify the number of top N words you require from the words distribution over each topic. see <http://radimrehurek.com/gensim/models/ldamodel.html>
So instead of the default `lda.show_topics()`. You can use the `len(dictionary)` for the full word distri... | There are two variable call `num_topics` and `num_words` in `show_topics()`,for `num_topics` number of topics, return `num_words` most significant words (10 words per topic, by default). see <http://radimrehurek.com/gensim/models/ldamodel.html#gensim.models.ldamodel.LdaModel.show_topics>
So you can use the `len(lda.id... | How to print out the full distribution of words in an LDA topic in gensim? | [
"",
"python",
"lda",
"topic-modeling",
"gensim",
""
] |
In Pascal we have `var` parameters, and functions can change parameter values to new values:
```
procedure a(var S1, S2: string);
begin
S1:= S1+'test'+S1;
S2:= S1+'('+S2+')';
end;
```
Does Python have such a feature? Can I change the `string` parameter inside the method, or must I use `return` and assign the vari... | Python can return *multiple* values (in the form of a tuple), obsoleting the need to pass values by reference.
In your simple sample case, even if you were able to apply the same technique, you could not achieve the same result as Python strings are not mutable.
As such, your simple example can be translated to Pytho... | This is called "pass by reference", and no, Python doesn't do it (although if you pass in a mutable object by value and change it in the function, it's changed everywhere because it's the same object.) | Pascal "var parameter" in Python | [
"",
"python",
""
] |
Ok, so I have read in a text file from a .txt file that came in the format as such:
```
home school 5
home office 10
home store 7
school store 8
office school 4
END OF FILE
```
I then turned it into a two dimensional list in python and it looks something like:
```
[['home', 'school', '5'], ['home','office','10'],['h... | The code may look like this:
```
result = {}
for item in data:
result.setdefault(item[0], {}).update({item[1]: item[2]})
```
Proof with whole code: <http://ideone.com/8XUA41> | Skip the intermediate list and just do it all at once:
```
d = {}
with open(myInputFile, 'r') as handle:
for line in handle:
if line == 'END OF FILE':
continue
key1, key2, value = line.split()
if key1 not in d:
d[key1] = {}
d[key1][key2] = int(value)
```
... | Turning a two dimensional list into a dictionary in python | [
"",
"python",
"list",
"dictionary",
"readfile",
""
] |
I have one table holding events and dates:
```
NAME | DOB
-------------------
Adam | 6/26/1999
Barry | 7/18/2005
Daniel| 1/18/1984
```
I have another table defining date ranges as either start or end times, each with a descriptive code:
```
CODE | DATE
---------------------
YearStart| 6/28/2013
YearE... | This seems strange and I still feel like we're missing a relevant piece of the requirements, but look at the following. It seems from your description that the years are irrelevant and you want birthdays that fall between the given months/days.
```
SELECT
t1.Name, t1.DOB
FROM
t1
JOIN t2 AS startDate ON (... | Try using a PIVOT to get the years on the same row, like this. This will return only 'Bob'
```
DECLARE @Names TABLE(
NAME VARCHAR(20),
DOB VARCHAR(10));
DECLARE @Dates TABLE(
CODE VARCHAR(20),
THEDATE VARCHAR(10));
INSERT @Names (NAME,DOB) VALUES ('Adam', '6/26/1999');
INSERT @Names (NAME,DOB) VALUES ('Daniel', '1/1... | How do I compare dates in one SQL table to a range defined in another table? | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
How do I parse a json output get the list from data only and then add the output into say google.com/confidetial and the other strings in the list.
so my json out put i will name it "text"
```
text = {"success":true,"code":200,"data":["Confidential","L1","Secret","Secret123","foobar","maret1","maret2","posted","rontes... | ```
jsonobj = json.loads(text)
print jsonobj['data']
```
Will print the list in the `data` section of your JSON.
If you want to open each as a link after `google.com`, you could try this:
```
def processlinks(text):
output = urllib.urlopen('http://google.com/' % text)
print output.geturl()
print output.r... | ```
info = json.loads(text)
json_text = json.dumps(info["data"])
```
Using `json.dumps` converts the python data structure gotten from `json.loads` back to regular json text.
So, you could then use `json_text` wherever you were using `text` before and it should only have the selected key, in your case: `"data"`. | Parse a json file and add the strings to a URL | [
"",
"python",
""
] |
Is there any way to understand what data type that a string holds... The question is of little logic but see below cases
```
varname = '444'
somefunc(varname) => int
varname = 'somestring'
somefunc(varname) => String
varname = '1.2323'
somefunc(varname) => float
```
My Case:
I get a mixed data in a list but they're... | ```
from ast import literal_eval
def str_to_type(s):
try:
k=literal_eval(s)
return type(k)
except:
return type(s)
l = ['444', '1.2', 'foo', '[1,2]', '[1']
for v in l:
print str_to_type(v)
```
*Output*
```
<type 'int'>
<type 'float'>
<type 'str'>
<type 'list'>
<type 'str'>
``` | You can use ast.literal\_eval() and type():
```
import ast
stringy_value = '333'
try:
the_type = type(ast.literal_eval(stringy_value))
except:
the_type = type('string')
``` | Get type of data stored in a string in python | [
"",
"python",
""
] |
I would like to find an occurrence of a word in Python and print the word after this word. The words are space separated.
example :
if there is an occurrence of the word "sample" "thisword" in a file . I want to get thisword. I want a regex as the thisword keeps on changing . | python strings have a built in method split that splits the string into a list of words delimited by white space characters ([doc](http://docs.python.org/2/library/stdtypes.html#str.split)), it has parameters for controlling the way it splits the word, you can then search the list for the word you want and return the n... | Sounds like you want a function.
```
>>> s = "This is a sentence"
>>> sl = s.split()
>>>
>>> def nextword(target, source):
... for i, w in enumerate(source):
... if w == target:
... return source[i+1]
...
>>> nextword('is', sl)
'a'
>>> nextword('a', sl)
'sentence'
>>>
```
Of course, you'll want to do so... | How to find word next to a word in Python | [
"",
"python",
"python-2.7",
""
] |
I'm reading throug a large gene file of the format
```
>GeneID
ACTCTCTCTATATATATATAT\n
GCTCTGCTTCTAGAGAGAGTG\n
TCTATTTGTTTATATATCTTT\n
>GeneID
GCTCTGCTTCTAGAAATTCCC\n
ACTCTGTATATATTTTCAAAA\n
GCTCTGCTTCTAGAGAGAGTG\n
```
Each gene start with a > then a unique ID. After comes line of the nucleotides of that gene.
Unfort... | I would use a generator instead of skipping through lines (something tells me this can be simplified greatly):
```
def parse_file(file):
id = ''
gene = ''
for line in file:
if line.startswith('>'):
if gene:
yield id, gene
id = line[1:]
gene = ''... | Here's another method that uses `re` and `mmap`:
```
import mmap, re
with open(your_file) as fin:
mm = mmap.mmap(fin.fileno(), 0, access=mmap.ACCESS_READ)
for match in re.finditer('>([^\n]+)([^>]*)', mm, flags=re.DOTALL):
print match.group(1), match.group(2).replace('\n', '')
#GeneID1 ACTCTCTCTATATAT... | Rewind File Pointer to Previous Line Python File IO | [
"",
"python",
"file-io",
""
] |
I wish to pass in some variables into python during run time
```
python add2values.py 123 124
```
then in the python script it will take those 2 values and add together.
OR
```
python add2values.py a=123 b=124
```
then in the python script it will take those 2 values and add together. | You can use `sys.argv`
test.py
```
#!/usr/bin/env python
import sys
total = int(sys.argv[1]) + int(sys.argv[2])
print('Argument List: %s' % str(sys.argv))
print('Total : %d' % total)
```
Run the following command:
```
$ python test.py 123 124
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
Total : 247
``` | There are a few ways to handle command-line arguments.
One is, as has been suggested, `sys.argv`: an array of strings from the arguments at command line. Use this if you want to perform arbitrary operations on different kinds of arguments. You can cast the first two arguments into integers and print their sum with the... | Passing variables at runtime | [
"",
"python",
""
] |
I've been using AS3 before, and liked its grammar, such as the keyword `as`.
For example, if I type `(cat as Animal)` and press `.` in an editor, the editor will be smart enough to offer me code hinting for the class `Animal` no matter what type `cat` actually is, and the code describes itself well.
Python is a beaut... | If you were to translate this literally, you'd end up with
```
cat if isinstance(cat, Animal) else None
```
However, that's not a common idiom.
> How am I suppose to do the above in Python?
I'd say you're not supposed to do this in Python in general, especially not for documentation purposes. | You are looking for a way to inspect the class of an instance.
`isinstance(instance, class)` is a good choice. It tells you whether the instance is of a class or is an instance of a subclass of the class.
In other way, you can use `instance.__class__` to see the exact class the instance is and `class.__bases__` to se... | What is the python way to declare an existing object as an instance of a class? | [
"",
"python",
""
] |
I have a structured array called "data" with several scores for the same entry. For the question sake, I reduced "data" to the following 2 columns.
> ```
> queryid bitscore
> gene1 500
> gene1 480
> gene1 440
> gene2 900
> gene2 300
> ```
What I want to do is to extract the highest values ... | It would probably be much faster to use logical indexing than `for` loops. How about something like this:
```
def high_bitscores(a,qid,thresh=0.9):
valid = a[a['queryid'] == qid]
return valid[valid['bitscore'] >= valid['bitscore'].max()*thresh]
```
**Edit:** If you want to return *all* elements in `data` whic... | If you are able to use pandas, it becomes a one-line problem:
```
from pandas import DataFrame
import numpy as np
# Taken from Theodros
data = zip(('gene1',) * 3 + ('gene2',) * 2, [500, 480, 440, 900, 300])
dtype = [('queryid', 'S6'), ('bitscore', 'i4')]
struct_arr = np.array(data, dtype=dtype)
# Create pandas DataF... | Extract highest values of numpy structured array | [
"",
"python",
"arrays",
"parsing",
"numpy",
""
] |
I have the following model.
```
class Location(models.Model):
name = models.CharField(max_length = 128, blank = True)
address =models.CharField(max_length = 200, blank= True)
latitude = models.DecimalField(max_digits=6, decimal_places=3)
longitude = models.DecimalField(max_digits=6, decimal_places=3)
... | But you can always make proposed by Brian approach better by filtering the results from previous step (which hoepfully should be smaller subset) and for each you check either they are within the radius.
Your user is in black point. Square approximation given by Brian return green but also orange points. The divernce i... | You can do range queries with `filter`.
```
LocationsNearMe = Location.objects.filter(latitude__gte=(the minimal lat from distance()),
latitude__lte=(the minimal lat from distance()),
(repeat for longitude))
```
Unfortunately, this re... | How to filter a django model with latitude and longitude coordinates that fall within a certain radius | [
"",
"python",
"django",
"haversine",
""
] |
I have a range of points x and y stored in numpy arrays.
Those represent x(t) and y(t) where t=0...T-1
I am plotting a scatter plot using
```
import matplotlib.pyplot as plt
plt.scatter(x,y)
plt.show()
```
I would like to have a colormap representing the time (therefore coloring the points depending on the index in... | Here is an example
```
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)
plt.scatter(x, y, c=t)
plt.show()
```
Here you are setting the color based on the index, `t`, which is just an array of `[1, 2, ..., 100]`.

Example:
```
import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)
```
or alternatively,
```
plt.scatter(x, y, c=t, cmap='jet')
``` | Scatter plot and Color mapping in Python | [
"",
"python",
"matplotlib",
""
] |
In [this post](https://superuser.com/questions/301431/how-to-batch-convert-csv-to-xls-xlsx) there is a Python example to convert from csv to xls.
However, my file has more than 65536 rows so xls does not work. If I name the file xlsx it doesnt make a difference. Is there a Python package to convert to xlsx? | Here's an example using [xlsxwriter](https://xlsxwriter.readthedocs.io/):
```
import os
import glob
import csv
from xlsxwriter.workbook import Workbook
for csvfile in glob.glob(os.path.join('.', '*.csv')):
workbook = Workbook(csvfile[:-4] + '.xlsx')
worksheet = workbook.add_worksheet()
with open(csvfile,... | With my library `pyexcel`,
```
$ pip install pyexcel pyexcel-xlsx
```
you can do it in one command line:
```
from pyexcel.cookbook import merge_all_to_a_book
# import pyexcel.ext.xlsx # no longer required if you use pyexcel >= 0.2.2
import glob
merge_all_to_a_book(glob.glob("your_csv_directory/*.csv"), "output.x... | Python convert csv to xlsx | [
"",
"python",
"excel",
"file",
"csv",
"xlsx",
""
] |
Product name contains words deliminated by space.
First word is size second in brand etc.
How to extract those words from string, e.q how to implement query like:
```
select
id,
getwordnum( prodname,1 ) as size,
getwordnum( prodname,2 ) as brand
from products
where ({0} is null or getwordnum( prodname,... | You could try to use function **split\_part**
```
select
id,
split_part( prodname, ' ' , 1 ) as size,
split_part( prodname, ' ', 2 ) as brand
from products
where ({0} is null or split_part( prodname, ' ' , 1 )= {0} ) and
({1} is null or split_part( prodname, ' ', 2 )= {1} )
``` | What you're looking for is probably `split_part` which is available as a String function in PostgreSQL. See <http://www.postgresql.org/docs/9.1/static/functions-string.html>. | how to extract specific word from string in Postgres | [
"",
"sql",
"postgresql",
""
] |
Why is `random.shuffle` returning `None` in Python?
```
>>> x = ['foo','bar','black','sheep']
>>> from random import shuffle
>>> print shuffle(x)
None
```
How do I get the shuffled value instead of `None`? | [`random.shuffle()`](https://docs.python.org/3/library/random.html#random.shuffle) changes the `x` list **in place**.
Python API methods that alter a structure in-place generally return `None`, not the modified data structure.
```
>>> x = ['foo', 'bar', 'black', 'sheep']
>>> random.shuffle(x)
>>> x
['black', 'bar', '... | This method works too.
```
import random
shuffled = random.sample(original, len(original))
``` | Why does random.shuffle return None? | [
"",
"python",
"list",
"random",
"shuffle",
""
] |
I have one `.tex`-document in which one graph is made by the python module `matplotlib`. What I want is, that the graph blends in to the document as good as possible. So I want the characters used in the graph to look exactly like the other same characters in the rest of the document.
My first try looks like this (the... | The difference in the fonts can be caused by incorrect parameter setting out pictures with matplotlib or wrong its integration into the final document.
I think problem in *text.latex.preamble: \usepackage{lmodern}*. This thing works very badly and even developers do not guarantee its workability, [how you can find here... | Alternatively, you can use Matplotlib's [PGF backend](http://matplotlib.org/users/pgf.html). It exports your graph using LaTeX package PGF, then it will use the same fonts your document uses, as it is just a collection of LaTeX commands. You add then in the figure environment using input command, instead of includegrap... | How to obtain the same font(-style, -size etc.) in matplotlib output as in latex output? | [
"",
"python",
"matplotlib",
"tex",
""
] |
`SELECT Val from storedp_Value` within the query editor of SQL Server Management Studio, is this possible?
**UPDATE**
I tried to create a temp table but it didn't seem to work hence why I asked here.
```
CREATE TABLE #Result
(
batchno_seq_no int
)
INSERT #Result EXEC storedp_UPDATEBATCH
SELECT * from #Result
DROP TA... | Well, no. To select from a stored procedure you can do the following:
```
declare @t table (
-- columns that are returned here
);
insert into @t(<column list here>)
exec('storedp_Value');
```
If you are using the results from a stored procedure in this way *and* you wrote the stored procedure, seriously cons... | This is not possible in sql server, you can insert the results into a temp table and then further query that
```
CREATE TABLE #temp ( /* columns */ )
INSERT INTO #temp ( /* columns */ )
EXEC sp_MyStoredProc
SELECT * FROM #temp
WHERE 1=1
DROP TABLE #temp
```
Or you can use `OPENQUERY` but this requires setting up a... | SELECT against stored procedure SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have this structure
```
table idc (numId,idInt, IdAffiliate)
table glob (idInt, IdAtt)
table gratt(IdAtt, dtRomp)
Table update(IdAffiliate, dateUpdate)
```
making this select statement will give me this :
```
SELECT
NumId,
dateUpdate,
DtRomp,
Idc.IdFiliale
FROM Idc inner join glob on glob .IdInt... | It worked with this!!!!!
```
SELECT
NumId,
dateUpdate,
DtRomp,
Idc.IdFiliale
FROM Idc inner join glob on glob .IdInt = Idc.IdInt
inner join Grat on Glob.IdAtt = Grat.IdAtt
inner join update on update.IdAffiliate = Idc.IdAffiliate
where NumId = 9976666
and datediff(day,dateUpdate,DtRomp) = (
... | You can do this with `row_number()`:
```
select NumId, dateUpdate, DtRomp, Idc.IdFiliale
from (SELECT NumId, dateUpdate, DtRomp, Idc.IdFiliale,
row_number() over (partition by NumID, DTRomp order by DTRomp desc) as seqnum
FROM Idc inner join glob on glob .IdInt = Idc.IdInt
inner joi... | top 1 date foreach date | [
"",
"sql",
"foreach",
"sybase",
""
] |
I need to write event calendar in Python which allows pasting events in any position AND works as FIFO (pop elements from the left side).
Python collections.deque can efficiently works as FIFO, but it don't allow to paste elements between current elements.
In the other hand, Python list allows inserting into the midd... | You can have a look at [`blist`](https://pypi.python.org/pypi/blist/). Quoted from their website:
*The blist is a drop-in replacement for the Python list the provides better performance when modifying large lists.*
*...*
*Here are some of the use cases where the blist asymptotically outperforms the built-in list:*
... | It's a bit of a hack but you can also use the `SortedListWithKey` data type from the [SortedContainers](http://www.grantjenks.com/docs/sortedcontainers/) module. You simply want the key to return a constant so you can order elements any way you like. Try this:
```
from sortedcontainers import SortedListWithKey
class ... | Effective queue/linked list in Python | [
"",
"python",
"queue",
"deque",
""
] |
i am trying to get a binary list contains all possibilities by providing the length of these possible lists , now i found a solution but it is not very handy to be used in other functions.
example : i want a list of lists each one represents one binary option of four digits.
if the length is 4 then the result should ... | Looks like a job for [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product):
```
>>> import itertools
>>> n = 4
>>> list(itertools.product((0,1), repeat=n))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (... | I think the `itertools` module in the standard library can help, in particular the `product` function.
<http://docs.python.org/2/library/itertools.html#itertools.product>
```
for x in itertools.product( [0, 1] , repeat=3 ):
print x
```
gives
```
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
... | binary list contains all possible options by knowing its length in python | [
"",
"python",
""
] |
I am having a bit of trouble with this SQL query, first some background
Table definition
```
create table [owner]
(
[patientid] nvarchar(10) NOT NULL,
[clientid] nvarchar(10) NOT NULL,
[percentage] float NULL,
[status] bit NOT NULL
)
alter table [owner] ADD CONSTRAINT PK_OWNER PRIMARY KEY CLUSTERED ([patient... | You should be able to use `row_number()` to get the result by applying a partition by the `patientid` and ordering it by the percentage and clientid:
```
select patientid, clientid
from
(
select patientid, clientid, percentage, status,
row_number() over(partition by patientid
order by perc... | A correlated subquery will also work, though partition may scale better
```
declare @tmpOwner table (
PatientID varchar(50),
ClientID varchar(50),
Percentage int,
Status smallint
)
insert @tmpOwner (PatientID,ClientID,Percentage,Status)
SELECT 'Pet1','Owner1',100,1 UNION
SELECT 'Pet2','Owner2',75,1 UN... | Complicated grouping query, finding a ID not part of the GROUP BY | [
"",
"sql",
"sql-server",
"sql-server-2005",
"group-by",
""
] |
I'm trying to convert the Date key in my table which is numeric into date time key. My current query is:
```
SELECT
DATEADD(HOUR,-4,CONVERT(DATETIME,LEFT([Date],8)+' '+
SUBSTRING([Date],10,2)+':'+
SUBSTRING([Date],12,2)+':'+
SUBSTRING([Date],14,2)+'.'+
SUBSTRING([Date],15,3))) [Date],
[Object] AS [Datas... | You may want to investigate the convert() function:
```
select convert(date, getdate()) as [Date], convert(varchar(8), convert(time, getdate())) as [Time]
```
gives
```
Date Time
---------- --------
2013-07-16 15:05:43
```
Wrapping these around your original SQL gives the admittedly very ugly:
```
SE... | ```
SELECT CONVERT(DATE,[Date])
SELECT CONVERT(TIME(0),[Date])
``` | Splitting Date into 2 Columns (Date + Time) in SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
i am trying to use codeacademy to learn python. the assignment is to "Write a function called fizz\_count that takes a list x as input and returns the count of the string “fizz” in that list."
```
# Write your function below!
def fizz_count(input):
x = [input]
count = 0
if x =="fizz":
count = ... | The problem is that you have no loop.
```
# Write your function below!
def fizz_count(input):
count = 0
for x in input: # you need to iterate through the input list
if x =="fizz":
count = count + 1
return count
```
There is a more concise way by using the `.count()` function:
``... | Get rid of `x = [input]`, that just creates another list containing the list `input`.
> *i think the code above the if loop is fine*
[`if`](http://docs.python.org/2/tutorial/controlflow.html#if-statements)s don't loop; you're probably looking for [`for`](http://docs.python.org/2/tutorial/controlflow.html#for-statemen... | how to change the value of a variable inside an if loop each time the if loop is triggered ? | [
"",
"python",
"loops",
""
] |
In mysql I have `tableA` with rows `userid` and `valueA` and `tableB` with `userid` and `valueB`.
Now I want all entries from `tableA` which don't have an entry in `tableB` with the same `userid`.
I tried several things but can't figure out what I do wrong.
```
SELECT * FROM `tableA`
left join `tableB` on `tableA`.`... | You are almost there. That second query is SO close! All it needs is one little tweak:
Instead of "`= NULL`" you need an "`IS NULL`" in the predicate.
```
SELECT * FROM `tableA`
left join `tableB` on `tableA`.`userid` = `tableB`.`userid`
where `tableB`.`valueB` IS NULL
^^
```
Note that the eq... | Change `= NULL` for `IS NULL` on your code. You can also use `NOT EXISTS` instead:
```
SELECT *
FROM `tableA` A
WHERE NOT EXISTS (SELECT 1 FROM `tableB`
WHERE `userid` = A.`userid`)
``` | How to get entries from tableA which have no entry in tableB? (SQL) | [
"",
"mysql",
"sql",
""
] |
I will calculate last Sunday and last Saturday on every Monday.
E.g. today is 08 July 2013 Monday
last Sunday: 30 June 2013 00:00:00
last Saturday: 6 July 2013 23:59:59.
Note the last Sunday is from 00:00:00 and last Saturday is until 23:59:59 | Given your question, where the query will be run only on Mondays and the objective is to obtain the dates as stated above, one way to solve it is:
```
SELECT TRUNC(SYSDATE) AS TODAYS_DATE,
TRUNC(SYSDATE)-8 AS PREVIOUS_SUNDAY,
TRUNC(SYSDATE) - (INTERVAL '1' DAY + INTERVAL '1' SECOND) AS PREVIOUS_SATURDAY
... | For those looking to get the last weekend days (Saturday and Sunday) on week where the first day is Monday, here's an alternative:
```
select today as todays_date,
next_day(today - 7, 'sat') as prev_saturday,
next_day(today - 7, 'sun') as prev_sunday
from dual
``` | oracle sql get last Sunday and last Saturday | [
"",
"sql",
"oracle",
"date-arithmetic",
""
] |
I'm running a South migration `python manage.py syncdb; python manage.py migrate --all` which breaks when run on a fresh database. However, if you run it *twice*, it goes through fine! On the first try, I get
```
DoesNotExist: ContentType matching query does not exist. Lookup parameters were {'model': 'mymodel', 'app_... | Turns out this is a bug in South.
<http://south.aeracode.org/ticket/1281> | Of course its going to be like this, you have not made any intial schemamigrations. The right way would be like this:
1. Register your django apps with `south` first. So something like:
`python manage.py schemamigration --initial <app_name>`.
2. Then you run `manage.py syncdb`.
3. After this, you run `migrate` l... | Django South Migration does not work the first time around | [
"",
"python",
"django",
"django-south",
""
] |
I try to define a generator function `mycount()` that can be reset with the generator function `send(0)` as in the example below. Everything works fine, except when I use `send(0)` on a new generator object that hasn't started yet. In this case it gives a `TypeError`. Is there any function that checks if the generator ... | To avoid sending a non-`None` value to a just-started generator, you need to call `next` or `send(None)` first. I agree with the others that David Beazley's [coroutine decorator](http://dabeaz.com/coroutines/coroutine.py) (in python 3.x you need to call to `__next__()` function instead of `next()`) is a great option. T... | As your error implies the `send` function must be called with `None` on a just-started generator
[(docs-link)](http://docs.python.org/3/reference/expressions.html?highlight=generator#generator.send).
You *could* catch the `TypeError` and roll from there:
```
#...
try:
g2.send(0)
except TypeError:
... | Is there a Python function that checks if a generator is started? | [
"",
"python",
"generator",
""
] |
Inspired by the <https://www.python.org/doc/essays/graphs/> information in this link, I have been implementing graph structures. I generally use the
```
graph = {'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C']}
edges = [('A','B',20),('A','C',40), ('B','C',10), ('B','D',... | You can use your class as a dict key if you implement `__eq__` and `__hash__`, for example:
```
class StateDetails(object):
def __init__(self, state, abbrev):
self.state = state
self.abbrev = abbrev
def __eq__(self, other):
return isinstance(other, self.__class__) and self.abbrev == oth... | Just store the extra info outside your graph. E.g. keep a dict
```
full_name = {"CA": California,
# 49 more entries
}
```
then use `"CA"` as the graph node.
This makes the graph algorithms must easier to implement because you don't have to work around the extra information that the nodes are... | implementation of graphs in python that have a label | [
"",
"python",
"graph-theory",
""
] |
I have an URL for example:
```
http://name.abc.wxyz:1234/Assts/asset.epx?id=F3F94D94-7232-4FA2-98EF-07sdfssfdsa3B5
```
From this Url I want to extract only '`asset.epx?id=F3F94D94-7232-4FA2-98EF-07sdfssfdsa3B5`' how could i do that?
I am still learning regular expressions and I am not able to solve the above. Any su... | In this specific example splitting the string is enough:
```
url.split('/')[-1]
```
If you have a more complex URL I would recommend the [yarl library](https://github.com/aio-libs/yarl) for parsing it:
```
>>> import yarl # pip install yarl
>>> url = yarl.URL('http://name.abc.wxyz:1234/Assts/asset.epx?id=F3F94D94-7... | You can use [`urlparse`](http://docs.python.org/2/library/urlparse.html) assuming `asset.epx` is the same:
```
>>> import urlparse
>>> url = 'http://name.abc.wxyz:1234/Assts/asset.epx?id=F3F94D94-7232-4FA2-98EF-07sdfssfdsa3B5'
>>> res = urlparse.urlparse(url)
>>> print 'asset.epx?'+res.query
asset.epx?id=F3F94D94-7232... | Extract a part of URL - python | [
"",
"python",
"regex",
"url",
"python-2.7",
""
] |
I have two dictionaries coming from JSON files that look something like that:
```
dict1 = {"data": [{"text": "text1", "id": "id1"}, {"text": "text2", "id": "id2"}]}
dict2 = {"data": [{"text": "text3", "id": "id3"}, {"text": "text4", "id": "id4"}]}
```
I want to create the following out of them:
```
dict = {"data": [... | ```
dict={"data": dict1["data"] +dict2["data"]}
``` | `update` and `append` don't make any assumptions about your structure, so they can't work. You'll have to construct a new dictionary:
```
dict3 = {'data': [dict1['data'] + dict2['data']]}
```
Or modify one of the existing ones:
```
dict1['data'].extend(dict2['data'])
``` | Append dictionaries in Python | [
"",
"python",
"dictionary",
"append",
""
] |
I have to construct a dictionary using variables `base=10` and `digits=set(range(10))` and have to write a comprehension that maps each integer from 0 through 999 to the list of three digits that represents that integer in base 10. That is, the value should be
```
{0: [0, 0, 0], 1: [0, 0, 1], 2: [0, 0, 2], 3: [0, 0, 3... | ```
alphabet = range(10)
base = 10
dict((x*base**2+y*base+z,(x,y,z)) for x in alphabet
for y in alphabet
for z in alphabet )
```
is what you want ... i think
```
alphabet = range(2)
base = 2
dict((x*base**2+y*base+z,(x,y,z)) for x in alphabet
... | I would use `itertools`. For example
```
dict( (i, tup) for i, tup in enumerate(itertools.product(range(10), repeat=3)) )
```
If you really require each value to be a list, you can add `(i, list(tup))` above.
The `product` function computes cartesian product, equivalent to a nested for-loop, according to the [docume... | python construct a dictionary {0: [0, 0, 0], 1: [0, 0, 1], 2: [0, 0, 2], 3: [0, 0, 3], ...,999: [9, 9, 9]} | [
"",
"python",
"list",
"dictionary",
"integer",
"list-comprehension",
""
] |
I have a data set like so in a pandas dataframe:
```
score
timestamp
2013-06-29 00:52:28+00:00 -0.420070
2013-06-29 00:51:53+00:00 -0.445720
2013-06-28 16:40:43+00:00 0.508161
2013-06-28 15:10:30+00:00 0.921474
2013-06-28 ... | If your `timestamp` index is a `DatetimeIndex`:
```
import io
import pandas as pd
content = '''\
timestamp score
2013-06-29 00:52:28+00:00 -0.420070
2013-06-29 00:51:53+00:00 -0.445720
2013-06-28 16:40:43+00:00 0.508161
2013-06-28 15:10:30+00:00 0.921474
2013-06-28 15:10:17+00:00 ... | Otherwise, using the [resample](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.resample.html) function.
```
In [419]: df
Out[419]:
timestamp
2013-06-29 00:52:28 -0.420070
2013-06-29 00:51:53 -0.445720
2013-06-28 16:40:43 0.508161
2013-06-28 15:10:30 0.921474
2013-06-28 15:10:17 0.876710... | summing the number of occurrences per day pandas | [
"",
"python",
"pandas",
"dataframe",
""
] |
What is the preferred way to write Python doc string?
`"""` or `"`
In the book [Dive Into Python](http://www.diveintopython.net/getting_to_know_python/documenting_functions.html), the author provides the following example:
```
def buildConnectionString(params):
"""Build a connection string from a dictionary of p... | From the [PEP8 Style Guide](http://www.python.org/dev/peps/pep-0008/):
* [PEP 257](http://www.python.org/dev/peps/pep-0257/#one-line-docstrings) describes good docstring conventions. Note that most
importantly, the """ that ends a multiline docstring should be on a
line by itself, e.g.:
```
"""Return a fooban... | They're both strings, so there is no difference. The preferred style is triple double quotes ([PEP 257](http://www.python.org/dev/peps/pep-0257/)):
> For consistency, always use `"""triple double quotes"""` around docstrings.
>
> Use `r"""raw triple double quotes"""` if you use any backslashes in your docstrings. For ... | Triple-double quote v.s. Double quote | [
"",
"python",
"pep8",
"quote",
"docstring",
"pep",
""
] |
I have a string array filled with smaller string arrays that I've split in to sets of three. It looks like this (except many more):
```
conv = ('http-get:*:audio/xxx', ':', 'YYY.ORG_XXXXXXXXXX;YYY.ORG_FLAGS=97570000000000000000000000000'), ('http-get:*:video/xxx', ':', 'YYY.ORG_PN=XXXXXXXXXXX;YYY.ORG_FLAGS=ED100000000... | Basically loop through the `conv` tuple and store/print out the 2nd object in each. It can be done as a traditional `for-loop` or using list-comprehensions. Try this -
```
>>> [i[2] for i in conv]
['YYY.ORG;YYY.ORG_FLAGS=97570000000', 'YYY.ORG_PN=XXXXXXXXXXX;YYY.ORG_FLAGS=ED100000']
``` | Like for so many other things, the solution is a list comprehension.
```
array = [[],[] etc. #your array]
print " ".join([item[2] for item in array])
>>>YYY.ORG;YYY.ORG_FLAGS=97570000000 YYY.ORG_PN=XXXXXXXXXXX;YYY.ORG_FLAGS=ED100000
```
Basically the key part here is the line:
```
[item[2] for item in array]
```
wh... | How can I print one part of a Python substring? | [
"",
"python",
"python-2.7",
""
] |
I have following two tables
Table Person
```
Id Name
1 A
2 B
3 C
4 D
5 E
```
Table RelationHierarchy
```
ParentId CHildId
2 1
3 2
4 3
```
This will form a tree like structure
```
D
|
C
|
B
|
A
```
ParentI... | I have also updated the answer in the [original question](https://stackoverflow.com/questions/17676944/finding-a-top-level-parent-in-sql/17677469), but never-mind, here is a copy also:
```
;WITH RCTE AS
(
SELECT ParentId, ChildId, 1 AS Lvl FROM RelationHierarchy
UNION ALL
SELECT rh.ParentId, rc.ChildId... | You could try to use a loop. As you will get many levels of recursion with your approach:
```
declare @child int = 0
declare @parent int = 1 --child to search
while @child <> @parent
BEGIN
set @child = @parent
select @parent = Parentid from @parentchild where ChildID = @child
END
select @parent
``` | Finding Top level parent of each row of a table [SQL Server 2008] | [
"",
"sql",
"sql-server",
"database",
"hierarchical-data",
""
] |
I am trying to test my Django views. This view passes a QuerySet to the template:
```
def merchant_home(request, slug):
merchant = Merchant.objects.get(slug=slug)
product_list = merchant.products.all()
return render_to_response('merchant_home.html',
{'merchant': merchant,
... | Use [assertQuerysetEqual](https://docs.djangoproject.com/en/2.2/topics/testing/tools/#django.test.TransactionTestCase.assertQuerysetEqual), which is built to compare the two querysets for you. You will need to subclass Django's `django.test.TestCase` for it to be available in your tests. | By default `assertQuerysetEqual` uses `repr()` on the first argument. This is why you were having issues with the strings in the queryset comparison.
To work around this you can [override the `transform` argument](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.TransactionTestCase.assertQueryse... | How do I test Django QuerySets are equal? | [
"",
"python",
"django",
"django-queryset",
"django-testing",
""
] |
I'm new to sql and for some reason, the arrow symbol ( -> ) that I am used to seeing in teh command line, which mean it is ready for input, is now displayed as ( '> ) and it does not accept commands. What does it mean and how do I get back to ( -> ) ?
Thanks | It means that it is treating any input which follows as part of a string literal, until it encounters a(n unescaped) string termination quote `'` character.
This will have happened because you previously began the string literal with such a string termination quote character. For example:
```
mysql> SELECT foo
->... | [find the attached image](https://i.stack.imgur.com/9z6Jm.png)
use '/ command and press enter then it will go on next line starting with ->
then use ; and press enter.
it happens if there is unbalanced '(single quote) in query. | What does the ( ' > ) symbol mean in the command line in MySQL? | [
"",
"mysql",
"sql",
"database",
"command-line",
""
] |
Suppose I have two number, @n1, @n2, I want to get bigger one in one simple expression like Max(@n1,@n2). How to write the expression for T-SQL? | ```
DECLARE
@n1 INT = 2,
@n2 INT = 3
SELECT MAX(n) FROM (VALUES(@n1), (@n2)) t(n)
``` | ```
CASE WHEN @n1 > @n2 THEN @n1 ELSE @n2 END
``` | What's the simple expression to get bigger number from two with T-SQL? | [
"",
"sql",
"t-sql",
"sql-server-2008-r2",
""
] |
# Code:
```
class C:
def __init__(self, **kwargs):
self.w = 'foo'
self.z = kwargs['z']
self.my_function(self.z)
def my_function(self, inp):
inp += '!!!'
input_args = {}
input_args['z'] = 'bar'
c = C(**input_args)
print c.z
```
# Expected Result
```
bar!!!
```
# Actual Re... | Modify `self.z`, not `inp`:
```
def my_function(self, inp):
self.z += '!!!'
```
Secondly strings are immutable in python, so modifying `inp` won't affect the original string object.
See what happens when `self.z` is mutable object:
```
class C:
def __init__(self, ):
self.z = []
self.my_funct... | The problem is, you are not actually modifying the value of `self.z`
Try this instead
```
class C:
def __init__(self, **kwargs):
self.w = 'foo'
self.z = kwargs['z']
self.z = self.my_function(self.z)
def my_function(self, inp):
inp += '!!!'
return inp
input_args = ... | How do you call a class' method in __init__? | [
"",
"python",
"constructor",
""
] |
Instead of using:
```
var = re.compile('old word',re.IGNORECASE)
```
And then using:
```
var2 = var.sub(r'new word', line)
```
How would I implement `IGNORECASE` into:
```
var = re.sub(r'WoRd',r'Word',line)
``` | Use the `flags` kwarg:
```
re.sub(r'WoRd',r'Word',line, flags=re.IGNORECASE)
```
Note that it's only available in 2.7 or later.
<http://docs.python.org/2/library/re.html#re.sub> | You can use the flags in re.sub() too, like this:
```
var = re.sub(r'WoRd',r'Word',line, flags=re.IGNORECASE)
``` | How to add IGNORECASE without Compiling a RE | [
"",
"python",
""
] |
I'm opening a file that might be something like this...
> It was the best of times,
>
> it was the worst of times.
Let's say this file name is myFile1.txt
I want the file to split up into this
```
[['It','was','the','best','of','times',','],
['it','was', 'the','worst','of','times','.']]
```
It should be a list of... | You can get your desired list by declaring `separate = []` outside of the loop, and then appending the result of `line.split()` to the list. You don't need to use the `list` function, as `line.split()` already returns a list.
You could try this:
```
def Split():
separate = []
with open('myFile1.txt','r') as inFil... | ```
def Split():
results=[]
inFile=open('myFile1.txt','r')
for line in inFile.readlines():
results.append(line.split())
return results
print(Split())
```
Then everything should work fine. :) | Python Text Files to list of strings | [
"",
"python",
"python-3.x",
""
] |
I try to build V8 javascript engine.
When I try to invoke the command `python build/git_v8`, I get error:
```
File build/gyp_v8, line 48 in < module >
import gyp
ImportError: No module named GYP
```
How I can tell python where search GYP module and what is the correct path to the module in the folder GYP?
My ve... | Obviously, the module gyp.py is not in the search path of modules (sys.path). sys.path is an array variable in sys module which contains all known paths of the modules. You can add the directory containing the module gyp.py manually by either of these methods:
1. set via PYTHONPATH environment variable (see <http://do... | Install the module will be fine.
```
git clone https://chromium.googlesource.com/external/gyp
cd gyp
sudo ./setup.py install
```
enjoy it. | how to add path with module to python? | [
"",
"python",
"v8",
"gyp",
""
] |
I have my development environment setup on Win 7 like this:
**Django development structure**
```
Apache -server- C:\Program Files (x86)\Apache Software Foundation\Apache2.4
PostgreSQL -database- C:\Program Files\PostgreSQL\9.2
Django -framework- C:\Python27\Lib\site-packages\django
Python ... | I can answer the question one by one:
* `Is if fine that Apache, PostgreSQL, and Python are installed all over the place in the Django environment?`
All over the place sounds weird but yes it is totally fine.
* `Did I miss a core Django component and/or directory?`
No you don't miss anything, Django core is in `... | Apache is just web server, it is used to serve files, but to make a website you do not necessary need it. Django comes with its own development server. See :
```
python manage.py runserver
```
Apache is required when you are developing PHP websites because your computer do not know how to compile and interpret it. Bu... | python django project and folder structure (differing from WAMP) | [
"",
"python",
"django",
"directory-structure",
"project-structure",
""
] |
While it is incredibly useful to be able to do set operations between the keys of a dictionary, I often wish that I could perform the set operations on the dictionaries themselves.
I found some recipes for taking [the difference of two dictionaries](http://code.activestate.com/recipes/576644-diff-two-dictionaries/) bu... | tl;dr Recipe: `{k:d1.get(k, k in d1 or d2[k]) for k in set(d1) | set(d2)}` and `|` can be replaced with any other set operator.
Based @torek's comment, another recipe that might be easier to remember (while being fully general) is: `{k:d1.get(k,d2.get(k)) for k in set(d1) | set(d2)}`.
Full answer below:
My first ans... | EDIT: The recipes here don't deal correctly with False values. I've submitted another improved answer.
Here are some recipes I've come up with:
```
>>> d1 = {'one':1, 'both':3}
>>> d2 = {'two':2, 'both':30}
>>>
>>> print "d1 only:", {k:d1.get(k) or d2[k] for k in set(d1) - set(d2)} # 0
d1 only: {'one': 1}
>>> pr... | How can I perform set operations on Python dictionaries? | [
"",
"python",
"dictionary",
""
] |
So I've started a simple sort of roguelike game project in python, but I have problems with editing a duplicate list editing the original. The code is as follows:
```
charx = 1
chary = 1
level = [["#","#","#","#","#","#","#"],["#",".",".",".",".",".","#"],["#",".","#",".",".",".","#"],["#","#","#","#","#","#","#"]]
wh... | You are *not* creating a duplicate of `level`. All you do is create another reference to the *same list*.
To create a copy of a list, you can just slice it from start to end:
```
display_level = level[:]
```
but for your case, that is *not enough*. You need to copy the *nested* lists. In this case, a list comprehens... | Assigning a variable to another is referencing not duplicating. Use [`copy()`](http://docs.python.org/2/library/copy.html) instead.
```
>>> l = range(10) # assign original list
>>> l # display list (l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = l ... | Editing a duplicate list edits the original | [
"",
"python",
"list",
"python-2.7",
""
] |
I have created a python (I m using 2.4) script to automatically create a virtual host in httpd.conf. But when I run it it gives the following error:
```
Traceback (most recent call last):
File "ApaPy2.py", line 2, in ?
from io import open
ImportError: No module named io
```
This is my script
```
import os
from... | The `io` module was introduced in Python 2.6, so it doesn't exist in 2.4. From the [documentation](http://docs.python.org/2/library/io.html):
> New in version 2.6.
The [`open`](http://docs.python.org/2/library/functions.html#open) keyword should work fine for what you're doing here. | The `io` module doesn't exist in 2.4 (and you don't need it to use `open` in this case). I would also simplify your code to use string formatting using `%` instead:
```
project = raw_input(u'Enter the name of project ')
domain = raw_input (u'Enter the domain ')
docroot = raw_input(u'Enter root folder ')
virtualhost=u... | Creation of virtual host through python | [
"",
"python",
"python-2.4",
""
] |
I have the following **[schema](http://sqlfiddle.com/#!2/6e52f/3/0)**:
```
CREATE TABLE `filmati` (
`idfilmato` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`idfilmato`)
) ;
CREATE TABLE `utenti` (
`idutente` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`idutente`)
) ;
CREATE TABLE `utenti_has_filmati` (
... | (cross) join the two tables, so you get the combination of all filmati and all utenti (=cathesian product).
Then you can `left join` the junction table `utenti_has_filmati` to join all existing relations.
Then use the where clause to only return those records that have no matching row in the junction table
```
selec... | ```
SELECT
A.idfilmato, B.idutente
FROM
filmati A,utenti B
WHERE NOT EXISTS
(
SELECT 1
FROM
utenti_has_filmati AB
WHERE
AB.fkutente = A.idfilmato AND
AB.fkfilmato = B.idutente
)
``` | Retrieve Missing relationship in SQL | [
"",
"mysql",
"sql",
""
] |
Is there a way to append a list of lines to a file in a line of python code? I've been doing it as such:
```
lines = ['this is the foo bar line to append','this is the second line', 'whatever third line']
for l in lines:
print>>open(infile,'a'), l
``` | Two lines:
```
lines = [ ... ]
with open('sometextfile', 'a') as outfile:
outfile.write('\n'.join(lines) + '\n')
```
We add the `\n` at the end for a trailing newline.
One line:
```
lines = [ ... ]
open('sometextfile', 'a').write('\n'.join(lines) + '\n')
```
I'd argue for going with the first though. | You can do that :
```
lines = ['this is the foo bar line to append','this is the second line', 'whatever third line']
with open('file.txt', 'w') as fd:
fd.write('\n'.join(lines))
``` | Append a list of strings to a file in a single line? - Python | [
"",
"python",
"string",
"file",
"append",
"output",
""
] |
I want one row in my mysql table to always equal the difference of another two, but the only way i seem to be able to do it is by setting it first time to 0 and then running an update command. Is there anyway to just automate this behaviour so i never have to think about it? Appreciate the advice! | You probably want to investigate using [triggers](http://dev.mysql.com/doc/refman/5.0/en/triggers.html), which are set to run whenever a particular operation occurs on another database object. e.g.,
```
CREATE TRIGGER foobar AFTER UPDATE ON table
FOR EACH ROW SET foo = foo + NEW.bar;
``` | You can also do this with a view:
```
create vw_table as
select t.*, (col2 - col1) as diff
from t;
```
The view will then do the calculation when it is used, so the results are always up-to-date. You don't need to store the data in separate columns.
The downside is that you cannot create a column on the resu... | How to automatically set a mysql column to equal an operation on another? | [
"",
"mysql",
"sql",
"database",
""
] |
I am having a bit of trouble filtering data with pandas NAs. I have a data frame looking like this:
```
Jan Feb Mar Apr May June
0 0.349143 0.249041 0.244352 NaN 0.425336 NaN
1 0.530616 0.816829 NaN 0.212282 0.099364 NaN
2 0.713001 0.073601 0.242077 0.553908 N... | As you say, looping (iterrows) is a last resort. Try this, which uses `apply` with `axis=1` instead of iterating through rows.
```
In [19]: def holey(s):
starts_at = s.notnull().argmax()
next_null = s[starts_at:].isnull().argmax()
if next_null == 0:
return False
any_values_left = s[next_null:].... | Here is another way using NumPy. It is faster because it uses NumPy functions on the underlying array as a whole, rather than applying a Python function to each row individually:
```
import io
import pandas as pd
import numpy as np
content = '''\
Jan Feb Mar Apr May June
0.349143 0... | Use Pandas' NaNs to filter out holes in time series | [
"",
"python",
"pandas",
""
] |
I am creating a web app using Flask.
I wonder if it is possible to save user session data like
```
session['ishappy'] = true
```
in database like it's done in Django using SessionMiddleware where you have options to choose between cookies and database.
And if it is what should I import to my Flask app. | I suggest you implement your own Session and SessionInterface by subclassing flask defaults. Basically, you need to define your own session class and a session interface class.
```
class MyDatabaseSession(CallbackDict, SessionMixin):
def __init__(self, initial=None, sid=None):
CallbackDict.__init__(self, ... | You should check out [Flask-KVSession](http://pythonhosted.org/Flask-KVSession/), which is self-described as
> a drop-in replacement for Flask‘s signed
> cookie-based session management. Instead of storing data on the
> client, only a securely generated ID is stored on the client, while
> the actual session data resid... | Flask - Save session data in database like using cookies | [
"",
"python",
"flask",
""
] |
I have a table with a *varchar* column with data like this:
```
"<tasa>
<parametros>
<parametro>
<nombre>ea</nombre>
<valor>35</valor>
</parametro>
</parametros>
<valorTasa>3.15</valorTasa>
</tasa>"
```
I need to be able to extract the value between the **valorTasa** tags, but don't know how... | More simple way would be using [extractvalue](http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions061.htm#i1131042) function to extract the value of the node.
```
-- sample of data
SQL> with t1(col) as(
2 select '<tasa>
3 <parametros>
4 <parametro>
5 <... | Actually `REGEXP_REPLACE` will work best for this. If you put a part of the search expression in parentheses you can refer to it in the third "replace-with" parameter - the first such expression is `\1`, the second is `\2`, and so on up to `\9` (you can't do more than 9).
For your requirement, try this:
```
SELECT RE... | extracting text from a column using regexp_substr | [
"",
"sql",
"regex",
"oracle",
""
] |
My requirement is to print the output of the file in the console as well as a log file. The following piece of code does it for me , exept for a minor hiccup. I am calling a perl script at the end of the file , whose output is getting displayed in the console , but not getting printed to the file.
```
import subproces... | Use [`subprocess.check_output`](http://docs.python.org/2/library/subprocess.html#subprocess.check_output):
```
print subprocess.check_output(['./MyScript])
```
In Python 2.6, either use the backport [`subprocess32`](http://code.google.com/p/python-subprocess32/), or copy the [2.7 source for `check_output`](http://hg.... | The below code did the trick for me. Thanks everyone for helping.
```
#!/usr/bin/python
import os
import subprocess
import sys
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f = open('MyFile.txt', 'w')
origi... | printing results in stdout file as well as console | [
"",
"python",
"logging",
"printing",
"python-2.6",
""
] |
I already have an existing Database that has a lot of tables and a lot of data in `MySQL`. I intend to create a `Flask` app and use sqlalchemy along with it. Now I asked out on irc and looked around on google and tried the following ideas:
**First** I used [sqlacodegen](https://pypi.python.org/pypi/sqlacodegen) to gen... | I'd say your question has nothing to do with flask at all. For example, you don't have a problem with the templates, routes, views or logon decorators.
Where you struggle at is at SQLAlchemy.
So my suggestion is to ignore Flask for a while and get used to SQLAlchemy first. You need to get used to your existing databa... | The key to connecting Holger's answer to a flask context is that `db.Model` is a `declarative_base` object like `Base`. Took me a while to notice this important sentence in flask-sqlalchemy's [documentation](https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/)
Below are the steps I used for my app:
1. ini... | How to build a flask application around an already existing database? | [
"",
"python",
"mysql",
"sqlalchemy",
"flask",
"flask-sqlalchemy",
""
] |
I have a dictionary, which contains a title and the data. Is there a way to split this data into two lists while keeping the order it was extracted from the dictionary? I have to process the key list and the value list separately, and then I use those lists to build a string.
It's important because I print them out se... | Even though the order you see the pairs in is arbitrary, the output from `keys()` and `values()` *will* always align, assuming you don't modify the dictionary. From the [docs](http://docs.python.org/2/library/stdtypes.html#dict.items):
> If items(), keys(), values(), iteritems(), iterkeys(), and
> itervalues() are cal... | ```
titles = myDict.keys()
allData = [myDict[t] for t in titles]
```
This way, `titles` might be in some unpredictable order, but each element in `allData` will be the data pertaining to the corresponding element in `titles` | A way to guarantee ordering of key/value list from unordered dictionary? | [
"",
"python",
"dictionary",
""
] |
For example:
700 means 700.00 - 700.99
400.1 means 400.10 - 400.19
Currently I have something like this:
```
Select codes
From code_table
where codes in ('700', '400.1')
```
which doesn't work because it's just looking for 700 and 400.1 so I tried:
```
Select codes
From code_table
where left (codes, 3) = '700'
... | If I've understood your comments correctly, you need to build the regular expressions explicitly if you compare against the varchar() values, or use strings with the BETWEEN operator.
So, this . . .
```
select *
from code_table
where codes = '700'
or codes like '700.[1-9]'
or codes like '700.[1-9][0-9]';
```... | You can try something like :
```
select *
from code_table
where codes like '700.__' or codes like '400.1_'
```
Or to be sure to take only numeric values :
```
select *
from code_table
where (codes like '700.__' or codes like '400.1_') and isnumeric(codes) = 1
``` | SQL - Returning a range of numbers 1 to 1.99 | [
"",
"sql",
"sql-server-2008",
""
] |
I have a variable `c`.
```
c = ' FR,DE,UK,IT '
```
I want to cut this variable on another variables: `c1`, `c2`, `c3`, `c4`
So that `c1 = 'FR'`, `c2 = 'DE'`, `c3 = 'UK'`, `c4 = 'IT'`.
How do I do that? | ```
c1, c2, c3, c4 = c.split(',')
```
Note that if, as I suspect, you're hoping for an arbitrary number of dynamic variables to be created depending on the length of the list, you should *not* try to do that. Keep them in a list:
```
c_list = c.split(',')
``` | You can use the [`split`](http://docs.python.org/2/library/stdtypes.html) function of strings:
```
c1, c2, c3, c4 = c.split(',')
``` | I want to cut variable on another variables using Python | [
"",
"python",
"string",
""
] |
I am trying to define a function to make the perimeter of a rectangle. Here is the code:
```
width = input()
height = input()
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
```
I think I haven't left any arguments opened or anything like that. | ```
width, height = map(int, input().split())
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
```
Running it like this produces:
```
% echo "1 2" | test.py
6
```
---
I suspect IDLE is simply passing a single string to your script. The first `input()` is... | Use a `try` / `except` block to get rid of the EOF error.
```
try:
width = input()
height = input()
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
except EOFError as e:
print(end="")
``` | EOFError: EOF when reading a line | [
"",
"python",
"python-3.x",
""
] |
```
/****** Script for SelectTopNRows command from SSMS ******/
DECLARE @user int;
DECLARE @aipNip varchar(20);
DECLARE @accessToBaseCompanies TABLE (baseCompanyId INT);
SET @user = 1;
INSERT INTO @accessToBaseCompanies (baseCompanyId)
((SELECT c.BaseCompanyFk FROM [dbo].Companies c WHERE c.CompaniesTeamFk IN (SELE... | The argument to `IN` is a value list or a subquery, not a table. Try:
```
WHERE bc.[Id] IN (select baseCompanyId from @accessToBaseCompanies)
``` | The problem is this line:
```
WHERE bc.[Id] IN @accessToBaseCompanies
```
It should be:
```
WHERE bc.[Id] IN (select baseCompanyId from @accessToBaseCompanies)
``` | TSQL table variable in WHERE statement causes error | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am fetching data from mysql table it works fine, but it shows `NULL` for `Status` in two fields. I want instead of `NULL` show `0`.
Here is my query:
```
SELECT ml.GroupID, ml.GroupTitle, ml.GroupDescription, ml.GroupCreatedDateTime, ml.GroupOwnerUserID, ml.ApprovalNeeded, ml.GroupStatus, ml.OrganizationCode, cat.S... | use the [COALESCE](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce) operator
```
COALESCE(cat.Status, 0)
SELECT
ml.GroupID,
ml.GroupTitle,
ml.GroupDescription,
ml.GroupCreatedDateTime,
ml.GroupOwnerUserID,
ml.ApprovalNeeded,
ml.GroupStatus,
ml.OrganizationCode,
... | You can try [ifnull()](http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull) function.
like belowing:
select **ifnull**(cat.status,0) as status
FROM GroupsMaster AS ml
LEFT JOIN UserGroupsMapping cat ON cat.GroupID = ml.GroupID
WHERE ml.OrganizationCode = '$organizationCode'"); | How to show 0 instead of NULL while fetching data my sql table | [
"",
"mysql",
"sql",
"null",
""
] |
i am trying to learn python with code academy, and the assignment is to "Write a for loop that populates square\_list with items that are the square (x \*\* 2) of each item in start\_list. Then sort square\_list!"
the hint says to have a for loop, an append function and a sort function, and i believe i am using those ... | There are a couple of things wrong with your code.
```
for start_list in square_list:
square_list.append(start_list**2)
sort(square_list)
```
On the first line you have `for start_list in square_list:`. That's saying "I want to do something in a loop for every `start_list` in `square_list`. The problem is th... | You need to iterate over each elements in `start_list`:
```
for item in start_list: # for each element in `start_list`
square_list.append(item ** 2) # add square of `item` in `square_list`
square_list.sort(); # finally sort the list
```
---
or you can use `sorted()` function over `gen... | when appending a list with math using another list, how do i make the second list the same length as the first ? | [
"",
"python",
"list",
""
] |
I'm having difficulty reading a csv file into the pandas data frame. I am a total newcomer to pandas, and this is preventing me from progressing. I have read the documentation and searched for solutions, but I am unable to proceed. I have tried the following to no avail...
```
import pandas as pd
import numpy as np
pd... | "\r" usually is interpreted as a special character and means carriage return. Either add a 'r' prefix to your string literals which prevents this special sequence from being interpreted (e.g. `path = r"foo\rar"`), or, as already suggested, just use a normal slash as path delimiter. Python is intelligent enough for it t... | Just use a raw string:
```
pd.read_csv(r'C:\Users\rcreedon\Desktop\TEST.csv')
``` | 'CSV does not exist' - Pandas DataFrame | [
"",
"python",
"pandas",
""
] |
I have a GUI where I ask the user to enter some values. When the user submits the data I do some validation:
1. first I check if the user has entered a value for each input
2. then I check if each of the inputted values are integers
Trying not to repeat myself to much I came up with this, but the second part of the v... | Since you're checking for integers, and not floats, you can simply do:
```
if self.start.GetValue().strip().isdigit():
pass
```
`isdigit()` returns `False` for both cases where the input is an empty string, and when the input contains non-digits.
If you want to send specific errors for incorrect assignment:
```... | I think the `try: ... except` is perfectly Pythonic. I would have uses an helper function instead of searching through an error message `get_int_of_name(name, value, error)` which return an int and update error if needed:
```
def get_int_of_name(name, value, error):
try:
res = int(value)
except ValueEr... | More pythonic way of checking if user input exists and consists of integers | [
"",
"python",
"validation",
""
] |
I am new to Python and Pyramid. In a test application I am using to learn more about Pyramid, I want to query a database and create a dictionary based on the results of a sqlalchemy query object and finally send the dictionary to the chameleon template.
So far I have the following code (which works fine), but I wanted... | well, yes, we can tighten this up a bit.
First, this pattern:
```
index = 0
for item in seq:
frobnicate(index, item)
item += 1
```
is common enough that there's a builtin function that does it automatically, `enumerate()`, used like this:
```
for index, item in enumerate(seq):
frobnicate(index, it... | @TokenMacGuy gave a nice and detailed answer to your question. However, I have a feeling you've asked a wrong question :)
You don't need to convert SQLALchemy objects to dictionaries before passing them to the template - that would be quite inconvenient. You can pass the result of a query as is and directly use SQLALc... | Create dictionary of a sqlalchemy query object in Pyramid | [
"",
"python",
"sqlalchemy",
"pyramid",
""
] |
All,
I have a personal script that I'm trying to write, and I've run into a small problem. The problem is that I want to be able to support a '-s' argument no matter where the argument is. I also want that argument to be allowed more than once. For example:
script.py firstargument secondargument -s thirdargument -s f... | See other solution:
```
args = ['firstargument', 'secondargument', '-s', 'thirdargument', '-s', 'fourth', 'fifth', '-s', 'sixth', 'seventh']
args1 = ['firstargument', 'secondargument', '-s', 'thirdargument', '-s', 'fourth', 'fifth', '-s', 'sixth', 'seventh', '-s']
marker = "-s"
def parser(arglist):
scraplist, res... | [argparse](http://docs.python.org/dev/library/argparse.html) is beautiful. Redesign your command line interface for it or write your own CLI-parser. CLI example:
```
args = ['firstargument', 'secondargument', '-s', 'thirdargument', '-s', 'fourth', 'fifth', '-s', 'sixth']
last_arg = None
container = []
marker = '-s'
fo... | Python - Need to get argument on command line | [
"",
"python",
"loops",
"arguments",
""
] |
I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:
```
with open('test.csv', 'wb') as f:
writer = csv.writer(f)
for val in test_list:
writer.writerow([val])
```
If I add another `for` loop, it just writes t... | Change them to rows:
```
rows = zip(list1, list2, list3, list4, list5)
```
Then just:
```
import csv
with open(newfilePath, "w") as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
``` | The following code writes python lists into columns in csv
```
import csv
from itertools import zip_longest
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j']
d = [list1, list2]
export_data = zip_longest(*d, fillvalue = '')
with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
w... | Writing Python lists to columns in csv | [
"",
"python",
"list",
"csv",
""
] |
I have a query that looks like:
```
SELECT 'asdf', '123' ...
FROM table1
LEFT JOIN table2
on
(
condition1
)
LEFT JOIN table3
on
(
condition2
)
where
(
main_condition
)
```
Now the problem is, I need to conditionally include `table1` as well. I tried this:
```
..
..
FROM table1
on
(
new_condition
)... | Thanks for contributing to the discussion. I found the answer. It's really simple:
```
SELECT temp_table.* FROM
(SELECT 'asdf', '123' ... FROM DUAL) temp_table
LEFT JOIN table1
on
(
new_condition
)
LEFT JOIN table2
on
(
condition1
)
LEFT JOIN table3
on
(
condition2
)
where
(
main_condition
)
```... | **Dummy table:**
Select a record from a dummy table first. `dual` is such a table, that is built in in MySQL for this exact purpose. I wrapped `dual` in a subselect, because MySQL apparently doesn't allow left joining against it.
```
SELECT 'asdf', '123' ...
FROM
(select 1 from dual) d
LEFT JOIN table1
on(
new_c... | Mysql - Left Join all tables | [
"",
"mysql",
"sql",
"join",
""
] |
Lets say there is a dictionary
```
foo = {'b': 1, 'c':2, 'a':3 }
```
I want to iterate over this dictionary in the order of the appearance of items in the dictionary.
```
for k,v in foo.items():
print k, v
```
prints
```
a 3
c 2
b 1
```
If we use sorted() function:
```
for k,v in sorted(foo.items()):
p... | Dictionaries have no order. If you want to do that, you need to find some method of sorting in your original list. Or, save the keys in a list in the order they are saved and then access the dictionary using those as keys.
From [The Python Docs](http://docs.python.org/2/tutorial/datastructures.html#dictionaries)
> It... | An [ordered dictionary](http://docs.python.org/2/library/collections.html#collections.OrderedDict) would have to be used to remember the order that they were stored in
```
>>>from collections import OrderedDict
>>>od = OrderedDict()
>>>od['b'] = 1
>>>od['c'] = 2
>>>od['a'] = 3
>>>print od
OrderedDict([('b',1), ('c',2)... | Python Sorted by Index | [
"",
"python",
""
] |
I have a DataFrame named `df` as
```
Order Number Status
1 1668 Undelivered
2 19771 Undelivered
3 100032108 Undelivered
4 2229 Delivered
5 00056 Undelivered
```
I would like to convert the `Status` column to boolean (`True` when Status is Delivered and `False` when Stat... | You can just use `map`:
```
In [7]: df = pd.DataFrame({'Status':['Delivered', 'Delivered', 'Undelivered',
'SomethingElse']})
In [8]: df
Out[8]:
Status
0 Delivered
1 Delivered
2 Undelivered
3 SomethingElse
In [9]: d = {'Delivered': True, 'Undelivered': Fals... | An example of `replace` method to replace values only in the specified column `C2` and get result as `DataFrame` type.
```
import pandas as pd
df = pd.DataFrame({'C1':['X', 'Y', 'X', 'Y'], 'C2':['Y', 'Y', 'X', 'X']})
C1 C2
0 X Y
1 Y Y
2 X X
3 Y X
df.replace({'C2': {'X': True, 'Y': False}})
C1 C2
0 ... | Convert Pandas series containing string to boolean | [
"",
"python",
"pandas",
"boolean",
"type-conversion",
"series",
""
] |
I'm running an animation using matplotlib's `FuncAnimation` to display data (live) from a microprocessor. I'm using buttons to send commands to the processor and would like the color of the button to change after being clicked, but I can't find anything in the `matplotlib.widgets.button` documentation (yet) that achiev... | Just set `button.color`.
E.g.
```
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import itertools
fig, ax = plt.subplots()
button = Button(ax, 'Click me!')
colors = itertools.cycle(['red', 'green', 'blue'])
def change_color(event):
button.color = next(colors)
# If you want the butto... | In current matplotlib version (1.4.2) 'color' and 'hovercolor' are took into account only when mouse '\_motion' event has happened, so the button change color not when you press mouse button, but only when you move mouse afterwards.
Nevertheless, you can change button background manually:
```
import matplotlib.pyplot... | Change matplotlib Button color when pressed | [
"",
"python",
"user-interface",
"animation",
"button",
"matplotlib",
""
] |
How can I rename a column in microsoft sql server managment studio?? I used this code but give me syntax error.
```
alter table sudents rename column old to new;
``` | Use `sp_Rename` function
```
sp_RENAME 'sudents.[OldColumnName]' , '[NewColumnName]', 'COLUMN'
``` | ```
EXEC sp_RENAME 'TableName.FieldName' , 'NewFieldName', 'COLUMN'
``` | Rename a column in microsoft sql server managment studio | [
"",
"sql",
"sql-server",
""
] |
I've given a task of exporting data from an Oracle view to a fixed length text file, however I've been given specification of how data should be exported to a text file. I.e.
```
quantity NUM (10)
price NUM (8,2)
participant_id CHAR (3)
brokerage NUM... | According to the [Oracle docs on types](http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#i16209)
> Optionally, you can also specify a precision (total number of digits)
> and scale (number of digits to the right of the decimal point):
>
> If a precision is not specified, the column stores values as g... | I assume that you mean NUMBER data type by NUM.
When it says NUMBER(8,2), it means that there will be **8 digits**, and that the number should be **rounded to the nearest hundredth**. Which means that there will be 6 digits before, and 2 digits after the decimal point.
Refer to [oracle doc](http://docs.oracle.com/cd/... | Number format in Oracle SQL | [
"",
"sql",
"oracle",
""
] |
**Description:**
I have a database of private messages users. Scheme:

For my task is only interested column `owner_user_id` and `viewer_user_id`.
The result of the query `SELECT owner_user_id, viewer_user_id FROM mail` roughly the:
[Result http://screencloud.ne... | Found a solution!
```
SELECT DISTINCT
LEAST(
`owner_user_id`,
`viewer_user_id`
) AS first_user,
GREATEST(
`owner_user_id`,
`viewer_user_id`
) AS second_user
FROM
`mail`
``` | You can use Jeffs answer (distinct) but need to "order" the tuples in order to unidirect what you call a dialogue.
e.g.
```
SELECT distinct
if(owner_user_id>viewer_user_id,owner_user_id,viewer_user_id),
if(viewer_user_id>owner_user_id,viewer_user_id,owner_user_id)
FROM mail
```
Rgds
R | Build dialogs list from mail database | [
"",
"mysql",
"sql",
""
] |
I have a simple `Employee` model that includes `firstname`, `lastname` and `middlename` fields.
On the admin side and likely elsewhere, I would like to display that as:
```
lastname, firstname middlename
```
To me the logical place to do this is in the model by creating a calculated field as such:
```
from django.d... | Ok... Daniel Roseman's answer seemed like it should have worked. As is always the case, you find what you're looking for *after you post the question*.
From the [Django 1.5 docs](https://docs.djangoproject.com/en/1.5/topics/db/models/#model-methods) I found this example that worked right out of the box. Thanks to all ... | That's not something you do as a field. Even if that syntax worked, it would only give the value when the class was defined, not at the time you access it. You should do this as a method, and you can use the `@property` decorator to make it look like a normal attribute.
```
@property
def name(self):
return ''.join... | How to add a calculated field to a Django model | [
"",
"python",
"django-models",
"django-admin",
""
] |
I need acculate how many days between today and Employee hiredate(but do not care the year). That mearn if one employee hire in 07/1/2012, i want to get a result is today 07/15/2013-07/1/2013, that is 15 days. I do not need the hire year 2012.
i play around with the dateadd and datediff but just did not get the correc... | This is a bit brute force, perhaps, but it seems to work. The idea is to add a number of years to the hiredate, then to check that against the current date. When it is greater, use one fewer years:
```
select (case when DATEADD(year, datediff(year, hiredate, getdate()), hiredate) < GETDATE()
then DATEDIFF... | You could use modulus division:
```
SELECT DATEDIFF(DAY,'20120101',GETDATE())%365
```
The downside is that you're treating leap year the same as every other year, which you could handle with case logic.
In your code:
```
SELECT
Co Employee,
LastName,
FirstName,
DATEDIFF(DAY,HireDate,GETDATE())%3... | Get the correct days in vacation accumulation report | [
"",
"sql",
""
] |
So lately I've been asking a few questions about more professional and pythonic style in Python, and despite being given great answers to my questions, I feel like I need to ask a much broader question.
In general, when writing utility functions (for a library, etc.) that deal more with side effects (file writes, dict... | Don't return something to indicate an error. Throw an exception. Definitely don't catch an exception and turn it into a return code. | When an exception is raised and not caught, [Python will exit with an error (non-zero) code for you](https://stackoverflow.com/a/5456201/691859). If you are defining your own exception types, you should [override `sys.excepthook()`](https://stackoverflow.com/a/16787722/691859) to provide you with the exit codes you des... | Python Return Codes | [
"",
"python",
"styles",
""
] |
```
from cs1graphics import *
from math import sqrt
numLinks = 50
restingLength = 20.0
totalSeparation = 630.0
elasticityConstant = 0.005
gravityConstant = 0.110
epsilon = 0.001
def combine(A,B,C=(0,0)):
return (A[0] + B[0] + C[0], A[1] + B[1] + C[1])
def calcForce(A,B):
dX = (B[0] - A[0])
dY = (B[1]... | `list(chain)` returns a shallow copy of `chain`, it is equivalent to `chain[:]`.
If you want a shallow copy of the list then use `list()`, it also used sometimes to get all the values from an iterator.
Difference between `y = list(x)` and `y = x`:
---
**Shallow copy:**
```
>>> x = [1,2,3]
>>> y = x #this s... | It is true that `list([])` is functionally equivalent to `[]`, both creating a new empty list.
But `x = list(y)` is not the same as `x = y`. The formers makes a shallow copy, and the latter creates a new reference to the existing list.
Note that `list([])` is inefficient -- it creates a new empty list (by doing `[]`)... | Python list([]) and [] | [
"",
"python",
"arrays",
"list",
""
] |
I have a pandas dataframe in the following format:
```
df = pd.DataFrame([
[1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3],
list('AAABBBBABCBDDD'),
[1.1, 1.7, 2.5, 2.6, 3.3, 3.8,4.0,4.2,4.3,4.5,4.6,4.7,4.7,4.8],
['x/y/z','x/y','x/y/z/n','x/u','x','x/u/v','x/y/z','x','x/u/v/b','-','x/y... | Followed by @Andy's answer, you can do following to solve your second question:
```
In [56]: df.groupby(['col5','col2']).size().reset_index().groupby('col2')[[0]].max()
Out[56]:
0
col2
A 3
B 2
C 1
D 3
``` | You are looking for [`size`](http://pandas.pydata.org/pandas-docs/stable/groupby.html#aggregation):
```
In [11]: df.groupby(['col5', 'col2']).size()
Out[11]:
col5 col2
1 A 1
D 3
2 B 2
3 A 3
C 1
4 B 1
5 B 2
6 B 1
dtype: int64
```
---
... | Pandas DataFrame Groupby two columns and get counts | [
"",
"python",
"pandas",
"dataframe",
"group-by",
"pivot-table",
""
] |
I have a pandas dataframe like this:
```
Balance Jan Feb Mar Apr
0 9.724135 0.389376 0.464451 0.229964 0.691504
1 1.114782 0.838406 0.679096 0.185135 0.143883
2 7.613946 0.960876 0.220274 0.788265 0.606402
3 0.144517 0.800086 0.287874 0.223539 0.206002
4 1.332838 0.430... | You could use one of the `is_monotonic` functions from algos:
```
In [10]: months = ['Jan', 'Feb', 'Mar', 'Apr']
In [11]: df.loc[:, months].apply(lambda x: pd.algos.is_monotonic_float64(-x)[0],
axis=1)
Out[11]:
0 False
1 True
2 False
3 True
4 False
dtype: bool
`... | ```
months = ['Jan', 'Feb', 'Mar', 'Apr']
```
Transpose so that we can use the `diff` method (which doesn't take an axis argument).
We fill in the first row (January) with 0. Otherwise it's `NaN`.
```
In [77]: df[months].T.diff().fillna(0) <= 0
Out[77]:
0 1 2 3 4
Jan True True True T... | Pandas dataframe: Check if data is monotonically decreasing | [
"",
"python",
"pandas",
""
] |
I have linux `centos 6.4` server with `mysql5.6`
I have the cron job for making hourly mysql database backups like this
Its in python
```
os.popen("mysqldump -u %s --password=%s -h %s -e --opt --skip-lock-tables --skip-extended-insert -c %s | gzip -c > %s.gz" % (username, password, hostname, database, filename))
``... | One hacky way may be, once you have taken full data base to a file. diff it against the weekly backup and store the patch on disk. When you want to retrieve, just apply diff to the weekly backup and get full db
To store
```
mysqldump -u $USERNAME --password=$PASSWORD -h $HOSTNAME -e --opt --skip-lock-tables --skip... | Since your concern is space rather than speed you could always go for a pattern something like:
Only keep the hourly backup for the last 24 hours.
Keep the midnight backup for each weekday as that days backup.
Weekly - archive backups to offline storage.
A lot of this could almost certainly be mostly automated by some... | How can i create in incremental backups of mysql databases | [
"",
"python",
"mysql",
"linux",
"backup",
""
] |
In the book Programming Collective Intelligence there is a regular expression,
```
splitter = re.compile('\\W*')
```
From context it looks like this matches any non-alphanumeric character. But I am confused because it seems like it matches a backslash, then one or more W's. What does it really match? | Your regex is equivalent to `\W*`. It matches 0 or more non-alphanumeric characters.
Actually, you are using python string literal, instead of raw string. In a python string literal, to match a literal backslash, you need to escape the backslash - `\\`, as a backslash has a special meaning there. And then for regex, y... | The first backslash is there just as an escape character, for programming languages that don't have a good string representation of regular expressions (for example: Java). In Python you can do better, this is equivalent:
```
r'\W*'
```
Notice the `r` at the beginning (a [raw string](http://docs.python.org/2/referenc... | Confused about regular expression | [
"",
"python",
"regex",
""
] |
I have a dataframe in Pandas, I would like to sort its columns (i.e. get a new dataframe, or a view) according to the mean value of its columns (or e.g. by their std value). The documentation talks about [sorting by label or value](http://pandas.pydata.org/pandas-docs/stable/basics.html#sorting-by-index-and-value), but... | You can use the [`mean`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mean.html) DataFrame method and the Series [`sort_values`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_values.html) method:
```
In [11]: df = pd.DataFrame(np.random.randn(4,4), columns=list('ABC... | You can use [assign](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html) to create a variable, use it to sort values and drop it in the same line of code.
```
df = pd.DataFrame(np.random.randn(4,4), columns=list('ABCD'))
df.assign(m=df.mean(axis=1)).sort_values('m').drop('m', axis=1)
`... | Pandas: Sorting columns by their mean value | [
"",
"python",
"pandas",
""
] |
As I learn Python (Specifically Jython, if the difference is important here) I'm writing a simple terminal game that uses skills and dice rolls based on the level of those skills to determine success/fail at an attempted action. I hope to use this code eventually in a larger game project.
Under a stress test, the code... | You're doing 10 million loops. Just the looping costs are probably 10% of your total time. Then, if the whole loop doesn't fit into cache at once, it may slow things down even more.
Is there a way to avoid doing all those loops in Python? Yes, you can do them in Java.
The obvious way to do that is to actually write a... | Well, one thing, use [`xrange`](http://docs.python.org/2/library/functions.html#xrange) instead of [`range`](http://docs.python.org/2/library/functions.html#range). `range` allocates an array with an element for each of the 10 million digits whereas `xrange` creates a generator. That's going to help out memory a bunch,... | Inefficient Random Dice Roll in Python/Jython | [
"",
"python",
"jython",
""
] |
I am trying to open a log file every 15 minutes and see if the file called a 'finalize' string. I know how to check the file for the string but I do not know if there is an easy way to have the script look every 15 minutes.
Is there a module of some sort that will allow me to do this?
**[EDIT]** I want this because I... | The [`sched`](http://docs.python.org/3/library/sched.html) module will let you do this. So will the [`Timer`](http://docs.python.org/2/library/threading.html#timer-objects) class in the `threading` module.
However, either of those is overkill for what you want.
The easy, and generally best, way to do it is to use you... | Take a look at [python-tail](https://github.com/kasun/python-tail) module:
```
import tail
def print_line(txt):
print 'finalize' in txt
t = tail.Tail('/var/log/syslog')
t.register_callback(print_line)
t.follow(s=60*15)
``` | Check a log file every 15 minutes with Python | [
"",
"python",
"time",
"scheduling",
""
] |
I'm creating this program and one of its functions is to output a list that is initialized in the constructor. But, what's happening is that it is outputting the memory location in hexadecimal or something and I don't know why.
I have two classes and a run class:
```
class Person :
def __init__(self, name, ID, age, l... | First, you're sending the bus as the person in the add2bus method.
```
def add2bus(self, Bus):
if Person.get_route(self) == Bus.get_route() :
Bus.get_on(Bus)
else :
print("not compatible")
```
So this will take C2C as the bus object, and then call C2C.get\_on(C2C)
Instead you... | When you use the `print()` function (or statement, pre 3.0), python asks the objecs you are printing to convert themselves to strings; via the `__str__` function. Since `object` defines this method for you, it always works; but the predefined version is not very helpful (in the way you are seeing).
Provide your own. I... | How to NOT print out the memory location python | [
"",
"python",
""
] |
I have some code which tots up a set of selected values. I would like to define an empty set and add to it, but `{}` keeps turning into a dictionary. I have found if I populate the set with a dummy value I can use it, but it's not very elegant. Can someone tell me the proper way to do this? Thanks.
```
inversIndex = {... | You can just construct a set:
```
>>> s = set()
```
will do the job. | The "proper" way to do it:
```
myset = set()
```
The `{...}` notation cannot be used to initialize an empty set | Creating an empty set | [
"",
"python",
""
] |
I have wrote a list in to a file, how can i get it back as old array list.
list looks like this
> ['82294', 'ABDUL', 'NAVAS', 'B', 'M', 'MSCS', 'CUKE', '30',
> 'Kasargod', 'CU', 'Kerala', 'Online', 'PG-QS-12', '15', 'June,',
> '2013', '12.00', 'Noon', '-', '02.00', 'PM\n', '29']
>
> ['82262', 'ABDUL', 'SHAFWAN', 'T',... | You can read the file line by line. For each line you can then eval it, or use json.loads to unpack it. | Why couldn't you just do it by hand ? You'll need to either be sure of the safety of the string or adapt the list comprehension to your needs.
```
foo = "['4','8','15','16','23','42']"
bar = [token.strip("'") for token in foo[1:-1].split(',')]
``` | Get array list from file | [
"",
"python",
"python-2.7",
""
] |
I have been beating my head against a wall over this problem. I create a list and make 4 copies, only one of which shares the same memory index. If I change the original list, is somehow changes 3 of those copies as well, 2 of which have a different memory index. Only if I make a list using the same command as the orig... | That's because you are just creating a shallow copy. You need to create a deep copy instead.
As per [copy](http://docs.python.org/2/library/copy.html) module doc:
> * A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in
> the original.
... | Your list is a list of [*names*](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables), not a list of lists as you are thinking of it. When you make a copy of the list using any of the methods you list (slicing, creating a new list based on the old one, etc) you make a ne... | Changing a value in one list changes the values in another list with a different memory ID | [
"",
"python",
"python-2.7",
""
] |
I'm wondering if there is a simpler, memory efficient way to select a subset of rows and columns from a pandas DataFrame.
For instance, given this dataframe:
```
df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
print df
a b c d e
0 0.945686 0.000710 0.909158 ... | `.loc` accept row and column selectors simultaneously (as do `.ix/.iloc` FYI)
This is done in a single pass as well.
```
In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
In [2]: df
Out[2]:
a b c d e
0 0.669701 0.780497 0.955690 0.451573 0.232194
1 0... | Use its value directly:
```
In [79]: df[df.c > 0.5][['b', 'e']].values
Out[79]:
array([[ 0.98836259, 0.82403141],
[ 0.337358 , 0.02054435],
[ 0.29271728, 0.37813099],
[ 0.70033513, 0.69919695]])
``` | How to convert a pandas DataFrame subset of columns AND rows into a numpy array? | [
"",
"python",
"arrays",
"numpy",
"pandas",
"scikit-learn",
""
] |
I've installed python and some other packages using web platform installer, but I was having some issues getting a Django project to work so I uninstalled everything and am trying to get it going from scratch. Web Platform Installer still shows that I have 'Windows Azure SDK for Python" and "Python 2.7 (32-bit)" instal... | I found a PowerShell script in the WPI directory that checked for python installs and I had to delete the registry keys specified in it.
---
Let me add some context:
Open the below path,
```
%LOCALAPPDATA%\Microsoft\Web Platform Installer\installers\PythonDetectInstalls
```
in the sub-folder of the above path, the... | For what it's worth, I just deleted the folder containing the installed PHP versions(5.3,5.4,5.5), which for me was \Program Files (x86)\IIS Express\PHP. Also, I removed "\Program Files (x86)\iis express\php\5.3" from the search path.
When I return to the web installer the 'Add' buttons are enabled.
I opened the opti... | How do I uninstall python from web platform installer? | [
"",
"python",
"web-platform-installer",
""
] |
I'm trying to install PyQt5 on my Ubuntu 12.04 box. So after downloading it from [here](http://www.riverbankcomputing.co.uk/software/pyqt/download5) I untarred it, ran `python configure.py` and `make`. Make however, results in the following:
```
cd qpy/ && ( test -f Makefile || /opt/qt5/bin/qmake /home/kram/Downloads/... | The problem is that the include path for all python headers in every Makefile will be pointing to `/usr/local/include/python2.7` , which should have been `/usr/include/python2.7`
There are 2 possible solutions for this. Either you can change all the occurrence of this in every Makefile or else you can create a symlink... | ```
sudo apt-get install python-dev
```
Your missing the python header files. | Fatal error while compiling PyQt5: Python.h does not exist | [
"",
"python",
"qt",
"installation",
"pyqt",
"qt5",
""
] |
A variable is set. Another variable is set to the first. The first changes value. The second does not. This has been the nature of programming since the dawn of time.
```
>>> a = 1
>>> b = a
>>> b = b - 1
>>> b
0
>>> a
1
```
I then extend this to Python lists. A list is declared and appended. Another list is declared... | Variable binding in Python works this way: you assign an object to a variable.
```
a = 4
b = a
```
Both point to `4`.
```
b = 9
```
Now `b` points to somewhere else.
Exactly the same happens with lists:
```
a = []
b = a
b = [9]
```
Now, `b` has a new value, while `a` has the old one.
Till now, everything is cle... | Python variables are actually **not** variables but **references** to objects (similar to pointers in C). There is a very good explanation of that for beginners in <http://foobarnbaz.com/2012/07/08/understanding-python-variables/>
One way to convince yourself about this is to try this:
```
a=[1,2,3]
b=a
id(a)
6861732... | Why are lists linked in Python in a persistent way? | [
"",
"python",
"list",
"immutability",
""
] |
When I try to receive larger amounts of data it gets cut off and I have to press enter to get the rest of the data. At first I was able to increase it a little bit but it still won't receive all of it. As you can see I have increased the buffer on the conn.recv() but it still doesn't get all of the data. It cuts it off... | TCP/IP is a *stream-based* protocol, not a *message-based* protocol. There's no guarantee that every `send()` call by one peer results in a single `recv()` call by the other peer receiving the exact data sent—it might receive the data piece-meal, split across multiple `recv()` calls, due to packet fragmentation.
You n... | You can use it as: `data = recvall(sock)`
```
def recvall(sock):
BUFF_SIZE = 4096 # 4 KiB
data = b''
while True:
part = sock.recv(BUFF_SIZE)
data += part
if len(part) < BUFF_SIZE:
# either 0 or end of data
break
return data
``` | Python Socket Receive Large Amount of Data | [
"",
"python",
"sockets",
""
] |
I want to create a table with a subset of records from a master table.
for example, I have:
```
id name code ref
1 peter 73 2.5
2 carl 84 3.6
3 jack 73 1.1
```
I want to store peter and carl but not jack because has same peter's code.
I need the max ref!
I try this:
```
SELECT id, name, DIST... | You can use window functions for this:
```
select t.id, t.name, t.code, t.ref
from (select t.*,
row_number() over (partition by code order by ref desc) as seqnum
from old_tab t
) t
where seqnum = 1;
```
The insert statement just wraps `insert` around this:
```
insert into new_tab(id, name, co... | You can try a sub-query like this:
```
SELECT ot.* FROM old_tab ot
JOIN
(
SELECT "code", MAX("ref") AS "MaxRef"
FROM old_tab
GROUP BY "code"
) tbl
ON ot."code" = tbl."code"
AND ot."ref" = tbl."MaxRef"
```
Output:
```
╔════╦═══════╦══════╦═════╗
║ ID ║ NAME ║ CODE ║ REF ║
╠════╬═══════╬══════╬═════╣
║ 1 ║ ... | How to insert many records excluding some in PostgreSQL | [
"",
"sql",
"database",
"postgresql",
"greatest-n-per-group",
""
] |
I have two tables: `customer` and `mailing` :
```
+==========+ +=============+
| customer | | mailing |
+==========+ +=============+
| id | | id |
+----------+ +-------------+
| name | | customer_id |
+----------+ +-------------+
| mailing_id |
+-------------+... | ```
select * from customer where id not in (
select customer_id from mailing where mailing_id = @mailing_id
)
``` | ```
SELECT * FROM customers c
JOIN mailings m
ON c.id = m.id
WHERE NOT EXISTS (
SELECT id
FROM mailings i
WHERE i.id = c.id
GROUP BY i.id
)
``` | SQL statement for join but not in other table | [
"",
"mysql",
"sql",
"select",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.