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 statement, but need some help making it more flexible. See the code below for what I have that does work for the limited set like above:
```
UPDATE ROTATION_LIST SET ORDER_NUM =
CASE
WHEN ORDER_NUM = 1 THEN 3
WHEN ORDER_NUM = 2 THEN 1
WHEN ORDER_NUM = 3 THEN 2
END
```
This is not a homework assignment or brain teaser I have an actual need for this. | 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, you could set the value for 1 to be the max order number + 1, and then run the query to decrement all the values by one to get it to the right spot. | 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
FROM rotation_list)
UPDATE rotation_list
SET order_no = new_order.new_order_no
FROM rotation_list
INNER JOIN new_order
ON rotation_list.rec_no = new_order.rec_no
```
[DEMO](http://sqlfiddle.com/#!6/90b53/14)
If your RDMS support ROW\_NUMBER but not LAG() (looking at you sql 2008) you can do this
```
WITH cte
AS (SELECT rec_no,
order_no,
Row_number() OVER ( ORDER BY order_no) rn
FROM rotation_list),
new_order
AS (SELECT no.rec_no,
COALESCE(no_prev.order_no,
Max(no.order_no) OVER (partition BY NULL )) new_order_no
FROM cte no
LEFT JOIN cte no_prev
ON no.rn - 1 = no_prev.rn)
UPDATE rotation_list
SET order_no = new_order.new_order_no
FROM rotation_list
INNER JOIN new_order
ON rotation_list.rec_no = new_order.rec_no;
```
[DEMO](http://sqlfiddle.com/#!3/90b53/37) | 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 output:
```
Countdown: 0
Countdown: 1
Countdown: 2
Countdown: 3
Countdown: 4
Countdown: 5
Countdown: 6
Countdown: 7
Countdown: 8
Countdown: 9
```
Sys.stdout.write Version:
```
for i in range(10):
sys.stdout.write("\rCountdown: %d" % i)
time.sleep(1)
print "\n"
```
Problem: All the sleep happens at the beginning, and after 10 seconds of sleep it just prints `Countdown: 9` to the screen. I can see the `\r` is working behind the scenes, but how do I get the prints to be interspersed in the sleep? | 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 suppresses the newline that would typically be appended.
Not sure how to fix the first one though... | 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/4622065) mentioned.
```
for i in range(10):
print "\rCountdown: %d" % i,
sys.stdout.flush()
time.sleep(1)
```
An alternative is to use the [print function](https://docs.python.org/2/library/functions.html#print), but `sys.stdout.flush()` is still needed.
```
from __future__ import print_function
for i in range(10):
print("\rCountdown: %d" % i, end="")
sys.stdout.flush()
time.sleep(1)
``` | 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 da Man J.D.,CEP
Green Eggs Jr. Ed.M.,CEP
Argle Bargle Sr. MA
Cersei Lannister M.A. Ph.D.
```
My issue is that some of the rows contain a comma, which is followed by an acronym which represents an "area of practice" for the professional and some do not.
My code relies on the principle that each line contains a comma, and I will now have to modify the code in order to account for lines where there is no comma.
```
def parse_ieca_gc(s):
########################## HANDLE NAME ELEMENT ###############################
degrees = ['M.A.T.','Ph.D.','MA','J.D.','Ed.M.', 'M.A.', 'M.B.A.', 'Ed.S.', 'M.Div.', 'M.Ed.', 'RN', 'B.S.Ed.', 'M.D.']
degrees_list = []
# separate area of practice from name and degree and bind this to var 'area'
split_area_nmdeg = s['name'].split(',')
area = split_area_nmdeg.pop() # when there is no area of practice and hence no comma, this pops out the name + deg and leaves an empty list, that's why 'print split_area_nmdeg' returns nothing and 'area' returns the name and deg when there's no comma
print 'split area nmdeg'
print area
print split_area_nmdeg
# Split the name and deg by spaces. If there's a deg, it will match with one of elements and will be stored deg list. The deg is removed name_deg list and all that's left is the name.
split_name_deg = re.split('\s',split_area_nmdeg[0])
for word in split_name_deg:
for deg in degrees:
if deg == word:
degrees_list.append(split_name_deg.pop())
name = ' '.join(split_name_deg)
# area of practice
category = area
```
re.search() and re.match() both do not work, it appears, because they return instances and not a boolean, so what should I use to tell if there's a comma? | 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(LON,LAT,squeeze(precip(t,:,:)),XI,YI);
end
```
In python I have tried `interp2d`, `map_coordinates`, and `interp` (basemap) functions, but without success.
Here's my code with `map_coordinates`, which got me closest to getting a result
```
new_indicies = np.mgrid[0:410, -89.5:89.5:180J, -179.5:179.5:360J]
newPrecip = ndimage.map_coordinates(precip, new_indicies, order=1)
```
The new data does have the dimensions I want (410,180,360), but it doesn't actually interpolate, instead it just fills the newly added grids (around the original data) with 0 values.
I am new to python, and I would appreciate any help in getting a solution to this problem. | 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 (assuming regular grid), dataIn is 2D array of the original data, lonOUT and latOUT are 2D grid you want to interpolate to, while Zg is the output on the new grid. The output grid can be created using:
```
x=np.arange(-180,180,1)
y=np.arange(-90,90,1)
lonOUT,latOUT=np.meshgrid(x,y)
```
Hope this helps. Cheers, Trond | 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.js"></script>
</head>
<body>
{% if user.is_authenticated %}
<div class="btn-group">
<a href="#" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" style="margin: 3px;">
{{ user.username }}
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a href="#">Action1</a></li>
</ul>
</div>
{% endif %}
```
yet I cannot seem to get the dropdown to work correctly, although it works fine in online simulators..
Thanks for any insight! | 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 failed:
```
CASE(completed_callbacks / completed_within_2hours * 100) as Percentage
```
i know this is a rather simple question but i havnt been able to find the answer anywhere | 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
END) AS completed_within_2hours
FROM yourtable
WHERE ...)
``` | 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 when completed='Y' then 1 else 0 end) as count_completed,
sum(case when completed='N' then 1 else 0 end) as count_not_completed,
sum(case when completed='Y' and completed_fast='Y' then 1 else 0 end) as count_completed_fast,
case when (sum(case when completed='Y' then 1 else 0 end) = 0) then 0 else
((sum(case when completed='Y' and completed_fast='Y' then 1 else 0 end) / sum(case when completed='Y' then 1 else 0 end))*100)
end pct_completed_fast
from x;
```
Results:
```
"COUNT_COMPLETED" "COUNT_NOT_COMPLETED" "COUNT_COMPLETED_FAST" "PCT_COMPLETED_FAST"
3 1 2 66.66666666666666666666666666666666666667
```
The trick is to use SUM rather than COUNT, along with a decode or CASE. | 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 'starting numbers,' the value represents how long it took the sequence to take the starting number and take it down to 1 using a particular formula.
I'm solving the problem using recursion, which itself is very easy but there's more to it for me.
**Each recursive step gives me the opportunity to update a different key in the library, but I am unable to find a way to do this.**
So where a sequence might look like 13 -> x -> y -> z ... -> 1, what would you do to not only update the 13 key with value, but also the x, y, x values in the dictionary during the same recursive path? Right now I'm only able to update one number per sequence.
```
cache = {1:1}
def solve(number):
if cache.has_key(number):
return cache[number]
else:
if condition one..
return 1 + solve(number * formula 1)
else condition two...
return 1 + solve(number * formula 2)
for x in xrange(1,1000):
cache[x] = solve(x) <-- right now only cache[x] is being updated.
```
Thank you! | 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 error message I am receiving:
```
Msg 104, Level 16, State 1, Line 1
ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.
```
The bottom set above returns a list we use for link names, and the right column provides the path they link to. We need to add a default link for everyone which is why we are trying the union part since this link everyone will get and the other table displays links based on permission.
It works just fine without the order by clause, but i need the return to ipacs one at the top, then home, then team and rest ordered desc.
What am I doing wrong here? | 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 nesting. I added some parenthesis. Anyway, the point is that you should just add values as shown to force the sort. | ```
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 sortOrder desc
```
[demo](http://sqlfiddle.com/#!6/1f6f2/10) | 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) also claims to work with python3.
[Here](http://wiki.python.org/moin/SQL%20Server) you can find a list with some more options. | 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.cursor()
cur.execute(SQL)
cur.close()
connection.close()
``` | 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 (perhaps using MIN) and the latest trantime with trantype Z (Using Max), all of which in that trandate (ie. trantype A for july 17 is 8:00 AM and trantype Z for july 17 is 7:00PM).
the problem is, the output should be in the same format as the table where it's coming from, meaning that I have to leave this data and filter out the rest (that aren't the earliest and latest in/out for that date, per employee)
My current solution is to use two different select commands to get all earliest, then get all the latest. then combine them both.
I was wondering though, is there a much simpler, single string solution?
Thank you very much.
EDIT (I apologize, here is the sample. Server is SQL Server 2008):
```
Timecardid | Trandate | employeeid | trantime | trantype | Projcode
1 2013-04-01 1 8:00:00 A SAMPLE1
2 2013-04-01 1 9:00:00 A SAMPLE1
3 2013-04-01 2 7:00:00 A SAMPLE1
4 2013-04-01 2 6:59:59 A SAMPLE1
5 2013-04-01 1 17:00:00 Z SAMPLE1
6 2013-04-01 1 17:19:00 Z SAMPLE1
7 2013-04-01 2 17:00:00 Z SAMPLE1
8 2013-04-02 1 8:00:00 A SAMPLE1
9 2013-04-02 1 9:00:00 A SAMPLE1
10 2013-04-02 2 7:00:58 A SAMPLE1
11 2013-04-02 2 18:00:00 Z SAMPLE1
12 2013-04-02 2 18:00:01 Z SAMPLE1
13 2013-04-02 1 20:00:00 Z SAMPLE1
```
Expected Results (the earliest in and the latest out per day, per employee, in a select command):
```
Timecardid | Trandate | employeeid | trantime | trantype | Projcode
1 2013-04-01 1 8:00:00 A SAMPLE1
4 2013-04-01 2 6:59:59 A SAMPLE1
6 2013-04-01 1 17:19:00 Z SAMPLE1
7 2013-04-01 2 17:00:00 Z SAMPLE1
8 2013-04-02 1 8:00:00 A SAMPLE1
10 2013-04-02 2 7:00:58 A SAMPLE1
12 2013-04-02 2 18:00:01 Z SAMPLE1
13 2013-04-02 1 20:00:00 Z SAMPLE1
```
Thank you very much | 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 answer to account for the "per employee" requirement:
```
;WITH EarliestIn AS
(
SELECT trandate, employeeid, min(trantime) AS EarliestTimeIn
FROM test
WHERE trantype = 'A'
GROUP BY trandate, employeeid
),
LatestOut AS
(
SELECT trandate, employeeid, max(trantime) AS LatestTimeOut
FROM test
WHERE trantype = 'Z'
GROUP BY trandate, employeeid
)
SELECT *
FROM test t
WHERE
EXISTS (SELECT * FROM EarliestIn WHERE t.trandate = EarliestIn.trandate AND t.employeeid = EarliestIn.employeeid AND t.trantime = EarliestIn.EarliestTimeIn)
OR EXISTS (SELECT * FROM LatestOut WHERE t.trandate = LatestOut.trandate AND t.employeeid = LatestOut.employeeid AND t.trantime = LatestOut.LatestTimeOut)
``` | 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,employeeid,trantype
ORDER BY trantime DESC) as rnLate
from
Test
)
select * from Ordered
where
(rnEarly = 1 and trantype='A') or
(rnLate = 1 and trantype='Z')
order by TimecardId
```
([SQLFiddle](http://sqlfiddle.com/#!3/071a7/2))
It produces the results you've requested, and I think it's quite readable. The reason that `trantype` is included in the `PARTITION BY` clauses is so that `A` and `Z` values receive separate numbering. | 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 items in the 'IN' clause
Below is some performance data from selecting rows using where in from a table with 1,000,000 rows
```
Querying for 1 random keys (where in) took 0ms
Querying for 1000 random keys (where in) took 46ms
Querying for 2000 random keys (where in) took 94ms
Querying for 3000 random keys (where in) took 249ms
Querying for 4000 random keys (where in) took 316ms
Querying for 5000 random keys (where in) took 391ms
Querying for 6000 random keys (where in) took 466ms
Querying for 7000 random keys (where in) took 552ms
Querying for 8000 random keys (where in) took 644ms
Querying for 9000 random keys (where in) took 743ms
Querying for 10000 random keys (where in) took 853ms
```
Is there a faster way than using WHERE IN to do this.
We cant do a join as this is between disconnected systems.
I have heard an [in memory temp table joined to the data in MYSQL may be faster](https://stackoverflow.com/questions/8519311/faster-way-of-executing-select-where-id-in-in-mysql) but from my research MSSQL doesn't have have an in memory table option and even so wouldn't it be prone to exactly the same index scan on insert into the temp table as the WHERE IN has?
**EDIT:**
This table has ID as a PK so has the default PK index, cf
```
CREATE TABLE [dbo].[Entities](
[Id] [int] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_dbo.Entities] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
```
Execution plan

Here is a GIST for a console app which produces these performance results <https://gist.github.com/lukemcgregor/5914774>
**EDIT 2**
I created a function which creates a temp table from a comma separated string, and then joined vs that table. Its faster but i think mostly because of the issue with parsing the query with where in
```
Querying for 1 random keys took 1ms
Querying for 1000 random keys took 34ms
Querying for 2000 random keys took 69ms
Querying for 3000 random keys took 111ms
Querying for 4000 random keys took 143ms
Querying for 5000 random keys took 182ms
Querying for 6000 random keys took 224ms
Querying for 7000 random keys took 271ms
Querying for 8000 random keys took 315ms
Querying for 9000 random keys took 361ms
Querying for 10000 random keys took 411ms
``` | 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));
toSelect.ToList().ForEach(selectItem => dataTable.Rows.Add(selectItem));
using (SqlCommand command = new SqlCommand(
@"SELECT *
FROM [dbo].[Entities] e
INNER JOIN @ids on e.id = value", con))
{
var parameter = command.Parameters.AddWithValue("@ids", dataTable);
parameter.SqlDbType = System.Data.SqlDbType.Structured;
parameter.TypeName = "IntTable";
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
results.Add(reader.GetInt32(0));
}
}
}
```
this produces the following results
```
Querying for 1 random keys (passed in table value) took 2ms
Querying for 1000 random keys (passed in table value) took 3ms
Querying for 2000 random keys (passed in table value) took 4ms
Querying for 3000 random keys (passed in table value) took 6ms
Querying for 4000 random keys (passed in table value) took 8ms
Querying for 5000 random keys (passed in table value) took 9ms
Querying for 6000 random keys (passed in table value) took 11ms
Querying for 7000 random keys (passed in table value) took 13ms
Querying for 8000 random keys (passed in table value) took 17ms
Querying for 9000 random keys (passed in table value) took 16ms
Querying for 10000 random keys (passed in table value) took 18ms
``` | 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 linked server for that, or maybe use BCP utility to fill a temporary table this and then delete it. | 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.
________________________________________________
```
Would it be better to list the name, age, etc. directly in that table.. or better to have a person table with their name, age, etc., and linked by person\_id or something?
This may be a little simplistic of an example, since there are more than just those two options. But for the sake of illustration, assume that the relationships cannot be stored in the person table.
I'm doing the latter of the two choices above currently, but I'm curious if this will get to a point where the performance will suffer, either when the person table gets large enough or when there are enough linked columns in the relations table. | 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 all the individual identifying info -- age, name, etc.
`Relationship_types` would have a key, a label, and potentially a description. This table is for elaborating the details of each possible relationship. So you would have a row for 'parent', a row for 'child', a row for 'sibling', etc.
Then the `Relationships` table has a four fields: one for the key of each person in the relationship, one for the key of the relationship\_type, and one for its own key. Note that you need to be explicit in how you name the `person` columns to make it clear which party is which part of the relationship (i.e. saying that A and B have a 'parent' relationship only makes sense if you indicate which person *is* the parent vs which *has* the parent). | 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 Microsoft SQL Database.
The Data looks like this:
```
CodeId Code CatalogType CodeGroup CodeText CodeGroupText CodeDesc State_ID
------- ----- ------------- ---------- -------- -------------- --------- ---------
1 AAAA 1 100 Plastic Plastic Center NULL 2
2 BBBB 1 100 Glass Glass Center NULL 2
3 CCCC 1 101 Steel Steel Center NULL 2
```
I just want to the data to look the same just where the code group is distinct.
Data would look like this:
```
CodeId Code CatalogType CodeGroup CodeText CodeGroupText CodeDesc State_ID
------- ----- ------------- ---------- -------- -------------- --------- ---------
1 AAAA 1 100 Plastic Plastic Center NULL 2
3 CCCC 1 101 Steel Steel Center NULL 2
``` | 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) codeid, codegroup
from yourtable
group by codegroup
) t2
on t1.codeid = t2.codeid
and t1.codegroup = t2.codegroup
``` | 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, True])
```
Which compares the vectors element-wise.
I realize that most of the functions on vectors from the mentioned modules don't need the differentiation. For example `outer(a,b)` or `a.dot(b)` but I'd like to differentiate for my own convenience. | 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.transpose()
array([[1, 2, 3]])
>>> a.dot(a.transpose())
array([[1, 2, 3],
[2, 4, 6],
[3, 6, 9]])
```
Another option is to use np.newaxis when you want to make the distinction:
```
>>> a = np.array([1, 2, 3])
>>> a
array([1, 2, 3])
>>> a[:, np.newaxis]
array([[1],
[2],
[3]])
>>> a[np.newaxis, :]
array([[1, 2, 3]])
``` | 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 achieve that.
Here is what I have tried so far:
```
UPDATE TABLE
SET C5 =
Case
when C1 IS NULL then 'C!'
WHEN C2 IS NULL then 'C2'
WHEN C3 IS NULL THEN 'C3'
WHEN C4 IS NULL ThEN 'C4'
END
``` | 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 field name if `NULL`.
You could craft the query in Excel pretty quickly, it will leave one errant comma at the end of the string, if that's a problem it can be easily dealt with:
```
UPDATE table
SET C5 = STUFF(ISNULL(REPLACE(C1,C1,''),',C1 ')
+ISNULL(REPLACE(C2,C2,''),',C2 ')
+ISNULL(REPLACE(C3,C3,''),',C3 ')
+ISNULL(REPLACE(C4,C4,''),',C4 '),1,2,'')
```
Update: Changed to using STUFF() function instead of LEFT() to eliminate errant comma, and added a space between listed items. | ```
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 very good introduction and shows how to nest decorators. Well all this is fine and dandy. But what I've yet to figure out is how many of the (python)-web-frameworks (flask, django etc.) manage to call, what I can only guess is a *decorated function* based on **arguments** passed to the **decorator**.
An example (using Flask, but is similar in many frameworks) to show you what I mean.
```
@application.route('/page/a_page')
def show_a_page():
return html_content
@application.route('/page/another_page')
def show_another_page():
return html_content
```
Now if I make a request to `mysite.com/page/a_page` flask somehow figures out that it should call `show_a_page`, and ofcourse the same goes for `show_another_page` if the request is to `mysite.com/page/a_page`.
I'm wondering how I would go about implementing similar functionality in my own project?
I suppose that there exists something similar to using `dir(module_name)` to extract information about the *decoration(?)* of each function? | 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 = {}
def add_to_table(name):
def dec(func):
def inner_func(*args, **kwargs):
return func(*args, **kwargs)
function_table[name] = inner_func
return inner_func
return dec
@add_to_table("my_addition_function")
def myfunction(a, b):
return a + b
@add_to_table("my_subtraction_function")
def myfunction2(a, b):
return a - b
print myfunction(1, 3)
# 4
print function_table["my_addition_function"](1, 4)
# 5
print function_table["my_subtraction_function"](1, 4)
# -3
```
This is a very simple version of what Flask is doing: storing a table of what functions to call based on what path is being used. | 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 example, we simply print out the the argument passed to the decorator's constructor when we define the function. Notice that we printed "Hello, world!" without actually invoking `my_func` - that's because the print occurs when we construct the decorator, rather than in the decorator itself.
What's happening, is that `application.route` is not a decorator itself. Rather, it is a function that takes a route, and produces a decorator that will be applied to the view function, as well as registering the view function at that route. In flask, the decorator constructor has access to both the route and the view function, so it can register the view function at that route on the application object. If you're interested, you might take a look at the Flask source code on Github:
<https://github.com/mitsuhiko/flask/blob/master/flask/app.py> | 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 file the user chooses?
```
##Writing to .cvs file
with open('test_write.csv', 'w') as fp:
a = csv.writer(fp)
# write row of header names
a.writerow(n)
```
Thank you | 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 related values in `Friend` and `User`, like below:
```
--------------------------
Friends of 2
--------------------------
1 - (from column User )
3 - (from column Friend)
5 - (from column user )
4 = (from column friend )
```
I want one column search result like below:
```
--------------------------
Friends of 2
--------------------------
1
3
5
4
```
How can I accomplish this by using a SELECT query in SQL Server? | ```
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 is the best way to put the functions because python needs to know the definition of the functions before calling them.
I don't want to create a new file for each function.
I would like to put all functions together but I can't figure it out.
I hope you can help me.
Thx, | 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 your file from another file, then it won't execute all the code in main(). | 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(meal)
retTax = int(tax)
retTip = int(tip)
except ValueError:
retMeal = float(meal)
retTax = float(tax)
retTip = float(tip)
return retMeal
return retTax
return retTip
convertInput(meal, tax, tip)
retTax = retTax / 100
retTip = retTip / 100
total = retMeal + retTax + retTip
print total
tipCalc(meal, tax, tip)
```
However, I am getting the following error:
```
Traceback (most recent call last):
File "/Users/dustin/Desktop/tipcalc.py", line 27, in <module>
tipCalc(meal, tax, tip)
File "/Users/dustin/Desktop/tipcalc.py", line 22, in tipCalc
retTax = retTax / 100
UnboundLocalError: local variable 'retTax' referenced before assignment
```
This seems like a simple error to fix, but I can't seem to find an error in my logic. | 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 = float(tip)
return retMeal, retTax, retTip
retMeal, retTax, retTip = convertInput(meal, tax, tip)
retTax = retTax / 100
retTip = retTip / 100
total = retMeal + retTax + retTip
print total
tipCalc(meal, tax, tip)
```
If you wish to return multiple values from a class method, multiple return statements do not work. You need to have 1 return statements, and send back as many values as you wish to.
Also, the error was, at the time of calculating `retTax = retTax / 100`, the variable was not already declared. | 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**: This answer is true for Python 2.x (which I see you're using). In Python 3.x, the default behavior of division changes and this answer would no longer be true (and your code would work correctly).
With that in mind, let's look at something in the Python interpreter for a minute.
```
Python 2.7.4 (default, Apr 19 2013, 18:28:01)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2.0 / 3.0
0.6666666666666666
>>> 2 / 3
0
```
In the first example, we see what happens when we divide two floats together: we get a float with the best approximation of the result we can. (2/3 will never be exactly represented by a float, but it's a close enough result for nearly all purposes). But see the second example? Instead of 0.666..., it returned 0. Why is that?
That's because in Python 2.x, dividing two `int`s together is guaranteed to always return an `int`, so it rounds down (always down) to the int. In combination with the `%` operator (which returns remainders), this lets you do "grade school" division, where 3 goes into 7 just 2 times, with 1 left over. This is quite useful in many algorithms, so it's kept around. If you want to use floating-point division (where you get a `float` result), you need to make sure that at least one of your numbers in the division is a `float`.
Thus, you should do `2.0 / 3` or `2 / 3.0` if you want the `0.6666...` result in our example. And in your code, you should either do:
```
retTax = retTax / 100
retTip = retTip / 100
```
or else you should change your `convertInput()` function to always return floats no matter what. I suggest the latter:
```
def convertInput(meal, tax, tip):
retMeal = float(meal)
retTax = float(tax)
retTip = float(tip)
return retMeal, retTax, retTip
```
That way when you divide them by 100 later, you'll get a fraction. Otherwise, you could have ended up with an `int` result in tax or tip, and gotten a rounded-off value in your calculation.
There's another way to change Python's behavior regarding division, with the `from __future__ import division` statement in Python 2.x (which applies some of the Python 3.x rules). I won't go into it in detail now, but now you know what to Google if you want to read more about it. | 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 | 1 |
| 4 | 2 | 2 |
| 5 | 3 | 1 |
| 1 | 3 | 3 |
| 2 | 4 | 2 |
| 3 | 4 | 1 |
| 4 | 4 | 2 |
| 5 | 5 | 3 |
+----+---------+----------+--
```
So he select result will be only `order_id = 5`
Please help!
If you want to include orders with status 1 and exclude those with status 3, then you can use a similar idea:
```
having sum(case when status_id = 1 then 1 else 0 end) > 0 and
sum(case when status_id = 3 then 1 else 0 end) = 0
```
EDIT: I like to EXCLUDE those order\_id's:
- Which has only status 1 (not status 2)
- and
- which has status 3
Lets have table like this:
```
id--order-id-Prod---Status
------------------------------
1 1 a 1
6 1 b 2
7 1 a 2
8 1 b 1
9 2 a 1
10 3 a 1
11 3 b 1
12 3 a 2
13 3 b 2
14 4 a 1
15 4 b 1
16 5 a 1
17 5 b 1
18 5 a 2
19 5 b 2
20 5 a 3
21 5 b 3
```
Select should show only order\_id "5" | 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 exclude those with status 3, then you can use a similar idea:
```
having sum(case when status_id = 1 then 1 else 0 end) > 0 and
sum(case when status_id = 3 then 1 else 0 end) = 0
``` | 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 True L-Left=> Result: count is 4
How to get the answer.? plz help me to fix it. | 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 need to find more `CASE WHEN` statements for each column | 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 it correctly when using without.
can someone help to understand what i have missed? and what should the right way to print this characters so that they are ok everywhere?
```
$ python testu.py
Råbjerg
$ python testu.py > A
Traceback (most recent call last):
File "testu.py", line 3, in <module>
print u"Råbjerg"
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 1: ordinal not in range(128)
```
using debian Debian GNU/Linux 6.0.7 (squeeze) configured with:
```
$ locale
LANG=fr_FR.UTF-8
LANGUAGE=
LC_CTYPE="fr_FR.UTF-8"
LC_NUMERIC="fr_FR.UTF-8"
LC_TIME="fr_FR.UTF-8"
LC_COLLATE="fr_FR.UTF-8"
LC_MONETARY="fr_FR.UTF-8"
LC_MESSAGES="fr_FR.UTF-8"
LC_PAPER="fr_FR.UTF-8"
LC_NAME="fr_FR.UTF-8"
LC_ADDRESS="fr_FR.UTF-8"
LC_TELEPHONE="fr_FR.UTF-8"
LC_MEASUREMENT="fr_FR.UTF-8"
LC_IDENTIFICATION="fr_FR.UTF-8"
LC_ALL=
```
EDIT: from other similar questions seen later from the pointing done below
```
#!/bin/env python1
# -*- coding: utf-8 -*-
import sys, locale
s = u"Råbjerg" # >>> unicodedata.name(u"å") = 'LATIN SMALL LETTER A WITH RING ABOVE'
if sys.stdout.encoding is None: # if it is a pipe, seems python2 return None
s = s.encode(locale.getpreferredencoding())
print s
``` | 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](http://docs.python.org/2/using/cmdline.html#envvar-PYTHONIOENCODING) to tell Python what encoding to use in such cases, or encode explicitly. | 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\folder\which\has\file")
ftp.storbinary('RETR %s' % filename, open(filename, 'w').write)
```
I am getting the following error:
```
Traceback (most recent call last):
File "Windows\folder\which\has\file\MyFile.py", line 11, in <module>
ftp.storbinary('RETR %s' % filename, open(filename, 'w').write)
File "windows\folder\Python\lib\ftplib.py", line 466, in storbinary
buf = fp.read(blocksize)
AttributeError: 'builtin_function_or_method' object has no attribute 'read'
```
Also all contents of `MyFile.py` got deleted .
Can anyone advise what is going wrong.I have read that ftp.storbinary is used for uploading files using FTP. | 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 " + filename, open(filename, 'rb'))
```
also if you plan on using the ftp lib you should probably go through a tutorial, I'd recommend this [article](http://effbot.org/librarybook/ftplib.htm) from effbot. | 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 ' + filename, myfile)
myfile.close()
``` | 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 1.61680784158; 1367653785
9 2.63461385408; 1367687746
9 0; 1367688520
9 0.780442217152; 1367740313
9 3.18328461662; 1367773889
9 0.775471247616; 1367774978
```
Table2
```
ID b_ref1 ref_id2
9 1367602349;
9 1367740313;
9 1367774978;
2 1357110511;
2 1357186899;
2 1357195928;
2 1357199525;
```
In a nutshell need to copy ref\_id1 to ref\_id2 by comparing id and a\_ref1 with b\_ref1, Please let me know how to do that. | ```
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 join. (I want to reduce my joining result to specific columns only)
```
SELECT * FROM tbEmployees
JOIN tbSupervisor
ON tbEmployees.ID = tbSupervisor.SupervisorID
```
The syntax above will give me all columns which I don't want. I just want EmpName, Address from the tblEmployees table and Name, Address, project from the tbSupervisor table
I know this step:
```
SELECT EmpName, Address FROM tbEmployees
JOIN tbSupervisor
ON tbEmployees.ID = tbSupervisor.SupervisorID
```
but I am not sure about the supervisor table.
I am using SQL Server. | 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 , Jessica , 4 , 4/28/1991
```
Query: Show the adults and their children for only the adults with 2 or more children.
So far I have:
```
SELECT Adult.Adname, COUNT(Children.Adult_id) AS NumberOfChildren FROM (Adult
INNER JOIN Children
ON Adult.ID=Children.Adult_id)
GROUP BY Adname
HAVING COUNT (Children.Adult_id) > 2
UNION SELECT Adult.Adname, Children.Chname
FROM Adult LEFT JOIN Children ON Adult.[ID] = Children.[Adult_id]
WHERE Children.Adult_id <> NULL;
```
but the result still shows the adults and children for less than 2 ?? | 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 (Children.Adult_id) > 2)
``` | 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 options i cannot find yyy-mmm-dd. [HERE](http://www.itrain.de/knowhow/sql/tsql/datum/datumconvert.asp) Need help to get my yyyy-mm-dd string to date. | 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 search. I believe language settings can affect some of them. | [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).*
Now, I have a lookup table that looks like this:
```
Name Value
placeholder130 Dog
myPlaceholder Cat
oneMore Cow
test Horse
```
*(Lookup table will contain anywhere from 10k to 100k records)*
I need to find the fastest way to join those placeholders from strings to a lookup table and replace with value. So, my result should look like this (1st row):
> This is some notes Dog this Cat, Cow. End.
What I came up with was to split each row into multiple for each placeholder and then join it to lookup table and then concat records back to original row with new values, but it takes around 10-30 seconds on average. | 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 extracts tokens from the input as *potential* tokens and uses that set to join to your lookup (dbo.Token below). It was far too much work to look for an occurrence of *any* of your tokens in each note.
I did a bit of perf testing using 50k tokens and 5k notes and this function runs really well, completing in <2 seconds (on my laptop). Please report back how this strategy performs for you.
**note:** In your example data the token format was not consistent (`##_#, ##_##, #_#`), I am guessing this was simply a typo and assume all tokens take the form of ##TokenName##.
```
--setup
if object_id('dbo.[Lookup]') is not null
drop table dbo.[Lookup];
go
if object_id('dbo.fn_ReplaceLookups') is not null
drop function dbo.fn_ReplaceLookups;
go
create table dbo.[Lookup] (LookupName varchar(100) primary key, LookupValue varchar(100));
insert into dbo.[Lookup]
select '##placeholder130##','Dog' union all
select '##myPlaceholder##','Cat' union all
select '##oneMore##','Cow' union all
select '##test##','Horse';
go
create function [dbo].[fn_ReplaceLookups](@input varchar(max))
returns varchar(max)
as
begin
declare @xml xml;
select @xml = cast(('<r><i>'+replace(@input,'##' ,'</i><i>')+'</i></r>') as xml);
--extract the potential tokens
declare @LookupsInString table (LookupName varchar(100) primary key);
insert into @LookupsInString
select distinct '##'+v+'##'
from ( select [v] = r.n.value('(./text())[1]', 'varchar(100)'),
[r] = row_number() over (order by n)
from @xml.nodes('r/i') r(n)
)d(v,r)
where r%2=0;
--tokenize the input
select @input = replace(@input, l.LookupName, l.LookupValue)
from dbo.[Lookup] l
join @LookupsInString lis on
l.LookupName = lis.LookupName;
return @input;
end
go
return
--usage
declare @Notes table ([Id] int primary key, notes varchar(100));
insert into @Notes
select 1, 'This is some notes ##placeholder130## this ##myPlaceholder##, ##oneMore##. End.' union all
select 2, 'Second row...just a ##test##.';
select *,
dbo.fn_ReplaceLookups(notes)
from @Notes;
```
Returns:
```
Tokenized
--------------------------------------------------------
This is some notes Dog this Cat, Cow. End.
Second row...just a Horse.
``` | 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 outer join Lookup as L
on L.Name = T.Value
where N.Number <= len(notes) and
substring('##' + notes, Number, 2) = '##'
order by N.Number
for xml path(''), type
).value('text()[1]', 'varchar(max)')
from Notes
```
[SQL Fiddle](http://sqlfiddle.com/#!3/66938/2)
I borrowed the string splitting from [this blog post by Aaron Bertrand](http://www.sqlperformance.com/2012/07/t-sql-queries/split-strings) | 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 = 'key-secret'
TWITTER_ACCESS_TOKEN = 'token'
TWITTER_ACCESS_TOKEN_SECRET = 'secret'
t = twython.Twython(app_key=TWITTER_APP_KEY,
app_secret=TWITTER_APP_KEY_SECRET,
oauth_token=TWITTER_ACCESS_TOKEN,
oauth_token_secret=TWITTER_ACCESS_TOKEN_SECRET,
client_args = {'proxies': {'http': 'proxy.company.com:10080'}})
```
now if I do
```
t = twython.Twython(app_key=TWITTER_APP_KEY,
app_secret=TWITTER_APP_KEY_SECRET,
oauth_token=TWITTER_ACCESS_TOKEN,
oauth_token_secret=TWITTER_ACCESS_TOKEN_SECRET,
client_args = client_args)
print t.client_args
```
I get only a {}
and when I try running
```
t.update_status(status='See how easy this was?')
```
I get this problem :
```
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
t.update_status(status='See how easy this was?')
File "build\bdist.win32\egg\twython\endpoints.py", line 86, in update_status
return self.post('statuses/update', params=params)
File "build\bdist.win32\egg\twython\api.py", line 223, in post
return self.request(endpoint, 'POST', params=params, version=version)
File "build\bdist.win32\egg\twython\api.py", line 213, in request
content = self._request(url, method=method, params=params, api_call=url)
File "build\bdist.win32\egg\twython\api.py", line 134, in _request
response = func(url, **requests_args)
File "C:\Python27\lib\site-packages\requests-1.2.3-py2.7.egg\requests\sessions.py", line 377, in post
return self.request('POST', url, data=data, **kwargs)
File "C:\Python27\lib\site-packages\requests-1.2.3-py2.7.egg\requests\sessions.py", line 335, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python27\lib\site-packages\requests-1.2.3-py2.7.egg\requests\sessions.py", line 438, in send
r = adapter.send(request, **kwargs)
File "C:\Python27\lib\site-packages\requests-1.2.3-py2.7.egg\requests\adapters.py", line 327, in send
raise ConnectionError(e)
ConnectionError: HTTPSConnectionPool(host='api.twitter.com', port=443): Max retries exceeded with url: /1.1/statuses/update.json (Caused by <class 'socket.gaierror'>: [Errno 11004] getaddrinfo failed)
```
I have searched everywhere. Tried everything that I possibly could. The only resources available were :
<https://twython.readthedocs.org/en/latest/usage/advanced_usage.html#manipulate-the-request-headers-proxies-etc>
<https://groups.google.com/forum/#!topic/twython-talk/GLjjVRHqHng>
<https://github.com/fumieval/twython/commit/7caa68814631203cb63231918e42e54eee4d2273>
<https://groups.google.com/forum/#!topic/twython-talk/mXVL7XU4jWw>
There were no topics I could find here (on Stack Overflow) either.
Please help. Hope someone replies. If you have already done this please help me with some code example. | 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 as I'm aware.
On top of that, reading a bit of Twython's [source](https://github.com/ryanmcgrath/twython/blob/master/twython/api.py#L102..L106) explains why `t.client_args` returns an empty dictionary. In short, if you were to instead print `t.client.proxies`, you'd see that indeed your proxies are being processed as they very well should be.
Finally, complaining about your workplace while on StackOverflow and linking to GitHub commits that have your GitHub username (and real name) associated with them in the comments is not the best idea. StackOverflow is indexed quite thoroughly by Google and there is little doubt that someone else might find this and associate it with you as easily as I have. On top of that, that commit has absolutely no effect on Twython's current behaviour. You're running down a rabbit hole with no end by chasing the author of that commit. | 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
```
if i keep
```
string = "abc shot0000 "
```
it works fine, i do need it to execute it only when the string ends with a space `\s`.
but if i keep
```
string = "abc shot0000 _"
```
then it doesn't wait for the space `\s` and executes the command. | 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 was possible to get the bash variables.
test.sh
```
#!/bin/bash
source env.sh
echo $test1
python pythontest.py
```
env.sh
```
#!/bin/bash
test1="hello"
```
pythontest.py
```
?
print test1 (that is what I want)
``` | 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 or even call a function in the shell script like in the following Python code:
```
import subprocess
def get_var(varname):
CMD = 'echo $(source myscript.sh; echo $%s)' % varname
p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True, executable='/bin/bash')
return p.stdout.readlines()[0].strip()
def call_func(funcname):
CMD = 'echo $(source myscript.sh; echo $(%s))' % funcname
p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True, executable='/bin/bash')
return p.stdout.readlines()[0].strip()
print get_var('myvar')
print call_func('print_myvar')
```
Note that both `shell=True` shall be set in order to process the shell command in `CMD` to be processed as it is, and set `executable='bin/bash'` to use process substitution, which is not supported by the default `/bin/sh`. | 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 either an aggregate function or the GROUP BY clause.
Does anybody know how can I deal with that error? | 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 by date2
order by date2 desc
```
or like this:
```
select top 20 d_date, date1, date2
from reestr_calculated
where reestr_id=2
group by d_date, date1, date2
order by date2 desc
``` | 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.MilestoneName,
IIF(Priority = 1, tbl3.BonusDaysFH,
IIF(Priority = 2, tbl3.BonusDaysFM,
IIF(Priority = 3, tbl3.BonusDaysFL))) AS BonusDaysAllotted
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.MilestoneDefID)
INNER JOIN project_active_status AS tbl4 ON tbl1.ProjectID = project_active_status.ProjectID)
WHERE tbl1.ChecklistDay = tbl3.ChecklistDayMin
AND tbl2.ChecklistDay = tbl3.ChecklistDayMax
AND tbl4.ProjectIsOpen = FALSE;
```
The error says **Syntax Error In Join Operation** and then it highlights milestone\_def right after the 2nd INNER JOIN. Funny thing is, if I switch this line...
```
INNER JOIN milestone_def AS tbl3 ON [@milestoneID] = milestone_def.MilestoneDefID)
```
with this line...
```
INNER JOIN milestone_def AS tbl3 ON [@milestoneID] = tbl3.MilestoneDefID)
```
I get the error **Join Expression Not Supported** and then it highlights...
```
[@milestoneID] = tbl3.MilestoneDefID)
```
But as you can see, in the first join...
```
INNER JOIN checklist_entries AS tbl2 ON tbl1.ProjectID = tbl2.ProjectID
```
I name it tbl2 and then use tbl2.ProjectID and the expression works just fine. Ultimately, I need to get this to work, regardless how how I name these things.
[@milestoneID] is a parameter passed into the query to match milestone\_def.MilestoneDefID | [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` clause references only an external variable, so isn't relevant to the `JOIN` operation, making this effectively a `CROSS JOIN` with a separate `WHERE` condition:
```
...
CROSS JOIN milestone_def AS tbl3
...
WHERE [@milestoneID] = milestone_def.MilestoneDefID
...
```
Looking at the bottom of your query, you have the actual join conditions for this table in the `WHERE` clause; these should be swapped into the `ON` clause, so that it actually specifies the `INNER JOIN` condition:
```
...
INNER JOIN milestone_def AS tbl3
ON tbl1.ChecklistDay = tbl3.ChecklistDayMin
AND tbl2.ChecklistDay = tbl3.ChecklistDayMax
...
WHERE [@milestoneID] = milestone_def.MilestoneDefID
...
```
It's certainly more logical that way, and it will possibly solve the problem Access's parser is having understanding your query. | 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.MilestoneDefID)
INNER JOIN project_active_status AS tbl4
ON tbl1.ProjectID = project_active_status.ProjectID
```
Notice you have aliased the table names. Therefore you must use those aliases instead of the table names in the `ON` clauses.
```
SELECT *
FROM
((checklist_entries AS tbl1
INNER JOIN checklist_entries AS tbl2
ON tbl1.ProjectID = tbl2.ProjectID)
INNER JOIN milestone_def AS tbl3
ON tbl1.[@milestoneID] = tbl3.MilestoneDefID)
INNER JOIN project_active_status AS tbl4
ON tbl1.ProjectID = tbl4.ProjectID
```
I don't know what `[@milestoneID]` is or where it comes from. My best guess is it's a field in `checklist_entries`, so I qualified it with the `tbl1` alias. | 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;340212343204;134530943204
```
I've seen some solutions for splitting one column into a specific number of columns, but not variable columns. The columns that have less data (2 series of strings separated by commas instead of 3) will have nulls in the third place.
Ideas? Let me know if I must clarify anything. | 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,
other_fields INT
);
CREATE TABLE entity_properties (
main_entity_id INT PRIMARY KEY,
property_value INT,
FOREIGN KEY (main_entity_id) REFERENCES main_entity(id)
);
```
`entity_properties.main_entity_id` is a [foreign key](http://en.wikipedia.org/wiki/Foreign_key) to `main_entity.id`.
Congratulations, you are on the right path, this is called [normalisation](http://en.wikipedia.org/wiki/Database_normalization). You are about to reach the [First Normal Form.](http://en.wikipedia.org/wiki/First_normal_form)
Beweare, however, these properties should have a sensibly similar nature (ie. all phone numbers, or addresses, etc.). Do not to fall into the dark side (a.k.a. the [Entity-Attribute-Value anti-pattern](http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model)), and be tempted to throw all properties into the same table. If you can identify several types of attributes, store each type in a separate table. | 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 hack if all the entries are the same size (not so easy if they are of different sizes). Do, however, think about the data structure because semi-colon (or comma) separated list is not a very good data structure. | 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` (on w32, I probably also need a disk-ID, like `C:`)
In order to not having to worry about path-separators, `os.join.path()` is obviously the tool of choice. But it seems that this will only ever create *relative* paths:
```
print("MYPATH: %s" % (os.path.join('etc', 'init.d'),)
MYPATH: etc/init.d
```
Adding a dummy first-element (e.g. `''`) doesn't help anything:
```
print("MYPATH: %s" % (os.path.join('', 'etc', 'init.d'),)
MYPATH: etc/init.d
```
Making the first element absolute obviously helps, but this kind of defeats the idea of using `os.path.join()`
```
print("MYPATH: %s" % (os.path.join('/etc', 'init.d'),)
MYPATH: /etc/init.d
```
**edit1:** using `os.path.abspath()` will only try to convert a relative path into an absolute path.
e.g. consider running the following in the working directory `/home/foo`:
```
print("MYPATH: %s" % (os.path.abspath(os.path.join('etc', 'init.d')),)
MYPATH: /home/foo/etc/init.d
```
So, what is the standard cross-platform way to "root" a path?
```
root = ??? # <--
print("MYPATH: %s" % (os.path.join(root, 'etc', 'init.d'),)
MYPATH: /etc/init.d
```
**edit2:** the question really boils down to: since the leading slash in `/etc/init.d` makes this path an absolute path, is there a way to construct this leading slash programmatically?
(I do not want to make assumptions that a leading slash indicates an absolute path) | 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
return drive+path
os.path.join(getRoot(), 'etc', 'init.d')
``` | 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: `/python/bin`
Windows: `C:\python\bin` | 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 makes any difference. | ## 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)
```
This method uses the [Audio](http://nbviewer.ipython.org/github/ipython/ipython/blob/38fd9b71f62c6c726871875d3bacfbdb4ffba13c/examples/IPython%20Kernel/Rich%20Output.ipynb#Audio) tag built into Newer versions of iPython/Jupyter.
### Note For Older Versions
Older versions without the Audio tag can use the following method.
Put this in a cell and run it before you want to play your sound:
```
from IPython.display import HTML
from base64 import b64encode
path_to_audio = "/path/to/snd/my-sound.mp3"
audio_type = "mp3"
sound = open(path_to_audio, "rb").read()
sound_encoded = b64encode(sound)
sound_tag = """
<audio id="beep" controls src="data:audio/{1};base64,{0}">
</audio>""".format(sound_encoded, audio_type)
play_beep = """
<script type="text/javascript">
var audio = document.getElementById("beep");
audio.play();
</script>
"""
HTML(sound_tag)
```
At the end of the cell you want to make a noise on completion put this:
```
HTML(play_beep)
```
How it works:
It reads a file from the filesystem using iPython's built in `open` and `read` methods. Then it encodes this into base64. It then creates an audio tag with the ID `beep` and injects the base64 data into it. The final piece of setup creates a small script tag that plays the sound.
This method should work in any browser that supports the HTML5 audio tag.
Note: if you'd rather not display the audio controls in your notebook, just remove the `controls` attribute from the variable named `sound_tag` | 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, re.IGNORECASE)
print m.group(0)
```
The desired output:
```
/profile/view?id=34232962&goback=%2Enmp_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1 trk=spm_pic
``` | 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_*1_*1 trk=spm_pic
``` | 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 supposed to do the same with MVC, rather use the Entity Framework (DbContext) to sync the data between the database and the models. Maybe I'm not fully understanding the logic behind this but I feel that its a waste of resources.
The current application I'm working on requires a lot of the same features as the nerd dinner application (I am currently studying the code) with a lot more search capabilities.
Could someone please give me a better understanding of why I should use the Entity Framework?
Thanks | 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 use EF Code-First, you can even do it by defining these classes in C#, and let Entity Framework set up your database so that you never need to touch SQL. Then, because your database and the tables in it are mapped as C# classes, you can add, query, update and delete entries in your database all from C# code. The main benefits are:
* All your logic in one place, in one language. This includes defining your types/tables, querying, insert and update, everything. This makes it easier to write, easier to debug, and easier to keep it all in source control.
* Your database entities are "plain old CLR objects" (POCOs). That means you can put them in a `List<T>`, you can give them constructors to do custom initialisation, you can use inheritance to simplify their structure, clarify their relationships and take advantage of polymorphism in your code... you can do anything you can do with a regular C# class, no mapping or conversion needed.
* You can use C# query syntax, either like this:
```
from x in table1
where x.foo == bar
select x.thing
```
or like this:
```
db.table1.x.Where(x => x.foo == bar).Select(x => x.thing);
```
Both give you compile-time type-checking and IntelliSense autocompletion, and both will generate equivalent SQL and only send the query to the database when you do something that needs to get the actual results, like `.ToList()`.
* Entity Framework's `DbContext` class acts like a snapshot of the database, applying any changes back the the database when you call `.SaveChanges()` on it. This makes it easy to use transactional access and the unit-of-work pattern, which basically means that if something goes wrong mid-operation, you can discard the whole set of changes and know that your database hasn't been messed up by a half-completed task.
There are drawbacks, mostly related to the performance penalty of taking snapshots and keeping them in sync, and the overhead of converting your C# into SQL (and sometimes it'll take more than you need into memory and do the operations there, but that can usually be avoided with a well-written query) but in many cases you won't notice the difference unless your database is enormous. For someone who's new to ASP.NET MVC, I would definitely recommend Entity Framework for database access; it'll take the hassle out of it and let you focus on the logic. | 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 boilerplate code. ORM's are there to map relational databases to objects to better match the data model the object model.
You're free to use smoke signals and carrier pigeons if you like. It might take you 10x longer to finish your app though. | 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","three"},
...
...
};
```
and accessing these by array[0], array[1] etc.
In python script, suppose i have listed these array elements in a text file like below, e.g. file.txt
```
Mac, char, list, one
John, char, list, three
...
...
```
Now i have to read the file.txt, and store them into my python script similar to array of structs and access accordingly. | 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"},
{"name": "John", "type": "char", "link": "list", "level": "three"},
...
...
]
```
To read this data from file into structure like #2:
```
import csv
XYZ = []
with open("data.csv") as csv_data:
entries = csv.reader(csv_data, delimiter=",")
# This can be done with list comprehension, but will be difficult to read
for entry in entries:
XYZ.append({
"name": entry[0],
"type": entry[1],
"link": entry[2],
"level": entry[3]
})
``` | ```
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 ascending order.
int sign = 0;
int temp = 0;
int temp2 = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length -1; j++){
if (nums[j] > nums[j+1]) {
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
//prepare for new array to actually do the wacky sort.
System.out.println();
int firstPointer = 0;
int secondPointer = nums.length -1;
int[] newarray = new int[nums.length];
int size = nums.length;
//increment by two taking second slot replacing the last (n-1) term
for (int i = 0; i < nums.length -1; i+=2) {
newarray[i] = nums[firstPointer++];
newarray[i+1] = nums[secondPointer--];
}
//store those values back in the nums array
for (int i = 0; i < nums.length; i++) {
nums[i] = newarray[i];
}
}
```
My goal is to do the same thing but in python, except backwards. Any ideas on how to convert that last for loop that does the wackysort into python and make it go backwards? | ```
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/library/functions.html#zip):
```
>>> list(zip([4, 3, 2, 1], [1, 2, 3, 4]))
[(4, 1), (3, 2), (2, 3), (1, 4)]
```
You can see we have almost the list we want, we have a problem: these are tuples. we want to flatten them.
```
>>> (4, 1) + (3, 2) + (2, 3) + (1, 4)
(4, 1, 3, 2, 2, 3, 1, 4)
```
Oh. That's nice. But how to do it inside the list? Simple: use [`sum()`](http://docs.python.org/2/library/functions.html#sum), which does exactly this - adding many things together. Only we need to give it something to start with - an empty tuple `()`:
```
>>> sum([(4, 1), (3, 2), (2, 3), (1, 4)], ())
(4, 1, 3, 2, 2, 3, 1, 4)
```
But the we don't want the second half, so let's remove it. We know he list is exactly twice too long, yes?
```
>>> (4, 1, 3, 2, 2, 3, 1, 4)[:len(nums)]
(4, 1, 3, 2)
```
That's it.
---
Another option:
```
from itertools import chain, islice
a = list(islice(chain.from_iterable(zip(nums, reversed(nums))), len(nums)))
``` | 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.com/fusiontables/v1/query?sql=>**SELECT%20ATCOCode%20FROM%2015n7Rpi190vjrPcmbiT\_hRcZ9JbXE8a\_I1euHyg%20WHERE%20ATCOCode%20STARTS%20WITH%20198**%20&key=AIzaSyALgi-LNGdOQ-yWXAjnIsBXY7GDUHt2kIs | 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 to be able to modify it. The basic select statement that I have so far is a follows:
```
select count(id)
from testComments
where comments like('%' + char(13) + char(10) + char(13) + char(10) + '%')
```
This query will find the results
```
"This is a entry in the testComments crlf
crlf
In the comments field that works"
```
Although the query will not find the results if the comment is listed as follows:
```
"This is an entry in the testComments crlf
crlf
crlf
That will not work"
```
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? | 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) + char(10) + char(13) + char(10) + '%')
or comments like('%' + char(10) + char(10) + '%')
or comments like('%' + char(13) + 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:
```
"This is an entry in the testComments crlf
crlf
That will not work"
```
Or this:
```
"This is an entry in the testComments crlf
crlf
crlf
crlf
crlf
That will not work"
```
**COUNT will still return 1!** (If you have one record that has this string)
**EDIT:** If you literally want to count the characters for each row, here you go:
```
SELECT LEN(REPLACE(myColumn, 'yourCharacter', '')) FROM ...
``` | 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 longer elements. I don't want `"foo/bar"`, as it is contained in `"foo/bar/baz"` and `"foo/bar/qux"`. I've been trying nested for and if statements here but I can't seem to get it right. Can anybody point me in the right direction? | 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('/')
if parts[0] == '':
raise ValueError("can't handle rooted directory %s" % path)
parent = '/'.join(parts[:-1])
parents[parent] = True
return [path for path in dirlist if path not in parents]
```
Basically, all "parent directory" names are put into a dictionary, and then we filter away those names. In the case of "foo/bar/baz" and "foo/bar/quux", the parent path (foo/bar) is entered twice, but we don't really care.
Edit: to fix the point noted by Omri Barel, instead of just using `parts[:-1]`:
```
while parts:
parts.pop() # strip last path component
parent = '/'.join(parts)
parents[parent] = True
```
This strips the last component and enters the parent. (I've deliberately entered the empty string here, it's a little simpler that way.) | 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 < length - 1) and (l[i] not in l[i + 1])]
new_list.append(l[-1]) // Append last element (as it will always be there).
print new_list
```
*Output*:
```
['fo/bar', 'foo/bar/baz/abc', 'foo/bar/qux/abc']
``` | 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, as shown in example below
```
key 1 : (0,) , value 1 : kvalue = 8 kweight = 4
key 2 : (1,) , value 2 : kvalue = 10 kweight = 5
key 3 : (2,) , value 3 : kvalue = 15 kweight = 8
```
1. Is there any good data structure to store the data above?
2. How can I convert (0,) into a key (of string) ?
3. I'd also need to sort the list by kweight later on, is it possible to use a data structure which can call some python sort function?
---
EDITED: I think I should extend the example above. I want to store, let say, (0,1,2) as key 7, with 2 values for this key : kvalue = -1, and kweight = 9
```
key 1 : (0,) , value 1 : kvalue = 8 kweight = 4
key 2 : (1,) , value 2 : kvalue = 10 kweight = 5
key 3 : (2,) , value 3 : kvalue = 15 kweight = 8
key 4 : (0, 1) , value 4 : kvalue = 18 kweight = 9
key 5 : (0, 2) , value 5 : kvalue = -1 kweight = 4
key 6 : (1, 2) , value 6 : kvalue = -1 kweight = 5
key 7 : (0, 1, 2) , value 7 : kvalue = -1 kweight = 9
``` | > 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 directly.
> I'd also need to sort the list by kweight later on, is it possible to use a data structure which can call some python sort function?
```
sorted(dictofnamedtuples.values(), key=operator.attrgetter('kweight'))
``` | 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 stop them in tandem, with the priorities regulating their start and stop order.
* Write an [event listener](http://supervisord.org/events.html) that listens for `PROCESS_STATE` `STARTING`-to-`RUNNING` transition and `STOPPING` events for `A`, then instruct `supervisord` to start and stop `B` according to those events. Have `A` autostart, but disable autostarting for `B`, so that the event handler controls it. | 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 started, and then starts `B`. For example, if you have a PostgreSQL database and a server that shouldn't start before PostgreSQL:
```
[program:server]
autorestart=true
command=/.../start-server.sh
[program:postgres]
user=postgres
autorestart=true
command=/usr/lib/postgresql/9.3/bin/postgres ...
```
And then inside `start-server.sh`:
```
#!/bin/bash
# Wait until PostgreSQL started and listens on port 5432.
while [ -z "`netstat -tln | grep 5432`" ]; do
echo 'Waiting for PostgreSQL to start ...'
sleep 1
done
echo 'PostgreSQL started.'
# Start server.
echo 'Starting server...'
/.../really-start-the-server
``` | 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 giving me wrong answer
for example in above
28 is sunday of july week, so as per my need i should get 22 07 2013
but as by default sql server take Sunday as first day of week
it giving me 29-07-2013
I have also tried
```
Set DateFirst 1
```
went through
<http://social.msdn.microsoft.com/Forums/sqlserver/en-US/8cc3493a-7ae5-4759-ab2a-e7683165320b/problem-with-datediff-and-datefirst>
dint help me,
i hope to get help here from the experts
Thank you | 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` settings are in effect. All that it does depend on is that 29th July 2013 was a Monday. You never change that fixed date. | 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 reason why though.
I found this page that documents [how database connections are handled in ColdFusion](http://helpx.adobe.com/coldfusion/kb/database-connections-handled-coldfusion.html). Note that the "Maintain Database Connections" setting is set for each data source.
Here is the section related to connection pooling from that page (in case it goes away):
> **If the "Maintain Database Connections" is set for a data source, how does ColdFusion Server maintain the connection pool?**
>
> When "Maintain Database Connections" is set for a data source, ColdFusion keeps the connection open after its first connection to the database. It does not log out of the database after this first connection. You can change this setting according to the instructions in step d above. Another setting in the ColdFusion Administrator, called "Limit cached database connection inactive time to X minutes," closes a "maintained" database connection after X inactive minutes. This setting is server wide and determines when a "maintained" connection is finally closed. You can modify this setting by going to the "Caching" tab within the ColdFusion Administrator. The interface for modifying the "Limit cached database connection inactive time to X minutes" looks like the following:
>
> 
>
> If a request is using a data source connection that is already opened, and another request to the data source comes in, a new connection is established. Since only one request can use a connection at any time, the simultaneous request will open up a new connection because no idle cached connections are available. The connection pool can increase up to the setting for simultaneous connections limit which is set for each data source. This setting, called, "Limit Connections," is in the ColdFusion Administrator. Click on one of the data source tabs and then click on one of your data sources. Click on "CF Settings" and put a check next to "Limit Connections" and enter a number in the sentence, "Enable the limit of X simultaneous connections." Please note that if you do not set this under the data source setting, ColdFusion Server will use the server wide "Simultaneous Requests" setting.
>
> At this point, there is a pool of two database connections that ColdFusion Server maintains. Each connection remains in the pool until either the "Connection Timeout" period is reached or exceeds the inactivity time. If neither of the first two options are implemented, the connections remain in the pool until ColdFusion is restarted.
>
> The "Connection Timeout" setting closes the connection and eliminates it from the pool whether or not it has been active or inactive. If the process is active, it will not terminate the connection. You can change this setting by going to "CF Settings" for your data source in the ColdFusion Administrator. Note: Only the "Cached database connection inactive time" setting will end the connection and eliminate it from the pool if it hasn't been used. You can also use the "Connection Timeout" to override the"Cached database connection inactive" setting as it applies only to a single data source, not all data sources. | 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 both pools. As pool access is single-threaded for each pool - including the time taken to run the verify - have 2 pages each accessing a different data source , request both. If they complete after 1 minute it's 2 pools, if one page takes 1 minute and the other takes 2 minutes - it's one pool
As a side note, if during this 1 minute verify you yank out the network cable (causing the jdbc socket to stay open forever waiting for a response ) your thread pool is now dead and you need to restart CF | 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 rabbits die after they have lived for m months.
Input of '6 3' should return 4, but it returns 3.
```
#run for n months, rabbits die after m months.
n, m = input("Enter months to run, and how many months rabbits live, separated by a space ").split()
n, m = int(n), int(m)
generations = [1, 1, 2] #Seed the sequence with the 1 pair, then in their reproductive month.
def fib(i, j):
count = 3 #we start at the 3rd generation.
while (count < i):
if (count < j):
generations.append(generations[count-2] + generations[count-1]) #recurrence relation before rabbits start dying
else: #is just the fib seq (Fn = Fn-2 + Fn-1)
generations.append((generations[count-2] + generations[count-1]) - generations[(count-j)]) #Our recurrence relation when rabbits die every month
count += 1 #is (Fn = Fn-2 + Fn-1 - Fn-j)
return (generations[count-1])
print (fib(n, m))
print ("Here's how the total population looks by generation: \n" + str(generations))
```
Thanks =] | 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 something that depends on input).
So 3 potential cases. The regular fib sequence when we don't need to account for deaths, the first and second generations of deaths to initialize our final sequence with the recurrence relation Fn-2 + Fn-1 - Fn-(monthsAlive+1)
I'm certain there's a way to merge 1 or 2 of these checks and make the algorithm more efficient, but as of now it solved a large test case (90, 17) instantly and correctly. So I'm happy.
Lesson learned: Use the entire white-board.
```
#run for n months, rabbits die after m months.
n, m = input("Enter months to run, and how many months rabbits live, separated by a space ").split()
n, m = int(n), int(m)
generations = [1, 1] #Seed the sequence with the 1 pair, then in their reproductive month.
def fib(i, j):
count = 2
while (count < i):
if (count < j):
generations.append(generations[-2] + generations[-1]) #recurrence relation before rabbits start dying (simply fib seq Fn = Fn-2 + Fn-1)
elif (count == j or count == j+1):
print ("in base cases for newborns (1st+2nd gen. deaths)") #Base cases for subtracting rabbit deaths (1 death in first 2 death gens)
generations.append((generations[-2] + generations[-1]) - 1)#Fn = Fn-2 + Fn-1 - 1
else:
generations.append((generations[-2] + generations[-1]) - (generations[-(j+1)])) #Our recurrence relation here is Fn-2 + Fn-1 - Fn-(j+1)
count += 1
return (generations[-1])
print (fib(n, m))
print ("Here's how the total population looks by generation: \n" + str(generations))
``` | 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(months-2, dieAfter) - 1;
else
return fibRec(months-1, dieAfter) + fibRec(months-2, dieAfter)
- fibRec(months-(dieAfter+1), dieAfter);
}
``` | 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 inside the file)"
**My Code**
```
with open('MyText.txt', 'r') as f:
f.readline()
for line in f:
if 'Sample Text' in line:
print "I have found it"
f.seek(0)
f.readline()
for line in f:
if 'Time Taken' in line:
print line
print ' '.join(line.split())
f.close()
```
The code is working fine. My question is if this code can be made even better . Considering I am new to python, I am sure there would be a better way to code this.Can anyone sugggest alternative/faster approach for this. | 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 all closed...I use the following:
```
>>> s = """<a>link</a>
... <div id="something">
... <p style="background-color:#f00">paragraph</p>
... </div>"""
>>> re.findall('(?m)<.*>',s)
['<a>link</a>', '<div id="something">', '<p style="background-color:#f00">paragraph</p>', '</div>']
```
I understand that it grabs everything between the two carrot brackets, and that that becomes the whole line. What would I use to return the following:
```
['<a>','</a>', '<div id="something">', '<p style="background-color:#f00">','</p>', '</div>']
``` | 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:#f00">', '</p>', '</div>']
```
`*?` matches 0 or more of the preceeding value (in this case, `.`). This is a lazy match, and will match as few characters as possible. | ```
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 class to match everything but `<`, since that will never exist anywhere inside the tag excepting the end. | 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.findall('bbox')
elem.txt = '40.5,41.5,-12.0,-1.2'
```
my xml file:
```
<geoEtl>
<source>
<server>localhost</server>
<port>xxxx</port>
<db>vxxx</db>
<user>xxxx</user>
<passwd>xxxx</passwd>
</source>
<targetDir>/home/firstuser/</targetDir>
<bbox>-52.50,-1.9,52.45,-1.85</bbox>
<extractions>
<extraction>
<table>geo_db_roads</table>
<outputName>highways</outputName>
<filter>highway = 'motorway'</filter>
<geometry>way</geometry>
<fields>
<field>name</field>
</fields>
</extraction>
</extractions>
</geoEtl>
```
have tried a variety of ways to do of things i found here but it doesnt seem to be working. thanks.
The error I'm receiving is as follows:
```
line 20, in <module> elem.txt = '40.5,41.5,-12.0,-1.2' AttributeError: 'list' object has no attribute 'txt' –
``` | 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:
```
elem.txt = '40.5,41.5,-12.0,-1.2'
```
Is going to give you an error:
```
AttributeError: 'list' object has no attribute 'txt'
```
If you want to do something to every member of a list, you have to loop over it:
```
elems = tree.findall('bbox')
for elem in elems:
elem.txt = '40.5,41.5,-12.0,-1.2'
``` | 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 output to be:
```
John, Smith, Music
John, Smith, Current Affairs
David, Jones, Sport
Mark, Clark, Music
```
There are currently 15 interests in the table, leaving 2^15 possible permutations (I think).
The only thing I can think of at the moment is using a loop/cursor of some sort to build a mapping table with every permutation which I can then join to.
Is there another way? (I wonder if I can just put each interest in the table and use a function in the join criteria to see if the bit is set for that interest?)
Or could you assist with the SQL to build the mapping table? | 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` (6) will get matched up with `Music` (2) and `Current Affairs` (4).
Unfortunately this won't allow for indices (as far as I know). To allow for indices, you may have to resort to a join on the `Interest` table for each bit that is set (either using a loop or a CTE) (or changing your table structure). Obviously this would be a lot more complex, and, since there are currently only 15 interests, the difference in complexity should be hardly noticeable. | 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 ON i.ID > r.ID
)
SELECT t.name, t.lastname, r.interests
FROM RCTE_Interests r
INNER JOIN Table1 t ON r.id = t.id
OPTION (MAXRECURSION 0)
```
**[SQLFiddle DEMO](http://sqlfiddle.com/#!6/a0b17/1)**
**EDIT:** After additional info from comment, I see query is not really returning the exactly expected answer. Here is additional tweak to get records for multiple records for multi-interest IDs.
Simple - just join `RCTE_Interests` back to `Interests` table:
```
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 ON i.ID > r.ID
)
SELECT r.ID, i.Name AS interests
FROM RCTE_Interests r
INNER JOIN dbo.Interests i ON r.interests LIKE '%' + i.name + '%'
ORDER BY r.ID
```
**[SQLFiddle DEMO - multiple rows per interest](http://sqlfiddle.com/#!6/a0b17/4)**
**[SQLFiddle DEMO - multiple rows results](http://sqlfiddle.com/#!6/a0b17/2)** | 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 slow, or could something be wrong with my program? | `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 it if requested). The latter requires reading the source file for each stack frame. *This is the expensive step*.
To switch off the file context loading, set the `context` parameter to `0`:
```
inspect.stack(0)
```
Even *with* context set to 0, you still incur some filesystem access per frame as the filename is determined and verified to exist for each frame. | `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_back
```
Note that the last `frame.f_back` *is* `None`, and the loop will then end.
`sys._getframe(1)` should obviously not be used because it is an internal method.
As an alternative, `inspect.getouterframes(inspect.currentframe())` can be looped over, but this is expected to be slower than the above approach. | 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 20:06', '4']
['2013-06-26 20:06', '3']
['2013-06-26 20:06', '2']
['2013-06-26 20:08', '1']
OUTPUT:-
['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 20:06', '4']
['2013-06-26 20:06', '3']
['2013-06-26 20:06', '2']
['2013-06-26 20:08', '1']
```
Code:
```
import csv
#Now read the recent 8 entries and print
cr = csv.reader(open("trend.csv","rb"))
for row in cr:
#print only the recent most 8 entries
print row
``` | 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 collections import deque
>>> deque(range(10000),8)
deque([9992, 9993, 9994, 9995, 9996, 9997, 9998, 9999], maxlen=8)
```
The [csv.reader](http://docs.python.org/2/library/csv.html#csv.reader) object is an iterator. Apply a limited-length deque to the csv reader and you are good to go:
```
import csv
from collections import deque
with open('/tmp/trend.csv','rb') as fin:
deq=deque(csv.reader(fin),8)
for sub_list in deq:
print sub_list
```
With your 10 line example, this prints:
```
['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 20:06', '4']
['2013-06-26 20:06', '3']
['2013-06-26 20:06', '2']
['2013-06-26 20:08', '1']
``` | ```
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[-8:]:
print line
``` | 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 show\_groupmembers is "N", the user can't see any members of his group
(So Peter for example can't see any "Alpha"-Group users)
## And here is what I wanna do:
I have a current\_user, Peter and want to check if Peter can see Bob.
So it must be checked that
1. there are in the same group and
2. the flag "show\_groupmembers" of the urrent\_user (Peter) is 'Y'.
If this check fails (like in my example), the "EXIST SELECT 1" should
return nothing of course, else it should return something.
I've seen solutions that work, but only if the current\_user is only member of one group. As soon as he is more groups, the check above seems not to work.
Any Ideas how to perform this? I am totally stuck with that. | 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 users that Peter can see in a certain group:
```
select u1.user, u1.group, u1.show_groupmembers
from users u1
where u1.group = 'Alpha'
and exists ( select 1
from users u2
where u2.user = 'Peter'
and u2.show_groupmembers = 'Y'
and u1.group = u2.group )
```
If you want to check whether Peter can see Bob:
```
select u1.user, u1.group, u1.show_groupmembers
from users u1
where u1.user = 'Bob'
and exists ( select 1
from users u2
where u2.user = 'Peter'
and u2.show_groupmembers = 'Y'
and u1.group = u2.group )
``` | ```
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` but which I can type test?
```
foo = InvalidKeyNone()
print(type(foo))
>>> InvalidKeyNone
```
[EDIT]
I want to do this because I am creating a selection scheme on Python datastructures:
```
bar = select(".foo.bar.[1].x", {"foo":{"bar":[{"x":1}, {"x":2}], "baz":3})
print(bar)
>> 2
```
And I want to be able to determine whether I get a None because the selected value is None or because the key was not found.
HOWEVER it must return a (ducktyped) None that behaves exactly like a None. No exceptions or custom type returning here.
[EDIT]
Ok, so the consensus is: can't be done. Which although unsatisfactory is a valid answer. Since I really want the default behavior to have it return a None when the key is not present I think I will have the select eat a param to switch to exception throwing when appropriate. Thanks. | `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 `types.NoneType`
```
from types import NoneType
class InvalidKeyNone(NoneType):
pass
foo = InvalidKeyNone()
print(type(foo))
```
you'll get this error
> *Python 2*
>
> TypeError: Error when calling the metaclass bases
> type 'NoneType' is not an acceptable base type
>
> *Python 3*
>
> ImportError: cannot import name 'NoneType'
in short, you cannot inherit from `NoneType`
Anyway, why would want a class to inherit `NoneType`? | 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 to create a unique instance of object:
```
InvalidKey = object()
result = doSomething()
if result is InvalidKey:
...
``` | 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 = photo, anchor = NW)
e1 = Entry(canvas)
e2 = Entry(canvas)
game1 = PhotoImage(file="1.gif")
canvas.create_image(30, 65, image = game1, anchor = NW)
canvas.create_window(window = e1, x=10, y=10)
canvas.create_window(window = e2 , x=400, y=10)
canvas.update()
window.mainloop()
```
This is what I currently have but a entry box doesn't appear anywhere on the canvas. I know this probably isn't the most efficient way to create a game in python but I'm not familiar with any other way.
Thanks for your help.
EDIT: I have updated the code with the suggestions provided. I now have an issue with
```
IndexError: tuple index out of range
```
This is occurring at the lines below
```
canvas.create_window(window = e1, x=10, y=10)
canvas.create_window(window = e2, x=400, y=10)
```
EDIT: Okay I figured out what was wrong, I had to remove the x= and y= and just have the coordinates by themselves. The entry boxes now appear. | 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 what to do to run a code using Python 3.3.2 , here what i did:
```
C:\>virtualenv.exe env1
C:\>env1\Scripts\activate
```
now i don't know what to do after a folder was created its name env1 , i downloaded Python 3.3.2 and installed it in the same folder (env1) , is that correct ? then i try the following:
```
(env1) C:\>python3.3.2
```
I got the following :
```
'python3.3.2' is not recognized as an internal or external command,
operable program or batch file.
```
also i tried :
```
(env1) C:\>python python33
```
I got the following:
```
python: can't open file 'python33': [Errno 2] No such file or directory
```
As i mentioned , i stuck at this point , any help will be very appreciated.
Thanks | **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 Answer**:
> 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 what to do to run a code using Python 3.3.2 , here what i did:
>
> C:>virtualenv.exe env1
> C:>env1\Scripts\activate
> now i don't know what to do after a folder was created its name env1 , i downloaded Python 3.3.2 and installed it in the same folder (env1) , is that correct ? then i try the following:
After the folder is created you activate the virtual environment with the activate script you just said above. Then you can use the python interpreter and check your version.
> (env1) C:>python3.3.2
> I got the following :
>
> 'python3.3.2' is not recognized as an internal or external command,
> operable program or batch file.
> also i tried :
Just call python and check your version. You are using the sandbox created by virtualenv
> (env1) C:>python python33
> I got the following:
>
> python: can't open file 'python33': [Errno 2] No such file or directory
> As i mentioned , i stuck at this point , any help will be very appreciated.
This is a weird call. You are trying to execute the python33 file as you do when you use
```
python hello_world.py
```
It is just saying that the file doesn't exist. | 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 you double click on a script. | 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.
I can find this third menu but when I click on it using `element.click()` instead of expanding the menu and showing me its sub menu items it is showing consolidated contents of all the sub menu.
(Manually the expansion to sub menu is achieved by actually clicking on the small arrow icons before the group names)
So how do I actually click on this arrow icons to expand one of the group menu into sub menus.
This is the `HTML` corresponding to third group menu if it helps.
```
<div id="node_3_item" class="treeLabelSelected" style="padding-left: 0px; background-position: 0px -24px;">
<span style="background-position: 0px -24px;">XXX Groups</span>
</div>
<div style="display: none;"></div>
</div>
```
The `display: none` line is actually hiding the sub menu (as far as I can make out)
Any suggestion on how to handle will be appreciated.
Thanks
Note: I have already gone through several questions on SO related to interacting with hidden web elements but they differ with my situation. | 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.cwd("/my/location")
print filename
ftp.retrbinary('RETR %s' % filename, file.write)
```
**Error**
```
Traceback (most recent call last):
File "FTP.py", line 10, in <module>
ftp.retrbinary('RETR %s' % filename, file.write)
File "/usr/lib/python2.6/ftplib.py", line 399, in retrbinary
callback(data)
TypeError: descriptor 'write' requires a 'file' object but received a 'str'
```
Can anyone advise how to sort this. Also if possible where can I get some sample examples to learn Python FTP. | 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 we run it, we get 2013-08-01 and not 2013-08-03 as we want. What would be the solution? | 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 (date > now()) desc,
(case when date > now() then date end) ,
date desc
limit 1;
```
EDIT (in response to comment):
To handle "today" as the closest date, you need to convert `now()` to a date and use `>=`:
```
select *
from your_table
order by (`date` >= date(now())) desc,
(case when `date` >= date(now()) then `date` end) ,
`date` desc
limit 1;
```
The `order by` clause has three components. The first is a flag for any future date. This puts future dates first. The second two clauses order by date. The first orders the future dates in ascending order. The past dates all have the same value (`'NULL'`), so these are affected by the third clause which orders them in descending order. | ```
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 sequences containing all alphanumeric characters.
```
ROW1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
```
The second row will contain the same characters but mixed up. The original content will be translated to the second sequence before transmission and translated back after.
Now I'm wondering if this system could be safe. | 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 (substitution alphabet) is changed.
In your case, other simple attacks such as replay attacks may also be relevant. An adversary could replay a previously eavesdropped command and the recipient would consider it fully valid, even though the adversary knows nothing about the key. Note that this attack would be possible even if you used a proper cipher like AES in a naive fashion – it serves to demonstrate how important the security of the whole protocol is.
There is a reason why proper cryptographic standards and protocols are so complex. Fortunately for us, we don't have to reinvent or reimplement them ourselves. A good choice in this case may be [TLS](http://en.wikipedia.org/wiki/Transport_Layer_Security). There are libraries available for almost every platform.
Also worth checking out: <http://blogs.msdn.com/b/ericlippert/archive/2011/09/27/keep-it-secret-keep-it-safe.aspx> | 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
GO
```
I want to combine the 2 IF confitions and perform the update only when both of them are satisfied. Is there some way in which I can club 2 IF EXISTS? | 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
GO
``` | 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
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
GO
``` | 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
from threading import Thread
times = 1000
def inc(a):
b = 1
return a + b
def processes():
for i in xrange(times):
p = Process(target=inc, args=(i, ))
p.start()
p.join()
def threads():
for i in xrange(times):
t = Thread(target=inc, args=(i, ))
t.start()
t.join()
```
Tests:
```
>>> timeit processes()
1 loops, best of 3: 3.8 s per loop
>>> timeit threads()
10 loops, best of 3: 98.6 ms per loop
```
So, processes are almost **40 times slower** to create! Why does it happen? Is it specific to Python or these libraries? Or did I just misinterpreted the answer above?
---
**UPD 1.** To make it more clear. I understand that this piece of code doesn't actually introduce any concurrency. The goal here is to test the time needed to create a process and a thread. To use real concurrency with Python one can use something like this:
```
def pools():
pool = Pool(10)
pool.map(inc, xrange(times))
```
which really runs much faster than threaded version.
---
**UPD 2.** I have added version with `os.fork()`:
```
for i in xrange(times):
child_pid = os.fork()
if child_pid:
os.waitpid(child_pid, 0)
else:
exit(-1)
```
Results are:
```
$ time python test_fork.py
real 0m3.919s
user 0m0.040s
sys 0m0.208s
$ time python test_multiprocessing.py
real 0m1.088s
user 0m0.128s
sys 0m0.292s
$ time python test_threadings.py
real 0m0.134s
user 0m0.112s
sys 0m0.048s
``` | 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 shouldn't be waiting for them to complete. You should be using test programs more like these...
**fork.py**
```
import os
import time
def main():
for i in range(100):
pid = os.fork()
if pid:
#print 'created new process %d' % pid
continue
else:
time.sleep(1)
return
if __name__ == '__main__':
main()
```
**thread.py**
```
import thread
import time
def dummy():
time.sleep(1)
def main():
for i in range(100):
tid = thread.start_new_thread(dummy, ())
#print 'created new thread %d' % tid
if __name__ == '__main__':
main()
```
...which give the following results...
```
$ time python fork.py
real 0m0.035s
user 0m0.008s
sys 0m0.024s
$ time python thread.py
real 0m0.032s
user 0m0.012s
sys 0m0.024s
```
...so there's not much difference in the creation time of threads and processes. | 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 process returns.
The thread just allocates a new stack and thread structure, does the context switch, and returns when the work is done.
... that's why we use threads. | 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), then use the first 50 elements as the line number for the 50 training examples. The same with testing set.
This could be achieved easily in Matlab
```
fid=fopen(datafile);
C = textscan(fid, '%s','delimiter', '\n');
plist=randperm(100);
for i=1:50
trainstring = C{plist(i)};
fprintf(train_file,trainstring);
end
for i=51:100
teststring = C{plist(i)};
fprintf(test_file,teststring);
end
```
But how could I accomplish this function in Python? I'm new to Python, and don't know whether I could read the whole file into an array, and choose certain lines. | 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 perform this task and organize the output? | 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 result then checking if a name is in the query text. If the procedure refers to a table in a comment section, then this result will not be returned in the first query, but will be in the second and other answers given.
```
SELECT t.TABLE_NAME, s.ROUTINE_NAME
FROM INFORMATION_SCHEMA.TABLES t
INNER JOIN INFORMATION_SCHEMA.ROUTINES s ON
s.ROUTINE_NAME IN (SELECT referencing_entity_name
FROM sys.dm_sql_referencing_entities(TABLE_SCHEMA + '.' + TABLE_NAME, 'OBJECT'))
AND s.ROUTINE_TYPE = 'PROCEDURE'
WHERE t.TABLE_TYPE = 'BASE TABLE'
```
*edit*: Here's how to get the dependencies without the function. (I like this method the best)
```
SELECT DISTINCT t.name [TableName], p.name [ProcedureName]
FROM sys.objects t
LEFT JOIN sys.sql_dependencies d ON
d.referenced_major_id = t.object_id
LEFT JOIN sys.objects p ON
p.object_id = d.object_id
AND p.type = 'p'
WHERE t.type = 'u'
```
If your specific use is to just find any string that matches a table name, below will work:
```
SELECT t.TABLE_NAME, s.ROUTINE_NAME
FROM INFORMATION_SCHEMA.TABLES t
INNER JOIN INFORMATION_SCHEMA.ROUTINES s
ON CHARINDEX(t.TABLE_NAME, s.ROUTINE_DEFINITION) > 0
AND s.ROUTINE_TYPE = 'PROCEDURE'
WHERE t.TABLE_TYPE = 'BASE TABLE'
``` | 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 other objects too. If you just want procs, you can add `where so.xtype = 'P'` to your inner query. | 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" "Not an Edit"
```
I do the select like this
```
select table1.name, table1.description,
table2.name, table2.description
from table1,table2
where table2.id=table1.id and table2.`type`=22;
```
Will using an inner join be quicker or more efficient when selecting some 500+ rows at a time?
I've seen most examples using a inner join to do this. | 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("(","")
phone_number=phone_number.replace(")","")
phone_number=phone_number.replace(" ","")
phone_number=phone_number.replace("-","")
print phone_number
``` | 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 = "(251) 342-7344"*1000
>>> %timeit strs.translate(None, punctuation+whitespace)
10000 loops, best of 3: 116 us per loop #clear winner
>>> %timeit "".join([x for x in strs if x.isdigit()])
100 loops, best of 3: 4.42 ms per loop
>>> %timeit re.sub(r'[^\d]', '', strs)
100 loops, best of 3: 2.19 ms per loop
``` | 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 sample request is as below:
```
files = {'file': ('wavfile', open(filename, 'rb'))}
data = {'duration': duration}
headers = {'content-type': 'multipart/form-data'}
r = self.session.post(url, files=files, data=data, headers=headers)
```
But when I execute the above code, I get this error:
5:59:55.338 Dbg 09900 [DEBUG] Resolving exception from handler [null]: org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found.
So my questions are: 1) How can I see the content of the request being sent? Couldn't use wireshark, its not across the network.
2) why is the boundary missing in the encoded data? Did I miss anything, please point out. | 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 of my code. Is there any way that it can be speeded up?
```
def make_ellipse(x, x0, y, y0, theta, a, b):
c = np.cos(theta)
s = np.sin(theta)
a2 = a**2
b2 = b**2
xnew = x - x0
ynew = y - y0
ellipse = (xnew * c + ynew * s)**2/a2 + (xnew * s - ynew * c)**2/b2 <= 1
return ellipse
```
To give the context, it is called with `x` and `y` as the output from `np.meshgrid` with a fairly large grid size, and all of the other parameters as simple integer values.
Although that function seems to be taking a lot of the time, there are probably ways that the rest of the code can be speeded up too. I've put the rest of the code at [this gist](https://gist.github.com/robintw/5918148).
Any ideas would be gratefully received. I've tried using numba and `autojit`ing the main functions, but that doesn't help much. | 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 on my system. A similar trick can be used to compute the sine, either from theta or from cos(theta) (or vice versa).
Third, and less concretely, think about short-circuiting some of the final ellipse formula evaluations. For example, wherever `(xnew * c + ynew * s)**2/a2` is greater than 1, the ellipse value must be False. If this happens often, you can "mask" out the second half of the (expensive) calculation of the ellipse at those locations. I haven't planned this thoroughly, but see numpy.ma for some possible leads. | 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 = float(a)
b = float(b)
ellipse = (xnew * (c/a) + ynew * (s/a))**2 + (xnew * (s/b) - ynew * (c/b))**2 <= 1
```
What was 12 array operations is now 10 (plus 4 scalar ops). I'm not sure if numba's jit would have tried this. It might just do all the broadcasting first, then jit the resulting operations. In this case, reordering so common operations are done at once should help.
Furthering along, you can rewrite this again as
```
ellipse = ((xnew + ynew * (s/c)) * (c/a))**2 + ((xnew * (s/c) - ynew) * (c/b))**2 <= 1
```
Or
```
t = numpy.tan(theta)
ellipse = ((xnew + ynew * t) * (b/a))**2 + (xnew * t - ynew)**2 <= (b/c)**2
```
Replacing one more array operation with a scalar, and eliminating other scalar ops to get 9 array operations and 2 scalar ops.
As always, be aware of what the range of inputs are to avoid rounding errors.
Unfortunately there's no way good way to do a running sum and bail early if either of the two addends is greater than the right hand side of the comparison. That would be an obvious speed-up, but one you'd need cython (or c/c++) to code. | 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 CLUSTERED
(
[FeasibilityID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[OrderMaster](
[orderid] [int] IDENTITY(1,1) NOT NULL,
[feasibilityid] [int] NULL,
CONSTRAINT [PK_OrderMaster] PRIMARY KEY CLUSTERED
(
[orderid] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
```
I want to update the orderstatus in feasibility table to 'Closed' of all those records that are present in ordermaster table | 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 between : a date line AND (a diff line OR the end of the list).
```
...
Date: Wed Jul 3 22:32:36 2013 +0200
Here is the comment
of a commit
and I have to
extract it
diff --git a/dir.c b/dir.c
...
```
---
```
...
Date: Wed Jul 3 22:32:36 2013 +0200
Here is the comment
of a commit
and I have to
extract it
```
So I tried to do this :
```
commentBlock = re.compile("(?<=Date:.{32}\n\n).+(?=|\n\ndiff)", re.M|re.DOTALL)
findCommentBlock = re.findall(commentBlock,commitBlock[i]) # I've splited my git log everytime I find a "commit" line.
```
Problems are :
* the length of the date line can change. It can be `Date:.{32}` if the date is between the 1st to 9th or `Date:.{33}` if the date is 2 numbers long.
* I don't know how to say : "the comment block stops when a line starts by `diff` OR when it's the end of the list (or the file)".
P.S. I'm working on Python 3.x and I almost finished my script so I don't really wanna use a specific tool like `GitPython` (that only works on 2.x) | 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 consume (non-greedily) everything through the first newlines. (2) You don't need a lookahead assertion; a non-capturing group `(?:...)` will work fine.
* It's probably a good idea to make the captured wildcard non-greedy as well: `.+?`.
* You can indicate the end of a string in a regex with `\Z`. Thus, the non-capturing group means: (a) a line beginning with "diff " or (b) end of string.
* More details on regex features can be found in the excellent [Python docs](http://docs.python.org/3/library/re.html). | 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 and it does not treat the `\` as an escape sequence.
i.e. it prints exactly the string above.
**UPDATE:(AGAIN)**
I'm using *python 2.7.5* to reproduce, create a script, lets call it `myscript.py`:
```
import sys
print(sys.argv[1])
```
now save it and call it from the windows command prompt as such:
```
c:\Python27\python.exe myscript.py "abcd \x00 abcd"
```
the result I get is:
```
> 'abcd \x00 abcd'
```
P.S in my actual script, I am using option parser, but both have the same effect. Maybe there is a parameter I can set for option parser to handle escape sequences? | 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 dateDiff(dd, getDate(), 2 ) < test
ELSE
AND dateDiff(hh, getDate(), 2 ) < test
END
``` | 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
(foo<>0 AND DATEADD(hour,-2,GETDATE()) < test)
)
```
I can't think that you really intended those `DATEDIFF` calls. For example, today (3rd July 2013), this expression:
```
select CAST(DATEDIFF(dd,getdate(),2) as datetime)
```
Produces `1786-07-03`1. I'm assuming that `test` is a `datetime` and that the implicit conversion is being performed. Even if it's not, the numerical value of `DATEDIFF(dd,getdate(),2)` will always be a large negative number (unless or until it's run on a machine where `GETDATE()` returns a value from before the 20th Century)
---
1 Weirdly, I think 3rd July is the only day of the year on which the result will have the same month and day number. | 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. When I tested out 'test' as the string it outputted: `729458`. And when I used some online tools to convert, I got: `1372205`. | 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 there is plenty of room for optimisation here, but these two functions fit my needs:
Encode:
```
def base10Encode(inputString):
stringAsBytes = bytes(inputString, "utf-8")
stringAsBase10 = ""
for byte in stringAsBytes:
byteStr = str(byte).rjust(3, '\0') # Pad left with null to aide decoding
stringAsBase10 += byteStr
return stringAsBase10
```
Decode:
```
def base10Decode(inputString):
base10Blocks = []
for i in range(0, len(inputString), 3):
base10Blocks.append(inputString[i:i+3])
decodedBytes = bytearray(len(base10Blocks))
for i, block in enumerate(base10Blocks):
blockStr = block.replace('\0', '')
decodedBytes[i] = int(blockStr)
return decodedBytes.decode("utf-8")
``` | 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 the number of times it appears in both lists. So in this instance the code would list Tom 4 times and George times 2, Otherwise do nothing. I am a relative novice with coding, so any comments and help would be greatly appreciated. | ```
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, 'George': 2})
``` | 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 exactly once per external clock cycle. I would prefer to do this by somehow getting an interrupt from the external trigger without needing to use a fast polling loop. As far as I can tell, you can't just use a parallel port pin for an interrupt in a modern OS like Linux. Any ideas?
I am also thinking of generating broadcast packets on my network to notify other machines on the network that a trigger event has occurred. Due to network latency however there may not be enough time available in the 200ms period between triggers to do the acquisition. | 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.
Specifically, you could use the `TIOCMIWAIT` ioctl on the connected serial device to wait for a change on say the DCD line, which you would connect to your clock source.
Your user space application would be blocked waiting in the `TIOCMIWAIT` ioctl system call until there is a change of status on your clock line, at which point your app would become runnable and return from the ioctl. You might have to take care to ensure that you handle the case where you get a change of status interrupt on both rising and falling edges of your serial control signals. On some UART hardware (eg TL16C554A UART) it's possible that you'll only get an interrupt for a signal transitioning in a single direction. For the TL16C554A for example, the `TIOCMIWAIT` would only fall through on the rising edge of any Ring Indicate signal change.
Using the serial ioctls in this manner also has the advantage that you could use a USB-Serial dongle that supports `TIOCMIWAIT` if required (eg PL2303), and still retain user level software compatibility, albeit at the expense of increased latency due to USB.
If you require lower latency than can be achieved through user space, you'd be best to write a kernel driver module which can handle the timing and sampling, but I wouldn't suggest this route unless absolutely needed. It's easier to develop user space code.
Here's some incomplete sample C code snippets for using the `TIOCMIWAIT` ioctl.
```
int serial_fd = open(cmdline.device_name, O_RDWR | O_NONBLOCK | O_NOCTTY);
static const unsigned int ri_flag = TIOCM_RNG;
/* Set up serial port here using tcsetattr. Set CRTSCTS | CLOCAL to ensure status interrupts
* are generated.
*/
while (1) {
/* Wait for positive RI transition. TIOCMIWAIT takes a mask
* as argument, only returning when the appropriate signal has changed.
*/
if (ioctl(serial_fd, TIOCMIWAIT, ri_flag)) {
fprintf(stderr, "ioctl() failed waiting for RI edge [%s]\n", strerror(errno));
break;
}
/* Do sensor sampling here. You could use TIOCMGET to first verify that
* the clock line is in the expected state, eg high, before continuing.
*/
}
``` | 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:
# 1) create subdirectory called "files"
# 2) Populate "files" with file1, file2, file3
```
I am familiar with creating directories and files on Terminal's command line (Mac)
but I don't know how to call those commands from Python.
I would greatly appreciate advice on what those commands look like and how to use them. | 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.org/2/library/shutil.html) If you want to create a new file and wrrite from that from your script, a built-in [`open()`](http://docs.python.org/2/library/functions.html#open) will suffice.
Here's an example (note that it assumes that the "fruit" directories already exist in current directory *and* that subdirectory "files" does not exist yet):
```
import os
import shutil
directories = ['apple', 'orange', 'banana']
for fruit in directories:
os.mkdir("%s/files" % fruit)
with open("%s/files/like" % fruit, "w") as fp:
fp.write("I like %ss" % fruit)
fp.close()
with open("%s/files/hate" % fruit, "w") as fp:
fp.write("I hate %ss" % fruit)
fp.close()
with open("%s/files/dont_care_about" % fruit, "w") as fp:
fp.write("I don't care about %ss" % fruit)
fp.close()
``` | 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 contains two functions, `levenshtein()` and `geofind()`.
I would like to call these as:
```
import bagoftricks
x = bagoftricks.levenshtein(arg1,arg2)
```
Instead, I find I have to do this:
```
import bagoftricks
x = bagoftricks.bagoftricks.levenshtein(arg1,arg2)
```
Is there a better way to organize my packages in the first place, without the naming redundancy?
**UPDATE**
So, I followed Avichal Badaya's instructions below, and removed one level of nesting. That is, I now have...
```
bagoftricks
├── bagoftricks
│ ├── __init__.py
│ └── bagoftricks.py
├── README.md
└── setup.py
```
However, to call this package, I still have...
```
from bagoftricks.bagoftricks import geofind()
```
or
```
import bagoftricks
```
then
```
>>> bagoftricks.bagoftricks.geofind()
```
Rather than the desired....
```
from bagoftricks import geofind()
```
or
```
import bagoftricks
>>> bagoftricks.geofind()
```
I cannot remove that extra layer of nesting. When I try, by analogy, to remove one more level of nesting, so that my module is flat, as:
```
bagoftricks
├── __init__.py
├── bagoftricks.py
├── README.md
└── setup.py
```
I cannot build the package at all...
```
$ python setup.py build
running build
running build_py
error: package directory 'bagoftricks' does not exist
```
What's the secret for natural imports like standard packages use, without redundant top-level name imports? | 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:
```
bagoftricks
├── bagoftricks.py
├── README.md
└── setup.py
```
But I would not recommend that, mostly because you might want to reorganize things later, and it's easier if you already have a "proper" package. Also most people, tools and docs assume you have a package, so it's easier.
So the minimum would be:
```
bagoftricks
├── bagoftricks
│ └── __init__.py
├── README.md
└── setup.py
```
With `__init__.py` containing the functions you want to import. You then use these functions like this:
```
from bagoftricks import levenshtein, anotherfunction
```
Once that `__init__.py` becomes too big, you want to split it up in several modules, giving you something like this:
```
bagoftricks
├── bagoftricks
│ ├── __init__.py
│ ├── anothermodule.py
│ └── levenshtein.py
├── README.md
└── setup.py
```
Your `__init__.py` should then import the functions from the various modules:
```
from bagoftricks.levenshtein import levenshtein
from bagoftricks.anothermodule import anotherfunction
```
And then you can still use them like like you did before. | 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
```
from bagoftricks import geofind
import bagoftricks; bagoftricks.geofind(); bagoftricks.bagoftriks.geofind()
```
note that you can import as well a wild card
```
from bagoftricks import *
``` | 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
where CAST(Created as time) between '23:00:00' and '06:59:59'
```
But no results are returned.
Do I need to convert my times to datetimes? | 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 = [v1 = 'a', v2 = 'b']`
After this statement, I want:
`self.superVar = ['a', 'b']`
`self.superVar.v1 = 'a'`
`self.superVar.v2 = 'b'`
i.e. have 'superVar' be part of the name of the other variables.
As you might have guessed, what I really want to do is (2) above. (1) is just the first step and I would be happy even with that, if (2) is not possible.
Thanks a lot!
Gaurav | 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']
```
If you want to keep order, you can use an [ordered dictionary](http://docs.python.org/2/library/collections.html#collections.OrderedDict) from the collections module. | ```
>>> 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-file). | 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 please suggest how I can achieve this or correct way to do this in SQL. Thanks | 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 EmpName BossName
1 Abhijit Haris
2 Haris Sanal
```
so I have written the following query.
```
select E1.ID,E1.EmpName, E.EmpName as BossName from #tmpEmployee E inner join #tmpEmployee E1 on E1.EmpBossID=E.ID.
```
But the problem is the 3rd employee (Sanal) has no boss.
So I want this exact result:
```
ID EmpName BossName
1 Abhijit Haris
2 Haris Sanal
3 Sanal Null
```
What should I do? | 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 that all employees are listed.
Using a *left* join means that employees without a boss (eg the CEO) will still be listed, but will have a `null` for the `BossName` column.
If you truly want only employee listed if they have a boss, change the query to simply `JOIN` instead of `LEFT JOIN` (note that the default join type is `INNER`)
p.s. formatting your query doesn't hurt either: | 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
rama2
rama3
rama10
rama11
```
Please help me with the query to get the above output.
Thanks In advance | 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 the numeric part from a string using T-SQL?](https://stackoverflow.com/questions/10443462/how-to-get-the-numeric-part-from-a-string-using-t-sql) for ms sql) and order by it. But this is wrong way to go. | 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(response)
sites = hxs.select('//div[@class=\'footer\']')
items = []
for site in sites:
item = CarrierItem()
item['title'] = site.select('.//a/text()').extract()
item['link'] = site.select('.//a/@href').extract()
items.append(item)
return items
```
Is there a way I can debug this? I also tried to use the `scrapy shell` command with an url but when I input `view(response)` in the shell it simply returns `True` and a text file opens instead of my Web Browser.
```
>>> response.url
'https://qvpweb01.ciq.labs.att.com:8080/dis/login.jsp'
>>> hxs.select('//div')
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'NoneType' object has no attribute 'select'
>>> view(response)
True
>>> hxs.select('//body')
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'NoneType' object has no attribute 'select'
``` | 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>
When that doesn't work, I tend to go back to pure lxml.etree and dump the whole document's elements:
```
import lxml.etree
import lxml.html
class myspider(BaseSpider):
...
def parse(self, response):
self.log("\n\n\n We got data! \n\n\n")
root = lxml.etree.fromstring(response.body).getroot()
# or for broken XML docs:
# root = lxml.etree.fromstring(response.body, parser = lxml.etree.XMLParser(recover=True)).getroot()
# or for HTML:
# root = lxml.etree.fromstring(response.body, parser=lxml.html.HTMLParser()).getroot()
# and then lookup what are the actual elements I can select
print list(root.iter()) # this could be very big, but at least you all what's inside, the element tags and 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 /usr/local/bin/scrapy crawl quotes
```
3. Once in the debugger shell, open another shell instance and locate the path to your spider script (residing in your spider project)
```
$ realpath path/to/your/spider.py
/absolute/spider/file/path.py
```
This will output the absolute path. Copy it to your clipboard.
4. In the pdb shell type:
```
b /absolute/spider/file/path.py:line_number
```
...where line number is the desired point to break when debugging that file.
5. Hit `c` in the debugger...
Now go do some PythonFu :) | 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 multiples.
```
primes=list(range(2,2001))
p=2
while p<len(primes):
for x in range (p*p, len(primes), p):
primes.remove(x)
print(primes)
```
this prints: [...] 1989, 1991, 1993, 1995, 1997, 1999, 2000]
As you can see, the number 2000 is still there, and it should not be.
```
Traceback (most recent call last):
File "C:/Users/Are/PycharmProjects/Project Euler/10.py", line 8, in <module>
primes.remove(x)
ValueError: list.remove(x): x not in list
```
What's wrong with my reasoning?
I'm using PyCharm, is there a way for me to print the value for x at the time of the error? | 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=list(range(limit))
# ...
for x in range (p*p, limit, p):
```
Next problem is that you continue to loop with `while p<len(primes):`; you will generate numbers that are *no longer* part of the `primes` list, so they cannot be removed a second time. You can use exception handler to catch the exception:
```
try:
primes.remove(x)
except ValueError:
# already removed
pass
```
but you may want to rethink the `while` loop condition. | 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()` function from `random`` module, then you can also do:
```
>>> from random import random #imports only random() from random module
>>> random() #now use random() directly,
0.7979255998231091
``` | `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://docs.python.org/2.7/library/argparse.html) module of python to parse command line options is there but am not sure it will work as all arguments I provide are used by ryu-manager not my script.
Any help would be appreciated. | 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/tunnel_port_updater.py>
The Ryu 'getting started' page simply suggests:
`ryu-manager [--flagfile <path to configuration file>] [generic/application specific options…]`
<http://www.osrg.net/ryu/_sources/getting_started.txt> | 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_str = "You read my data :)"
param3_list = 1,2,3
param4_float = 3.14
```
2. Add the following code to your \_\_init\_\_ method. I did this to the simple\_switch\_13.py which comes with ryu:
```
from ryu import cfg
:
:
class SimpleSwitch13(app_manager.RyuApp):
def __init__(self, *args, **kwargs):
super(SimpleSwitch13, self).__init__(*args, **kwargs)
:
CONF = cfg.CONF
CONF.register_opts([
cfg.IntOpt('param1_int', default=0, help = ('The ultimate answer')),
cfg.StrOpt('param2_str', default='default', help = ('A string')),
cfg.ListOpt('param3_list', default = None, help = ('A list of numbers')),
cfg.FloatOpt('param4_float', default = 0.0, help = ('Pi? Yummy.'))])
print 'param1_int = {}'.format(CONF.param1_int))
print 'param2_str = {}'.format(CONF.param2_str))
print 'param3_list = {}'.format(CONF.param3_list))
print 'param4_float = {}'.format(CONF.param4_float))
```
3. Run Script
```
ryu-manager paramtest.py --config-file [PATH/TO/FILE/params.conf]
```
4. Profit
---
I referenced the following when putting together my answer, they can provide more detail (such as the oslo.config stuff, which I had never heard of prior to running into this issue).
More info on oslo.config: <http://www.giantflyingsaucer.com/blog/?p=4822>
Ryu email chain on this issue: <https://sourceforge.net/p/ryu/mailman/message/33410077/> | 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 any year that's why I allow them to input as they want. But now problem is they can insert mistakenly one member for the same year more than 2 times.
Please help me what can I do now here? | 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.fill((0,0,0))
if tkinput_1 == True:
tkinput_root1 = tk.Tk()
tkinput_root1.geometry("200x200")
tkinput_root1.title("How many teams?")
tkinput_input1 = tk.Entry(tkinput_root1)
tkinput_1 = False
pygame.display.update()
tkinput_root1.mainloop()
```
This was just me giving the tkinter text input box a shot in pygame. I was fairly sure it wouldn't work out properly but decided I'd try it anyway cause I had nothing to lose.
The tkinter screen does not show up till you've exited pygame.
So, I'm not asking if anyone knows how to fix the code, but instead if anyone knows the simplest way to create a text box in pygame. I know there is a textinput class module that can be imported. If you believe that is the easiest way to do it then can you walk me through it. If not could you please let me know what you think the easiest way is. It's a small program so I want to avoid a lot of heavy lines of code for a simple text box. Let me know what you guys think.
Thanks a lot in advance. | 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`
then do something like this:
```
inp = int(inputbox.ask(screen, 'Message')) #inp will equal whatever the input is
```
this is pretty much like `raw_input` but for pygame
its not the most aesthetically pleasing but im sure if you search around you can find maybe a nicer one | 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():
input_box.update(e)
```
and at the end, render it :
```
input_box.render(screen)
```
You can get the text with `input_box.text` at any moment | 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"` would return false. And so on...
I try this:
```
SELECT * FROM table WHERE charindex('IV=>0J',mapping)
```
But when I have `"IV=>0"`, it returns TRUE. But, it should return FALSE.
Thank You.. | 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_normal_form#Atomicity), and therefore the 1NF. Your current difficulties in querying and the future difficulties with performance that you are about to encounter all stem from this root problem... | 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 - so what is not similar between [A] & [B] is output. For example...
```
List [A]
1
2
3
List [B]
1
2
3
4
```
Using Python, I now want to compare the two lists to each other, and then output the differences.
```
Output = 4
```
Hopefully this makes sense! | ```
>>> 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
28508111 --> 28508111
``` | ```
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 2012 adds the [FORMAT](http://msdn.microsoft.com/en-us/library/hh213505.aspx) function which acceps a .NET format string. The following statement returns a string formatted using both techniques, although FORMAT is far more powerful:
```
SELECT ArticleNo,
REPLACE(str(ArticleNo ,8,0),' ','0'),
FORMAT(ArticleNo,'00000000')
FROM testtable
``` | 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 = name
def __hash__(self):
return hash(str(self.name))
def __eq__(self, other):
return str(self.name) == str(other,name)
def TestMethod():
test_Dict = {}
obj = Test('abc')
test_Dict[obj] = obj
print "%s" %(test_Dict[hash(str('abc'))].name) # expecting this to print "abc"
```
But it is giving me a key error message:
```
KeyError: 1453079729188098211
``` | 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 use the hash of the object but the object itself as key to access the dictionary value.
---
The examples you found like [python: my classes as dict keys. how?](https://stackoverflow.com/questions/5221236/python-my-classes-as-dict-keys-how?rq=1) or [Object of custom type as dictionary key](https://stackoverflow.com/questions/4901815/object-as-a-dictionary-key?rq=1) redefine `hash` and `eq` for specific purpose.
For example consider these two objects `obj = Test('abc')` and `obj2 = Test('abc')`.
```
test_Dict[obj] = obj
print test_Dict[obj2].name
```
This will throw a `KeyError` exception because obj and obj2 are not the same object.
```
class Test:
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(str(self.name))
def __eq__(self, other):
return str(self.name) == str(other.name)
obj = Test('abc')
obj2 = Test('abc')
test_Dict[obj] = obj
print test_Dict[obj2].name
```
This print `abc`. `obj` and `obj2` are still different objects but now they have the same hash and are evaluated as equals when compared. | 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.html) but I am trying to take it a step further by running it on my [personal hosting](http://www.i.madbro.org) site that I use to mess around with stuff like this.
My question is. What do I pass to `make_server(host, port, app)` as parameters and what url do I go to to check to see if it is running? I know it's a simple question, I'm just not used to this kind of work and the [documentation](http://docs.python.org/2/library/wsgiref.html#wsgiref.simple_server.make_server) isn't helping me.
**Bonus Points:**
What are the differences between running this on a local virtual environment and on proper hosting in terms of this kind of web application?
**important edit:** my provider is bluehost and since I don't have a dedicated IP, I am not allowed to open my own ports, which makes me wonder if this is even possible | 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 frameworks (Django) explicitly state that their built-in server should only be used for development.
In a production environment a Python application is usually served by a "industrial-grade" webserver, such as Apache or Nginx, which takes care of such issues as binding to low ports, dropping privileges, spawning multiple "worker" processes, dealing with virtual hosts, sanitizing malformed requests etc. The Python application is then run within the web server using something like `mod_wsgi` or `fcgi` for Apache or `uwsgi` for Nginx. Alternatively, your application runs as a separate process listening on 127.0.0.1:6543 (just like you do it locally) and the "front" web server proxies all requests to your application and back.
The point is: It may be tricky/impossible to host a Python application on a general purpose shared hosting unless your provider has explicit support for hosting WSGI applications (ask them for instructions)
Another point: for $5/mo these days you can get a nice dedicated virtual machine where you can install whatever your want and not share it with anyone. Hosting a Python website is much easier this way then dealing with shared hosting.
Ahh, and to answer the question: in a real production application the last 2 lines of the example:
```
server = make_server('0.0.0.0', 8080, app)
server.serve_forever()
```
will not be used - instead you configure the webserver so it knows that the `app` variable contains your wsgi application. Refer to the [next chapter](http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/project.html) in the docs for a more realistic example. | 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 one). As for specifics, just ask on their forums, they will help you out.
I initially made a django site there, and it was was my first online app, and I learned a decent amount.
Secondly, running your app online and on your own computer has very few differences, and these differences vary from webhost to webhost. So, you are going to have to be a bit more specific about what you want to know.
Hope this helps. | 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 white space "Operator A". Is there any way that I can alter this query so that results that contain white space in the operator name are excluded? | 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.