Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a table that has two cols REC\_NO (INT), and ORDER\_NO (INT). Structured like below
REC\_NO || ORDER\_NO
1 || 1
2 || 2
3 || 3
There can any number of rows in the table what I need to do is rotate the ORDER\_NO so that 1 becomes 3, 2 becomes 1, and 3 becomes 2. I have done this using a hard coded case sta... | Is it that you want to set the value for row 1 to be the # of rows and all the other rows is simply one less than the current value? Seems like a couple of queries would be my suggestion. Update the row with the number - 1 first, and then fix the value for one by taking the count of the order numbers.
Alternatively, y... | If your RDMS supports LAG you could use it like so
```
WITH new_order
AS (SELECT rec_no,
COALESCE(Lag(order_no) OVER ( ORDER BY order_no), --Previous value
Max(order_no) OVER ( ORDER BY order_no DESC)) --Max Value when no previous
NEW_ORDER_NO
... | How to rotate rows in sql | [
"",
"sql",
""
] |
I'm having trouble implementing a simple countdown in python using a carriage return. I have two versions, each with problems.
Print Version:
```
for i in range(10):
print "\rCountdown: %d" % i
time.sleep(1)
```
Problem: The `\r` doesn't do anything because a newline is printed at the end, so it gives the ou... | For solution number 2, you need to flush stdout.
```
for i in range(10):
sys.stdout.write("\rCountdown: %d" % i)
sys.stdout.flush()
time.sleep(1)
print ''
```
Also, just print an empty string since print will append the newline. Or use `print '\n' ,` if you think it is more readable as the trailing comma ... | For solution 1 (the Print Version), including a comma at the end of the print statement will prevent a newline from being printed at the end, as indicated in the [docs](https://docs.python.org/2/reference/simple_stmts.html#print). However, stdout still needs to be flushed as [Brian](https://stackoverflow.com/a/17439198... | Python 2.7 carriage return countdown | [
"",
"python",
"python-2.7",
"carriage-return",
"sys",
""
] |
I'm trying to execute a bunch of code only if the string I'm searching contains a comma.
Here's an example set of rows that I would need to parse (name is a column header for this tab-delimited file and the column (annoyingly) contains the name, degree, and area of practice:
```
name
Sam ... | The easiest way in python to see if a string contains a character is to use `in`. For example:
```
if ',' in s['name']:
``` | ```
if re.match(...) is not None :
```
instead of looking for boolean use that. Match returns a MatchObject instance on success, and None on failure. | Execute only if string contains a ','? | [
"",
"python",
"regex",
""
] |
I have a global precipitation data with dimensions (time=410,lat=72,lon=144). I wish to interpolate lat to 180 and lon to 360 (i.e., downscale the data from 2.5 degrees to 1 degree).
In Matlab I used to do:
```
%LAT,LON,XI,YI are old and new meshgridded lat-lons
for t = 1:size(precip,1)
newPrecip(t,:,:)=interp2(L... | I usually use the interpolation routine that comes with [Basemap](http://matplotlib.org/basemap/).
```
import mpl_toolkits.basemap as mp
Zg = mp.interp(dataIN,lonIN,latIN,lonOUT,latOUT,
checkbounds=False, masked=False, order=1)
```
Here, lonIN and latIN are 1D longitude-latitude of the original grid (a... | I would look into `scipy.interpolate`. Looks like [griddata](http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html#multivariate-data-interpolation-griddata) might be what you need. | Python 2d interpolation of 3d array | [
"",
"python",
"2d",
"interpolation",
""
] |
Here is my template section, loading jquery from CDN:
```
<head>
{% load staticfiles %}
<title>My Schedule</title>
<link href="{{ STATIC_URL }}css/bootstrap.min.css" rel="stylesheet">
<script src="{{ STATIC_URL }}js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.6.1.min.... | You need to place the `jquery` js file before all other js files. Something like this (Note the switch in order):
```
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap.min.js"></script>
``` | Shouldn't the cdn be this one
```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"</script>
```
Also, put it before all the js files | jquery not working from cdn with django template | [
"",
"jquery",
"python",
"html",
"django",
"cdn",
""
] |
if i have the following select two count cases:
```
COUNT(CASE WHEN STATUS ='Færdig' THEN 1 END) as completed_callbacks,
COUNT(CASE WHEN SOLVED_SECONDS /60 /60 <= 2 THEN 1 END) as completed_within_2hours
```
and i want to devide the two results with eachother how can i achieve this?
this is my attemt however that ... | You have to create a derived table:
```
SELECT completed_callbacks / completed_within_2hours * 100
FROM (SELECT Count(CASE
WHEN status = 'Færdig' THEN 1
END) AS completed_callbacks,
Count(CASE
WHEN solved_seconds / 60 / 60 <= 2 THEN 1
... | Try this:
```
with x as (
select 'Y' as completed, 'Y' as completed_fast from dual
union all
select 'Y' as completed, 'N' as completed_fast from dual
union all
select 'Y' as completed, 'Y' as completed_fast from dual
union all
select 'N' as completed, 'N' as completed_fast from dual
)
select
sum(case wh... | Oracle SQL dividing two self defined columns | [
"",
"sql",
"oracle",
""
] |
I'm excited to ask my first question here. I've run into some problems with recursion. I am coding with Python.
I am using a dictionary to store previously solved numbers in a mathematical sequence. I then check this dictionary when solving later sequences to make the program run faster. Each key represents solved 'st... | Couldn't you just put it in cache before returning it for each recursive call?
instead of:
```
return 1 + solve(number * formula 1)
```
you'd do:
```
result = 1 + solve(number * formula 1)
cache[number] = result
return result
```
Or are you after something different? | In principle the dictionary.update() method is able to update several values of a dictionary in one shot. But I assume your problem lies in the fact, that you update cache[x] only in the caller, i. e. outside of the recursion. | Update a key by calling a recursive function, updating other keys during same sequence | [
"",
"python",
"if-statement",
"recursion",
"for-loop",
"dictionary",
""
] |
Here is the query I am using:
```
select top 1 'Return To IPACS' as name, 'http://domain:88' as link
union
select name,link
from jrm_intranetlinks l
inner join jrm_intranetpermissions p on l.id = p.linkid
where p.userid = 155
order by case name when 'Home' then 2 when 'Team' then 1 end desc, name
```
Here is the... | How about:
```
select
'Return To IPACS' as name,
'http://domain:88' as link,
1 as sort_me
union all
(select
name,
link,
2 as sort_me
from jrm_intranetlinks l
inner join jrm_intranetpermissions p on l.id = p.linkid
where p.userid = 155 )
order by sort_me
```
I am worried about your ne... | ```
select
'Return To IPACS' as name,
'www.home.com' as link,
3 sortOrder
union all
select
name,
link,
case name
when 'Home' then 2
when 'Team' then 1
end sortOrder
from links l
inner join jrm_intranetpermissions p on l.id = p.linkid
where p.userid = 155
order by sor... | SQL Union problems when using Order By | [
"",
"sql",
"t-sql",
""
] |
I am new to python. I am using Pydev IDE with Eclipse for python programming in my Windows machine. I am using python 3.3 vern and want to connect with MS Sql Server 2008. Could someone suggest how should I connect with MS Sql Server 2008. | [pyodbc](http://code.google.com/p/pyodbc/) supports python3 and can connect to any databas for wich there's an odbc driver, including sql server.
There's also a pure python implementation [pypyodbc](http://code.google.com/p/pypyodbc/) which also should supoort python3.
[adodbapi](https://pypi.python.org/pypi/adodbapi... | I will augment mata's answer with a pypyodbc example.
```
import pypyodbc
connection_string ='Driver={SQL Server Native Client 11.0};Server=<YOURSERVER>;Database=<YOURDATABASE>;Uid=<YOURUSER>;Pwd=<YOURPASSWORD>;'
connection = pypyodbc.connect(connection_string)
SQL = 'SELECT * FROM <YOURTABLE>'
cur = connection.curso... | Connecting python 3.3 to microsoft sql server 2008 | [
"",
"python",
"sql-server-2008",
"python-3.x",
"pydev",
""
] |
I have the following table which contains all the time in and time out of people:
```
CREATE TABLE test (
timecardid INT
, trandate DATE
, employeeid INT
, trantime TIME
, Trantype VARCHAR(1)
, Projcode VARCHAR(3)
)
```
The task is to get all the earliest trantime with trantype A (per... | Perhaps this is what you're looking for:
```
select
t.*
from
test t
where
trantime in (
(select min(trantime) from test t1 where t1.trandate = t.trandate and trantype = 'A'),
(select max(trantime) from test t2 where t2.trandate = t.trandate and trantype = 'Z')
)
```
Changing my ans... | I would use [`ROW_NUMBER`](http://msdn.microsoft.com/en-us/library/ms186734.aspx) to sort out the rows you want to select:
```
;with Ordered as (
select *,
ROW_NUMBER() OVER (PARTITION BY Trandate,employeeid,trantype
ORDER BY trantime ASC) as rnEarly,
ROW_NUMBER() OVER (PARTITION BY Trandate,employee... | SQL First Time In Last Time Out (Transact-SQL..preferrably) | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a SQL Table and I would like to select multiple rows by ID. For example I would like to get the row with IDs 1, 5 and 9 from my table.
I have been doing this with a WHERE IN statement similar to below:
```
SELECT [Id]
FROM [MyTable]
WHERE [Id] IN (1,5,9)
```
However this is quite slow for large numbers of ite... | OK so I got it going really fast by defining a table type and then passing that type directly into the query and joining onto it.
in SQL
```
CREATE TYPE [dbo].[IntTable] AS TABLE(
[value] [int] NULL
)
```
in code
```
DataTable dataTable = new DataTable("mythang");
dataTable.Columns.Add("value", typeof(Int32));
... | I guess if you joined your table with a memory table indexed by a primary key, such as:
```
declare @tbl table (ids int primary key)
```
you could fill this table with the id's you need, and preform an optimized inner join.
The problem could be the time it would take to fill it. I guess you could either have a linke... | Selecting multiple rows by ID, is there a faster way than WHERE IN | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I have a very basic question, which would be a more efficient design, something that involves more joins, or just adding columns to one larger table?
For instance, if we had a table that stored relatives like below:
```
Person | Father | Mother | Cousing | Etc.
________________________________________________
... | It is a much more flexible design to separate out the details of each person from the table relating them together. Typically, this will lead to less data consumption.
You could even go one step further and have three tables: one for people, one for relationship\_types, and one for relationships.
`People` would have ... | Id' go for more "Normality" to increase flexibility and reduce data duplication.
```
PERSON:
ID
First Name
Last Name
Person_Relations
PersonID
RelationID
TypeID
Relation_Type
TypeID
Description
```
This way you could support any relationship (4th cousin mothers side once removed) without change code. | More joins or more columns? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying to select distinct value from a column but return all rows related to the values selected. In psuedo code it will look like this.
```
SELECT *
FROM table
WHERE field is Distinct
```
I googled the question and I've tried using GROUP BY but the query never executes. Thanks for the help.
I am using a Micros... | You could always use a subquery to return the `min(codeid)` for each `codegroup` and join this result to your table:
```
select t1.codeid,
t1.code,
t1.catalogtype,
t1.codegroup,
t1.codetext,
t1.codegrouptext,
t1.codedesc,
t1.state_id
from yourtable t1
inner join
(
select MIN(codeid) cod... | In most databases, you can do:
```
select t.*
from (select t.*
row_number() over (partition by field order by field) as seqnum
from t
) t
where seqnum = 1
``` | Select Distinct value from column and return all rows | [
"",
"sql",
"sql-server",
""
] |
Is there a good way of differentiating between row and column vectors in numpy? If I was to give one a vector, say:
```
from numpy import *
v = array([1,2,3])
```
they wouldn't be able to say weather I mean a row or a column vector. Moreover:
```
>>> array([1,2,3]) == array([1,2,3]).transpose()
array([ True, True, ... | You can make the distinction explicit by adding another dimension to the array.
```
>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a.transpose()
array([1, 2, 3])
>>> a.dot(a.transpose())
14
```
Now force it to be a column vector:
```
>>> a.shape = (3,1)
>>> a
array([[1],
[2],
[3]])
>>> a.transp... | Use double `[]` when writing your vectors.
Then, if you want a row vector:
```
row_vector = array([[1, 2, 3]]) # shape (1, 3)
```
Or if you want a column vector:
```
col_vector = array([[1, 2, 3]]).T # shape (3, 1)
``` | Python: Differentiating between row and column vectors | [
"",
"python",
"arrays",
"numpy",
"vector",
""
] |
I have a table with 5 columns.
I want to update 5th column (NULL by default) based on values in columns 1 to 4. If 1st column is null, Add "c1" to 5th column If 2nd column is null, add "c2" to the 5th column and so on.
Also, if 1st and 2nd columns are null, I want to add "C1, C2" to 5th column and so on.
How can I achi... | I would use this:
```
UPDATE table
SET C5 = ISNULL(REPLACE(C1,C1,''),',C1')
+ISNULL(REPLACE(C2,C2,''),',C2')
+ISNULL(REPLACE(C3,C3,''),',C3')
+ISNULL(REPLACE(C4,C4,''),',C4')
```
etc.
The idea is that you use `REPLACE` to leave you with blank '' or `NULL`, then use `ISNULL` to add the f... | ```
UPDATE tbl
SET fifth = CASE
WHEN first IS NULL AND second IS NULL and third IS NULL and fourth IS NULL THEN "C1, C2, C3, C4"
WHEN .... -- all 15 cases
``` | Update Table/T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
**disclaimer: I'm obviously quite new to decorators**
To create and decorate functions in python is quite simple and straight forward, and this [excellent answer](https://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python#answer-739665) (the one with the most upvotes), gives a v... | What a decorator does with a function is up to it. It can wrap it in another function, add some meta information to its attributes, or even store it in a dictionary.
Here's an example of how you could save multiple functions into a dictionary, which can later be used to look up those functions:
```
function_table = {... | There's no reason a decorator can't do other stuff, in addition to wrapping the function
```
>>> def print_stuff(stuff):
... def decorator(f):
... print stuff
... return f
... return decorator
...
>>> @print_stuff('Hello, world!')
... def my_func():
... pass
...
Hello, world!
```
In this e... | How to call specific function based on parameters to decorator | [
"",
"python",
"design-patterns",
"decorator",
""
] |
I would like to have my tkinter program prompt the user to select the path the want to save the file which will be produced by the program.
My code looks like this. At this stage the program only saves to one file (the one I defined to test the program)
What code would I use to have `'test_write.csv'` changed to any f... | Solution for python3.xxx
```
import tkinter
from tkinter.filedialog import asksaveasfilename
with open(asksaveasfilename(), 'w') as fp:
``` | Use the [tkFileDialog module](http://effbot.org/tkinterbook/tkinter-file-dialogs.htm).
Example:
```
import tkFileDialog
with open(tkFileDialog.asksaveasfilename(), "w") as fp:
...
``` | Python CSV.Writer changing saving path | [
"",
"python",
"csv",
"tkinter",
"save",
"filepath",
""
] |
Please see below to understand what I want:
```
------------------------------
Friend | User
------------------------------
2 | 1
3 | 2
2 | 5
4 | 2
------------------------------
```
When I search for value `2`, I want my search result to return... | ```
SELECT Friend FROM MyTable WHERE User = 2
UNION
SELECT User FROM MyTable WHERE Friend = 2;
``` | ```
select case Friend when 2 then User else Friend end
FROM table
where User = 2
or Friend = 2;
``` | How to retun a value depending on Two column values in SQL server select statement? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I bring a few days working on python coming from Matlab and I have the next doubt:
I had a matlab program with a lot of functions defined at the end of my m-file. Matlab recognizes those functions even if I call them at the beginning and they are defined at the bottom of my code.
Now, with python, I don't know what i... | Another way you can have all the functions is to add a function that does everything you want it to do:
```
def main():
#do stuff
f()
g()
...
```
And add this to the end of the file:
```
if __name__ == '__main__':
main()
```
This will only execute if your file is the main file. If you import you... | You can put all the functions in a functions.py and include it in every document
```
import functions
```
then you can call a function by adding the prefix `functions.` | Best way to put functions python | [
"",
"python",
"function",
""
] |
I am learning Python, and trying to write a tip calculator as a first small project.
I came up with the following code:
```
meal = raw_input("Cost of meal: ")
tax = raw_input("Tax: ")
tip = raw_input("Tip: ")
def tipCalc(meal, tax, tip):
def convertInput(meal, tax, tip):
try:
retMeal = int(m... | You probably mean this:
```
def tipCalc(meal, tax, tip):
def convertInput(meal, tax, tip):
try:
retMeal = int(meal)
retTax = int(tax)
retTip = int(tip)
except ValueError:
retMeal = float(meal)
retTax = float(tax)
retTip = floa... | The other answers have covered the reason for the exception you're getting, so I'm going to skip over that. Instead, I want to point out a subtle mistake that's going to bite you sooner or later and make your code calculate the wrong values if either the tax or the tip are ever entered as whole numbers.
**IMPORTANT**:... | Variable Referenced Before Assignment | [
"",
"python",
""
] |
I'm totally stuck on how to create this select. I need to select from the status table only those `order_id`'s which to not have status 2.
Here is the table:
```
+----+---------+---------+--
| id | order_id| status |
+----+---------+---------+--
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 ... | This is an example of a set-within-sets query:
```
select order_id
from t
group by order_id
having sum(case when status = 2 then 1 else 0 end) = 0
```
The `having` clause counts the number of rows with a status of 2. The `= 0` finds the orders with no matches.
EDIT:
If you want to include orders with status 1 and e... | Here's one way.
```
Select * from TableName
where Order_ID not in (Select order_ID from tableName where status=2)
```
Another way would be to use the not exists clause. | SQL Select records excluding some statuses | [
"",
"sql",
"select",
""
] |
I have a table below.

how to get the count of the column value whose value is 'M' in a particular row?
ex: If i give the condition, where shape\_name='Rectangle' it will return the count of the column whose value is = 'M'. Result: count is 2
If Tr... | A solution with CASE WHEN is like this:
```
SELECT shape_name,
CASE WHEN a = 'm' THEN 1 ELSE 0 END +
CASE WHEN b = 'm' THEN 1 ELSE 0 END +
CASE WHEN c = 'm' THEN 1 ELSE 0 END as mcount
FROM t1
```
[SQLFiddle](http://sqlfiddle.com/#!4/25f8c/9)
Just adjust the SQL to your table structure - you will... | Very old solution - fetch all columns, iterate through all of them, and count occurrences of `M`. | how to get the count of the column value of a particular row? | [
"",
"mysql",
"sql",
"oracle",
""
] |
simple test program of an encoding issue:
```
#!/bin/env python
# -*- coding: utf-8 -*-
print u"Råbjerg" # >>> unicodedata.name(u"å") = 'LATIN SMALL LETTER A WITH RING ABOVE'
```
here is what i get when i use it from a debian command box, i do not understand why using redirect here broke the thing, as i can see ... | When redirecting the output, `sys.stdout` is not connected to a terminal and Python cannot determine the output encoding. When *not* directing the output, Python can detect that `sys.stdout` is a TTY and will use the codec configured for that TTY when printing unicode.
Set the [`PYTHONIOENCODING` environment variable]... | Use: `print u"Råbjerg".encode('utf-8')`
Similar question was asked today : [Understanding Python Unicode and Linux terminal](https://stackoverflow.com/questions/17419126/understanding-python-unicode-and-linux-terminal) | python... encoding issue when using linux > | [
"",
"python",
"encoding",
"utf-8",
""
] |
I am trying to upload file from windows server to a unix server (basically trying to do FTP). I have used the code below
```
#!/usr/bin/python
import ftplib
import os
filename = "MyFile.py"
ftp = ftplib.FTP("xx.xx.xx.xx")
ftp.login("UID", "PSW")
ftp.cwd("/Unix/Folder/where/I/want/to/put/file")
os.chdir(r"\\windows\fol... | If you are trying to store a **non-binary file** (like a text file) try setting it to read mode instead of write mode.
```
ftp.storlines("STOR " + filename, open(filename, 'rb'))
```
for a **binary file** (anything that cannot be opened in a text editor) open your file in read-binary mode
```
ftp.storbinary("STOR " ... | Combined both suggestions. Final answer being
```
#!/usr/bin/python
import ftplib
import os
filename = "MyFile.py"
ftp = ftplib.FTP("xx.xx.xx.xx")
ftp.login("UID", "PSW")
ftp.cwd("/Unix/Folder/where/I/want/to/put/file")
os.chdir(r"\\windows\folder\which\has\file")
myfile = open(filename, 'r')
ftp.storlines('STOR ' + f... | FTP upload files Python | [
"",
"python",
"ftp",
""
] |
I need to copy ref\_id1 from table1 TO the column ref\_id2 in the table2 the two things matching will be : id (same column name), a\_ref1 & b\_ref1 (column names are different but numerical value will be identical).
Table1
```
ID ref_id1 a_ref1
9 2.3456762498; 1367602349
9 ... | ```
UPDATE public.clean_trips_byobu
SET trip_dist = clean_trips.bktp_mt_total
FROM public.clean_trips
WHERE public.clean_trips.obu_id = clean_trips_byobu.obu_id
AND clean_trips.bktp_trip_id = clean_trips_byobu.trip_id;
```
Hope it will work for you. | ```
UPDATE Table2 --format schema.table_name
SET
ref_id2 = table1.ref_id1
FROM table1 -- mention schema name
WHERE table1.id = table2.id
AND
table1.a_ref1 = table2.b_ref1;
``` | How to copy one column of a table into another table's column in PostgreSQL comparing same ID | [
"",
"sql",
"postgresql",
""
] |
I am new to SQL, I know this is really basic but I really do not know how to do it!
I am joining two tables, each tables lets say has 5 columns, joining them will give me 10 columns in total which I really do not want. What I want is to select specific columns from both of the tables so that they only show after the jo... | This is what you need:
```
Select e.EmpName, e.Address, s.Name, S.Address, s.Project
From tbEmployees e
JOIN tbSupervisor s on e.id = SupervisorID
```
You can read about this on [W3Schools](http://www.w3schools.com/sql/default.asp) for more info. | You can get columns from specific tables, either by their full name or using an alias:
```
SELECT E.EmpName, E.Address, S.Name, S.Address, S.Project
FROM tbEmployees E
INNER JOIN tbSupervisor S ON E.ID = S.SupervisorID
``` | Joining two tables with specific columns | [
"",
"sql",
"sql-server-2012",
""
] |
Table Adult:
```
id, Adname
1 , Harry
2 , Sally
3 , Beth
4 , David
```
Table Children:
```
id, Chname , adult_id , DOB(YYYY-MM-DD)
1 , Rebecca , 1 , 5/23/1987
2 , Stanley , 3 , 9/7/2003
3 , Emma , 3 , 3/17/2000
4 , Maria , 4 , 11/8/1995
5 , Michael , 4 , 8/15/1998
6 ... | Although you don't specify an expected output example, I understand that you want to show the adult's name and their child's names:
```
SELECT Adult.Adname, Children.Chname
FROM Adult INNER JOIN Children
ON Children.Adult_Id = Adult.ID
WHERE Adult.ID IN
(SELECT Adult_id
FROM Children
GROUP BY Adult_id
HAVING COUNT (C... | Try
```
SELECT a.*, c.*
FROM Adults a
JOIN (
SELECT AdultId
FROM Children
GROUP BY AdultId
HAVING COUNT(*) >= 2
) n
ON n.AdultId = a.Id
JOIN Children c
ON c.AdultId = n.AdultId
```
[demo](http://sqlfiddle.com/#!6/1078b/1) | SQL Show only rows from both tables when joined PK count is greater than a criteria | [
"",
"sql",
""
] |
I have a Date format in excel like "20.03.2013" i transformed that to "2013-03-20" since this is how the dates look like in my sql-server table. I created a staging table where i gave that field the varchar(15) datatype. now i have to convert that varchar field to a date field but when i check the list of the convert o... | You can just use:
`CAST('2013-03-20' AS DATE)` to convert it to a `DATE` field.
There are a number of formats that will CAST() as DATE without issue, including:
```
20130320
2013-03-20
2013 mar 20
March 20, 2013
2013.03.20
```
I'm sure there's a comprehensive list somewhere, but couldn't find one with a quick searc... | [check here](http://msdn.microsoft.com/en-us/library/ms187928%28v=sql.90%29.aspx)
Syntax for CAST:
```
CAST ( expression AS data_type [ (length ) ])
```
Syntax for CONVERT:
```
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
``` | convert string to yyyy-mm-dd | [
"",
"sql",
"sql-server",
"t-sql",
"sqldatatypes",
""
] |
I have a table that contains text field with placeholders. Something like this:
```
Row Notes
1. This is some notes ##placeholder130## this ##myPlaceholder##, #oneMore#. End.
2. Second row...just a ##test#.
```
*(This table contains about 1-5k rows on average. Average number of placeholders in one row is 5-15).*
... | I second the comment that tsql is just not suited for this operation, but if you must do it in the db here is an example using a function to manage the multiple replace statements.
Since you have a relatively small number of tokens in each note (5-15) and a very large number of tokens (10k-100k) my function first extr... | You could try to split the string using a numbers table and rebuild it with `for xml path`.
```
select (
select coalesce(L.Value, T.Value)
from Numbers as N
cross apply (select substring(Notes.notes, N.Number, charindex('##', Notes.notes + '##', N.Number) - N.Number)) as T(Value)
left o... | replace value in varchar(max) field with join | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I keep getting this error everytime I try running my code through proxy. I have gone through every single link available on how to get my code running behind proxy and am simply unable to get this done.
```
import twython
import requests
TWITTER_APP_KEY = 'key' #supply the appropriate value
TWITTER_APP_KEY_SECRET = 'k... | Your code isn't using your proxy. The example shows, you specified a proxy for plain `HTTP` but your stackstrace shows a `HTTPSConnectionPool`. Your local machine probably can't resolve external domains.
Try setting your proxy like this:
```
client_args = {'proxies': {'https': 'http://proxy.company.com:10080'}}
``` | In combination with @t-8ch's answer (which is that you must use a proxy as he has defined it), you should also realize that as of this moment, requests (the underlying library of Twython) does not support proxying over HTTPS. This is a problem with requests underlying library urllib3. It's a long running issue as far a... | Proxy using Twython | [
"",
"python",
"proxy",
"python-requests",
"twython",
""
] |
i am trying to do some string search with regular expressions, where i need to print the [a-z,A-Z,\_] only if they end with " " space, but i am having some trouble if i have underscore at the end then it doesn't wait for the space and executes the command.
```
if re.search(r".*\s\D+\s", string):
print string
```
... | You're using `search` and this function, as the name says, search in your string if the pattern appear and that's the case in your two strings.
You should add a `$` to your regular expression to search for the end of string:
```
if re.search(r".*\s\D+\s$", string):
print string
``` | You need to anchor the RE at the end of the string with `$`:
```
if re.search(r".*\s\D+\s$", string):
print string
``` | python regex issue with underscore | [
"",
"python",
"regex",
""
] |
I am running a bash script (test.sh) and it loads in environment variables (from env.sh). That works fine, but I am trying to see python can just load in the variables already in the bash script.
Yes I know it would probably be easier to just pass in the specific variables I need as arguments, but I was curious if it ... | You need to export the variables in bash, or they will be local to bash:
```
export test1
```
Then, in python
```
import os
print os.environ["test1"]
``` | There's another way using `subprocess` that does not depend on setting the environment. With a little more code, though.
For a shell script that looks like follows:
```
#!/bin/sh
myvar="here is my variable in the shell script"
function print_myvar() {
echo $myvar
}
```
You can retrieve the value of the variable... | Read Bash variables into a Python script | [
"",
"python",
"bash",
"scripting",
"environment-variables",
""
] |
I'm trying to do something like this:
```
select ('hi' in ('hi')) as hi
```
It's not working due to bad syntax at the "in" portion.
Is it possible to return the boolean result of a subquery with an IN clause? | Try a CASE, e.g.
```
select
case
when 'hi' in ('hi') then 1 else 0
end as hi
``` | You can use a conditional expression using `CASE`:
```
select
case when 'hi' in ('hi') then 1 else 0 end
```
[Here is a demo on sqlfiddle](http://www.sqlfiddle.com/#!3/d41d8/16579). | Is it possible to return the results of a select statement with an IN clause? | [
"",
"sql",
"t-sql",
""
] |
I try to run an sql query (mssql 2005) like the following:
```
select top 20 d_date, date1, date2
from reestr_calculated
where reestr_id=2
group by date2
order by date2 desc
```
and I get the following error:
> Column 'reestr\_calculated.d\_date' is invalid in the select list because it is not contained in eithe... | When you use `GROUP BY`, multiple rows get "collapsed" to one row. To determine which of those rows in a group should be displayed, you have to use an aggregate function.
Like `MIN()` or `SUM()` or others.
Like this:
```
select top 20 MIN(d_date), MAX(date1), date2
from reestr_calculated
where reestr_id=2
group b... | All the column names present in `SELECT` must be present in `GROUP BY` unless you are using aggregate functions. Hence, add date1 also in group by. | got error in sql query with group by | [
"",
"sql",
"sql-server",
"sql-server-2005",
"group-by",
""
] |
I keep receiving a syntax error on this particular statement.
```
SELECT tbl1.ProjectID, tbl1.EntryDate AS StartDate, tbl2.EntryDate AS EndDate,
(tbl3.ChecklistDayMax - tbl3.ChecklistDayMin + 1) AS DaysAllotted,
(SELECT ProjectPriority FROM project_master WHERE ProjectID = tbl1.ProjectID) AS Priority,
tbl3.Milestone... | [Expanded from comments.] This is just a hunch, as I don't have access to Access (ha ha), but your query currently specifies an `INNER JOIN` that doesn't actually relate the table to the rest of the query:
```
...
INNER JOIN milestone_def AS tbl3
ON [@milestoneID] = milestone_def.MilestoneDefID
...
```
The `ON` clau... | Since the problem is with the joins, you would be wise to investigate the issue with a simpler query.
```
SELECT *
FROM
((checklist_entries AS tbl1
INNER JOIN checklist_entries AS tbl2
ON tbl1.ProjectID = tbl2.ProjectID)
INNER JOIN milestone_def AS tbl3
ON [@milestoneID] = milestone_def.MilestoneDe... | Issue with access inner join | [
"",
"sql",
"ms-access",
""
] |
I am working on MSSQL, trying to split one **string** column into multiple columns. The string column has numbers separated by semicolons, like:
```
190230943204;190234443204;
```
However, some rows have more numbers than others, so in the database you can have
```
190230943204;190234443204;
121340944534;34021234320... | Splitting this data into separate columns is a very good start (coma-separated values are an heresy). However, a "variable number of properties" should typically be modeled as a [one-to-many relationship](http://en.wikipedia.org/wiki/Cardinality_%28data_modeling%29).
```
CREATE TABLE main_entity (
id INT PRIMARY KEY... | If these are all fixed length strings (as in the question), then you can do the work fairly simply (at least relative to other solutions):
```
select substring(col, 1+13*(n-1), 12) as val
from t join
(select 1 as n union all select union all select 3
) n
on len(t.col) <= 13*n.n
```
This is a useful hac... | SQL How to Split One Column into Multiple Variable Columns | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I'd like to construct an absolute path in python, while at the same time staying fairly oblivious of things like path-separator.
**edit0:** for instance there is a directory on the root of my filesystem `/etc/init.d` (or `C:\etc\init.d` on w32), and I want to construct this only from the elements `etc` and `init.d` (o... | so the solution i came up with, is to construct the root of the filesystem by following a given file to it's root:
```
def getRoot(file=None):
if file is None:
file='.'
me=os.path.abspath(file)
drive,path=os.path.splitdrive(me)
while 1:
path,folder=os.path.split(path)
if not folder:
break
... | Using `os.sep` as root worked for me:
```
path.join(os.sep, 'python', 'bin')
```
Linux: `/python/bin`
Windows: `\python\bin`
Adding `path.abspath()` to the mix will give you drive letters on Windows as well and is still compatible with Linux:
```
path.abspath(path.join(os.sep, 'python', 'bin'))
```
Linux: `/pytho... | constructing absolute path with os.path.join() | [
"",
"python",
"path",
"absolute-path",
""
] |
I often run long-running cells in my IPython notebook. I'd like the notebook to automatically beep or play a sound when the cell is finished executing. Is there some way to do this in iPython notebook, or maybe some command I can put at the end of a cell that will automatically play a sound?
I'm using Chrome if that m... | ## TL;DR
At the top of your notebook
```
from IPython.display import Audio
sound_file = './sound/beep.wav'
```
`sound_file` should point to a file on your computer, or accessible from the internet.
Then later, at the end of the long-running cell
```
<code that takes a long time>
Audio(sound_file, autoplay=True)
`... | My favorite solution (no need for an external module) :
```
import os
os.system("printf '\a'") # or '\7'
```
Works on OS X.
However DaveP's remark still apply : it is not the browser playing the sound but the server. | Automatically play sound in IPython notebook | [
"",
"python",
"ipython",
"jupyter-notebook",
""
] |
I newbie in python and I'm trying to extract a value from string but it doesn't work.
my string is something like:
```
<a href="/profile/view?id=34232962&goback=%2Enmp_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1&trk=spm_pic" title="View your profile">
```
My attempt is:
```
m = re.search('^.*\b(view|your|profile)\b.*$', newp... | Ah? You want to crawl LinkedIn private pages? ;)
Something like that should work:
```
m = re.search('href="(/profile/[^"]+)"', newp, re.IGNORECASE)
```
But, as usual, **don't use regular expressions to parse HTML**. | Regex is horrible for parsing HTML as you have found out. Use a tool built for the job. In the case of python, use BeautifulSoup.
```
soup = BeautifulSoup(html_doc)
profile_a = soup.find(title="View your profile")
link = profile_a['href']
print link
>> /profile/view?id=34232962&goback=%2Enmp_*1_*1_*1_*1_*1_*1_*1_*1_... | Regular Expression in python, a particular case | [
"",
"python",
"regex",
""
] |
I have developed sites with php in the past and I have now deiced to learn ASP.NET MVC since I find my self coding a lot of c# for desktop applications.
The problem that I have is that I'm use to establishing the connection to the SQL server via functions and custom SQL commands. From what I understand your not suppos... | ASP.NET MVC is entirely independent of database access of any kind; you can pick whatever you want to use. A lot of tutorials will use Entity Framework, though, mostly because it's new and it's easy to use.
Entity Framework simplifies your data access somewhat by mapping your SQL tables to standard C# classes. If you ... | You understand incorrectly. MVC has no database support whatsoever. You can use any database technology you want, and MVC has nothing to say about it.
Yes, it's true that most samples and demos use Entity Framework, but that's because EF makes it trivial to do database access in seconds, without writing a bunch of boi... | ASP.NET MVC Database Usage | [
"",
"sql",
"asp.net-mvc",
"database",
"asp.net-mvc-4",
""
] |
i want to implement the following in python,
in C, it is like below, there is a structure
```
struct xyz {
char name[50];
char type[50];
char link[50];
char level[50];
}XYZ;
```
And i have created an array of this struct xyz as following:
```
XYZ array[] =
{ {"Mac", "char", "list","one"},
{"John", "char", "list",... | Your syntax is a bit off.
This will create an array of arrays of 4 values:
```
XYZ = [
["Mac", "char", "list","one"],
["John", "char", "list","three"],
...
...
]
```
This will create an array of objects with 4 fields:
```
XYZ = [
{"name": "Mac", "type": "char", "link": "list", "level": "one"},... | ```
import csv
with open('somefile.txt') as f:
reader = csv.reader(f, delimiter=',')
lines = list(reader)
print(lines)
``` | Implementing array of structures( similar to C) in python by reading data from a file | [
"",
"python",
""
] |
In my little project here I have sorted a list in decending order, however, my goal is to sort it in this custom pattern. (largest -> smallest -> next largest -> next smallest ->)etc.
In java I was able to do this like this:
```
public static void wackySort(int[] nums) {
//first, this simply sorts the array by as... | ```
nums = [1, 2, 3, 4]
newarray = sum(zip(reversed(nums), nums), ())[:len(nums)]
>>> print(newarray)
(4, 1, 3, 2)
```
---
What it does, step by step. first, [reversed()](http://docs.python.org/2/library/functions.html#reversed):
```
>>> list(reversed(nums))
[4, 3, 2, 1]
```
Then [zip()](http://docs.python.org/2/l... | I would suggest sorting it normally first, then doing your shuffle:
```
inlist=[3,5,7,6,9,8,2,1]
inlist.sort()
outlist=[]
while len(inlist)>0:
if (len(outlist)%2==0):
outlist.append(inlist.pop())
else:
outlist.append(inlist.pop(0))
``` | Python: Alternating elements of a sorted array | [
"",
"python",
""
] |
the query below returns a list of data I need. I need to make it so that it returns codes that start with 198 **and** 190. I tried simply adding: 'AND ATCOCode STARTS WITH 190' but that simply resulted in no returned data. Currently it returns all data starting with 198 with no problem.
Thanks
<https://www.googleapis... | Fusion Tables SQL doesn't support OR, so those suggestions aren't going to help. The best you can do is get values starting with 19 and the postprocess the result, at least if it's a string value. If it's a number you can get the same effect by getting values >= 190 and <= 198. | ```
SELECT * FROM YOUR_TABLE_NAME WHERE COLUMN_NAME LIKE '198%' OR COLUMN_NAME LIKE '190%'
``` | How to query data where value starts with two possibilities (198 or 190)? | [
"",
"sql",
"http",
"google-maps-api-3",
"google-fusion-tables",
""
] |
I have table that one of the fields needs to be cleaned up. The basic table structure is as follows:
```
create table testComments(id int, comments text)
```
In the comments column some of the rows had to many "carriage returns" (char(13)) and "line feed" (char(10)). If there is more then one grouping per line I need... | Using the code you gave us, your query should work properly. So the details appear to be different, and I suspect that GolezTrol's comment is on the right track -- some of the CRLF pairs are really just solo CR or LF characters.
Try this:
```
select count(id)
from #testComments
where comments like('%' + char(13)... | *The query will only return a count of 1 entry for the above data. Any idea how I can change the query to return a count of 2?*
I think you're misunderstanding something basic.
The COUNT-Function returns the count of all returned rows. In your example it is still returning **one** row.
So no matter if you have this:
... | Search for ASCII values in sql server table | [
"",
"sql",
"sql-server",
""
] |
I have a list in Python that contains strings:
```
["foo/bar","foo/bar/baz","foo/bar/qux"]
```
I'm trying to separate out the smallest elements in that list that are not contained in any other longer elements. In this case, I want to return a list `["foo/bar/baz","foo/bar/qux"]` as they are not contained in any longe... | Assuming you're really looking for leaf directories (i.e., "contained in" really means "prefixed by" and slashes *are* special), here's a simple algorithm:
```
def leaf_dirs(dirlist):
"""Given a list of directories, find leaf directories"""
parents = {}
for path in dirlist:
parts = path.split('/')
... | I would sort the list first (in this case, it is already sorted though), and then just compare each string to the next string:
Using List Comprehension:
```
l = ["foo/bar/baz/abc", "fo/bar","foo/bar/baz","foo/bar/qux", "foo/bar/qux/abc"]
l.sort()
length = len(l)
new_list = [v for (i, v) in enumerate(l) if (index < ... | finding smallest unique element in a list | [
"",
"python",
"list",
""
] |
I use the code portion below
```
num_item = 3
for i in range(1,num_item+1):
list(itertools.combinations(range(0,num_item), i))
```
to generate a list of combinations
```
[[(0,), (1,), (2,)], [(0, 1), (0, 2), (1, 2)], [(0, 1, 2)]]
```
I'd like to make these combinations as key for two values: kvalue and kweight, ... | > Is there any good data structure to store the data above?
[`collections.namedtuple`](http://docs.python.org/2/library/collections.html#collections.namedtuple)
> How can I convert (0,) into a key (of string) ?
You don't actually need to. Since `(0,)` is a tuple and tuples are hashable, it can be used as a key direc... | You can either use a nested dict or create a value object.
```
{0:{'value':1, 'kvalue':8, 'kweight':4}}
```
or
```
class Value:
def __init__(self, value, kvalue, kweight):
self.value = value
self.kvalue = kvalue
self.kweight = kweight
{0:Value(1,8,4)}
``` | Python store lists with single key and two values | [
"",
"python",
"python-2.7",
""
] |
I have `[program:A]`, `[program:B]` in my supervisord.conf
`B` depend `A`, means:
`A` should start before `B`.
How to ensure this by supervisor? | `supervisord` does not directly support dependencies. Your options instead are:
* Use priorities. Set `priority` for `A` to a low value and it'll be started before `B`, and shut down after `B`. The default value for `priority` is `999`.
If you put the two programs into one group as well, that'd let you start and st... | If you want to take a shortcut, and skip reading the documentation about [event listeners](http://supervisord.org/events.html) and skip modifying your programs so they understand events, then:
Instead of starting program `B` (which depends on `A`) directly, you could start a Bash script that sleeps until `A` has been ... | python supervisord program dependency | [
"",
"python",
"supervisord",
""
] |
I want to find the date of Monday of current week
```
declare @td datetime
set @td = CONVERT(datetime,'28-07-2013',105)
print @td
declare @dt datetime
set @dt = (SELECT DATEADD(wk, DATEDIFF(wk,0,@td), 0) MondayOfCurrentWeek)
print @dt
```
This is giving me correct result , only if i have giv the sunday date , its gi... | I would, instead, use the following construct:
```
set @dt = DATEADD(day,
-(DATEPART(weekday,@td) - DATEPART(weekday,'20130729') + 7) % 7
,@td)
```
This should always work out the correct offset to subtract from a particular date to get to the previous monday - and it *doesn't* depend on what `DATEFIRST` sett... | I prefer using a calendar table for queries like this. On my local system . . .
```
select max(cal_date)
from calendar
where cal_date <= '2013-07-28'
and day_of_week = 'Mon'
```
The greatest benefit of calendar tables, in my opinion, is that queries can be seen to be obviously correct. | set default start day as monday in sql server | [
"",
"sql",
"sql-server",
"date",
""
] |
I have created 2 distinct data source connections (to MS SQL Server 2008) in the ColdFusion Administrator that have exactly the same settings except for the actual name of the connection. My question is will this create two distinct connection pools or will they share one? | They will have different pools. The pools are defined at the data source level and you have two distinct data sources as far as ColdFusion is concerned. Why would you have two different data sources with the exact same settings? I guess if you wanted to force them to use different connection pools. I can't think of a r... | They have different pools. Pooling is implemented by cf java code. (Or was that part in the jrun code.... ). It doesn't use any jdbc based pooling. Cf10 could have switched to jdbc based pooling but I doubt it.
As a test
Set the 'verify connection' sql to wait-for delay '00:01:00' or similar (wait for 1 minute) on bo... | If you have two distinct Data Source Connections in ColdFusion with the same settings do they share the same pool? | [
"",
"sql",
"sql-server",
"jdbc",
"coldfusion",
"coldfusion-9",
""
] |
So, I've seen a few solutions for this problem or similar problems, but I really want to know *why* mine isn't working. It is much easier to read than a lot of solutions I've found, so I'd love to make it work!
Starting with 1 pair of rabbits, which will begin to reproduce after 2 months. Run for n months, where rabbi... | This is copied from the answer in SpaceCadets question to help rbump it out of the "unanswered" list of questions.
---
The two keys here were drawing out the tree to a large number, AND making sure to include a base case check for the first and second generations of deaths (It's -1 in both cases, and then it's someth... | Using recursion.
```
public static int fibRec(int months, int dieAfter) {
if(months <= 0) return 0;
if(months == 1) return 1;
if(months <= dieAfter)
return fibRec(months-1, dieAfter) + fibRec(months-2, dieAfter);
else if (months == dieAfter+1)
return fibRec(months-1, dieAfter) + fibRec(... | Fibonacci Rabbits Dying After Arbitrary # of Months | [
"",
"python",
"fibonacci",
"rosalind",
""
] |
**My Text File MyText.txt**
```
This is line 1
This is line 2
Time Taken for writing this# 0 days 0 hrs 1 min 5 sec
Nothing Important
Sample Text
```
**Objective**
To read the text file and find if "Sample Test is present in the file. If present print the time taken to write the file(which is a value already i... | This should work..
```
with open('MyText.txt', 'r') as f:
lineArr=f.read().split('\n')
if 'Sample Text' in lineArr:
timeTaken = [s for s in lineArr if "Time Taken" in s]
print timeTaken[0]
``` | ```
f = open('sample', 'r') # open file in read mode
data = f.read() # copy to a string
f.close() # close the file
print data # print the data
``` | Text File Reading and Printing Data | [
"",
"python",
"file",
"python-2.7",
""
] |
So I am trying to write my own scripts that will take in html files and return errors as well as clean them (doing this to learn regex and because I find it useful)
I am starting by having a quick function that takes the document, and grabs all of the tags in the correct order so I can check to make sure that they are... | Although you really [shouldn't be parsing HTML with regex](https://stackoverflow.com/a/1732454/1971805), I understand that this is a learning exercise.
You only need to add one more character:
```
>>> re.findall('(?m)<.*?>',s) # See the ? after .*
['<a>', '</a>', '<div id="something">', '<p style="background-color:#f... | ```
re.findall('(?m)<.*?>',s)
```
-- or --
```
re.findall('(?m)<[^>]*>',s)
```
The question mark after the `*` causes it to be a **non-greedy match**, meaning that it only takes as much as it needs, as opposed to normal, where it takes as much as possible.
The second form is used more often, and it uses a character... | file cleaner using regex | [
"",
"python",
"html",
"regex",
""
] |
I am trying to replace the element inside of bbox with a new set of coordinates.
my code :
```
# import element tree
import xml.etree.ElementTree as ET
#import xml file
tree = ET.parse('C:/highway.xml')
root = tree.getroot()
#replace bounding box with new coordinates
elem = tree.finda... | The [`findall`](http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findall) function, as the name implies, finds *all* matching elements, not just one.
So, after this:
```
elem = tree.findall('bbox')
```
`elem` is a list of `Element`s. And, as with any other list, this:
```
el... | If your file isn't update it is most likely because you are not saving it, you can use the [`tree.write`](http://docs.python.org/2/library/xml.etree.elementtree.html#modifying-an-xml-file) method to do just that.
```
tree.write('output.xml')
``` | Replacing XML element in Python | [
"",
"python",
"xml",
"elementtree",
""
] |
I have a table with a column containing an integer which when converted to binary represents a permutation of interests. For example:
```
John, Smith, 6
David, Jones, 512
Mark, Clark, 2
```
Let's say our `Interests` table looks something like:
```
1, TV
2, Music
4, Current Affairs
...
512, Sport
```
I would want my... | Try this:
```
SELECT S.Name, S.Surname, I.Name
FROM SomeTable S
JOIN Interests I
ON I.ID & S.InterestCombinedID > 0
```
`&` is a [bitwise AND operator](http://en.wikipedia.org/wiki/Bitwise_operation).
As example,
```
2 & 6 = 10b & 110b = 10b = 2 > 0 and
4 & 6 = 100b & 110b = 100b = 4 > 0
```
Thus `John Smith`... | You can use recursive CTE to calculate all your combinations of interesets and just join on it:
```
WITH RCTE_Interests AS
(
SELECT id, CAST(name AS NVARCHAR(MAX)) interests FROM dbo.Interests i
UNION ALL
SELECT r.id + i.id, r.interests + ',' + i.name FROM RCTE_Interests r
INNER JOIN dbo.Interests i... | How to join on integer "binary" composite key | [
"",
"sql",
"sql-server",
"binary",
""
] |
I was just profiling my Python program to see why it seemed to be rather slow. I discovered that the majority of its running time was spent in the `inspect.stack()` method (for outputting debug messages with modules and line numbers), at 0.005 seconds per call. This seems rather high; is `inspect.stack` really this slo... | `inspect.stack()` does two things:
* collect the stack by asking the interpreter for the stack frame from the caller (`sys._getframe(1)`) then following all the `.f_back` references. This is cheap.
* per frame, collect the filename, linenumber, and source file context (the source file line plus some extra lines around... | `inspect.stack(0)` can be faster than `inspect.stack()`. Even so, it is fastest to avoid calling it altogether, and perhaps use a pattern such as this instead:
```
frame = inspect.currentframe()
while frame:
if has_what_i_want(frame): # customize
return what_i_want(frame) # customize
frame = frame.f_... | Python inspect.stack is slow | [
"",
"python",
"introspection",
"inspect",
""
] |
I have an input csv file as below,I want to print only the most recent 8 entries..can anyone provide inputs on how to do this?
```
INPUT:-
trend.csv
['2013-06-25 20:01', '10']
['2013-06-25 20:06', '9']
['2013-06-25 20:06', '8']
['2013-06-26 20:06', '7']
['2013-06-26 20:06', '6']
['2013-06-26 20:06', '5']
['2013-06-26... | You can use the [tail recipe](http://docs.python.org/2/library/collections.html#deque-recipes) with a deque with n=8.
This creates a double ended queue where adding an item to the end (right) will efficiently pop off an item at the beginning (the left) to keep the length no more than max length:
```
>>> from collecti... | ```
import csv
# Open the file with a "with" statement to provide automatic cleanup
# in case of exceptions.
with open("trend.csv","rb") as file:
cr = csv.reader(file)
lines = [row for row in cr]
# Use slice notation and the wonderful fact that python treats
# negative indices intelligently!
for line in lines[... | printing only the last 8 entries in a .csv file | [
"",
"python",
"csv",
""
] |
## This is my db "users":
```
user group show_groupmembers
----------------------------------
Bob Alpha Y
Peter Alpha N
Peter Beta Y
Chris Beta Y
```
If show\_groupmembers is "Y", the user can see the all other members of his group.
(So Bob for example can see all "Alpha"-Group users)
If sho... | Since you mentioned using an exist:
```
select u1.user, u1.group, u1.show_groupmembers
from users u1
where exists ( select 1
from users u2
where u2.user = 'Peter'
and u2.show_groupmembers = 'Y'
and u1.group = u2.group )
```
Some edits:
If you want the list of u... | ```
select u1.user, u1.group, u1.show_groupmembers
from users u1
join (select user, group, show_groupmembers
from users where user = 'Joe' and show_groupmembers = 'Y'
) u2
on u1.group = u2.group;
```
See this fiddle: <http://sqlfiddle.com/#!1/22ff1/7> | SQL: How can I check if two values in column A belong to the same group defined in column B? | [
"",
"sql",
"postgresql",
""
] |
I would like to create a class that inherites from `None`.
Tried this:
```
class InvalidKeyNone(None):
pass
```
but that gives me:
```
TypeError: Error when calling the metaclass bases
cannot create 'NoneType' instances
```
What would be the correct solution that gives me a type that behaves exactly like `... | `None` is a [constant](http://docs.python.org/2/library/constants.html), the sole value of `types.NoneType` (for [v2.7](https://docs.python.org/2/library/constants.html?highlight=nonetype#None), for [v3.x](https://docs.python.org/3/library/constants.html?highlight=nonetype#None))
Anyway, when you try to inherit from `... | Subclassing None does not make sense, since it is a singleton and There Can Be Only One. You say you want a class with the same behaviour, but None does not have any behaviour!
If what you really want is a unique placeholder that you can return from a function to indicate a special case then simplest way to do this is... | How to inherit from Python None | [
"",
"python",
""
] |
I want to create a userinput box for integers inside a canvas I created with Tkinter. How I would go about doing this?
```
def gamescreen():
photo = PhotoImage(file="gamescreen.gif")
canvas.bind("<Button-1>", buttonclick_gamescreen)
canvas.pack(expand = YES, fill = BOTH)
canvas.create_image(1, 1, image... | Ok I did some more reading up on what a tuple actually is and I was able to fix the error.
Just had to remove the x= and y= so that the coordinates of the window are by themselves. | You can use [create\_window](http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_window-method) to place a widget within a canvas.
```
e1 = Entry(canvas)
canvas.create_window(400,10,window=e1)
``` | Python - Text input within a Tkinter canvas | [
"",
"python",
"tkinter",
"user-input",
"tkinter-canvas",
""
] |
I apologize in advance if the question is dummy ,i use Python 3.2.3 on Windows xp ,now i need Python3.3.2 , but i can't remove Python 3.2.3 because i have many codes and packages need to be run by it.
I installed virtualenv to run two versions of Python in two different environments , but after that i didn't know wha... | **Fast answer**: You can install the other version and say which one you want to use in your virtualenv using the flag -p
Install the new version as you did with the old. Say you have C:\Python32\ and C:\Python33\
folders. Now just call the command
```
virtualenv -p C:\Python33\python.exe venv
```
---
**Complete An... | You don't need virtualenv to use two different versions of python once you have installed Python 3.3.2 you can run a given script
```
C:\python33\python.exe script.py
```
or
```
C:\python32\python.exe script.py
```
since Python 3.3 was the last version you installed that is the version that windows will use when yo... | Run another version of Python using virtualenv | [
"",
"python",
"virtualenv",
""
] |
I have a web application which I am automating using WebDriver and `Python`.
The issue is that there is a menu something like this 
if I click manually on the arrow button it expands to another submenu from where I need to select a particular field.
... | Grab the element you want to click:
```
# Or using xparth or something
element = driver.find_element_by_css_selector(css_selector)
```
Click it using javascript:
```
driver.execute_script("$(arguments[0]).click();", element)
```
*NOTE: I'm using jQuery otherwise select it native with javascript* | You can use JavaScriptExecutor
For Eg. - `document.getElementsByClassName('post-tag')[0].click();`
Issue that JS via JavaScriptExecutor
```
(JavascriptExecutor(webdriver)).executeScript("document.getElementsByClassName('post-tag')[0].click();");
``` | How do you click on an element which is hidden using Selenium WebDriver? | [
"",
"python",
"web-applications",
"selenium",
"automation",
"webdriver",
""
] |
I am trying to implement FTP download from a UNIX server into a windows box. I have got this far(code below) , but get an error specifying a `file` object is required but `str`
is passed
**Code**
```
#!/usr/bin/python
import ftplib
filename = "filename"
ftp = ftplib.FTP("xx.xxx.xxx.xxx")
ftp.login("uid", "psw")
ftp.c... | You need to open a local file to write to.
Change
```
ftp.retrbinary('RETR %s' % filename, file.write)
```
to
```
ftp.retrbinary('RETR %s' % filename, open(filename, 'wb').write)
``` | ```
ftp.retrbinary('RETR %s' % filename, open('myoutputfile.txt', 'wb').write)
``` | Python FTP query | [
"",
"python",
"ftp",
""
] |
We have two dates in database:
1. 2013-08-01
2. 2013-08-03
Let say that today's date is 2013-08-02 and we want to get next closest date from database. I've found this query, but it's not getting the next day but previous:
```
SELECT
*
FROM
your_table
ORDER BY
ABS(DATEDIFF(NOW(), `date`))
LIMIT 1
```
When... | Others have already posted the answer if you always want a future date:
```
select *
from your_table
where date > now()
order by date
limit 1
```
If there is no future date and you still want to return the last date, then you can do this by modifying the `order by` clause:
```
select *
from your_table
order by (dat... | ```
SELECT *
FROM your_table
WHERE date >= CURRENT_DATE
ORDER BY date
LIMIT 1
``` | MySQL - Get next closest day between two days | [
"",
"mysql",
"sql",
"sql-order-by",
"sql-limit",
""
] |
Two computers communicate using sockets via Internet.
I just send the server program to another person and then my client program will send and receive strings.
I need the data to be cryptographed during the transmission.
My idea is to simply use a childish algorithm that doesn't need any key, but a pair of seque... | What you have described is a simple [substitution cipher](http://en.wikipedia.org/wiki/Substitution_cipher). These sorts of ciphers were used in ancient Rome. A trivial frequency analysis of a few dozen letters of the ciphertext allows full key recovery, rendering the encryption as good as plain text, until the key (su... | Don't ever do this. You must use a standard approach; which will be tried and tested and well-researched.
Read these as a starting point
<http://en.wikipedia.org/wiki/RSA>
<http://en.wikipedia.org/wiki/Secure_Socket_Layer> | Is this simple cryptographic algorithm strong enough? | [
"",
"python",
"sockets",
"cryptography",
""
] |
```
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'X' AND COLUMN_NAME = 'Y')
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Z' AND COLUMN_NAME = 'A')
BEGIN
UPDATE [dbo].[X]
SET Y= (SELECT inst.[A] FROM [dbo].[Z] s WHERE s.[B] = [dbo].[x].[B]);
END
G... | Simple:
```
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'X' AND COLUMN_NAME = 'Y')
AND EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Z' AND COLUMN_NAME = 'A')
BEGIN
UPDATE [dbo].[X]
SET Y= (SELECT inst.[A] FROM [dbo].[Z] s WHERE s.[B] = [dbo].[x].[B]);
END... | No need to select all columns by doing SELECT \* . since you are checking for existence of rows , do SELECT 1 instead to make query faster.
```
IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'X' AND COLUMN_NAME = 'Y')
IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
W... | How can I use AND condition in IF EXISTS in SQL? | [
"",
"sql",
"sql-server",
"if-statement",
""
] |
Based on this [question](https://stackoverflow.com/questions/807506/threads-vs-processes-in-linux) I assumed that creating **new process** should be **almost as fast as** creating **new thread** in Linux. However, little test showed very different result. Here's my code:
```
from multiprocessing import Process, Pool
f... | The question you linked to is comparing the cost of just calling `fork(2)` vs. `pthread_create(3)`, whereas your code does quite a bit more, e.g. using `join()` to wait for the processes/threads to terminate.
If, as you say...
> The goal here is to test the time needed to create a process and a thread.
...then you s... | Yes, it is true. Starting a new process (called a heavyweight process) is costly.
As an overview ...
The OS has to (in the linux case) fork the first process, set up the accounting for the new process, set up the new stack, do the context switch, copy any memory that gets changed, and tear all that down when the new ... | Python threading vs. multiprocessing in Linux | [
"",
"python",
"linux",
"multithreading",
"multiprocessing",
""
] |
I have a large dataset and want to split it into training(50%) and testing set(50%).
Say I have 100 examples stored the input file, each line contains one example. I need to choose 50 lines as training set and 50 lines testing set.
My idea is first generate a random list with length 100 (values range from 1 to 100), ... | This can be done similarly in Python using lists, (note that the whole list is shuffled in place).
```
import random
with open("datafile.txt", "rb") as f:
data = f.read().split('\n')
random.shuffle(data)
train_data = data[:50]
test_data = data[50:]
``` | ```
from sklearn.model_selection import train_test_split
import numpy
with open("datafile.txt", "rb") as f:
data = f.read().split('\n')
data = numpy.array(data) #convert array to numpy type array
x_train ,x_test = train_test_split(data,test_size=0.5) #test_size=0.5(whole_data)
``` | How to split data into trainset and testset randomly? | [
"",
"python",
"file-io",
""
] |
I'm using the following t-sql code:
```
USE [my_database]
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%table_name%'
```
in order to show all the Stored Procedures that use the table `table_name`.
I want do this work for all tables in my database.
How can I... | This uses information schema for both tables, and stored procedures. You can change or get rid of ROUTINE\_TYPE condition to add functions, and you can change table type to return views.
This answer produces its results by checking what tables a stored procedure depends on. I think this will be a much more accurate re... | You could do a `JOIN` on `LIKE`:
```
select * from INFORMATION_SCHEMA.TABLES t
join
(
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
) x on x.name like '%' + t.TABLE_NAME + '%'
```
Note that your query doesn't restrict to procs - you'll also get views, defaults, and ot... | T-SQL: Show stored procedures related to tables, cyclically | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I've got `table1` and `table2` and need to get data out from each of them.
**Table1**
```
"id" "name" "description"
"1" "Windows" "Microsoft Windows 8"
```
**Table2**
```
"id" "type" "name" "description"
"1" "22" "Microsoft Windows" "Microsoft Windows 8 Home"
"2" "2" "Not an Edit" ... | You can do like this..
```
select table1.name, table1.description,
table2.name, table2.description
from table1 inner join Table2 on table2.id=table1.id and table2.`type`=22
``` | No difference, just a syntax difference, internally they yield the same execution plan:
[ANSI vs. non-ANSI SQL JOIN syntax](https://stackoverflow.com/questions/1599050/ansi-vs-non-ansi-sql-join-syntax) | Selecting data from two different tables without using joins | [
"",
"mysql",
"sql",
""
] |
I want to convert a phone number with parentheses and a hyphen between the sixth and seventh digit to 10 numbers with no formatting. This code does the trick, but it's unwieldy and I was wondering whether there's a more efficient method?
Thanks!
```
phone_number = "(251) 342-7344"
phone_number=phone_number.replace("... | You can use `str.translate`:
```
>>> from string import punctuation,whitespace
>>> strs = "(251) 342-7344"
>>> strs.translate(None, punctuation+whitespace)
'2513427344'
```
Using `str.isdigit` and `str.join`:
```
>>> "".join([x for x in strs if x.isdigit()])
'2513427344'
```
**Timing comparisons**:
```
>>> strs = ... | I'd go for:
```
import re
phone_number = "(251) 342-7344"
print re.sub(r'[^\d]', '', phone_number)
# 2513427344
``` | Is there a more efficient way to convert this phone number to plain text? | [
"",
"python",
""
] |
I have a form-data as well as file to be sent in the same POST. For ex, {duration: 2000, file: test.wav}. I saw the many threads here on multipart/form-data posting using python requests. They were useful, especially [this one](https://stackoverflow.com/questions/12592553/python-requests-multipart-http-post?rq=1).
My ... | You should NEVER set that header yourself. We set the header properly with the boundary. If you set that header, we won't and your server won't know what boundary to expect (since it is added to the header). Remove your custom Content-Type header and you'll be fine. | Taking out the Content-Type header with explicit "multipart/form-data" worked! | multipart data POST using python requests: no multipart boundary was found | [
"",
"python",
"multipartform-data",
"python-requests",
""
] |
I've written some Python code to do some image processing work, but it takes a huge amount of time to run. I've spent the last few hours trying to optimize it, but I think I've reached the end of my abilities.
Looking at the outputs from the profiler, the function below is taking a large proportion of the overall time... | Let's try to optimize make\_ellipse in conjunction with its caller.
First, notice that `a` and `b` are the same over many calls. Since make\_ellipse squares them each time, just have the caller do that instead.
Second, notice that `np.cos(np.arctan(theta))` is `1 / np.sqrt(1 + theta**2)` which seems slightly faster o... | Since everything but x and y are integers, you can try to minimize the number of array computations. I imagine most of the time is spent in this statement:
```
ellipse = (xnew * c + ynew * s)**2/a2 + (xnew * s - ynew * c)**2/b2 <= 1
```
A simple rewriting like so should reduce the number of array operations:
```
a =... | Any way to speed up this Python code? | [
"",
"python",
"performance",
"numpy",
""
] |
I have these tables. I want to write update query
```
CREATE TABLE [dbo].[Feasibility](
[FeasibilityID] [int] IDENTITY(1,1) NOT NULL,
[orderstatus] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_Feasibility_orderstatus] DEFAULT ('Not Placed')
CONSTRAINT [PK_Feasibility] PRIMARY KEY CLU... | try this...
```
update feasibility set orderstatus='Closed' where feasiablityID in(select distinct
feasiablityID from ordermaster)
```
you should you Distinct keyword to efficient, fast and error less working.......... | Its better to have `JOIN` statement rather than `IN`. It will be much faster.
You can try this below
```
UPDATE F
SET F.OrderStatus = 'closed'
FROM Feasibility AS F
JOIN OrderMaster AS O
ON F.FeasibilityID = O.FeasibilityID
``` | sql query for 2 tables to update a table | [
"",
"sql",
"sql-server",
""
] |
I'm stuck on something that might be very simple, but I can't find a solution. I'm using Python since few days and I need to use regex to get part of a file.
I put the result of a `git log -p` into a file, and now I want to extract some informations. The only thing I can't extract is the comment block.
This block is ... | Here's one way to do it:
```
rgx = re.compile(r'^Date: .+?\n+(.+?)(?:^diff |\Z)', re.MULTILINE | re.DOTALL)
comments = rgx.findall(txt)
```
A few notes:
* I don't think you need to worry about the length of the Date line.
* Capture the part you care about. This has two implications. (1) To ignore the Date line, just... | Though the date may change in length, it is definitely terminated by a new-line, so why limit the number of characters at all?
Anyway, you should be able to do something like `{32,33}` to capture the range. | Use regex to get comment block from a git log | [
"",
"python",
"regex",
"python-3.x",
""
] |
I want to pass in a string to my python script which contains escape sequences such as: `\x00` or `\t`, and spaces.
However when I pass in my string as:
```
some string\x00 more \tstring
```
python treats my string as a raw string and when I print that string from inside the script, it prints the string literally a... | The string you receive in `sys.argv[1]` is exactly what you typed on the command line. Its backslash sequences are left intact, not interpreted.
To interpret them, follow [this answer](https://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python): basically use `.decode('string_escape')`. | myscript.py contains:
```
import sys
print(sys.argv[1].decode('string-escape'))
```
result
abcd abcd | Pass in string as argument without it being treated as raw | [
"",
"python",
"python-2.7",
""
] |
SQL is not my strong suit, but I cannot figure out why this isn't working. I simply want to run a different AND statement based on a value. Specifically, I want to change the datePart in the dateDiff function if foo is = 0
```
SELECT foo,
bar,
test
FROM table
WHERE bar = 1,
CASE WHEN foo = 0
AND ... | Try this one -
```
SELECT foo,
bar,
test
FROM [table]
WHERE bar = 1
AND (
(
foo = 0
AND
DATEDIFF(dd, GETDATE(), 2 ) < test
)
OR
DATEDIFF(hh, GETDATE(), 2 ) < test
)
``` | If I had to guess at what you're actually aiming for, it's that you wanted to subtract 2 hours or days from `GETDATE()` for use in your comparison.
Here's what I think you're aiming for:
```
SELECT foo,
bar,
test
FROM table
WHERE bar = 1 AND
(
(foo = 0 AND DATEADD(day,-2, GETDATE()) < test)
OR
... | SQL Server 2012 - Case statement in where clause | [
"",
"sql",
"sql-server",
"sql-server-2012",
"case",
"where-clause",
""
] |
I've tried to create a simple method to convert a string into a base-10 integer (in Python):
```
def strToNum(strData, num=0 ,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
return ((len(strData)==0) and num) or (strToNum(strData[0:-1], num+numerals.index(strData[-1])**len(strData)))
```
It doesn't seem to work... | You can simply use `int` here:
```
>>> strs = 'test'
>>> int(strs, 36)
1372205
```
Or define your own function:
```
def func(strs):
numerals = "0123456789abcdefghijklmnopqrstuvwxyz"
return sum(numerals.index(x)*36**i for i, x in enumerate(strs[::-1]))
...
>>> func(strs)
1372205
``` | If your input is in UTF-8 you can encode each byte to Base10, rather than limit yourself to some fixed set of numerals. The challenge then becomes decoding. Some web-based Base10 encoders separate each encoded character/byte with a space. I opted to left-pad with a null character which can be trimmed out.
I am sure th... | Convert string to decimal (base 10) in Python | [
"",
"python",
"numbers",
"converters",
"radix",
""
] |
I am looking for some help adding to my current code, I'm have two lists of usernames the lists would look like this:
```
Fishermen A:
George
Tom
Joel
Tom
Lance
Fishermen B:
George
Tom
Tom
```
What I want to be able to do is essentially if a username appears in Fisherman A list and Fisherman B list, then count th... | ```
fishermanA = ['George', 'Tom', 'Joel', 'Tom', 'Lance']
fishermanB = ['George', 'Tom', 'Tom']
a_set = set(fishermanA)
b_set = set(fishermanB)
inter = a_set.intersection(b_set)
for i in inter:
print(i, fishermanA.count(i) + fishermanB.count(i))
Output:
('George', 2)
('Tom', 4)
``` | Looks like a job for [`collections.Counter`](http://docs.python.org/2/library/collections.html#counter-objects):
```
>>> from collections import Counter
>>> l1 = ['George', 'Tom', 'Joel', 'Tom', 'Lance']
>>> l2 = ['George', 'Tom', 'Tom']
>>> Counter(filter((set(l1) & set(l2)).__contains__, l1 + l2))
Counter({'Tom': 4,... | If function to perform function upon matching two user ids from different lists? | [
"",
"python",
"if-statement",
"python-2.7",
""
] |
I am looking for a simple means of triggering my data acquisition software using an external TTL pulse. I need to sample data from multiple sources synchronously with a 5 Hz reference clock. The acquisition does not need real-time priority but I want to ensure that my software is triggered as soon as possible and exact... | Rather than use the parallel port, have you considered using a serial device? Since you have a TTL signal, you'll possibly need a level converter to convert TTL to RS232 +/- 12V levels. Once you're using a serial device, you can use the standard serial `ioctl()` calls to detect a change in control signal status.
Speci... | Polling is a fine method for such a slow data rate. Poll at 1 ms. That should be fine. Trying to use a hardware interrupt is going to cause much pain.
Google for "Interrupt Linux GPIO" if you want to do it the hard way. :)
<https://developer.ridgerun.com/wiki/index.php/How_to_use_GPIO_signals> | Hardware interrupt for synchronous data acquisition | [
"",
"python",
"linux",
"hardware-interface",
""
] |
I have a directory full of subdirectories.
What I would like to do is write a Python script that loops through each of those
sub-directories and for each one it creates an additional subdirectory and populates
it with three files.
For example:
```
directories = ['apple', 'orange', 'banana']
for fruit in directories... | You can achieve what you want by using the builtin functions **os.path.walk** (to walk through the directory tree) and **os.mkdir** (to actually create the directories). | Python [os](http://docs.python.org/2/library/os.html) module has all you need for creating the directories, particularly [`os.mkdir()`](http://docs.python.org/2/library/os.html#os.mkdir).
You don't say what you want in that files. If you want a copy of another ("template") file, use [shutil.copy()](http://docs.python.... | Looping through a list of directories to make subdirectories | [
"",
"python",
"loops",
"terminal",
"directory",
""
] |
I'm brand new at python package management, and surely have done something wrong. I was encouraged to create a directory structure as follows:
```
bagoftricks
├── bagoftricks
│ ├── bagoftricks
│ │ ├── __init__.py
│ │ └── bagoftricks.py
│ └── __init__.py
├── README.md
└── setup.py
```
bagoftricks.py contai... | The first level "bagoftricks" is fine. That's just the name of your "project" so to speak. In the you have a setup.py, and other files that tell the packaging systems what they need to know.
You can then have the code directly in this module, or in a src directory. You can even go as far as just having this structure:... | with the updated structure you posted
```
bagoftricks
├── bagoftricks
│ ├── __init__.py
│ └── bagoftricks.py
├── README.md
└── setup.py
into bagoftricks/__init__.py import all functions that you need
__init__.py
from bagoftricks import geofind, levenshtein
```
into a different program you can do the follwing
`... | How to structure python packages without repeating top level name for import | [
"",
"python",
"module",
"package",
""
] |
I have a table that has a column "Created" as a datetime.
I'm trying to query to check if the time for the Created value is between two times.
The Created datetime for the first row is '2013-07-01 00:00:00.000' (Midnight) and I'm trying to query for items with a time between 11PM and 7AM.
```
select *
from MyTable
w... | I suspect you want to check that it's *after* 11pm or *before* 7am:
```
select *
from MyTable
where CAST(Created as time) >= '23:00:00'
or CAST(Created as time) < '07:00:00'
``` | ```
select *
from MyTable
where CAST(Created as time) not between '07:00' and '22:59:59 997'
``` | Check if a time is between two times (time DataType) | [
"",
"sql",
"t-sql",
""
] |
I have two questions:
1) I want to write a statement like: `superVar = [subVar1 = 'a', subVar2 = 'b']`
After this statement, I want:
`superVar = ['a', 'b']`
`subVar1 = 'a'`
`subVar2 = 'b'`
Is this somehow achievable in python?
2) I want to do the following inside a class's **init** function:
`self.superVar = [v... | Do you mean a dictionary?
```
superVar = {'subVar1': 'a', 'subVar2': 'b'}
superVar['subVar1']
# 'a'
superVar['subVar2']
# 'b'
```
In a class:
```
class Foo(object):
def __init__(self, a, b):
self.superVar = {'subVar1' : a, 'subVar2' : b}
bar = Foo('one', 'two')
bar.superVar.values()
# ['one', 'two']
``... | ```
>>> from collections import namedtuple
>>> T = namedtuple('supervar', ['v1', 'v2'])
>>> superVar = T('a', 'b')
>>> superVar.v1
'a'
>>> superVar.v2
'b'
``` | Is it possible to assign variables within the assignment of another variable? | [
"",
"python",
"variable-assignment",
""
] |
I have problem to write data into file from my flask developments server (win7),
```
@app.route('/')
def main():
fo = open("test.txt","wb")
fo.write("This is Test Data")
return render_template('index.html')
```
Why this don't works in flask ? | You should either `flush` the output to the file or `close` the file because the data may still be present in the I/O buffer.
Even better use the `with` statement as it'll automatically close the file for you.
```
with open("test.txt", "w") as fo:
fo.write("This is Test Data")
``` | @Ashwini's answer is likely correct, but I wanted to point out that if you are writing to a file to have a logfile, then you should use Flask's support for logging instead. This is based on Python's `logging` module, which is very flexible. Documentation [here](http://flask.pocoo.org/docs/errorhandling/#logging-to-a-fi... | flask to write data into file | [
"",
"python",
"python-2.7",
"flask",
""
] |
I have 5 different ranges data on a column I was to put filter on like
```
10-20
110-120
250-260
```
I am using below but its throwing incorrect results.
```
Select * from test where
testnumber between '10' and '20'
or testnumber between '110' and '120'
or testnumber between '250' and '260'
```
Could someone plea... | Try this:
```
select * from test where testnumber between ('10') and ('20')
``` | If you can get your ranges into a table with `BeginNum` and `EndNum` columns you could do
```
SELECT *
FROM test t
INNER JOIN Ranges r on t.testnumber BETWEEN r.BeginNum and r.EndNum
``` | Between operator in sql for multiple value ranges | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have the following table with values
```
CREATE TABLE #tmpEmployee(ID int, EmpName varchar(50), EmpBossID int)
insert into #tmpEmployee values ( 1, 'Abhijit', 2);
insert into #tmpEmployee values ( 2, 'Haris', 3);
insert into #tmpEmployee values ( 3, 'Sanal', 0);
```
Now I want the result become following
```
ID ... | Use Right Join
```
select E1.ID,E1.EmpName, E.EmpName as BossName from #tmpEmployee E right join #tmpEmployee E1 on E1.EmpBossID=E.ID
ID EmpName BossName
1 Abhijit Haris
2 Haris Sanal
3 Sanal NULL
```
I think its ok for u | Use a `LEFT JOIN` and reverse the order of your tables:
```
select
E.ID,
E.EmpName,
B.EmpName as BossName
from tmpEmployee E
left join tmpEmployee B on E.EmpBossID = B.ID
```
See a [**live demo**](http://sqlfiddle.com/#!2/6cb9e/8) of this query on SQLFiddle
Putting the "employee" part of the join *first* means... | Write a self join query? | [
"",
"sql",
"join",
""
] |
I am using **oder by name** in my sql query.
The following is the name in my table.
```
rama1
rama2
rama10
rama3
rama11
```
I am using the query to display the name **order by name**
the output is coming like,
```
rama1
rama10
rama11
rama2
rama3
```
But I need the output should be,
```
rama1 ... | Query:
```
SELECT t1.*
FROM Table1 t1
ORDER BY CAST(REPLACE(t1.col, 'rama', '') AS UNSIGNED) ASC
```
Result:
```
| COL |
----------
| rama1 |
| rama2 |
| rama3 |
| rama10 |
| rama11 |
``` | I suppose you have a wrong structure of your table. You should have a separate column, like ID of the numeric datatype, where you could keep your rama numeric part. In this case you would be able to make such queries without developing a bycicle.
In your case you can get numeric part from your string (see [How to get ... | sql Order by Query to display the name in order | [
"",
"sql",
""
] |
I'm 99% sure something is going on with my `hxs.select` on this website. I cannot extract anything. When I run the following code, I don't get any error feedback. `title` or `link` doesn't get populated. Any help?
```
def parse(self, response):
self.log("\n\n\n We got data! \n\n\n")
hxs = HtmlXPathSelector(res... | Scrapy shell is a good tool for that indeed. And if your document has an XML stylesheet, it's probably an XML document. So you can use scrapy shell with `xxs` instead of `hxs` as in this Scrapy documentation example about removing namespaces:
<http://doc.scrapy.org/en/latest/topics/selectors.html#removing-namespaces>
... | You can use pdb from the command line and add a breakpoint in your file. But it might involve some steps.
(It may differ slightly for windows debugging)
1. Locate your `scrapy` executable:
```
$ whereis scrapy
/usr/local/bin/scrapy
```
2. Call it as python script and start pdb
```
$ python -m pdb ... | How can I debug Scrapy? | [
"",
"python",
"web-scraping",
"scrapy",
""
] |
I'm trying to create a prime sieve in Python.
I start with making a list from 2 to 2000. I want to iterate through all primes with a check, and remove all multiples of the primes from the list.
I've not gotten around the loop for primes yet, but what I do have a method to start with the number 2, and remove all its m... | You create a list of 1999 elements:
```
>>> len(range(2,2001))
1999
```
You then loop over a `range()` up to, but not including, that length:
```
for x in range (p*p, len(primes), p):
```
Thus `x` is never going to be larger than 1998.
Instead of `len(primes)`, use an upper limit constant:
```
limit = 2001
primes... | your list is not 2000 long, you start at 2..
```
>>> primes=list(range(2,2001))
>>> print len(primes)
1999
```
So when you do the while loop, it doesn't get up to 2000... :) | Python list.remove for loop "x not in list" | [
"",
"python",
"list",
"pycharm",
""
] |
Got this weird error
can anyone help?
```
Traceback (most recent call last):
File "./test.py", line 172, in <module>
main()
File "./test.py", line 150, in main
if random() < .5 and losttwice < 5:
TypeError: 'module' object is not callable
import urllib2,urllib,os,simplejson, random
``` | You should use `random.random()` not just `random`. `random` is a module that contains functions like `random`, `randint` etc:
```
>>> import random
>>> random.random()
0.376462621569017
```
help on `random.random`:
```
random(...)
random() -> x in the interval [0, 1).
```
If you only want to use the `random()`... | `random` is the name of a module; `random.random` is a function in that module. So you want to do `random.random() < .5`, not `random() < .5`. | TypeError: 'Module' object is not callable Help please | [
"",
"python",
""
] |
I am developing [ryu](http://osrg.github.io/ryu/) app. The app is basically a python script. The ryu apps are invoked by ryu-manager like this
> ryu-manager {filename}
There are certain parameters that are taken by ryu-manager. I want to know if there is a way i could pass arguments to my file?
[argparse](http://doc... | I haven't tried this, but:
> "Ryu currently uses oslo.config.cfg for command-line parsing.
> (ryu/contrib/oslo/config).
> There are several examples in the tree. ryu/app/tunnel\_port\_updater.py"
from
<http://comments.gmane.org/gmane.network.ryu.devel/2709>
see also
<https://github.com/osrg/ryu/blob/master/ryu/app/t... | Doing so is a 4-step process. I'll show an example where you read parameters and then print them, but you could assign them to variables or do whatever you would like to by referencing this process.
---
1. Create a .conf file (e.g. params.conf)
```
#Example Conf File
[DEFAULT]
param1_int = 42
param2... | Passing own arguments to ryu proxy app | [
"",
"python",
"open-source",
"command-line-arguments",
""
] |
I have one table named:
```
Delegates
```
This table has four fields:
```
ID(Auto increment, Primary)
MemberNo, FromYr, ToYr
```
I am inserting with this query:
```
INSERT INTO Delegates ([MemNo],[FromYr],[ToYr]) values(@MemNo, @FromYr,@ToYr)
```
The values comes from user input. One member can be a Delegate for ... | Before inserting check if there is a record with the same values:
```
if not exists (select * from Delegates d where d.FromYr = @FromYr and d.MemNo = @MemNo)
INSERT INTO Delegates ([MemNo],[FromYr],[ToYr]) values(@MemNo, @FromYr,@ToYr)
``` | Use [MERGE](http://technet.microsoft.com/en-us/library/bb510625%28v=sql.100%29.aspx)
```
MERGE INTO Delegates D
USING (values(@MemNo, @FromYr,@ToYr)) X ([MemNo],[FromYr],[ToYr])
ON (insert unique key join)
WHEN NOT MATCHED BY TARGET THEN
INSERT ([MemNo],[FromYr],[ToYr]))
VALUES (X.[MemNo],X.[FromYr],X.[ToYr]);
``` | How to avoid Duplicate values for INSERT in SQL? | [
"",
"sql",
"sql-server-2008",
""
] |
```
import tkinter as tk
import pygame
pygame.init()
ss = width, height = 1024, 600
screen = pygame.display.set_mode(ss)
tkinput_1 = True
while True:
event = pygame.event.poll()
keys = pygame.key.get_pressed()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fil... | I've tryed using Tk but the thing about using is it stops the whole pygame program when the Tk window pops up and its just not good
this is what i use [Pygame InputBox](http://www.pygame.org/pcr/inputbox/) its not the prettiest but it works great just download it and its really easy to use
just `import inputbox`
the... | You can use a small library i'm making, just download [it](https://github.com/ddorn/GUI/) and use it.
To make a simple Text box try:
```
from GUI import *
input_bow = InLineTextBox((0, 0), 200)
```
You must give it at least a postion and the size
Then in your input loop, update it :
```
for e in pygame.event.get()... | Using text inputs in pygame | [
"",
"python",
"input",
"textbox",
"tkinter",
"pygame",
""
] |
I have a table with column `mapping` which store record: `"IV=>0J,IV=>0Q,IV=>2,V=>0H,V=>0K,VI=>0R,VI=>1,"`
What is the sql to check whether or not a substring is in column mapping.
so, I would like this:
* if I have `"IV=>0J"` would return true, because `IV=>0J` is exact in string "mapping"
* if I have `"IV=>01"` wou... | This should do the trick:
```
SELECT * FROM table
WHERE
mapping LIKE '%,IV=>0J,%'
OR mapping LIKE '%,IV=>0J'
OR mapping LIKE 'IV=>0J,%'
OR mapping = 'IV=>0J'
```
But you should really normalize the database - you are currently violating the principle of [atomicity](http://en.wikipedia.org/wiki/First_n... | You can search with commas included. Just also add one at beginning and end of `mapping`:
```
SELECT * FROM table WHERE charindex(',IV=>0J,',',' + mapping + ',') <> 0
```
or
```
SELECT * FROM table WHERE ',' + mapping + ',' LIKE '%,IV=>OJ,%'
``` | SQL Checking Substring in a String | [
"",
"sql",
"sql-server",
""
] |
After entering a command I am given data, that I then transform into a list. Once transformed into a list, how do I copy ALL of the data from that list [A], and save it - so when I enter a command and am given a second list of data [B], I can compare the two; and have data that is the same from the two lists cancel out... | ```
>>> b=[1,2,3,4]
>>> a=[1,2,3]
>>> [x for x in b if x not in a]
[4]
``` | You can use set operations.
```
a = [1,2,3]
b = [1,2,3,4]
print set(b) - set(a)
```
to output the data in list format you can use the following print statement
```
print list(set(b) - set(a))
``` | How to copy data in Python | [
"",
"python",
"list",
"copy",
"compare",
""
] |
I've a table with the name `Article`. It has one column,type's float. I'd want to cast this field to nvarchar and also complete 8 characters. I tried to a a lot of things, but doesn't work. I need your helps.
```
ArticleNo
11536 ---> 00011536
28508 ---> 00028508
285082 ---> 00285082
28508111 --> 28508111
2850811... | ```
SELECT
REPLACE(STR(MyFloatColumn, 8, 0), ' ', '0')
FROM
MyTable;
``` | This is a question of formatting rather than conversion. SQL Server versions before 2012 are very poor at string formatting. [gbn's](https://stackoverflow.com/a/17443049/134204) solution is probably the easiest to use. It would be better to do string formatting on the client side or on your reporting tool.
SQL Server ... | float casting to nvarchar with constraint max size | [
"",
"sql",
"sql-server",
"database",
""
] |
I am trying to sort list of strings containing numbers:
```
a = ["1099.0","9049.0"]
a.sort()
a
['1099.0', '9049.0']
b = ["949.0","1099.0"]
b.sort()
b
['1099.0', '949.0']
a
['1099.0', '9049.0']
```
But list `b` is sorting and not list `a`. | You want to sort based on the `float` values (not string values), so try:
```
>>> b = ["949.0","1099.0"]
>>> b.sort(key=float)
>>> b
['949.0', '1099.0']
``` | Use a [lambda](http://docs.python.org/2/reference/expressions.html#lambda) inside 'sort' to convert them to float and then sort properly:
```
a = sorted(a, key=lambda x: float(x))
```
So you will maintain them as strings, but sorted by value and not lexicographically. | How to sort a Python list of strings of numbers | [
"",
"python",
""
] |
I am trying to use an object as the key value to a dictionary in Python. I follow the recommendations from some other posts that we need to implement 2 functions: `__hash__` and `__eq__`
And with that, I am expecting the following to work but it didn't.
```
class Test:
def __init__(self, name):
self.name ... | Elements of a mapping are *not* accessed by their hash, even though their hash is used to place them within the mapping. You *must* use the same value when indexing both for storage and for retrieval. | You don't need to redefine `hash` and `eq` to use an object as dictionary key.
```
class Test:
def __init__(self, name):
self.name = name
test_Dict = {}
obj = Test('abc')
test_Dict[obj] = obj
print test_Dict[obj].name
```
This works fine and print `abc`.
As explained by Ignacio Vazquez-Abrams you don't... | Using object as key in dictionary in Python - Hash function | [
"",
"python",
"object",
"dictionary",
"key",
""
] |
I have successfully run the [simplest pyramid app](http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/firstapp.html#firstapp-chapter) in my local virtual environment. I am now working on [this tutorial](http://docs.pylonsproject.org/projects/pyramid_tutorials/en/latest/getting_started/01-helloworld/index.htm... | In fact, hosting a Python application on a "real" webserver is quite different from running it on you local machine: locally you rely on a small webserver which is often built into the framework - however, that webserver often has limitations (for example, it may only execute requests in a single thread). Some framewor... | Try running the site on a free account on PythonAnywhere, its the simplest to get started with.
You can simple make a git repo from your files on github, and then clone then on PythonAnywhere (I mention a host in specific, because you want to know how to run something on a host, and I have found it to be the most easy... | Getting started with pyramid on a live server | [
"",
"python",
"python-2.7",
"pyramid",
"wsgi",
""
] |
I have a SQL query that I use for a search function (shown below)
```
SELECT t.op_id, t.op_desc FROM operator
WHERE UPPER(t.op_id) LIKE UPPER(?);
```
when my web page first loads, it simply returns every operator in the table.
There a few entries in the database for which the operator id (t.op\_id) contains some whi... | To ignore white spaces, you can try
```
WHERE NOT LIKE '% %'
```
This will [perform the same](https://stackoverflow.com/questions/2451608/which-is-faster-instr-or-like) as `INSTR`. | You can try this :
```
SELECT t.op_id, t.op_desc FROM operator
WHERE t_op_id not like '% %'
``` | Is there any way that I can alter this SQL query so that it doesn't return any results containing whitespace? | [
"",
"mysql",
"sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.