Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
```
if losttwice <= 2:
bet = _________ # <- Here
elif losttwice <= 5:
bet = bet * 2
else:
bet = startingbet
```
Can anyone help me to add one more thing to this? I would like to do a random 50% chance when `losttwice <= 2` (when I lost 1-2 times) for it to be `bet = startingbet` or `bet = bet * 2` based o... | ```
if losttwice <= 2:
bet = random.choice((startingbet, bet*2))
``` | `if random.random() > 0.5:` (and `import random` on the top) might be useful. You should be able to figure it out based on that. | Python: randomly assign one of two values | [
"",
"python",
""
] |
```
def temperature(weather):
'''(list of ints) -> list of strs
Modify and return list, replacing each temp in list for weather condition.
Hot being over 25 degrees, and cool being under.
'''
```
So, if I run temperature([24, 29, 11]), I want it to return ['cool', 'hot', 'cool'].
This is what I got. I think I'm crea... | While modifying the input list is usually a bad idea, if you really want to do that, use `enumerate` to get the indices and element access notation to change the list contents:
```
for index, degrees in enumerate(weather):
if degrees > 25:
weather[index] = 'hot'
else:
weather[index] = 'cold'
``... | Never mutate arguments passed to you.
```
temp = []
...
temp.append('hot')
...
temp.append('cool')
``` | Python: modifying list of ints to list of strs using for loop | [
"",
"python",
"list",
"for-loop",
""
] |
I have two lists
```
A=[['1','1'],['2','1'],['3','2']]
B=[['1','1'],['2','2']]
```
I want to perform A-B operation on these comparing only first element.
so A-B should give
```
Output=[['3', '2']]
```
So far, I could do only on row comparison
```
[x for x in A if not x in B]
```
which gives output as `[['2', '1... | This?
```
>>> [i for i in A if not any(i[0] == k for k, _ in B)]
[['3', '2']]
```
`any()` is used to check if the first element of each list is the same as any other value in every list in `B`. If it is, it returns True, but as we want the opposite of this, we use `not any(...)` | You can also use [`collections.OrderedDict`](http://docs.python.org/2/library/collections.html#collections.OrderedDict) and set difference here:
```
>>> from collections import OrderedDict
>>> dic1 = OrderedDict((k[0],k) for k in A)
>>> [dic1[x] for x in set(dic1) - set(y[0] for y in B)]
[['3', '2']]
```
Overall comp... | Difference between list of lists | [
"",
"python",
"list",
"compare",
""
] |
I am using a DBN (deep belief network) from [nolearn](https://pypi.python.org/pypi/nolearn) based on scikit-learn.
I have already built a Network which can classify my data very well, now I am interested in exporting the model for deployment, but I don't know how (I am training the DBN every time I want to predict som... | First, install [joblib](https://github.com/joblib/joblib).
You can use:
```
>>> import joblib
>>> joblib.dump(clf, 'my_model.pkl', compress=9)
```
And then later, on the prediction server:
```
>>> import joblib
>>> model_clone = joblib.load('my_model.pkl')
```
This is basically a Python pickle with an optimized ha... | Pickling/unpickling has the disadvantage that it only works with matching python versions (major and possibly also minor versions) and sklearn, joblib library versions.
There are alternative descriptive output formats for machine learning models, such as developed by the [Data Mining Group](http://dmg.org), such as th... | Python scikit-learn: exporting trained classifier | [
"",
"python",
"scikit-learn",
""
] |
I am trying to cast a string and a column value concatenated with the following sql commant:
```
CAST('Strign:'+[KlirAn] as NVARCHAR(max))
```
After executing this command i get the following error:
```
Msg 402, Level 16, State 1, Line 1
The data types varchar and ntext are incompatible in the add operator.
```... | Try the following:
```
'String:'+ CAST([KlirAn] as NVARCHAR(max))
``` | Try this
```
SELECT
'String:'+CONVERT(NVARCHAR(max),[KlirAn])
FROM table
``` | Cast string+ntext to nvarchar error | [
"",
"sql",
"sql-server",
""
] |
I would like the user to use control-c to close a script, but when control-c is pressed it shows the error and reason for close (which make sense). Is there a way to have my own custom output to the screen rather than what is shown? Not sure how to handle that specific error. | You could use `try..except` to catch KeyboardInterrupt:
```
import time
def main():
time.sleep(10)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('bye')
``` | use the [signal module](https://docs.python.org/3.5/library/signal.html) to define a handler for the SIGINT signal:
```
import signal
import sys
def sigint_handler(signal_number, stack_frame):
print('caught SIGINT, exiting')
sys.exit(-1)
signal.signal(signal.SIGINT, sigint_handler)
raw_input('waiting...')
``... | custom output when control-c is used to exit python script | [
"",
"python",
"error-handling",
""
] |
I want the end of a python script to open windows photo gallery from python
I try:
```
os.system("C:\\Program Files (x86)\\Windows Live\\Photo Gallery\\WLXPhotoGallery.exe");
```
I get:
```
'C:\Program' is not recognized as an internal or external command,
operable program or batch file.
```
any ideas how to get t... | Don't use `os.system()`. Use the [`subprocess` module](http://docs.python.org/2/library/subprocess.html#replacing-os-system) instead:
```
import subprocess
subprocess.call("C:\\Program Files (x86)\\Windows Live\\Photo Gallery\\WLXPhotoGallery.exe")
``` | As Martijn Pieters points out, you really should use `subprocess`. However, if you are really curious as to why your call didn't work, it's because calling `os.system("C:\\Program Files (x86)\\Windows Live\\Photo Gallery\\WLXPhotoGallery.exe");` is equivalent to typing this on the command line: `C:\Program Files (x86)\... | Open windows photo gallery from python | [
"",
"python",
"windows",
""
] |
As the answer that I got receive from my question which drive me nuts applying to my code for some reason, why it did not worked.
Here's a part of my data on table.

**Original Code:**
```
SELECT AGE_RANGE, COUNT(*) FROM (
SELECT CASE
W... | This should work: Think of each subquery as it's own table, so you just need to make sure to select all the columns you need. (CASE WHEN THEN END AS) is actually just a single column value. You will probably also want to group on location so you can get the same age ranges for different locations. (Ex. 11-15 in Canada ... | Try this
```
SELECT AGE_RANGE, COUNT(*), location FROM (
SELECT CASE
WHEN YearsOld BETWEEN 0 AND 5 THEN '0-5'
WHEN YearsOld BETWEEN 6 AND 10 THEN '6-10'
WHEN YearsOld BETWEEN 11 AND 15 THEN '11-15'
WHEN YearsOld BETWEEN 16 AND 20 THEN '16-20'
WHEN Yea... | Mysql select with CASE not retrieving other column value? | [
"",
"mysql",
"sql",
""
] |
I would like to count all possible combinations of each number from my table.
I would like my query to return something like this:
```
Number (Value) Count
1 39
2 450
3 41
```
My table looks like this:

from (select pk, val
from test
... | Assuming I did understand correctly your needs, I solved the problem in the following way.
My assumptions are that you need to count the number of occurrencies a single value appears on either val columns (val1,val2,val3,etc..) indifferently.
this is my test data:
```
CREATE TABLE Test(
pk int PRIMARY KEY IDENTITY(1,... | Counting the number of times a number comes up | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I'm writing a function that will return a list of square numbers but will return an empty list if the function takes the parameter ('apple') or (range(10)) or a list. I have the first part done but can't figure out how to return the empty set if the parameter n is not an integer- I keep getting an error: unorderable ty... | You can use the `type` function in python to check for what data type a variable is. To do this you would use `type(n) is int` to check if `n` is the data type you want. Also, `map` already returns a list so there is no need for the cast. Therefore...
```
def Squares(n):
squareList = []
if type(n) is int and ... | You can chain all the conditions which result in returning an empty list into one conditional using `or`'s. i.e if it is a list, or equals `'apple'`, or equals `range(10)` or `n < 0` then return an empty list. ELSE return the mapResult.
```
def square(n):
return n**2
def squares(n):
if isinstance(n,list) or n ... | Python Squares Function | [
"",
"python",
"python-3.x",
""
] |
hi i have ssis package and following expression
which gives me todays date and time for file name
```
@[User::FilePath]+ "Bloomberg_"+REPLACE((DT_STR, 20, 1252)
(DT_DBTIMESTAMP)@[System::StartTime], ":", "")+".xls"
\\public\\Bloomberg_Upload\\Bloomberg_2013-07-05 005738.xls
```
I need to get one date previous like f... | If I understand you correctly you are just trying to work out how to obtain the previous day's date and if the previous day's date happens to be the weekend then get the last workday.
You almost had it right with your code, you just needed to change your weekday constant.
This code will check to see if it is Monday a... | Maybe it is better to use `GETDATE()`
and then you can do the minus like this:
```
DATEADD("day", -1, GETDATE())
```
Also have a look here:
[DATEADD (SSIS Expression)](http://msdn.microsoft.com/en-us/library/ms141719.aspx) | how do i select previous date using ssis expression? | [
"",
"sql",
"ssis",
""
] |
I have the following data in a SQL Table:

I need to query the data so I can get a list of missing "**familyid**" per employee.
For example, I should get for Employee 1021 that is missing in the sequence the IDs: 2 and 5 and for Employee 1027 should... | **Find the first missing value**
I would use the `ROW_NUMBER` [window function](http://msdn.microsoft.com/en-us/library/ms189461.aspx#sectionToggle3 "OVER Clause (Transact-SQL)") to assign the "correct" sequence ID number. Assuming that the sequence ID restarts every time the employee ID changes:
```
SELECT
e.id,
... | Here is one approach. Calculate the maximum family id for each employee. Then join this to a list of numbers up to the maximum family id. The result has one row for each employee and expected family id.
Do a `left outer join` from this back to the original data, on the `familyid` and the number. Where nothing matches,... | SQL query find missing consecutive numbers | [
"",
"sql",
"sql-server",
""
] |
Hi all im a beginner at programming, i was recently given the task of creating this program and i am finding it difficult. I have previously designed a program that calculates the number of words in a sentence that are typed in by the user, is it possible to modify this program to achieve what i want?
```
import strin... | Use [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter) for counting words and [open()](http://docs.python.org/2/library/functions.html#open) for opening the file:
```
from collections import Counter
def main():
#use open() for opening file.
#Always use `with` stateme... | To open files, you can use the [open](http://docs.python.org/2/library/functions.html#open) function
```
from collections import Counter
with open('input.txt', 'r') as f:
p = f.read() # p contains contents of entire file
# logic to compute word counts follows here...
words = p.split()
wordCount = len... | A program that opens a text file, counts the number of words and reports the top N words ordered by the number of times they appear in the file? | [
"",
"python",
"file",
"word-count",
""
] |
In Django 1.4 and above :
> There is a new file called `app.py` in every django application. It defines the scope of the app and some initials required when loaded.
Why don't they use `__init__.py` for the purpose? Any advantage over `__init__.py` approach? Can you link to some official documentation for the same? | As all the links you have provided clearly show, this is nothing at all to do with Django itself, but a convention applied by the third-party app django-oscar. | Even though the details are wrong (there's no app.py in new Django projects), the question is still valid.
`__init__.py` is imported implicitly when importing a sub-module. So if something in `__init__.py` executes automatically with side effects, you might run into unintended consequences. Doing everything in `app.py... | What is the purpose of app.py in django apps? | [
"",
"python",
"django",
"web",
""
] |
These is one keyword confliction issue in the query module of my application,please see if you can tell me a smart solution.
First,In query module,each query condition contains three parts in UI:
1.field name,its value is fixed,e.g origin,finalDest...
2.operator,it is a select list which includes "like","not like","... | ```
0 An ASCII NUL (0x00) character.
' A single quote (“'”) character.
" A double quote (“"”) character.
b A backspace character.
n A newline (linefeed) character.
r A carriage return character.
t A tab character.
Z ASCII 26 (Control+Z). See note following the table.
\ A backslash (“\”) character.
% ... | The code should begin attempting to stop SQL injection on the server side prior to sending any information to the database. I'm not sure what language you are using, but this is normally accomplished by creating a statement that contains bind variables of some sort. In Java, this is a `PreparedStatement`, other languag... | smart solution of SQL injection | [
"",
"mysql",
"sql",
"database",
""
] |
Hey I am running into an issue when trying to run a cron job with a python script from ubuntu. This is what I have done:
1.) Wrote a simple tkinter app: source for the code is from this url - <http://www.ittc.ku.edu/~niehaus/classes/448-s04/448-standard/simple_gui_examples/sample.py>
```
#!/usr/bin/python
from Tkinte... | I'm not sure what you expect to happen here. The cronjob won't have access to a display where it can display the GUI, so the button will never be displayed, so `print_this` will never be run
FWIW, when I tried to run your code I got an error:
```
File "./t.py", line 4
def __init__(self,parent):
^
Indentat... | In linux mint 17 I had to do the following:
Make the scripts executable
~$chmod +x script.py
You have to enable X ACL for localhost to connect to for GUI applications to work
~$ xhost +local:
Add the following line in the crontab "env DISPLAY=:0.0"
\* \* \* \* \* env DISPLAY=:0.0 /usr/bin/python /your-script-s... | Trying to run a python script from ubuntu crontab | [
"",
"python",
"ubuntu",
"cron",
"tkinter",
""
] |
I am new to pandas and I am struggling to figure out how to convert my data to a timeseries object. I have sensor data, in which there is a relative time index with reference to the beginning of the experiment. This is not in date/time format. All documentation that I have found online deals/starts with some sort of da... | You should construct pandas TimeSeries objects by parsing the timestamps to dateTime objects. This requires you to pick some arbitrary starting point
```
start = dt.datetime(year=2000,month=1,day=1)
time = datalvm['time'][1:]
floatseconds = map(float,time) #str->float
#floats to datetime objects -> this is you timese... | You can just do it using `cut` on the groupby (you can specify the bins if you want), or groupby however you want, using the data above (that's why I am reading via `StringIO`)
```
In [22]: df= pd.read_csv(StringIO(data), header=None, delimiter='\s+')
In [23]: df.columns = ['time','col1','col2','col3','col4']
In [24... | pandas timeseries with relative time | [
"",
"python",
"pandas",
"time-series",
""
] |
I have a simple script that graphs the TPR/SP tradeoff.
It produces a pdf like (note the placement of the x-axis numbers): 
The relevant code is likely:
```
xticks(range(len(SP_list)), [i/10.0 for i in range(len(SP_list))], size='small')
```
The wh... | You can call `autoscale()` after `xticks()`, which will set the new axes' limits automatically.
 | It is doing exactly what you told it to. The problem is a poor interaction of the default tick locator and your use of `xticks`. By default the locator tries to set a range to give you 'nice' tick locations. If you remove the `xticks` line, you will see that it gives you a range of `[0, 25]`. When you use `xticks` it p... | xticks ends placement of numbers on x-axis prematurely, i.e. the ticks do not reach the right end | [
"",
"python",
"python-2.7",
"matplotlib",
""
] |
I have the following variables:
```
query = "(first_name = ?) AND (country = ?)" # string
values = ['Bob', 'USA'] # array
```
I need the following result:
```
result = "(first_name = Bob) AND (country = USA)" # string
```
The number of substitutions varies (1..20).
What is the best way to do it in Ruby? | If you don't mind destroying the array:
`query.gsub('?') { values.shift }`
Otherwise just copy the array and then do the replacements.
**Edited:** Used gsub('?') instead of a regex. | If you can control the `query` string, the [String#%](http://www.ruby-doc.org/core-2.0/String.html#method-i-25) operator is what you need:
```
query = "(first_name = %s) AND (country = %s)" # string
values = ['Bob', 'USA'] # array
result = query % values
#=> "(first_name = Bob) AND (country = USA)"
```
You have to re... | What is the most elegant way in Ruby to substitute '?' in string with values in array | [
"",
"sql",
"ruby-on-rails",
"ruby",
"string",
""
] |
I know this question has been asked before but those questions typically lack specific details and result in answers that say something like "It depends what you are trying to do..." so the main gist of this app is that it retrieves remote data (ex. text) and object (ex. images).
Since PHP and python are the two progr... | Welcome to a *fun* area:
1. Watch out for urllib2: it doesn't check the certificate or the certificate chain. Use requests instead or use ssl library and check it yourself. See [Urllib and validation of server certificate](https://stackoverflow.com/questions/6648952/urllib-and-validation-of-server-certificate) Sometim... | ## GUI library
First of all, please leverage the work people have done to compile [this GuiProgramming list](http://wiki.python.org/moin/GuiProgramming).
One one the packages that stood out to me was [`Kivy`](http://kivy.org/#home). You should definitely check it out (at least the videos / intro). The `Kivy` project ... | Considerations for python gui toolkit for app that queries remote database? | [
"",
"python",
"tkinter",
"wxpython",
"pyqt",
"pygtk",
""
] |
What is the best way to handle return values when using multiple update statements in a stored procedure.
I am using this stored procedure in a data adapter and am trying to get the update result total.
I'm using **SQL Server 2008** and .NET 4.5
For example:
```
CREATE PROCEDURE [dbo].[usrsp_MessageConversation_del... | You want to do something like below:
```
CREATE PROCEDURE [dbo].[usrsp_MessageConversation_delete]
(
@fromMbrID int,
@toMbrID int
)
AS
BEGIN
SET NOCOUNT OFF;
DECLARE @RowCount1 INTEGER
DECLARE @RowCount2 INTEGER
DECLARE @TotalRows INTEGER
UPDATE mbr_Messages
SET fromDeleted = 1
WHERE (fromMbrID =... | If your stored procedure is short, I not really suggest to use any error handling.
But here is one example for error handling
```
IF @@ERROR <> 0
BEGIN
--your statement
return 12345; -- to mark your error location
END
```
More information about [@@Error](http://msdn.microsoft.com/en-us/library/ms188790%28v=... | sql multiple updates in stored procedure | [
"",
"sql",
"sql-server",
"sql-server-2008",
"stored-procedures",
""
] |
Lets say i have a tuple of list like:
```
g = (['20', '10'], ['10', '74'])
```
I want the max of two based on the first value in each list like
```
max(g, key = ???the g[0] of each list.something that im clueless what to provide)
```
And answer is ['20', '10']
Is that possible? what should be the key here?
Accordin... | Just pass in a callable that gets the first element of each item. Using [`operator.itemgetter()`](http://docs.python.org/2/library/operator.html#operator.itemgetter) is easiest:
```
from operator import itemgetter
max(g, key=itemgetter(0))
```
but if you *have* to test against integer values instead of lexographical... | You can use `lambda` to specify which item should be used for comparison:
```
>>> g = (['20', '10'], ['10', '74'])
>>> max(g, key = lambda x:int(x[0])) #use int() for conversion
['20', '10']
>>> g = (['42', '50'], ['30', '4'])
>>> max(g, key = lambda x:int(x[0]))
['42', '50']
```
You can also use `operator.itemegtt... | Python: Maximum of lists of 2 or more elements in a tuple using key | [
"",
"python",
"python-2.7",
"max",
""
] |
I have 3 tables : **champions, roles, champs\_to\_roles**
The champs\_to\_roles table looks like this :
```
|ID_champ|ID_role|
----------------
| 2| 2|
| 4| 5|
| 5| 3|
| 3| 2|
| 1| 1|
| 1| 2|
```
I'm trying to SELECT the ID\_champ WHERE ID\_role = 1 ... | Use two inner joins to the association table - one for each role type:
```
SELECT c.name
FROM champions c
JOIN champs_to_roles ctr1 ON ctr1.ID_champ = c.id AND ctr1.ID_role = 1
JOIN champs_to_roles ctr2 ON ctr2.ID_champ = c.id AND ctr2.ID_role = 2
```
By using a *inner* join, *both* rows in `champs_to_roles` must exi... | I would probably go with the solution by Bohemian, but for completeness there is also the possibility to use a count and check the number of roles returned from a subselect
```
SELECT c.name
FROM champions AS c
INNER JOIN
(
SELECT ID_champ, COUNT(DISTINCT ID_role) AS NumRole
FROM champs_to_roles
WHERE ID_... | Multiple required value for a WHERE clause? | [
"",
"mysql",
"sql",
""
] |
This is the problem I'm running into, instead of returning new\_word and printing it out it just prints 'None'
```
text = "hey hey hey,hey"
word = 'hey'
def censor(text,word):
new_word = ""
count = 0
if word in text:
latter_count = ((text.index(word))+len(word))
... | A function returns `None` if there is no return statement.
Probably while doing recursion, `if word in text:` is False, and so there is nothing to return. You also did not return the recursive step. You must *return* `censor(new_word,word)` | You're not returning in the first branch of the `if` toward the end. Change that to
```
if word in new_word:
return censor(new_word,word)
```
Your function will also return None if `word in text` is false, so you might want to add an `else` at the end to return an empty string or some other default value in that ... | Why does my python method print out 'None' when I try to print out the string that the method returns? | [
"",
"python",
""
] |
My stored procedure receives a parameter which is a comma-separated string:
```
DECLARE @Account AS VARCHAR(200)
SET @Account = 'SA,A'
```
I need to make from it this statement:
```
WHERE Account IN ('SA', 'A')
```
What is the best practice for doing this? | Create this function (sqlserver 2005+)
```
CREATE function [dbo].[f_split]
(
@param nvarchar(max),
@delimiter char(1)
)
returns @t table (val nvarchar(max), seq int)
as
begin
set @param += @delimiter
;with a as
(
select cast(1 as bigint) f, charindex(@delimiter, @param) t, 1 seq
union all
select t + 1, charindex(@de... | Try this one -
**DDL:**
```
CREATE TABLE dbo.Table1 (
[EmpId] INT
, [FirstName] VARCHAR(7)
, [LastName] VARCHAR(10)
, [domain] VARCHAR(6)
, [Vertical] VARCHAR(10)
, [Account] VARCHAR(50)
, [City] VARCHAR(50)
)
INSERT INTO dbo.Table1 ([EmpId], [FirstName], [LastName], [Vertical], [Accoun... | Parse comma-separated string to make IN List of strings in the Where clause | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have a python file (`my_code.py`) in `Home/Python_Codes` folder in `ubuntu`. I want to run it in python shell. How can I do that?
I do [this](https://stackoverflow.com/questions/7420937/run-program-in-python-shell)
`>>> execfile('~/Python_Codes/my_code.py')`
but it gives me path error | You should expand tilde(~) to actual path. Try following code.
In Python 2.x:
```
import os
execfile(os.path.expanduser('~/Python_Codes/my_code.py'))
```
In Python 3.x (no `execfile` in Python 3.x):
```
import os
with open(os.path.expanduser('~/Python_Codes/my_code.py')) as f:
exec(f.read())
``` | Importing your module will execute any code at the top indent level - which includes creating any functions and classes you have defined there.
```
james@Brindle:/tmp$ cat my_codes.py
def myfunc(arg1, arg2):
print "arg1: %s, arg2: %s" % (arg1, arg2)
print "hello"
james@Brindle:/tmp$ python
Python 2.7.5 (default,... | run python file in python shell | [
"",
"ubuntu",
"python",
""
] |
This is my situation:
I have 2 tables, **tickets** and **tickets-details**. I need to retrieve the info inside **"tickets"** and just the LAST reply from **"tickets-details"** for each ticket, then show em in a table. My problem is that **"ticket-details"** returns a row per each reply and I'm getting more than one ro... | I do not know Your datatabase model, but if ID is autoincremented you can extend your script with this condition:
```
SELECT ti.id_ticket,ti.title,tiD.Reply,ti.status
FROM tickets ti
INNER JOIN ticket-details tiD ON ti.id_ticket = tiD.id_ticket
WHERE user = '$id_user'
and tiD.id_ticket in (select max(a.id) from ... | Assuming that the max `id_ticketDetail` represents the most recent record in `ticket-details` you can try
```
SELECT ti.id_ticket,
ti.title,
tiD.Reply,
ti.status
FROM tickets ti JOIN
(
SELECT id_ticket, reply
FROM `ticket-details` d JOIN
(
SELECT MAX(id_ticketDetail) ma... | SQL INNER JOIN returning more rows than I need | [
"",
"mysql",
"sql",
""
] |
Set to string. Obvious:
```
>>> s = set([1,2,3])
>>> s
set([1, 2, 3])
>>> str(s)
'set([1, 2, 3])'
```
String to set? Maybe like this?
```
>>> set(map(int,str(s).split('set([')[-1].split('])')[0].split(',')))
set([1, 2, 3])
```
Extremely ugly. Is there better way to serialize/deserialize sets? | Use `repr` and `eval`:
```
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
```
Note that `eval` is not safe if the source of string is unknown, prefer `ast.literal_eval` for safer conversion:
```
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(... | The question is little unclear because the title of the question is asking about string and set conversion but then the question at the end asks how do I serialize ? !
let me refresh the concept of [Serialization](https://www.cs.uic.edu/~troy/fall04/cs441/drake/serialization.html) is the process of encoding an object,... | Convert set to string and vice versa | [
"",
"python",
"string",
"python-2.7",
"set",
""
] |
I am working on a python program. I want to take a user input which is less then 140 characters. If the sentence exceeds the word limit, It should just print the 140 characters. I am able to enter characters but this is what happens. I am new to python. How can I achieve this?
```
def isAlpha(c):
if( c >= 'A' and ... | ```
userInput = str(input("Enter The Sentense: "))
truncatedInput = userInput[:140]
``` | Why not just test for the `len`?
```
if len(input) > 140:
print "Input exceeds 140 characters."
input = input[:140]
```
You can also put up other errors using this or quit the program, if you want to. The `input = input[:140]` makes sure that only the first 140 characters of the string are captured. This is wra... | How to take user input for less then 140 characters? | [
"",
"python",
""
] |
I do not know what is the problem
```
SELECT
DP.CODE_VALEUR CODE,
MAX(VA.CODE_TYPE_VALEUR) CODE_TYPE_VALEUR,
MAX(VA.NOM_VALEUR) STOCK_NAME,
(SUM(COURS_ACQ_VALEUR) / SUM(QUANTITE_VALEUR)) CMP,
MAX(DP.CODE_COMPTE) CODE_COMPTE,
SUM(DP.QUANTITE_VALEUR) QTEVALEUR,
round(SUM(DP.VALORISATION_BOUR... | try to add
```
GROUP BY DP.CODE_VALEUR
``` | A SELECT list cannot include both a group function, such as AVG, COUNT, MAX, MIN, SUM, STDDEV, or VARIANCE, and an individual column expression, unless the individual column expression is included in a GROUP BY clause.
Drop either the group function or the individual column expression from the SELECT list or add a GRO... | Error code 937, SQL state 42000: ORA-00937: not a single-group group function | [
"",
"sql",
"oracle11g",
""
] |
It's possible to delete using join statements to qualify the set to be deleted, such as the following:
```
DELETE J
FROM Users U
inner join LinkingTable J on U.id = J.U_id
inner join Groups G on J.G_id = G.id
WHERE G.Name = 'Whatever'
and U.Name not in ('Exclude list')
```
However I'm interested in deleting both sid... | Nope, you'd need to run multiple statements.
Because you need to delete from two tables, consider creating a temp table of the matching ids:
```
SELECT U.Id INTO #RecordsToDelete
FROM Users U
JOIN LinkingTable J ON U.Id = J.U_Id
...
```
And then delete from each of the tables:
```
DELETE FROM Users
WHERE Id IN ... | The way you say is Possible in `MY SQL` but *not* for `SQL SERVER`
You can use of the "deleted" pseudo table for deleting the values from Two Tables at a time like,
```
begin transaction;
declare @deletedIds table ( samcol1 varchar(25) );
delete #temp1
output deleted.samcol1 into @deletedIds
from #temp1 t1
jo... | Is it possible to delete from multiple tables in the same SQL statement? | [
"",
"sql",
"sql-server",
"delete-row",
"cascading-deletes",
""
] |
Here is the issue I am facing. I have a User model that `has_one` profile. The query I am running is to find all users that belong to the opposite sex of the `current_user` and then I am sorting the results by last\_logged\_in time of all users.
The issue is that last\_logged\_in is an attribute of the User model, whi... | An index on gender is unlikely to be effective, unless you're looking for a gender that is very under-represented in the table, so index on last\_logged\_in and let the opposite gender be filtered out of the result set without an index.
It might be worth it if the columns were on the same table as an index on (gender,... | ```
add_index :users, :last_logged_in
add_index :profiles, :gender
```
This will speed up finding all opposite-sex users and then sorting them by time.
You can't have cross-table indexes. | Rails: Indexing and optimizing db query | [
"",
"sql",
"ruby-on-rails",
"ruby-on-rails-3",
"indexing",
""
] |
I have had a `python` script that uses `rpy2` internally. This script was working until very recently. However, it stopped working now. I got an error that I had not seen previously. I can reproduce the error with the following lines of code:
```
$ python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (A... | rpy2-2.2.5 belongs to the previous series (2.2.x), and was working with older versions of R (R keeps evolving).
The current releases of rpy2 are in the 2.3.x series (latest is 2.3.6), but they require Python 2.7, or Python 3.3 (if you want the latest R, you'll have to get a recent Python ;-) ) | [This page](http://thomas-cokelaer.info/blog/2012/01/installing-rpy2-with-different-r-version-already-installed/) describes a potential solution for this problem (at least, the problem described by the author looks very similar): apparently, rpy2 has to be recompiled and given the new version of R as an argument. | rpy2 not working after upgrading R to 3.0.1 | [
"",
"python",
"r",
"rpy2",
""
] |
I am trying to compare two rows in a csv.
For example:
```
abc, 2, foo, bar, baz
abc, 2, bar,baz, band
cab, 3, baz,bar, foo
cab, 3, baz,bar, foo
```
Is there way `csv` module or any module in python to check if the column 1 is same or different.
For example:
in the first two lines, we see `2` and in the third line w... | Something like this:
```
>>> from collections import Counter
>>> c = Counter()
with open('abc') as f:
reader = csv.reader(f, delimiter = ',', skipinitialspace = True)
for row in reader:
c[row[1]] += int(row[-1])
...
>>> c
Counter({'2': 21, '3': 9})
```
To find the columns use `itertools.group... | Have a look at the [pandas](http://pandas.pydata.org/) library, you can easily aggregate columns based on groups. For example if you have a csv like:
```
col1,col2,col3,col4,col5
abc,2,10,11,12
abc,2,7,8,9
cab,3,4,5,6
cab,3,1,2,3
```
You can group and sum based on the values in `col2` with just a couple of lines of c... | Comparing two lines in csv file - Python | [
"",
"python",
"linux",
"csv",
"numpy",
""
] |
Using Django 1.5.1. Python 2.7.3.
I wanted to do a unique together constraint with a foreign key field and a slug field. So in my model meta, I did
```
foreign_key = models.ForeignKey("self", null=True, default=None)
slug = models.SlugField(max_length=40, unique=False)
class Meta:
unique_together = ("foreign_key... | In Postgresql `NULL` isn't equal to any other `NULL`. Therefore the rows you create are not the same (from Postgres' perspective).
**Update**
You have a few ways to deal with it:
* Forbid the `Null` value for foreign key and use some default value
* Override the `save` method of your model to check that no such row ... | Add a `clean` method to your model, so you can edit an existing row.
```
def clean(self):
queryset = MO.objects.exclude(id=self.id).filter(slug=self.slug)
if self.foreign_key is None:
if queryset.exists():
raise ValidationError("A row already exists with this slug and no key")
else:
... | Django unique together constraint failure? | [
"",
"python",
"django",
"postgresql",
""
] |
I am reading two columns of a csv file using pandas `readcsv()` and then assigning the values to a dictionary. The columns contain strings of numbers and letters. Occasionally there are cases where a cell is empty. In my opinion, the value read to that dictionary entry should be `None` but instead `nan` is assigned. Su... | NaN is used as a placeholder for [missing data *consistently* in pandas](https://pandas.pydata.org/pandas-docs/dev/user_guide/gotchas.html#choice-of-na-representation), consistency is good. I usually read/translate NaN as **"missing"**. *Also see the ['working with missing data'](https://pandas.pydata.org/docs/user_gui... | `NaN` can be used as a numerical value on mathematical operations, while `None` cannot (or at least shouldn't).
`NaN` is a numeric value, as defined in [IEEE 754 floating-point standard](http://en.wikipedia.org/wiki/IEEE_floating_point).
`None` is an internal Python type (`NoneType`) and would be more like "inexistent... | What is the difference between NaN and None? | [
"",
"python",
"numpy",
"pandas",
"nan",
""
] |
I have 1034961 rows data from database(mysql) table.
structure..
table : tb\_blog\_image
```
| id(pk) | link(TEXT) | img_link(TEXT) |
| 1 |blogpost.com/aaa|http://sky.png |
| 2 |blogpost.com/aaa|http://girl.png |
| 3 |blogpost.com/aaa|http://cad.png ... | Ideally, you'd use the primary key, (id) within your program.
But failing that, an index on the link column would solve your problem. Right now, the query you are running requires that all one million rows from the table be loaded from disk, and then compared to your query string value. Using an index, this could be r... | You may be interested in the variables to be tuned for fine performances.
```
Set global thread_cache_size = 4;
Set global query_cache_size = 1024*1024*1024;
Set global query_cache_limit=768*1024;
Set global query_cache_min_res_unit = 2048;
Set long_query_time = 5;
```
Source:
**<http://www.snip2code.com/Snippet/117... | how to improve select performance in mysql? | [
"",
"mysql",
"sql",
"performance",
""
] |
I have been searching and although I find long and complicated (many features I do not need) on how to just simply have python have linux use the cat function to concatenate files to a single file.
From my reading apparently subprocess is the way to do this.
Here is what I have but obviously does not work :(
```
subp... | since `>` is a shell function you need to do `shell=True`
`subprocess.call("echo hello world > some.txt",shell=True)` ... works in windows at least
alternatively you can do somethign like
```
with open("redirected_output.txt") as f:
subprocess.call("/home/bin/cat some_file.txt",stdout=f)
``` | If you want to use cat and redirection > you must call a shell, for example via system:
```
from os import system
system("cat a.txt b.txt > c.txt")
```
However you must pay attention to code injection. | python concatenate files using subprocess | [
"",
"python",
"linux",
"concatenation",
""
] |
I need to compare two sets for equality.
I have an **Employee** table as
```
emp_id | Name
-----------------
1 Thomas
2 John
3 Jeff
.....
.....
```
and an **Employee\_Language** table
```
Emp_id | Language
------------------
1 English
1 French
2 Thai ... | ```
WHERE language IN('x','y') GROUP BY emp_id HAVING COUNT (*) = 2
```
(where '2' is the number of items in the IN clause)
So your whole query could be:
```
SELECT e.emp_Id
, e.Name
FROM Employee e
JOIN Employee_Language l
ON e.emp_id = l.emp_id
WHERE l.Language IN('English', 'French')
GROUP
BY... | I just Improved the Accepted Answer by removing the constant (2) in the 'HAVING' clause and parameterized the criteria .. hope this help someone
```
set @lst = 'English,French,Chinese' ;
SELECT e.emp_Id,Name
FROM Employee e
JOIN Employee_Language l
ON e.emp_id = l.emp_id
WHERE FIND_IN_SET(l.Language,@lst)
GROUP ... | Compare two sets in MySQL for equality | [
"",
"mysql",
"sql",
""
] |
I'm trying to read a column of numbers into python with the `csv` module. I get the following behavior:
```
import csv
f=open('myfile.txt','r')
reader=csv.reader(f)
print [x for x in reader] # This outputs the contents of "myfile.txt",
# broken up by line.
print [x for x in reader] # This... | Same reason here:
```
>>> li=[1,2,3,4,5,6,7,8,9]
>>> it=iter(li)
>>> print [x for x in it], [x for x in it]
[1, 2, 3, 4, 5, 6, 7, 8, 9], []
```
Note the empty list...
csv.reader is an [iterator](http://docs.python.org/2/glossary.html#term-iterator) that produces items from a container or sequence one by one until th... | The reason you can only go one way is because the file you passed it only goes one way, if you want loop over the csv file again you can do something like
```
>>> with open("output.csv", 'r') as f:
r = csv.reader(f)
for l in r:
print l
f.seek(0)
for l in r:
print l
```
that was a reall... | Why can I only use a reader object once? | [
"",
"python",
"csv",
"python-2.4",
""
] |
I'm newbie to sql.
There are two different tables with same columns and assume that Name unique.
**TABLE\_A**
```
Name | AGE
-----------
Toby | 2
Milo | 1
Achmed| 3
```
**TABLE\_B**
```
Name | AGE
-----------
Milo | 2
```
TABLE\_B is my superior table, If TABLE\_B name value contains in TABLE\_A, than TA... | You can use `FULL JOIN` to get all rows from both tables and `COALESCE` to give precedence to Table\_B if Name exists in both tables.
```
SELECT
COALESCE (b.Name, a.Name) as Name
,COALESCE (b.Age, a.Age) as Age
FROM Table_A a
FULL JOIN Table_B b ON a.Name = b.Name
```
**[SQLFiddle DEMO](http://www.sqlfiddle.com... | You could also eliminate any duplicates while using union, I think this would be faster than a full join:
```
SELECT Name, Age FROM Table_B
UNION
SELECT Name, Age FROM Table_A WHERE TABLE_A.NAME NOT IN (SELECT Name FROM Table_B)
ORDER BY Name;
``` | merging two tables with a query | [
"",
"sql",
"sql-server",
"t-sql",
"plsql",
"toad",
""
] |
I am using [this buildpack](https://github.com/arg0s/heroku-buildpack-python-ffmpeg-lame) (heroku-python-buildpack-ffmpeg-lame) for my app on heroku that uses ffmpeg to convert uploaded videos to .mp4. I had been using the version without libmp3lame, and since I switched I am getting the error
```
ffmpeg: error while... | Fortunately, I stumbled across [this similar question](https://stackoverflow.com/questions/13799636/why-changing-heroku-buildpack-for-existing-app-doesnt-run-bin-release), and I was able to see that all I needed to do was look at the bin/release file from the buildpack I was using and make sure the correct PATH and LD\... | I solved the problem like this
```
ln -s /usr/local/lib/libmp3lame.so.0 /usr/lib64/libmp3lame.so.0
``` | ffmpeg: error while loading shared libraries: libmp3lame.so.0: cannot open shared object file: No such file or directory | [
"",
"python",
"heroku",
"ffmpeg",
""
] |
I've been all day trying to solve the `test_errors()` function in "[Exercise 48: Advanced User Input](http://learnpythonthehardway.org/book/ex48.html)" of the book [Learn Python The Hard Way](http://learnpythonthehardway.org/book/).
`assert_equal()`, a function in the tests asks me for the tuples in order and I haven'... | The words in the test are in the same order going in as coming out. As such you need to re-order your `for`-loops to iterate over the input first:
```
value = []
for rompe in stringo.split():
for asigna in vocabulary:
for encuentra in asigna:
if encuentra[1] == rompe:
... | ```
for word in self.stringo.split():
for pair in vocabulary:
if pair[0][1] == word:
value.append(pair[0])
elif pair[1][1] == word:
value.append(pair[1])
elif pair[2][1] == word:
value.append(pair[2])
... | Learn Python the Hard Way, Exercise 48 | [
"",
"python",
"tuples",
""
] |
My regex is something like below
```
text = 'id 5 result pass
id 4 result fail
id 3 result fail
id 2 result fail
id 1 result pass'
for i in re.finditer('id (.+?) result (.+)', text):
id = i.group(1)
result = i.group(2)
print 'id'
... | A good way is (which will be faster than using a `lambda` in the sorted):
```
sorted(re.finditer(...,text),key=attrgetter('group'),reverse=True):
```
Or you could turn the iterator into a list and reverse it:
```
for i in reversed(list(re.finditer('id (.+?) result (.+)', text))):
``` | Assign the finditer call to a list and reverse it.
```
matches = list(re.finditer(...))
matches.reverse()
for i in matches:
# etc.
``` | how to reverse a regex in python? | [
"",
"python",
"regex",
"reverse",
""
] |
I have a list of data in ten columns as shown below. It has few thousands lines.
```
$1 $2 $3 $4 $5 $6 $7 $8 $9 $10
| 8455 105@O13 | 8132 101@H13 8131 101@O13 | 68.43
| 7490 93@O16 | 8868 110@H16 8867 110@O16 | 68.30
| 7561 94@O12 | 9185 114@H13 9184 114@O13 | 66.83
| ... | Try the following in awk. Split `$3` and `$6` into arrays based on the `@` separator and print if the first elements of each match
```
awk '{split($3, a, "@"); split($6, b, "@");if (a[1] == b[1]) print}'
```
Or more idiomatically
```
awk '{split($3, a, "@"); split($6, b, "@")}; a[1] == b[1]'
```
Or a quick Python 2... | Code for GNU [sed](/questions/tagged/sed "show questions tagged 'sed'"):
```
sed -r '/^\|\s+\S+\s+([0-9]+@).*\|.*\1/!d' file
```
---
Assuming there is a header of two rows:
```
sed -r '1,2p;/^\|\s+\S+\s+([0-9]+@).*\|.*\1/!d' file
``` | selecting lines according certain criteria | [
"",
"python",
"perl",
"awk",
""
] |
Suppose I have an ASOC-type table with the following entries:
```
+----------+----------+
| PERSON | SKILL |
+----------+----------+
| Bob | Java |
| Bob | Database |
| Sarah | Java |
| Sarah | HTML |
| Jane | Java |
| Jane | HTML |
| Jane | Database |
+----------+-... | ```
select a.person
from (select person from person_skills_asoc where skill = 'Java') a
(select person from person_skills_asoc where skill = 'Database') b
where a.person = b.person;
```
or
```
select a.person
from person_skills_asoc a, person_skills_asoc b
where a.person = b.person
and a.skill = 'Java'
and b... | In SQL Server for example you could use `INTERSECT`, apparently that's not available in MySQL (yet?). A possible solution using a self join (check the **[SQLFiddle](http://www.sqlfiddle.com/#!2/45d94/3)**):
```
SELECT P1.PERSON
FROM PERSON_SKILLS_ASOC AS P1
INNER JOIN PERSON_SKILLS_ASOC AS P2 ON P1.PERSON = P2.PERSO... | Retrieving rows that have multiple association entries | [
"",
"mysql",
"sql",
""
] |
My list of Dicts
```
[
{'town':'A', 'x':12, 'y':13},
{'town':'B', 'x':100, 'y':43},
{'town':'C', 'x':19, 'y':5}
]
```
My starting point is:
```
x = 2
Y =3
```
My maximum range:
```
mxr = 30
```
My function:
```
def calculateRange (x1, x2, y1, y2):
squareNumber = math.sqrt(math.pow ((x1-x2),2) + math.p... | Just use a loop:
```
for entry in inputlist:
entry['r'] = min(mxr, calculateRange(x, entry['x'], y, entry['y']))
```
Dictionaries are mutable, adding a key is reflected in all references to the dictionary.
Demo:
```
>>> import math
>>> def calculateRange (x1, x2, y1, y2):
... squareNumber = math.sqrt(math.pow... | I guess you're looking for something like this:
```
>>> lis = [
{'town':'A', 'x':12, 'y':13},
{'town':'B', 'x':100, 'y':43},
{'town':'C', 'x':19, 'y':5}
]
>>> x = 2
>>> y = 3
for dic in lis:
r = calculate(x,y,dic['x'],dic['y'])
dic['r'] = r
...
>>> lis = [x for x in lis... | Python iterate list of dicts and create a new one | [
"",
"python",
"dictionary",
""
] |
I am using a subquery to get the maximum id from a group.
The query is returning the correct `max(id)` from a group. But what I want as a result out of this table:
```
id--------Name--------GROUP------------Result
1---------ABC----------A----------------Pass
2---------DEF----------B----------------FAIL
3---------G... | @Narayan-this will give the max(id) for each group for students with Result as Pass
```
SELECT MAX(ID)
FROM YourTable
WHERE Result = 'PASS'
GROUP BY `GROUP`;
``` | If you only want groups where **all** students passed use
```
select max(id) as max_id, `group`
from your_table
group by `group`
having sum(result <> 'Pass') = 0
``` | mysql query not returning specific rows with max(id) data | [
"",
"mysql",
"sql",
""
] |
Maybe the title of the question is not the appropiate but here is the explanation:
I have the following tables:

There are only 5 benefit codes available:

So, one employee can ha... | First off, note that this operation actually [*de-normalizes*](http://en.wikipedia.org/wiki/Denormalization) the model and I would *keep the normalized table design* if it were my decision. I'm not sure what "pressure" mandates this situation, but I find that such approaches make the model harder to maintain and use. S... | Why not just join to a table that codes the benefits to an integer (Life -> 10000, Medical -> 1000, ..., education -> 1; and then
* Sum the benefit code integer;
* convert the sum to a string;
* prepend the string '0000' and take the right-most 5 characters.
*Update:*
```
select
EmployeeID,
right('0000' + conv... | SQL query normalize multiple row values into one row one column field | [
"",
"sql",
"sql-server",
"database",
""
] |
I have some code like:
```
class Pump:
def __init__(self):
print("init")
def getPumps(self):
pass
p = Pump.getPumps()
print(p)
```
But I get an error like:
```
Traceback (most recent call last):
File "C:\Users\Dom\Desktop\test\test.py", line 7, in <module>
p = Pump.getPumps()
Type... | To use the class, first create an instance, like so:
```
p = Pump()
p.getPumps()
```
A full example:
```
>>> class TestClass:
... def __init__(self):
... print("init")
... def testFunc(self):
... print("Test Func")
...
>>> testInstance = TestClass()
init
>>> testInstance.testFunc()
Test Func... | You need to initialize it first:
```
p = Pump().getPumps()
``` | Why do I get "TypeError: Missing 1 required positional argument: 'self'"? | [
"",
"python",
"constructor",
"typeerror",
"positional-argument",
""
] |
So, I finally gave in and grabbed South. The problem is, every time I try to follow the tutorial and run
```
"python manage.py schemamigration myapp --initial"
```
I get an error
```
"There is no enabled application matching 'myapp'"
```
--Things I have tried--
I have tripple checked my settings file, running Impo... | migrations exist on a per-app basis. each app may or may not have its own migrations, but you need to create them for each app where you want to use them. (often all apps)
`./manage.py migrate` is a shortcut that runs migrations for all apps | This error can be misleading: it is thrown not when South tries to import the app, but when it tries to get the app's `models` module.
* perhaps it cannot import the application (because you didn't add its name to `INSTALLED_APPS`)
* perhaps it cannot import the `models` module, because the file `models.py` does not e... | Django South Error: "there is no enabled application matching 'myapp'" | [
"",
"python",
"django",
"django-south",
""
] |
How to select row with name starting with 'A' until name starting with 'D'? And sort them alphabetically? Something like a combination of LIKE and =<> ?
Sample Table:
```
ID Name
4001 Spartakol
4002 Tabunjong
4003 Mabini
4004 Carlos
4005 Antonio
4006 Babsy
4007 Jose
4008 David
40... | Select the names from `'A'` up to, but not including `'E'`:
```
select ID, Name
from SampleTable
where Name >= 'A' and Name < 'E'
order by Name
```
As this is a plain comparison, it can use an index if you have one for that field. | Guffa's answer is probably the most efficient. To be complete, you could also use
```
LIKE '[a-d]%'
```
Depending on your database `COLLATION`, `LIKE` might be case sensitive or not. | Select a Range of Letters | [
"",
"sql",
"sql-server",
""
] |
i am given a csv file but i want to skip the first row of data and move on to the next. Here is my code:
```
def read_csv(inputfile):
return list(csv.reader(inputfile)) #<-----
def generate_xml(reader,outfile):
root = Element('Solution')
root.set('version','1.0')
tree = ElementTree(root)
h... | You have a *list*, not an iterator. Just slice it instead:
```
for row in reader[1:]:
```
or skip that first row when you still have an actual `csv.reader()` object:
```
def read_csv(inputfile):
reader = csv.reader(inputfile)
next(reader)
return list(reader)
```
You'd be better off returning the `reader... | For python 2.x, the code is:
```
data = []
with open('xxx.csv') as f:
r = csv.reader(f)
name = r.next()[1] # assume the first 2 rows are name and unit
unit = r.next()
for row in r:
data.append(row)
```
For python 3.x, use `next(r)` instead of `r.next()` | CsvReader Next function | [
"",
"python",
"csv",
""
] |
I have a query similar to this:
```
select 'table_1', count(*)
from table_1
union
select 'table_2', count(*)
from table_2
union
select 'table_n', count(*)
from table_n
```
returning the total of rows for each table (n tables).
```
table_1 | 100
table_2 | 150
table_n | 400
```
I want to know if there is a my... | ```
select ifnull(table_name,'Total'), sum(row_count)
from (select 'table_1' table_name, count(*) row_count
from table_1
union
select 'table_2' table_name, count(*) row_count
from table_2
union
select 'table_n' table_name, count(*) ro... | Maybe use WITH ROLLUP:-
```
SELECT TableName, TableCount
FROM
(
SELECT 'table_1' AS TableName, COUNT(*) AS TableCount
FROM table_1
union
SELECT 'table_2' AS TableName, COUNT(*) AS TableCount
FROM table_2
SELECT
select 'table_n' AS TableName, COUNT(*) AS TableCount
FROM table_n
) Sub1
... | mySQL union with calculated row | [
"",
"mysql",
"sql",
"sum",
""
] |
I'm looking for a way to split a text into n-grams.
Normally I would do something like:
```
import nltk
from nltk import bigrams
string = "I really like python, it's pretty awesome."
string_bigrams = bigrams(string)
print string_bigrams
```
I am aware that nltk only offers bigrams and trigrams, but is there a way to ... | Great native python based answers given by other users. But here's the `nltk` approach (just in case, the OP gets penalized for reinventing what's already existing in the `nltk` library).
There is an [ngram module](http://www.nltk.org/_modules/nltk/model/ngram.html) that people seldom use in `nltk`. It's not because i... | I'm surprised that this hasn't shown up yet:
```
In [34]: sentence = "I really like python, it's pretty awesome.".split()
In [35]: N = 4
In [36]: grams = [sentence[i: i + N] for i in range(len(sentence) - N + 1)]
In [37]: for gram in grams: print (gram)
['I', 'really', 'like', 'python,']
['really', 'like', 'python,... | n-grams in python, four, five, six grams? | [
"",
"python",
"string",
"nltk",
"n-gram",
""
] |
I have this SQL Syntax but it's not working and receive this error:
> "#1248 - Every derived table must have its own alias".
Could you help me?
```
SELECT *
FROM produse_comenzi
JOIN comenzi ON comenzi.id_comanda = produse_comenzi.id_comanda
JOIN (SELECT DISTINCT numar_factura FROM facturi)
ON facturi.id_comanda = c... | In the second join you are using a subquery but you haven't given the result an alias, i.e. something to identify the result by
```
SELECT *
FROM produse_comenzi
JOIN comenzi
ON comenzi.id_comanda = produse_comenzi.id_comanda
JOIN (SELECT DISTINCT numar_factura FROM facturi) -- has no alias
ON facturi.i... | You must add an alias to each subquery that's being treated as a table:
```
SELECT *
FROM produse_comenzi
JOIN comenzi ON comenzi.id_comanda = produse_comenzi.id_comanda
JOIN (SELECT DISTINCT numar_factura FROM facturi) x
ON x.id_comanda = comenzi.id_comanda
```
Here I have named the result set `x` and referred to th... | Error message - Every derived table must have its own alias | [
"",
"sql",
"distinct",
"alias",
""
] |
I assume there's some beautiful Pythonic way to do this, but I haven't quite figured it out yet. Basically I'm looking to create a testing module and would like a nice simple way for users to define a character set to pull from. I could potentially concatenate a list of the various charsets associated with string, but ... | Paul McGuire, author of [Pyparsing](http://pyparsing.wikispaces.com), has written an [inverse regex parser](http://pyparsing.wikispaces.com/file/view/invRegex.py), with which you could do this:
```
import invRegex
print(''.join(invRegex.invert('[a-z]')))
# abcdefghijklmnopqrstuvwxyz
```
If you do not want to install ... | A regex is not needed here. If you want to have users select a character set, let them just pick characters. As I said in my comment, simply listing all the characters and putting checkboxes by them would be sufficent. If you want something that is more compact, or just looks cooler, you could do something like one of ... | Generate random string from regex character set | [
"",
"python",
"regex",
"string",
""
] |
In Python, is it possible to write a function that returns the dimensions of a multidimensional array (given the assumption that the array's dimensions are not jagged)?
For example, the dimensions of `[[2,3], [4,2], [3,2]]` would be `[3, 2]`, while the dimensions of `[[[3,2], [4,5]],[[3,4],[2,3]]]` would be `[2,2,2]`.... | No, there's nothing built-in because with such "arrays"1 it can be jagged and the concept of "dimensions" or "shape" doesn't make any sense at all. So, you'll have to write your own. If you can make an assumption of uniformity along all dimensions, you can proceed as follows:
```
dim1 = len(a)
dim2 = len(a[0])
dim3 = ... | You can do it with numpy:
```
import numpy
l = [[2,3], [4,2], [3,2]]
m = numpy.array(l)
print m.shape
```
But the shape of your second example is [2,2,2], not [1,4,5], unless I've misunderstood your question... | Find the dimensions of a multidimensional Python array | [
"",
"python",
"arrays",
"dimensions",
""
] |
I was looking all over for any kind of small example or something to help me and I couldn't find it. I feel like I am missing something obvious. I have a large function in one .py file that I want to call in another .py file and use all the variables from the function and I couldn't do it. So I was trying to do it with... | 1. Local variables only exist while the function is being run.
2. Local variables are never attributes of their containing function.
If you want to get values from a function then you need to return them from it. Otherwise, look into OOP if you need more persistence. | You can return multiple values from a function as tuple:
```
def mod(num):
a = 5
b = 6
c = num
return (a, b, num)
```
Then in the other file, use it something like this:
```
import mod1
d, b, num = mod1.mod(1)
print(d)
``` | Accessing variables that are inside a function | [
"",
"python",
"module",
""
] |
Quick question to mainly satisfy my curiosity on the topic.
I am writing some large python programs with an SQlite database backend and will be dealing with a large number of records in the future, so I need to optimize as much as I can.
For a few functions, I am searching through keys in a dictionary. I have been us... | First, `key in d.keys()` is guaranteed to give you the same value as `key in d` for any dict `d`.
And the `in` operation on a `dict`, or the `dict_keys` object you get back from calling `keys()` on it (in 3.x), is *not* O(N), it's O(1).
There's no real "optimization" going on; it's just that using the hash is the obv... | In Python 2 `dict.keys()` creates the whole list of keys first that's why it is an `O(N)` operation, while `key in dict` is an `O(1)` operation.
`if(dict[key] != None)` will raise `KeyError` if key is not found in the dict, so it is not equivalent to the first code.
Python 2 results:
```
>>> dic = dict.fromkeys(rang... | Python dictionary keys. "In" complexity | [
"",
"python",
"dictionary",
"hashmap",
"complexity-theory",
"big-o",
""
] |
I'd like to concatenate a sequence of integers with a list of tokens in a single byte string, so that, for example, the following:
```
foo
bar
baz
```
would become (with 1 byte for the integer representation):
```
b'\x00foo'
b'\x01bar'
b'\x02baz'
```
The best I've come up with looks like this:
```
for i, token in ... | I think might be faster:
```
from struct import pack
for i, token in enumerate(b"foo bar bazq".split()):
print(pack('@B%ds' % len(token), i, token))
```
Output:
```
b'\x00foo'
b'\x01bar'
b'\x02bazq'
```
If you only have or want 3 character strings you could use the simpler `print` function/statement:
```
... | You can use numpy and access directly the buffer interface to avoid conversions:
On python 2.7 (numpy 1.7.1), this code:
```
N = arange(256, dtype='uint8')
for i, token in enumerate("foo bar baz".split()):
print repr(N.data[i] + token.encode())
```
gives:
```
'\x00foo'
'\x01bar'
'\x02baz'
``` | Increment efficiently over a sequence of integers in byte representation | [
"",
"python",
"python-3.x",
""
] |
When i return a list of product stating with the letter "A" it obviously returns all products that start with the letter "A".
I would also like to return all products that start with the letter "A" and products which also have "The" at the begining. I also would like to get a better idea of how the best way to do this... | To exclude specifically "The" from the front of the title:
```
SELECT title
FROM dbo.product
WHERE title LIKE 'R%'
OR title LIKE 'The R%'
```
This approach has the advantage of avoiding a leading wildcard, which breaks the index lookup. If you have a list of leading words you would like to ignore, you would use a set... | Try this one -
```
SELECT title
FROM dbo.product
WHERE title LIKE '%R%'
``` | how to ignore the "the" in a product title ASP.NET/SQL | [
"",
"sql",
"asp.net",
"sql-server",
"linq-to-sql",
""
] |
I'd like to store a set of data into a database **but** if it's a pre-existing record, I'd like to alter it. Otherwise, create a new one. Is there a combine statement for that? (Haven't got any when googling.)
Right now, the best I have is to check if already exists and then perform one of the operations. Seems cumber... | MySQL uses `INSERT... ON DUPLICATE KEY` and MSSQL uses `MERGE`
`MERGE` is [supported by Azure](http://msdn.microsoft.com/en-us/library/windowsazure/ee336270.aspx), and I can highly recommend this [blog article](http://www.purplefrogsystems.com/blog/2011/12/introduction-to-t-sql-merge-basics/) on it, as a good intro to... | IN MYSQL :
You may use INSERT ... ON DUPLICATE KEY UPDATE .
eg:
```
INSERT INTO table (a,b,c) VALUES (4,5,6)
ON DUPLICATE KEY UPDATE c=9;
```
For more information: <http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html> | Insert and alter in one statement | [
"",
"sql",
"azure-sql-database",
""
] |
I am drawing two subplots with Matplotlib, essentially following :
```
subplot(211); imshow(a); scatter(..., ...)
subplot(212); imshow(b); scatter(..., ...)
```
Can I draw lines between those two subplots? How would I do that? | The solution from the other answers are suboptimal in many cases (as they would only work if no changes are made to the plot after calculating the points).
A better solution would use the specially designed [`ConnectionPatch`](https://matplotlib.org/tutorials/text/annotations.html#using-connectionpatch):
```
import m... | You could use `fig.line`. It adds any line to your figure. Figure lines are higher level than axis lines, so you don't need any axis to draw it.
This example marks the same point on the two axes. It's necessary to be careful with the coordinate system, but the transform does all the hard work for you.
```
import matp... | Drawing lines between two plots in Matplotlib | [
"",
"python",
"matplotlib",
""
] |
I am trying to learn inheritance in python. I write class "Course" as super class of class "AdvacedCourse" as shown below.
```
class Course(object):
def __init__(self, crsName ="python", duration=45):
self.crsName = crsName
self.duration = 25
```
And the sub class is:
```
import Course
class A... | This is a problem with importing, not inheritance. `Course` is the module: you need to inherit from `Course.Course`. (In Python we usually name modules in lower case, though). | I assume that class `Course` is in another module `Course.py`.
Then you should import it with `from Course import Course`. And @Daniel is right - you should have module in file `course.py` (lowercase) and import statement will be `from course import Course`. | TypeError Inheritance in Python | [
"",
"python",
"inheritance",
""
] |
I'm trying to get the syntax to show a list of records where the `Actual Live Date` is equal to or greater than today by 7 days and ideally show how many per day (thursday = 7 records).
i was thinking something along the lines of:
```
SELECT [PW Number]
,[status]
,[install Date]
,[ICL Client Code]
,[Actual Li... | If you need "today" to start at 00:01 this morning, then you need to remove the time portion from e.g. `GETDATE()`. I'm also using explicit functions to show that I'm adding days:
```
SELECT [PW Number]
,[status]
,[install Date]
,[ICL Client Code]
,[Actual Live Date]
FROM
[QuoteBase].[dbo].[Circuits]
WHERE... | you can use the `BETWEEN` and `GETDATE()` functions for this, the `GETDATE() + 7` will add 7 days onto todays date
```
SELECT [PW Number]
,[status]
,[install Date]
,[ICL Client Code]
,[Actual Live Date]
FROM
[QuoteBase].[dbo].[Circuits]
WHERE
[Actual Live Date] BETWEEN GETDATE() AND GETDATE() + 7
``` | Selecting records where 'ActualLiveDate' is between today and X days in to the future with SQL Server | [
"",
"sql",
"sql-server",
""
] |
I need to return daily SUM from two columns covering 7 months
I am attempting to do this, but this is way too time consuming. Is there a method to return these in sequence incremented one day at a time?
```
select SUM(TotalBet)SALES, SUM(TotalWin)PRIZES from play nolock where CurrentDate between '1/1/2013 07:00:00' an... | You want an aggregation. The key is to convert the `datetime` to a `date`. To get the right date, subtract 7 hours:
```
select cast(CurrentDate - 7.0/24 as date) as thedate,
SUM(TotalBet) as SALES, SUM(totalbet) as PRIZES
from play nolock
group by cast(CurrentDate - 7.0/24 as date)
order by 1;
``` | Use a [numbers table](http://www.kodyaz.com/articles/sql-server-tsql-cte-numbers-table.aspx) to generate your dates, and then join to the table and group by the day. You could go straight to the table, but if you have missing dates (say, a holiday) they won't show in the results without a numbers table.
```
SELECT
... | I need to return daily SUM from two columns covering 7 months | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I need to populate a list with a few 1's in random places. I can successfully create a list of random numbers with:
```
from random import randint
l = [randint(0,1023) for _ in range(0,10)]
```
How do I populate a list with 1's in the position specified by l? | # A Sparse List
My understanding of "sparse list" is that most (say, more than 95% of) values will be zero and for reasons of **memory efficiency** you don't wish to *store* these (*cf.* [Sparse array](http://en.wikipedia.org/wiki/Sparse_array)).
## List comprehension
Using your list comprehension, you can use [***C... | > I need to create a large list of 0's with 10 - 40 l's in random places
> to benchmark an algorithm.
Might this work for you?
```
import random
zeros = [0] * 1024
ones = [1] * random.randint(10, 40)
l = zeros + ones
random.shuffle(l)
# the list l contains many zeros and 10 - 40 1's in random places.
where_the_on... | Populating a sparse list with random 1's | [
"",
"python",
""
] |
I am currently learning the concept of list comprehensions in python. However, I have huge problems when the list I am iterating over contains sublists of equal or different length. For example, I would like to turn the code for `union_set()` into a one-line-comprehension:
```
def union_set(L):
S_union = set()
... | Using list-comprehension, you can do something like that:
```
>>> L1 = [1, 2, 3]
>>> L2 = [4, 5, 6]
>>> L3 = [7, 8, 9]
>>> L = [L1, L2, L3]
>>> s=set([x for y in L for x in y])
>>> s
set([1, 2, 3, 4, 5, 6, 7, 8, 9])
```
y is iterating over the sublist, while x iterates over items in y. | Use an empty `set` and `.union` it:
```
L1 = [1, 2, 3]
L2 = [4, 5, 6]
L3 = [7, 8, 9]
print set().union(L1, L2, L3)
```
Used in your code as:
```
L = [L1, L2, L3]
def union_set(L):
return set().union(*L)
``` | How extract items of sublists in a one-line-comprehension in python? | [
"",
"python",
"python-3.x",
"list-comprehension",
""
] |
I am using a temporary table in a function to save some results however I don't know how to return the table from the function. Ideally I would like to do everything in one query (i.e. not two queries: one for calling the function, the other to get data from the temp table).
Currently my `main_function()` is as follow... | Inside your main\_function():
```
RETURN QUERY SELECT * FROM temp_t;
```
...if temp\_t table consists of e.g. column1 (type integer), column2 (boolean) and column3 (varchar(100)), you should also define returned type as:
```
CREATE OR REPLACE FUNCTION main_function(column1 OUT integer, column2 OUT boolean, column3 O... | Are you sure you *need* a temporary table? Most of the time, there is a cheaper solution. Your example can simply be:
```
CREATE OR REPLACE FUNCTION main_function()
RETURNS SETOF tbl_t AS
$BODY$
BEGIN
RETURN QUERY EXECUTE 'SELECT * FROM tbl_t LIMIT 10';
END
$BODY$
LANGUAGE plpgsql;
```
You also don't need `EXECUT... | How to return temp table result in postgresql function | [
"",
"sql",
"postgresql",
"types",
""
] |
How can I get the record details of an aggregate function without using a sub query?
I have a data set as follows:
```
CREATE TABLE SOMEDATA(
id int,
low int,
op int,
yc int,
tc int,
volume int,
Atimestamp time)
INSERT INTO SOMEDATA VALUES(5631, 5500, 5600, 5680, 5680, 300527, '13... | You should be able to use the RANK() function for this. Something like:
```
SELECT id, low, op, yc, tc, volume, Atimestamp
FROM
(
SELECT
id,
low,
op,
yc,
tc,
volume,
Atimestamp,
RANK() OVER (PARTITION BY id ORDER BY Atimestamp DESC) AS rank
FROM somedata
) a
WHERE a.rnk = 1
``` | Please try:
```
SELECT * FROM(
SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY Atimestamp DESC) RNum
From SOMEDATA
)x
WHERE RNum=1
```
OR
```
;WITH x AS(
SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY Atimestamp DESC) RNum
From SOMEDATA
)
SELECT * FROM x
WHERE RNum=1
``` | How to get details of row with an aggregate function without subquery? | [
"",
"sql",
"sql-server",
""
] |
I created a stored procedure which when passed nothing as parameter should return the entire table. But if the studentId is passed, then return her details.
Something like this
```
create procedure usp_GetStudents @studentId int = null
as
if (@studentId = null)
select * from Student
else
select * from Stud... | You're trying to test for null using `=`, a [comparison operator](http://msdn.microsoft.com/en-us/library/ms188074.aspx). If you're using ANSI nulls, any comparison against `null` is `false`.
Where `@studentId` is *any* value (or `null`) the following expressions are all `false`:
```
@studentId = null -- false
@stud... | Shorter way to do that:
```
create procedure usp_GetStudents @studentId int = null
as
select * from Student
where studentId = isnull(@studentId,studentId)
```
You can't chack if value is null using `=`.
For your example you have to replace condition `@studentId = null` to `is null` syntax.
Try to change your co... | conditional stored procedure with/without passing parameter | [
"",
"sql",
"stored-procedures",
""
] |
I'm writing a function to read from socket and return exact size of data. And I thought of codes like:
```
whlie len(buf) < required:
buf += socket.recv(required - len(buf))
return buf
```
But I think this might waste some CPU resources(not sure). I'm looking for a system call or something to return exact amount... | This will not waste CPU resources.
`sock.recv` will [block](http://docs.python.org/2/library/socket.html#socket.socket.setblocking) until at least one byte is available (but may buffer and return multiple bytes if they are available), so your application will not enter a busy loop.
In general, the buffer length of th... | If you are using the default socket library you can use the following.
```
import socket
host, port = "localhost", 8000
num_bytes = 5000
sock = socket.socket()
sock.connect((host, port))
while True:
data = sock.recv(num_bytes)
handle(data)
```
You can take a look at the possible parameters here [socket.recv... | How to receive certain size of data in socket programming? | [
"",
"python",
"sockets",
""
] |
I am trying to select all the elements where x\_id=1 but there will be multiple rows for that result with the same user\_id and I just want it to show one result for each user id (instead of multiple). How would I be able to do this in SQL im completely lost?
Table:
## a
id | x\_id | user\_id | `SELECT DISTINCT user_id FROM table WHERE x_id = 1;` | select distinct user\_id from a where x\_id = 1; | Select Data From Table Without Multiple Of The Same User ID | [
"",
"mysql",
"sql",
"database",
""
] |
Using `requests` in Python I am performing a GET, requesting a JSON file which I can later access and modify, tweak, etc. with the command `solditems.json()`. However I would like to save this JSON file to my computer. Looking through the requests docs I found nothing, does anybody have an easy way I can do this? | You can do it just as you would without `requests`. Your code might look something like,
```
import json
import requests
solditems = requests.get('https://github.com/timeline.json') # (your url)
data = solditems.json()
with open('data.json', 'w') as f:
json.dump(data, f)
``` | Based on @Lukasa's comment, this accelerates @Jared's solution :
```
import requests
solditems = requests.get('https://github.com/timeline.json') # (your url)
data = solditems.content
with open('data.json', 'wb') as f:
f.write(data)
``` | Saving a json file to computer python | [
"",
"python",
"python-requests",
""
] |
I have 2 tables with the following structure:
Table A:
```
id_A col1
1 val1
2 val2
3 val3
... ....
```
Table B:
```
id_B mycol id_A_val
1 smval1 null
2 null 1
3 null 2
... ... ...
```
I want to copy values from Table A's col1 into Table B's mycol
This... | Try this:
```
update
b
set
mycol=table_a.col1
from table_b b
inner join table_a on
b.id_A_val=table_a.id_A
``` | Try This
```
UPDATE tableb
SET mycol=a.col1
FROM tableb b
INNER JOIN tablea a ON a.id_A=b.id_A_val
WHERE b.mycol is null
``` | how to copy data from multiple rows of one table to another in sql server? | [
"",
"sql",
"sql-server",
"sql-update",
"multiple-records",
""
] |
I have a numpy matrix where each row is a picture. I can reshape the rows and display the images with matplotlib.pyplot. The problem is: I don't want to display the Images separately, I want to display them after each other like a video.
How is that possible in python? | Well, I don't know if it is the best way but I've used matplotlib.pyplot to solve my problem. Import it as "plt" and do the following:
```
matrix=numpy.genfromtxt(path,delimiter=',') # Read the numpy matrix with images in the rows
c=matrix[0]
c=c.reshape(120, 165) # this is the size of my pictures
im=plt.imshow(c)
for... | Hello my solutions using matplotlib animations:
```
from matplotlib import pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
video # my numpy matrix of shape (frames, channel, w, h)
# initializing a figure in
# which the graph will be plotted
fig = plt.figure(figsize=(10,10))
# crea... | Displaying Numpy Matrix as Video | [
"",
"python",
"numpy",
""
] |
It looks like celery does not release memory after task finished. Every time a task finishes, there would be 5m-10m memory leak. So with thousands of tasks, soon it will use up all memory.
```
BROKER_URL = 'amqp://user@localhost:5672/vhost'
# CELERY_RESULT_BACKEND = 'amqp://user@localhost:5672/vhost'
CELERY_IMPORTS =... | It was this config option that made my worker does not release memory.
```
CELERYD_TASK_TIME_LIMIT = 600
```
refer to: <https://github.com/celery/celery/issues/1427> | There are two settings which can help you mitigate growing memory consumption of celery workers:
* [Max tasks per child setting](http://docs.celeryproject.org/en/latest/userguide/workers.html#max-tasks-per-child-setting) (v2.0+):
> With this option you can configure the maximum number of tasks a worker can execute be... | Celery does not release memory | [
"",
"python",
"rabbitmq",
"celery",
"amqp",
""
] |
I want to get current identity value of a specific table
Like IDENT\_CURRENT('table') in sql server | ```
SELECT AUTOINC_SEED
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='TableName'
AND COLUMN_NAME='ColumnName'
```
from [Hamid's answer](https://stackoverflow.com/a/17544448/161250) is fine if what you're looking for is what the identity column's seed value is (i.e. what the first ever value of the identity colu... | If you want to get a last identity inserted value for a particular table use the following statement:
```
select IDENT_CURRENT('tablename')
```
For example:
```
select IDENT_CURRENT('Employee')
``` | How to get current identity number of specific table in sql server compact | [
"",
"sql",
"sql-server-ce",
""
] |
I am working on an anonymizer program which sensors the given words in the list. This is what i have so far. I am new to python so not sure how can i achieve this.
```
def isAlpha(c):
if( c >= 'A' and c <='Z' or c >= 'a' and c <='z' or c >= '0' and c <='9'):
return True
else:
return False
def... | You have several problems with your code:
1. There already exists an `islpha` function; it is a `str` method (see example below).
2. Your `trucatedInput` is a `str`, which is an immutable type. You can't reassign parts of an immutable type; i.e. `myStr[3]='x'` would normally fail. If you really want to do this, you're... | You could use [string.replace()](http://docs.python.org/2/library/string.html#string.replace)
```
truncatedInput.replace('DRAT', 'xxxx')
```
This will replace the first occurence of DRAT with xxxx, even if it is part of a longer sentence. If you want different functionality let me know. | How to make anonymizer in python? | [
"",
"python",
""
] |
I wrote this python function which takes a list as a parameter and determines which elements of the list are perfect squares and then returns a new list of just those select elements.
Here is my function:
```
def square(n):
return n**2
def perfectSquares1(L):
import math
m=max(L)
for n in L:
... | You can do:
```
import math
def perfect_sq(n):
return n == int(math.sqrt(n)) * int(math.sqrt(n))
```
Or you can use:
```
import math
def perfect_sq(n):
return n == int(math.sqrt(n)) ** 2
``` | ```
lambda n: math.sqrt(n) % 1 == 0
``` | Python Program on Perfect Squares | [
"",
"python",
"python-3.x",
""
] |
I'm trying to implement PageObject pattern for my first Login test. While running it I'm receiving the following error:
```
>> py.test -v test_login.py
============================= test session starts ==============================
platform linux2 -- Python 2.7.3 -- pytest-2.3.4
plugins: xdist
collected 0 items / 1 ... | Your `base` module is located in the `ui` module. Hence line:
```
from base import BasePage
```
should be:
```
from ui.base import BasePage
``` | i was just a beginner when this error struck what i did was
instead of:
```
from models.post import Post
```
i did the following after installing post as package:
```
from post import Post
```
it worked for me | ImportError: No module named base | [
"",
"python",
"python-2.7",
"selenium-webdriver",
"pytest",
"pageobjects",
""
] |
I am working in Oracle Apex 4.2. I have two tables:
I have simple report to build
```
select id, name, location_id from tablel1
-----------------------------------
| ID | NAME | PROJECT_ID |
-----------------------------------
| 1 | P1 | 23:45:56 |
| 2 | P2 | 23 |
| 3 | ... | With SQL only (Oracle 11g):
```
select x.id, x.name, listagg(t2.name || t2.site, ', ') within group (order by t2.id)
from
(
select distinct t1.id, t1.name, regexp_substr(t1.project_id, '[^:]+', 1, level) id_site
from tablel1 t1
connect by level <= regexp_count(t1.project_id, ':') + 1
) x, table22 ... | Here is procedure:
```
DECLARE
CURSOR c (p_id NUMBER) IS
SELECT NAME||' - '||SITE
FROM TABLE2
WHERE ID = p_id;
l_tsv VARCHAR2(1000) := '23:45:56';
l_item NUMBER;
lc_t VARCHAR(200);
lc_result VARCHAR2(4000);
BEGIN
FOR i IN 1 .. LENGTH(l_tsv) - LENGTH(REPLACE(l_tsv, ':', '')) + 1 ... | Conversion of multiple values within one column | [
"",
"sql",
"oracle",
"report",
"oracle-apex",
"lov",
""
] |
I just started learning python and was wondering if their was a way to shortcut a line of code.
For example could I use something along the lines of.
```
command = input()
if command = "create turtle"
t =turtle.Pen()
```
or
```
turtleCommand = input()
if turtleCommand = "circle"
t.forward(100)
t.left(91)... | You can write a function:
```
def draw_circle(t):
t.forward(100)
t.left(91)
```
And then call it:
```
t = turtle.Pen()
command = input()
if command == "circle":
draw_circle(t)
elif command = "stuff":
...
```
A more robust solution would be to use a dictionary that maps commands to functions:
```
c... | ```
def docircle(pen):
pen.forward(100)
pen.left(91)
commands = {
'circle': docircle,
...
}
...
commands[turtleCommand](t)
``` | How To create a shortcut for a command in python 3.3 | [
"",
"python",
"python-3.x",
""
] |
I would like to test if a string is computable using the built in function "eval". I would like to make a condition in my definition. I want it to produce true if the string is computable using eval, and false if trying to "eval" the string produces and error. Any functions that would help me to do so? Thanks.
Example... | I'm assuming you want to check the syntax before making a call to eval(). You can try [ast.parse](http://docs.python.org/2/library/ast.html#ast.parse), as mentioned in this other [answer](https://stackoverflow.com/a/11854793/1046267).
(Example as given in that answer, for easier reference):
```
import ast
def is_vali... | ```
def f(string):
try:
return eval(string)
except:
return False
``` | Python Conditions | [
"",
"python",
"wing-ide",
""
] |
```
CREATE TABLE app_for_leave
(
sno integer NOT NULL,
eid integer,
ename varchar(20),
sd date,
ed date,
sid integer,
status boolean DEFAULT false,
CONSTRAINT pk_snoa PRIMARY KEY (sno)
);
```
Basic Insertion is ::
```
INSERT INTO app_for_leave(sno, eid, sd, ed, sid, status)
VALUES(1,101,'2013-04-04',... | PostgreSQL [didn't support stored procedures](https://wiki.postgresql.org/wiki/FAQ#Does_PostgreSQL_have_stored_procedures.3F) until PG11. Prior to that, you could get the same result using a function. For example:
```
CREATE FUNCTION MyInsert(_sno integer, _eid integer, _sd date, _ed date, _sid integer, _status boolea... | Starting from PostgreSQL 11 you could [create stored procedures](https://www.postgresql.org/docs/11/static/sql-createprocedure.html) and invoke them using [CALL](https://www.postgresql.org/docs/11/static/sql-call.html):
```
CREATE PROCEDURE MyInsert(_sno integer, _eid integer, _sd date,
_ed d... | How to insert data into table using stored procedures in postgresql | [
"",
"sql",
"postgresql",
"postgresql-9.2",
""
] |
I have troubles getting proper data.
I have table structure like:
```
id INT(11) AI
order_id INT(11)
status varchar(45)
```
This table log status changes for orders.
So order\_id's will have few statuses.
Now I need to select rows and group them by order\_id, where order never had status (not even one st... | Not quite sure if you want the records for order which have had a status of example, or ones which have never had a status of example
To get a list of orders (with the status grouped up) which have had a status of example:-
```
SELECT a.order_id, GROUP_CONCAT(a.status)
FROM SomeTable a
INNER JOIN
(
SELECT order_... | you can do it by simple join query :
```
select a.order_id
from ordrstatus as a left outer join (select orderid , count(*) as status from orderstatus where status = 'example' group by orderid) as b on a.orderid = b.orderid
where b.status = 0 or b.status is NUll
```
Join query always run faster then IN query . by us... | MySQL: SELECT if non of group by members is equal to x | [
"",
"mysql",
"sql",
""
] |
I am getting the following error when trying to do a bulk insert into an *empty* mongodb collection.
> pymongo.errors.DuplicateKeyError: E11000 duplicate key error index:
> cmdDistros.locDistro.$*id* dup key: { :
> ObjectId('51dac9d0c74cd81acd85c0fd') }
I am not specifying an \_id when I create any of the documents, ... | You need to understand that your entries list has a bunch of references to **one** entry dict. So when PyMongo sets entries[0]['\_id'], all the other entries get the same \_id. (In fact, PyMongo will iterate through the list setting each entry's \_id, so all the entries will have the **final** \_id at the end.) A quick... | Delete the key `"_id"`:
```
for i in xrange(2):
doc['i'] = i
if '_id' in doc:
del doc['_id']
collection.insert(doc)
```
Or manually create a new one:
```
from bson.objectid import ObjectId
for i in xrange(2):
doc['i'] = i
doc['_id'] = ObjectId()
collection.insert(doc)
```
[Ge... | MongoDB insert raises duplicate key error | [
"",
"python",
"mongodb",
"pymongo",
"database",
""
] |
# My Problem:
I have this problem where if I try to run py2exe on my python file that uses Pyqt/Pyside I get the following error when trying to run the EXE generated in I:\Documents\Python\Buttonio\_Testio\dist :
## Error recieved when running Package.exe:
```
I:\Documents\Python\Buttonio_Testio\dist>Package.exe
Tra... | The problem was that \_utils.py used `__file__`, but `__file__` is not available in frozen executables. This has been fixed in PySide 1.2.1 that was released a few days ago (it was fixed by commit [817a5c9bd39d3a22e2a7db9aa497059be57d58d7](https://qt.gitorious.org/pyside/pyside/commit/817a5c9bd39d3a22e2a7db9aa497059be5... | I was desperately looking for a solution to this for the past three hours. I ended up going into the \_ \_ init\_ \_.py file in C:\Python27\Lib\site-packages\PySide directory. I changed the last line to the following:
```
try:
_setupQtDirectories()
except WindowsError:
pass
```
It is ugly I admit. I hope PySi... | System path error with PyQt and Py2exe | [
"",
"python",
"pyqt",
"exe",
"pyside",
"py2exe",
""
] |
I do this `linear regression` with `StatsModels`:
```
import numpy as np
import statsmodels.api as sm
from statsmodels.sandbox.regression.predstd import wls_prediction_std
n = 100
x = np.linspace(0, 10, n)
e = np.random.normal(size=n)
y = 1 + 0.5*x + 2*e
X = sm.add_constant(x)
re = sm.OLS(y, X).fit()
print(re.summa... | **update** see [the second answer](https://stackoverflow.com/a/47191929/1234438) which is more recent. Many of the models and results classes have now a `get_prediction` method that provides additional information including prediction intervals and/or confidence intervals for the predicted mean.
**old answer:**
`iv_l... | For test data you can try to use the following.
```
predictions = result.get_prediction(out_of_sample_df)
predictions.summary_frame(alpha=0.05)
```
I found the summary\_frame() method buried [here](https://github.com/statsmodels/statsmodels/issues/987#issuecomment-133575422) and you can find the get\_prediction() met... | confidence and prediction intervals with StatsModels | [
"",
"python",
"statistics",
"statsmodels",
""
] |
Given, for example, the following from table `alpha`:
```
Field1 | Field2 | Field3
------------------------
Foo | Bar | ABCD
```
How could I break this data down into:
```
Field1 | Field2 | Field3
------------------------
Foo | Bar | A
Foo | Bar | B
Foo | Bar | C
Foo | Bar | D
```
I'm ... | you can do it by following steps easily :
1. Step1 : Create one sql table valued function which can split word in to characters . you can do it by run following script .
```
CREATE FUNCTION [dbo].[SPLITWORD](
@WORD VARCHAR(MAX)
) RETURNS @words TABLE (item VARCHAR(8000))
BEGIN
declare @count int... | Something like:
```
declare @alpha table (Field1 varchar(20), Field2 varchar(20), Field3 varchar(6))
insert into @alpha(Field1, Field2, Field3) values
('Foo','Bar','ABCD')
;With Numbers(n) as (
select 1 union all select 2 union all select 3 union all
select 4 union all select 5 union all select 6
)
select Fie... | SQL - Break down a field's data into separate rows | [
"",
"sql",
"sql-server",
""
] |
Although I may be very confused as to what the [`property()`](http://docs.python.org/2/library/functions.html#property) function does, I'm trying to use it to create an attribute which is read-only. Ideally, I'd like to be able to refer to the attribute directly but not be allowed to assign to it. When experimenting, I... | The problem here has nothing to do with `property`, but with double-underscore attributes, which are subject to what's called ["Private name mangling"](http://docs.python.org/2/reference/expressions.html#atom-identifiers).
```
>>> b = Boo(1)
>>> '__x' in dir(b)
False
>>> '_Boo__x' in dir(b)
True
```
So, when you do t... | Your problem is that using double underscore attribute names *mangles the name*. So when you are dealing with `__x` inside of your class definition, outside of the class it actually looks like `_Boo__x`. That is,
> \_ + (class name) + (double underscore attribute name)
To demonstrate,
```
>>> b = Boo(1)
>>> b.__x = ... | Attempting to create a read-only property attribute - getter returns initialized value, direct access returns changed value | [
"",
"python",
"oop",
"python-2.7",
"properties",
""
] |
```
> pip install yolk
Downloading/unpacking yolk
Cannot fetch index base URL https://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement yolk
No distributions at all found for yolk
Storing complete log in /Users/harith/.pip/pip.log
```
when I read the file I see
```
> cat /Users/har... | This is the full text of the blog post linked below:
If you've tried installing a package with pip recently, you may have encountered this error:
```
Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1... | I used to use the `easy_install pip==1.2.1` workaround but I randomly [found](https://stackoverflow.com/questions/25662073/python-django-cannot-use-imagefield-because-pillow-is-not-installed) that if you're having this bug, you probably installed a 32bit version of python on a 64bit machine.
In short : If you install ... | pip cannot install anything | [
"",
"python",
"pip",
""
] |
I have a tab delimited file with \n EOL characters that looks something like this:
```
User Name\tCode\tTrack\tColor\tNote\n\nUser Name2\tCode2\tTrack2\tColor2\tNote2\n
```
I am taking this input file and reformatting it into a nested list using `split('\t')`. The list should look like this:
```
[['User Name','Code'... | Count the tabs; if you presume that the note field never has 4 tabs on one line in it, you can collect the note until you find a line that *does* have 4 tabs in it:
```
def collapse_newlines(s):
# Collapse multiple consecutive newlines into one; removes trailing newlines
return '\n'.join(filter(None, s.split('... | The first problem you're having is `in` - which tries to be helpful and reads in one line of text from the file at a time.
```
>>> [i for i in open('SomeFile.txt', 'r') ]
['User Name\tCode\tTrack\tColor\tNote\n', '\n', 'User Name2\tCode2\tTrack2\tColor2\tNote2\n', '\n']
```
Adding in the call to `.strip()` does strip... | Remove multiple EOL in file | [
"",
"python",
"eol",
""
] |
I have below tow table
table 1: The teacher table
```
teacher_id teacher_name
1 xx
2 yy
3 zz
```
table 2: the student table
```
stu_id stu_name tearcher1_id teacher2_id tearcher3_id
1 aa 1 2
2 bb 2 ... | ```
SELECT
teacher_id
teacher_name
NVL(num1, 0) + NVL(num2, 0) + NVL(num3,0) as num_selected_by_stu
FROM
teacher t
left outer join ( SELECT count(*) as num1, tearcher1_id FROM student group by tearcher1_id ) t1 on t1.tearcher1_id = t.tearcher_id
left outer join ( SELECT count(*) as num2, tearcher2_id FROM... | Please try:
```
SELECT
*,
(SELECT
COUNT(*)
FROM
Student t2
WHERE
t1.teacher_id=t2.tearcher1_id OR
t1.teacher_id=t2.teacher2_id OR
t1.teacher_id=t2.tearcher3_id) num_selected_by_stu
FROM
Teacher t1
``` | how to select a record from one table and count the number of which appears another table and count it | [
"",
"sql",
"oracle",
""
] |
I have a table that looks like this
```
fID_a fID_b
1 1
1 2
2 2
3 1
```
I want all `fID_a` where `fID_b` is 1 AND where `fID_a` is a single record in that table.
I have a sql query that looks like this
```
select fID_a from tbl
where fID_b = 1
group by fID_a
having count(*) = 1
`... | Try this
```
SELECT fID_a FROM tbl
GROUP BY fID_a
HAVING MAX(fID_b)=1
AND MIN(fID_b)=1
``` | If you use a `where` clause then you would filter out other values what would make the `count` inaccurate.
```
select fID_a
from tbl
group by fID_a
having count(*) = 1
and sum(case when fID_b = 1 then 1 else 0 end) = 1
``` | Select distinct value when count = 1 in SQL | [
"",
"sql",
"select",
"group-by",
"having-clause",
""
] |
In the following code, I want to calculate the percent of G and C characters in a sequence. In Python 3 I correctly get `0.5`, but on Python 2 I get `0`. Why are the results different?
```
def gc_content(base_seq):
"""Return the percentage of G and C characters in base_seq"""
seq = base_seq.upper()
return ... | `/` is a different operator in Python 3; in Python 2 `/` alters behaviour when applied to 2 integer operands and returns the result of a floor-division instead:
```
>>> 3/2 # two integer operands
1
>>> 3/2.0 # one operand is not an integer, float division is used
1.5
```
Add:
```
from __future__ import division
``... | In python2.x `/` performs integers division.
```
>>> 3/2
1
```
To get desired result you can change either one of the operands to a float using `float()`:
```
>>> 3/2. #3/2.0
1.5
>>> 3/float(2)
1.5
```
or use `division` from `__future__`:
```
>>> from __future__ import division
>>> 3/2
1.5
``` | Division in Python 3 gives different result than in Python 2 | [
"",
"python",
"python-3.x",
"python-2.x",
""
] |
I have imported some data from an excel table in to an SQL table and I now need to write a view over the data to combine it with some other fields.
My problem is that the table is in the following form with these columns;
**Name** **Project\_One\_ID** **Project\_Two\_ID** **Project\_Three\_ID**
Rather than the form ... | You could do it as a `UNION` and then join to other tables:
```
SELECT * FROM
(
SELECT Name, Project_One_ID ProjectID
FROM Projects
UNION ALL
SELECT Name, Project_Two_ID ProjectID
FROM Projects
UNION ALL
SELECT Name, Project_Three_ID ProjectID
FROM Projects
) AS P
INNER JOIN ProjectData... | Depending on your version of SQL Server you can use CROSS APPLY to UNPIVOT the data.
CROSS APPLY and VALUES will work in SQL Server 2008+:
```
select name,
ProjectId
from yourtable
cross apply
(
values
('Project_One_ID', Project_One_ID),
('Project_Two_ID', Project_Two_ID),
('Project_Three_ID', Project_Three... | SQL flat table query | [
"",
"sql",
"sql-server",
""
] |
I'm plotting some data based on pandas dataframes and series. Following is a part of my code. This code gives an error.
```
RuntimeError: underlying C/C++ object has been deleted
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
fig = plt.figure()
dfs = df['col2'].resample('1... | Following is the part of code which gave me the expected result, there may be more elegant ways to do this;
```
def plotGraph(X):
fig = plt.figure()
X.plot()
return fig
plot1 = plotGraph(dfs)
plot2 = plotGraph2(reg[:-10])
pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.close()
``` | Please see the [following](http://pandas.pydata.org/pandas-docs/dev/visualization.html#targeting-different-subplots) for targeting different subplots with Pandas.
I am assuming you need 2 subplots (in row fashion). Thus, your code may be modified as follows:
```
from matplotlib import pyplot as plt
fig, axes = plt.s... | Multiple matplotlib plots in same figure + in to pdf-Python | [
"",
"python",
"pdf",
"matplotlib",
"plot",
"pandas",
""
] |
I'm looking for a way to essentially screen capture a whole wxPanel, and save it as a PNG. The kicker is, there is no screen. I need to be able to "draw" the panel and save the drawn panel with no actual screen. I'm using Python 2.7, running on Ubuntu 12.04.
Is this possible? | I found the trick, and lo, its name is VFB: <http://linux.die.net/man/1/xvfb> | I wrote a tutorial on how to do this sort of thing here:
* <http://www.blog.pythonlibrary.org/2010/04/16/how-to-take-a-screenshot-of-your-wxpython-app-and-print-it/>
However, as someone already pointed out, if X (or similar) is unavailable, then you won't be able to generate a GUI of any sort. Or perhaps you meant a ... | Saving wxPanel to Image | [
"",
"python",
"python-2.7",
"wxpython",
"wxwidgets",
"image-capture",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.