Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I want to write code to get data from Excel and write it to a text file. Here is the code I have:
```
import xlrd
import os.path
wb = xlrd.open_workbook(os.path.join('D:\TRB 2014 Data','SPS1 demo data.xlsx'))
wb.sheet_names()
sh = wb.sheet_by_index(0)
i = 1
while sh.cell(i,11).value != 0:
Load = sh.cell(i,11).val... | You should [open](http://docs.python.org/2/library/functions.html#open) the `output.txt` file with `append mode`:
```
file = open("Output.txt", "a")
```
Also, you should do this before entering the loop, and it should be closed after that loop.
---
**Update**:
In cases like this one, you could use `with` instead o... | ```
import xlrd
workbook=xlrd.open_workbook("xxx.xls")
sh=workbook.sheet_by_name("test1")
print sh.nrows
print sh.ncols
n=0
i=0
file=open("xxx.txt","w")
for n in range(sh.nrows):
for i in range(sh.ncols):
data =sh.cell_value(n,i)+" "
print data,
file.write(data+" ")
print
file.wri... | How to read data from Excel and write it to text file line by line? | [
"",
"python",
"xlrd",
""
] |
I have a list: `[6,7,8,9,10]` , Now I want to shift it 2 times to the right and replace the shifted position by `0`. The output will be something like : `[0,0,6,7,8]`
Is it possible? | You could do it directly:
```
>>> a = [6, 7, 8, 9, 10]
>>> [0, 0] + a[:3]
[0, 0, 6, 7, 8]
```
To shift it by a variable number of positions `n`:
```
>>> [0]*n + a[:len(a)-n]
```
Appropriate bounds checking is up to you (try `n=6` to with a 5-element list for an unexpected result). | ```
>>> s = [6,7,8,9,10]
>>> def lpadzero(s, n):
... return [0] * n + s[:-n]
>>> lpadzero(s, 2)
[0, 0, 6, 7, 8]
``` | How to shift a list nth time in Left or Right and fill it up with 0 in python | [
"",
"python",
""
] |
I've created a general tree in python, by creating a Node object. Each node can have either 0, 1, or 2 trees.
I'm trying to create a method to print a list of all the nodes in a tree. The list need not be in order. Here's my simplistic attempt:
```
def allChildren(self, l = list()):
l.append(self)
for child i... | try this:
```
def allChildren(self, l = None):
if(l==None):
l = list()
l.append(self)
for child in self.children:
l = child.allChildren(l)
return l
```
And check out [this answer](https://stackoverflow.com/questions/1651154/why-are-default-arguments-evaluated-at-definition-time-in-pyt... | You have a mutable value as the default value of your function parameter `l`. In Python, this means that when you call `l.append(self)`, you are permanently modifying the default parameter.
In order to avoid this problem, set `l` to a new list every time the function is called, if no list is passed in:
```
def allChi... | Python: printing all nodes of tree unintentionally stores data | [
"",
"python",
"class",
"python-3.x",
"tree",
""
] |
I'm newbie to algorithm and optimization.
I'm trying to implement **capacitated k-means**, but getting unresolved and poor result so far.
This is used as part of a CVRP simulation (capacitated vehicle routing problem).
I'm curious if I interprets the referenced algorithm wrong.
Ref: ["Improved K-Means Algorithm ... | When the total demand is close to the total capacity, this problem begins to take on aspects of [bin packing](https://en.wikipedia.org/wiki/Bin_packing_problem). As you've discovered, this particular algorithm's greedy approach is not always successful. I don't know whether the authors admitted that, but if they didn't... | Without going through all the details, the paper you cite says
```
if ri is not assigned then
choose the next nearest centroid
end if
```
in the algorithm at the end of section 5.
There must be a next nearest centroid - if two are equidistant I presume it doesn't matter which you choose. | Capacitated k-means clustering? | [
"",
"python",
"algorithm",
"optimization",
"cluster-analysis",
"k-means",
""
] |
I want to implement a basic auth dialog style authentication in Django
Example -
When you visit some website, a dialog pops up. It's a native dialog. It has a simple message asking for username, password and below it there are two textboxes to enter username password.
I have searched a bit but did not find anythin... | There are plenty of ways to do that.
If you want standard HTTP Basic Auth with static username/password that can be configured via `settings.py`, you can create a middleware. Check <http://djangosnippets.org/snippets/2468/>. It's also quite simple with [Apache](http://wiki.apache.org/httpd/PasswordBasicAuth) or [nginx... | You can use <https://github.com/nopped/django-http-auth> which gives you the ability to add HTTP Basic Authentication using middleware or decorator on specific views. | How to implement basic auth in Django | [
"",
"python",
"ruby-on-rails",
"django",
"authentication",
""
] |
I have a db in PostgreSQL 9.0, which has a table with a string field to store client codes.
These codes are alphanumeric and can start with a letter or number, for example `1, 2, A0001-4, A0001-2, 10`
I want to order numeric first and then order by string, like
```
1, 2, 10, A0001-2, A0001-4
```
I do this with `to_n... | ```
WITH empleados(legajo) AS (
VALUES
('A0001-4'::text)
,('123.345-56')
,('ve')
,('123')
,('123 ve')
)
SELECT *
FROM empleados
ORDER BY CASE WHEN legajo ~ '\D' THEN 1000000000::int
ELSE to_number(legajo, '999999999')::int END
,legajo;
```
[`~` is ... | You can use a case statement to find the numbers:
```
select *
from empleados
order by (case when legajo not similar to '%[^0-9]%' then 1 else 0 end) desc,
(case when legajo not similar to '%[^0-9]%' then to_number(legajo, '999999999') end),
legjo;
```
The `similar to` expression is saying that all ... | How to order query by number first and then by string in the same field | [
"",
"sql",
"postgresql",
"pattern-matching",
"sql-order-by",
"natural-sort",
""
] |
I have the following table in SQL
```
AL1 | AL2 | AL3 | ACB | LL1 | LL2 | LL3 | LCB
------------------------------------------------
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
```
I would like to convert it as
```
| L1 | L2 | L3 | CB
-----------------------------
A | 1 | 2 | 3 | 4
L | 5 ... | You can select both with different query and join them using `UNION`
```
SELECT 'A' AS COL, AL1, AL2, AL3, ACB
FROM TBL
UNION
SELECT 'L' AS COL, LL1, LL2, LL3, LCB
FROM TBL;
```
Output:
```
| COL | AL1 | AL2 | AL3 | ACB |
-------------------------------
| A | 1 | 2 | 3 | 4 |
| L | 5 | 6 | 7 | ... | Another way (the same plan as Devart's but more concise syntax)
```
SELECT V.*
FROM TBL
CROSS APPLY (VALUES ('A', AL1,AL2,AL3,ACB),
('L', LL1,LL2,LL3,LCB)) V( COL, LL1, LL2, LL3, LCB)
```
[SQL Fiddle](http://sqlfiddle.com/#!3/5d7d3/2) | SQL multiple columns grouping in one row | [
"",
"sql",
"sql-server",
"grouping",
""
] |
I have a function which performs an expensive operation and is called often; but, the operation only needs to be performed once - its result could be cached.
I tried making an infinite generator but I didn't get the results I expected:
```
>>> def g():
... result = "foo"
... while True:
... yield resu... | Here's a dead-simple caching decorator. It doesn't take into account any variations in parameters, it just returns the same result after the first call. There are fancier ones out there that cache the result for each combination of inputs ("memoization").
```
import functools
def callonce(func):
result = []
... | `g()` is a generator *function*. Calling it returns the generator. You then need to use that generator to get your values. By looping, for example, or by calling [`next()`](http://docs.python.org/2/library/functions.html#next) on it:
```
gen = g()
value = next(gen)
```
Note that calling `g()` again will calculate the... | Function which computes once, caches the result, and returns from cache infinitely (Python) | [
"",
"python",
"caching",
"python-2.7",
"generator",
""
] |
I have a project setup looks like this:
**Base project**
```
/some_disk/some_folder/
|-- project/
| |-- package/
| | |-- src/
| | | |-- file_a.py
| | | |-- file_b.py
```
**Extension project**
```
/some_other_disk/some_folder/
|-- project/
| |-- package/
| | |-- src/
| | | |-- file_c.py... | Create a package file `__init__.py` in each of your `src` directories. They should contain the following two lines. See [this documentation](http://docs.python.org/2/library/pkgutil.html#module-pkgutil) for details. This solution works on Python 2.6 and is the canonical solution.
```
from pkgutil import extend_path
__... | This will make python search in your current directory/standard directories first, and for the second one, python will search in your pathtofile\_c first before standard directories.
```
import project.module.src.file_a #<--- here it searches some_disk first
sys.path.insert(0,'pathtofile_c') #<--- Changes your PYTHON... | Python: How to import sub-modules, from packages with the same name? | [
"",
"python",
"import",
"module",
""
] |
Recently I was Playing with SQL Server data types, and a Large number of data in the table and trying to figure out the Performance with Varchar and Numeric data. But, I got some error which I don't think should not have been but it is. My problem is below :
I have a table :
```
create table sa(f1 varchar(100))
```
... | According to MS documentation (see <https://learn.microsoft.com/en-us/sql/t-sql/functions/sum-transact-sql>), the `SUM()` function returns values of a different type, according to the datatype of the column you are adding: if the column is of type `int`, `tinyint`, or `smallint`, then SUM returns values of type `int`.
... | You're summing as `INT` which has a range that cannot hold that sum.
The `DECIMAL` can.
The sum of all values from 1 up to 99999 is 4999950000, the maximum INT value is 2147483647, less than half of what the sum ends up as.
When you sum INT's, you're getting a new INT. When you're summing DECIMAL's, you're getting a... | Sql Server SUM function with Int and Decimal Conversion | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Please help me find the cause of this problem with my Django installation on Windows.
```
C:\Djangoprojects>django-admin.py startproject mydjangoblog
Traceback (most recent call last):
File "C:\Python27\Scripts\django-admin.py", line 4, in <module>
import pkg_resources
File "build\bdist.win-amd64\egg\pkg_resourc... | I finally was able to fix this problem. Here is what I did after spending some time on Stackoverflow:
* Leave everything the way it was installed by easy\_install when I installed it.
* Make sure that there is one django installation.
* Make sure the `django-admin.py` is inside Python27\Scripts
* To create a django pr... | I suggest you to use [virtualenv](http://www.virtualenv.org/en/latest/) to maintain a clean python environment.
1. install virtualenv, and add it to your env-path
2. run cmd `mkvirtualenv django` to create the env for your django project
3. run `pip.exe install` to install needed libraries. | I cannot create a project because of Django installation on Windows | [
"",
"python",
"django",
""
] |
I am adding some validation to a couple of stored procedures and need to check if some of the variables are not null (they are populated earlier in the stored procedure).
I have been trying to add a "throw" inside an if statement like below:
```
IF (@val is null)
BEGIN
THROW 50001, 'Custom text', 1
END
```
This ... | The syntax error is showing up because the previous statement hasn't been terminated. The other answers will work, but in order to do it this way you can either throw a semicolon right before the THROW, or get in the habit of terminating all statements with semicolons.
```
IF (@val is null)
BEGIN
;THROW 50001, 'Cu... | If this is for SQL Server, the intellisense syntax highlighter doesn't like it, but the code should compile and run fine. Of course, with it being a single statement, you don't need the `BEGIN`...`END` block at all:
```
IF (@val is null) THROW 50001, 'Custom text', 1
``` | SQL only a throw inside if statement | [
"",
"sql",
"sql-server",
"if-statement",
"throw",
""
] |
What is the fastest way to check if a SQLite table has more than 100,000 rows?
---
The test table has 26 columns and 200,000,000 rows.
```
SELECT COUNT(*) FROM ( SELECT * FROM table LIMIT 100001 )
```
took 0.27 seconds.
The following three needed 12 and a half minutes
```
SELECT COUNT(*) FROM table
SELECT COUNT(*... | ```
select count(*) from (
select top 100001 ID from T
) x
```
We need to scan an index to answer the query. This at least restricts the index scan to the first 100001 rows. If the table has 1m rows, this saves 90% of the work.
(Using SQL Server syntax here - please translate yourself because I can't do it).
Instea... | ```
SELECT COUNT(indexed_column) FROM TableName
```
Now the indexed column part is the important thing, you don't want to do something like counting \*, you want to be as specific as possible forcing SQL to use an index that is existing for each row on that table. | SQLite: fastest way to check if a table has more than x rows | [
"",
"sql",
"sqlite",
""
] |
I have a large sorted file with one number per line. I want to output the number of numbers in each range of some size. So for example taking the range to be 10 and the input as
```
1
4
34
37
42
48
53
```
The output should be `[2, 1, 3, 2, 2, 2, 1]`. This is the length of `[1,4], [4], [34,37,42], [37,42], [42,48], [4... | Here is a solution that uses `itertools.tee()` to simulate reading from handles, but only actually opening one:
```
from itertools import tee
def sliding_range(file, size):
fin1, fin2 = tee(int(ln.strip()) for ln in open(file) if ln.strip())
n = 1
next(fin2)
val2 = next(fin2)
for val1 in fin1:
... | Here's an implementation, there might be a better way to do it but this should work. I'm assuming the same input you posted in your question.
```
def ranges(n):
f = open("tmp.txt")
while True:
i = f.tell()
try:
curr = int(f.readline().rstrip())
except ValueError:
... | Counting the number of points in a sliding range | [
"",
"python",
""
] |
I am creating a `setup.py` file for a project which depends on private GitHub repositories. The relevant parts of the file look like this:
```
from setuptools import setup
setup(name='my_project',
...,
install_requires=[
'public_package',
'other_public_package',
'private_repo_1',
... | I was trying to get this to work for installing with pip, but the above was not working for me. From [1] I understood the `PEP508` standard should be used, from [2] I retrieved an example which actually does work (at least for my case).
Please note; this is with `pip 20.0.2` on `Python 3.7.4`
```
setup(
name='<pa... | Here's what worked for me:
```
install_requires=[
'private_package_name==1.1',
],
dependency_links=[
'git+ssh://git@github.com/username/private_repo.git#egg=private_package_name-1.1',
]
```
Note that you have to have the version number in the egg name, otherwise it will say it can't find the packa... | Python setuptools: How can I list a private repository under install_requires? | [
"",
"python",
"github",
"setuptools",
""
] |
```
allt = []
with open('towers1.txt','r') as f:
towers = [line.strip('\n') for line in f]
for i in towers:
allt.append(i.split('\t'))
print allt [0]
```
now i need help, im inputting this text
```
mw91 42.927 -72.84 2.8
yu9x 42.615 -72.58 2.3
HB90 42.382 -72.679 2.4
```
and when i output im g... | Are you sure those are tabs? You can specify no argument for split and it automatically splits on whitespace (which means you won't have to strip newlines beforehand either). I copied your sample into a file and got it to work like this:
```
allt = []
with open('towers1.txt','r') as f:
for line in f:
all... | [] implies a list.
'' implies a string.
allt = ['mw91 42.927 -72.84 2.8']
allt is a list that contains a string:
allt[0] --> 'mw91 42.927 -72.84 2.8'
allt[0][2] --> '9'
allt.split() --> ['mw91', '42.927', '-72.84', '2.8']
allt.split()[2] --> '-72.84' #This is still a string.
float(allt.split()[2]) --> -72.84 #T... | Trying to input data from a txt file in a list, then make a list, then assign values to the lines | [
"",
"python",
"string",
"list",
"append",
""
] |
I'm just learning to program on Codeacademy. I have an assignment, but cant figure out what I'm doing wrong.
First I need to define a function that returns the cube of a value. Then I should define a second function that checks if a number is divisible by 3. If it is I need to return it, otherwise I need to return `Fa... | You are not catching the return value of the function `cube`. Do `b = cube(b)`. Or better yet, do `return cube(b)`.
```
def cube(c):
return c**3
def by_three(b):
if b % 3 == 0:
b = cube(b)
return b # Or simply return cube(b) and remove `b = cube(b)`
else:
return False
```
When... | I think this answer might also work:
```
def cube(b,c):
b = c ** 3
if b % 3 == 0:
return b
else:
return False
return b
```
I know that might be a little redundant but I think that might be another way of doing what you're trying to do. What Sukrit did I thin... | (Beginner)Python functions Codeacademy | [
"",
"python",
""
] |
I have a class Population that contains several method.
According to an input I want the run the method on an instance of the class `Population` in a given order.
To be a bit more accurate in what I am trying to achieve is quite the same than using is something like that:
```
stuff = input(" enter stuff ")
dico = {... | Pass the instance explicitly as first argument:
```
method_to_use = order[i]
method_to_use(my_pop)
```
Full working code:
```
order_type = 'a'
class Population (object):
def __init__(self,a):
self.a = a
def method1 (self):
self.a = self.a*2
return self
def method2 (self):
... | Use `getattr`:
```
order = {1:'method1', 2:'method2', 3:'method3'} #values are strings
...
method_to_use = order[i]
getattr(mypop, method_to_use)()
``` | Using a dictionary to control the flow of methods | [
"",
"python",
"methods",
"dictionary",
""
] |
I have csv files with unwanted first characters in the header row except the first column.
The while loop strips the first character from the headers and writes the new header row to a new file (exit by counter). The else statement then writes the rest of the rows to the new file. The problem is the else statement begi... | If you only want to change the header and copy the remaining lines without change:
```
with open('file.csv', 'r') as src, open('file2.csv', 'w') as dst:
dst.write(next(src).replace(" ", "")) # delete whitespaces from header
dst.writelines(line for line in src)
```
If you want to do additional transformati... | If all you want to do is remove spaces, you can use:
```
string.replace(" ", "")
``` | Python loops through CSV, but writes header row twice | [
"",
"python",
"csv",
"python-2.7",
""
] |
I'm trying to upload an image to my uploads folder on my remote server. The folder structure is always `uploads/year/month/` and I can't get paramiko to check if the folders exist and if not make them.
SSH connection is working, uploading a file is working too, but creating the subfolders in the uploads directory isn'... | [CClauss](https://github.com/cclauss) got the answer and put it in the comment section of the gist linked above. I take no credit.
This was his answer - in cause anyone else tries to emulate `mkdir -p` with paramiko, then here you go:
> My sense is that you need to: Try to mkdir on :/home/ Try to mkdir on
> :/home/us... | You run into the same problem with FTP, you can't mkdir /some/long/path, you have to
```
cd /
mkdir some # ignore errors if it exists
cd some
mkdir long # ignore errors if it exists
cd long
mkdir path # ignore errors if it exists
cd path
```
I'm guessing that the historical reason for this model is to provide a simp... | SFTP Upload via Python and Pythonista with Paramiko. Can't create directory/subdirectory | [
"",
"python",
"sftp",
"paramiko",
"mkdir",
"pythonista",
""
] |
I'm current working through *Learning Python the Hard Way*, and it is perhaps going a little fast for me. I've input the following code, with along with the corresponding file. In the py file, I wrote:
```
#!/usr/bin/python
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %... | 1. `#!/usr/bin/python` is the so-called Shebang, a hint to the OS kernel that it is a Python script which should be executed with the given Python binary. Thus, if you `chmod +x` the script, you can even call it with `./script.py readme.txt`.
2. `from sys import argv` is a command to import `argv` from the `sys` module... | Answers:
1) #!/usr/bin/python is there for UNIX users, it shows python where to find certain files. ([Why do people write #!/usr/bin/env python on the first line of a Python script?](https://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script))
2) sys import... | Opening files with Python | [
"",
"python",
"python-2.7",
"python-3.x",
""
] |
I have this code to get followers of a twitter user:
```
followers=[]
for user in tweepy.Cursor(api.followers,id=uNameInput).items():
followers.append(user.screen_name)
```
However if this is used on a user with multiple followers, the script gets a rate limit and stops. I would usually put this in a while true; ... | If you want to avoid rate limit, you can/should wait before the next follower page request:
```
for user in tweepy.Cursor(api.followers, id=uNameInput).items():
followers.append(user.screen_name)
time.sleep(60)
```
Doesn't look beautiful, but should help.
UPD: According to the official [twitter limits](https... | There's a more precise way to do this with the new rate\_limit\_status' reset attribute. Whereas @alecxe's answer forces you to wait 15 minutes each time, even if the window is much smaller, you can instead wait just the right amount of time and no longer by doing:
```
import time
import tweepy
import calendar
import ... | Tweepy Hipchat API - Except rate limit? | [
"",
"python",
"twitter",
"tweepy",
""
] |
I have read alot of strange syntaxerror questions and have not seen mine among it yet and I am really at a loss. I am doing some homework for which the deadline is coming closer and this error I cant get rid of:
```
def create_voting_dict():
strlist = [voting_data[i].split() for i in range(len(voting_data))]
r... | You cannot define in a `return`. (Because assignments do not return values) Just do
```
return {strlist[h][0]:[int(strlist[h][g]) for g in range(3, len(strlist[h]))] for h in range(len(strlist))}
```
Or define a `voting_dict` in a new statement and then `return voting_dict`.
See the example -
```
>>> def test():
... | Its problem with your return statement in which you cannot carry out assignments. Just do it a step before. | Strange SyntaxError: invalid syntax after defining statement in return | [
"",
"python",
"return",
"syntax-error",
""
] |
I have a table like this:
```
id description status login
XWPggD bbbbbbbb 1 js
0JIERf test1 1 js
0gd2x0 nothing NULL js
bSIUIu dev NULL bob
0BNh27 hello 1 js
2TYXjd down NULL inge
axE1m5 bob... | Why so complicated answers ...
```
SELECT id, description, status, login FROM dev
ORDER BY status IS NULL, status DESC, login IS NULL, login DESC
``` | ```
SELECT id, description, status, login FROM dev
ORDER BY (Case when status is null then -1 Else status End ) Desc,
(Case when login is null then -1 Else 1 End ) Desc
``` | Order by NULL values with mysql | [
"",
"mysql",
"sql",
"sql-order-by",
""
] |
I thought i've learned enough python to make a caesar cipher, so I started making it and i've hit a brick wall.
Here is my code:
```
phrase = raw_input("Enter text to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ("Encrypted text is: ")
for character in phrase:
x = ord(character)
x = x ... | Your code is printing `ord()` value of `'j'` because at the end of loop character is equal to `'i'`. You should store the new characters to a list, and after the end of the loop you should join them and then print.
```
new_strs = []
for character in phrase:
x = ord(character)
x = x + shift
new_strs.append(... | Append each encrypted character to the `result` string.
```
phrase = raw_input("Enter text to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ""
for character in phrase:
x = ord(character)
result += chr(x + shift)
print result
``` | Python Caesar Cipher Using Ord and Chr | [
"",
"python",
"loops",
""
] |
I have a pandas dataframe with the following columns:
```
data = {'Date': ['01-06-2013', '02-06-2013', '02-06-2013', '02-06-2013', '02-06-2013', '03-06-2013', '03-06-2013', '03-06-2013', '03-06-2013', '04-06-2013'],
'Time': ['23:00:00', '01:00:00', '21:00:00', '22:00:00', '23:00:00', '01:00:00', '21:00:00', '2... | It's worth mentioning that you may have been able to read this in **directly** e.g. if you were using [`read_csv`](https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html) using `parse_dates=[['Date', 'Time']]`.
Assuming these are just strings you could simply add them together (with a space), allowing you t... | The accepted answer works for columns that are of datatype `string`. For completeness: I come across this question when searching how to do this when the columns are of datatypes: date and time.
```
df.apply(lambda r : pd.datetime.combine(r['date_column_name'],r['time_column_name']),1)
``` | Combine Date and Time columns using pandas | [
"",
"python",
"pandas",
"datetime",
"time-series",
""
] |
I am at a complete loss here. I have two databases. One on my localhost site that I use for development and one on my remote site that I use for my live (production) site. I manage both of them through phpMyadmin. As I have been doing for months now, when I need to update the live site, I dump the related database and ... | you need to dump with the drop statements. The table exists and has data already and your trying to insert more which is identical. Im not 100% sure on phpmyadmin but the dumps will have an option for "add drop table" statements | Dump your database on localhost with "mysqldump --insert-ignore ..." then try to import with phpmyadmin on your live machine.
Or try to connect to your live database with command line tools (configure your database to be able to connect from other hosts than "localhost" first!)
Then you can try following:
$ mysql -f... | #1062 - Duplicate entry '1' for key 'PRIMARY' | [
"",
"mysql",
"sql",
"phpmyadmin",
""
] |
I need all entrys where the `curdate` is today...
`curdate` is of type `timestamp`.
Of course I searched in google for this but I think I have used the wrong keywords.
```
select * from ftt.element fee, ftt.plan p
where p.id=ftt.p_id and curdate ???
order by p_id, curdate desc;
```
Could you provide me? | `SYSDATE` returns the current datea **and** time in Oracle. A `DATE` column also contains a time part in Oracle - a `TIMESTAMP` column as well.
In order to check for "today" you must remove the time part in both values:
```
select *
from ftt.element fee
join ftt.plan p on p.id=ftt.p_id
where trunc(curdate) = trun... | This answer is very similar to a\_horses\_with\_no\_name's answer. Difference is that it perform faster. Making a calculation on a column before comparing will slow down performance.
```
select *
from ftt.element fee
join ftt.plan p on p.id=ftt.p_id
where curdate >= trunc(sysdate)
and curdate < trunc(sysdate + 1)
or... | SQL "Where" syntax for is today | [
"",
"sql",
"oracle",
"timestamp",
""
] |
Say I have the following as a join in a larger query aliased as 'overall'
```
INNER JOIN (SELECT
tts.typ,tts.amount,
tts.term_sale_id,
tts.term_sale_id,
tts.from_price
FROM tb_term_sale_entries tts
W... | Viewing the query execution plan ([How do I obtain a Query Execution Plan?](https://stackoverflow.com/questions/7359702/how-do-i-obtain-a-query-execution-plan)) should help you determine which of the two options will be more efficient.
In this case though, I'm 99% that you are going to want to keep your condition insi... | As it is treated as Sub query SQL Engine executes the term\_sale and operates on the data set that has been created after the execution of this query.Only the comparison part i.e. On
part is done row by row.
regards
Ashutosh Arya | Is a JOIN subquery, created once as a table or is it reevaluated each time? | [
"",
"sql",
"join",
"subquery",
""
] |
Is it possible to only merge some columns? I have a DataFrame df1 with columns x, y, z, and df2 with columns x, a ,b, c, d, e, f, etc.
I want to merge the two DataFrames on x, but I only want to merge columns df2.a, df2.b - not the entire DataFrame.
The result would be a DataFrame with x, y, z, a, b.
I could merge t... | You could merge the sub-DataFrame (with just those columns):
```
df2[list('xab')] # df2 but only with columns x, a, and b
df1.merge(df2[list('xab')])
``` | You want to use TWO brackets, so if you are doing a VLOOKUP sort of action:
```
df = pd.merge(df,df2[['Key_Column','Target_Column']],on='Key_Column', how='left')
```
This will give you everything in the original df + add that one corresponding column in df2 that you want to join. | Python Pandas merge only certain columns | [
"",
"python",
"merge",
"pandas",
""
] |
In Python 2, we could reassign `True` and `False` (but not `None`), but all three (`True`, `False`, and `None`) were considered builtin variables. However, in Py3k all three were changed into keywords as per [the docs](http://docs.python.org/3.0/whatsnew/3.0.html).
From my own speculation, I could only guess that it w... | Possibly because Python 2.6 not only allowed `True = False` but also allowed you to say funny things like:
```
__builtin__.True = False
```
which would reset `True` to `False` for the entire process. It can lead to really funny things happening:
```
>>> import __builtin__
>>> __builtin__.True = False
>>> True
False
... | For two reasons, mainly:
1. So people don't do a `__builtin__.True = False` prank hidden on a random module. (as explained by devnull)
2. Because keywords are faster than global builtins. In Python 2.x, the interpreter would have to resolve those variables' values before using them, which is a bit slower than keywords... | Why were True and False changed to keywords in Python 3 | [
"",
"python",
"keyword",
""
] |
I want All **CREATE** statements of MySql Tables in 1 query result.
For example, **INFORMATION\_SCHEMA** contains all *table names,comments* etc. but where are the **CREATE** statements are stored in MySql ? can it be retrieved in one query for all tables ?
Currently i am retrieving **TABLE** ddl as below for 1 table... | ```
mysqldump -h localhost -u root -p --no-data --compact some_db
mysqldump -d --compact --compatible=mysql323 ${dbname}|egrep -v "(^SET|^/\*\!)"
```
[How do I use mysqldump to export only the CREATE TABLE commands](https://stackoverflow.com/questions/1842076/how-do-i-use-mysqldump-to-export-only-the-create-table-c... | I needed this today, and [the `mysqldump` answer](https://stackoverflow.com/a/18050973/2223027) generated me a .sql file that I could not import: it declared full `CREATE TABLE` statements with foreign keys pointing to tables it had not declared yet.
Instead, I used [Liquibase](https://docs.liquibase.com/):
1. Downlo... | Generate CREATE statements for all MySql Tables | [
"",
"mysql",
"sql",
"information-schema",
""
] |
I want to replicate boolean `NA` values as they behave in R:
> NA is a valid logical object. Where a component of x or y is NA, the result will be NA if the outcome is ambiguous. In other words NA & TRUE evaluates to NA, but NA & FALSE evaluates to FALSE.
> <http://stat.ethz.ch/R-manual/R-devel/library/base/html/Logic... | As other have said, you can define your own class.
```
class NA_(object):
instance = None # Singleton (so `val is NA` will work)
def __new__(self):
if NA_.instance is None:
NA_.instance = super(NA_, self).__new__(self)
return NA_.instance
def __str__(self): return "NA"
def _... | You can do this by creating a class and overriding the boolean operation methods.
```
>>> class NA_type(object):
def __and__(self,other):
if other == True:
return self
else:
return False
def __str__(self):
r... | How to do boolean algebra on missing values? | [
"",
"python",
"boolean-expression",
""
] |
I create a LabelFrame widget. It has a nice size in the beginning:
```
import Tkinter
form = Tkinter.Tk()
errorArea = Tkinter.LabelFrame(form, text=" Errors ", width=250, height=80)
errorArea.grid(row=2, column=0, columnspan=2, sticky="E", \
padx=5, pady=0, ipadx=0, ipady=0)
```
![enter image descriptio... | That problem always was interesting to me. One way I found to fix it is by using the `place` method instead of `grid`:
```
import Tkinter
form = Tkinter.Tk()
errorArea = Tkinter.LabelFrame(form, text=" Errors ", width=250, height=80)
errorArea.grid(row=2, column=0, columnspan=2, sticky="E", \
padx=5, pa... | If you use a sticky value that sticks the widget to all four sides of its cell rather than just one side, it won't shrink when you put a small label widget in it.
Another option is to call `errorArea.grid_propagate(False)`, which tells the grid area not to shrink or expand to fit its contents. This will often result i... | How to prevent Tkinter labelframe size changes when an empty label is inserted | [
"",
"python",
"widget",
"tkinter",
"size",
""
] |
I don't know why i can't find it, but i wanted to replace the special character `'\'` in python.
I have a String within i have `'\'` characters but i confident find the solution, to replace it with '-'.
This is what happening while i am trying to replace,
```
>>> x = 'hello\world'
>>> x
'hello\\world'
>>> x.replace('... | You need to escape it with another backslash:
```
x.replace('\\', '-')
```
Backslashes are special, in that they are used to introduce non-printing characters like newlines into a string.
It's also how you add a `'` character to a `'`-quoted string, which is what Python thinks you were trying to do. It sees `\'` an... | According to [docs](http://docs.python.org/2/reference/lexical_analysis.html):
> The backslash (\) character is used to escape characters that
> otherwise have a special meaning, such as newline, backslash itself,
> or the quote character.
You need to escape backslash with another backslash:
```
x.replace('\\', '-')... | Replace '\' character in python | [
"",
"python",
"string",
""
] |
I am using python's subprocess `call()` to execute shell command.
It works for a single command.
But what if my shell command calls a command and pipe it to another command.
I.e. how can I execute this in python script?
```
grep -r PASSED *.log | sort -u | wc -l
```
I am trying to use the Popen way, but i always get... | Call with `shell=True` argument. For example,
```
import subprocess
subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True)
```
---
## Hard way
```
import glob
import subprocess
grep = subprocess.Popen(['grep', '-r', 'PASSED'] + glob.glob('*.log'), stdout=subprocess.PIPE)
sort = subprocess.Popen(['s... | The other answers would work. But here's a more elegant approach, IMO, which is to use [`plumbum`](http://plumbum.readthedocs.org/).
```
from plumbum.cmd import grep, sort, wc
cmd = grep['-r']['PASSED']['*.log'] | sort['-u'] | wc['-l'] # construct the command
print cmd() # run the command
``` | How can I execute shell command with a | pipe in it | [
"",
"python",
"shell",
""
] |
I have a Python list as follows,
```
demo= {'age': 90, 'id': '12#2'}
{'age': 12, 'id': '12#3'}
{'age': 67, 'id': '12#1'}
{'age': 56, 'id': '12#2'}
{'age': 34, 'id': '12#2'}
```
How can I sort this list with id attribute?
I have tried
```
sorted(demo, key=lambda x: x.id) # sort by id
```
but it failed.
Expected ... | Your code fails with an `AttributeError` because you are trying to do a lookup of `id` in a `dict` object, which doesn't have one. You need to access the desired dictionary key:
```
sorted(demo, key=lambda x: x['id'])
```
However, that will fail with a `KeyError` if at least one entry in the list does not have the `i... | If `demo` is the list (note the brackets and commas)
```
demo= [{'age': 90, 'id': '12#2'},
{'age': 12, 'id': '12#3'},
{'age': 67, 'id': '12#1'},
{'age': 56, 'id': '12#2'},
{'age': 34, 'id': '12#2'}]
```
Then you could sort it by `id` with:
```
sorted(demo, key=lambda x: x['id'])
```
For ... | How to custom sort in a Python list? | [
"",
"python",
""
] |
Before you mark this as duplicate please take a look at this [SQLFiddle](http://sqlfiddle.com/#!2/336d6/1).
I have this schema:
```
CREATE TABLE book(book_id int,
book_name varchar(100),
author_id int,
editor_id varchar(100),
isbn varchar(100... | Instead of `MAX()` you can simply use `LIMIT` for the same. Also use `JOIN` instead.
```
SELECT book_count,a.author_id,a.fn, a.ln
FROM author a
JOIN
(
SELECT c.author_id,COUNT(*) book_count FROM book c
GROUP BY c.author_id
) b
ON a.author_id = b.author_id
ORDER BY book_count DESC LIMIT 1
```
Output:
```
| BOOK... | In fact, MySQL has a lack of support SQL's standard, because it allows use aggregate functions w/o GROUP BY clause and returns random data in result. You should avoid the usage of aggregates in that way.
EDIT:
I mean, for example in MySQL you can execute query like this:
```
SELECT
MAX(a), b, c
FROM
table
GROUP B... | MySQL: Select MAX() from sub-query with COUNT() | [
"",
"mysql",
"sql",
"aggregate-functions",
""
] |
My table will contain the following values. **h1,h2,h3** are varchar fields with size 1
```
**Register Date Year Batch h1 h2 h3**
1138M0321 02-08-2013 3 1 A A NULL
1138M0323 02-08-2013 3 1 P P NULL
1138M0324 02-08-2013 ... | The `NULL` value must be SQL, not a .NET value, so instead of trying things like:
```
"... SET h1 = " & NULL & " ... "
```
Simply use this in the query:
```
"... SET h1 = NULL ... "
```
Note that:
> Null values cannot be used for information that is required to distinguish one row in a table from another row in a ... | Why use VB Nulls at all ...
```
UPDATE student_attendance_table SET h1 = NULL WHERE...
``` | Replacing a value with NULL in a table in SQL Server using vb.net | [
"",
"sql",
"sql-server",
"vb.net",
""
] |
I am having some trouble figuring out how to do relative imports in Python. I am currently working on my first major project so I want to do it right using unit tests. However, I am having trouble with my file structure and relative imports.
Here is my current structure:
```
App/
__init__.py
src/
__init__.py
... | you could append it to sys.path.
```
import sys
sys.path.append("../src")
import person
``` | My guess (and I'll delete this if I'm wrong) is that you're trying to use `person_tests.py` as a top-level script, rather than as a module inside a package, by doing something like this:
```
$ cd App/tests
$ python person_tests.py
```
In that case, `person_tests` does not end up as `App.tests.person_tests`, but as ju... | Relative Import Confusion in Python | [
"",
"python",
"import",
"importerror",
""
] |
I'm looking for a list of strings *and their variations* within a very large string.
What I want to do is find even the *implicit* matches between two strings.
For example, if my start string is `foo-bar`, I want the matching to find `Foo-bAr` `foo Bar`, or *even* ***`foo(bar...`.*** Of course, `foo-bar` should also ... | ```
>>> def findString(inputStr, targetStr):
... if convertToStringSoup(targetStr).find(convertToStringSoup(inputStr)) != -1:
... return True
... return False
...
>>> def convertToStringSoup(testStr):
... testStr = testStr.lower()
... testStr = testStr.replace(" ", "")
... testStr = tes... | I'm going to assume that your rules are right, and your examples are wrong, mainly since you added the rules later, as a clarification, after a bunch of questions. So:
> EDIT: More specifically, I need the following matches.
>
> 1. The string itself, case insenstive.
> 2. The string with spaces separating any of the c... | A more powerful method than Python's find? A regex issue? | [
"",
"python",
"regex",
"string",
"find",
""
] |
I have a table with two string columns: `Name` and `Code`. `Code` is unique, but `Name` is not. Sample data:
```
Name Code
-------- ----
Jacket 15
Jeans 003
Jeans 26
```
I want to select unique rows with the smallest `Code` value, but not in terms of numeric value; rather, the length of the string. O... | ```
;WITH cte AS
(
SELECT Name, Code, rn = ROW_NUMBER()
OVER (PARTITION BY Name ORDER BY LEN(Code))
FROM dbo.Clothes
)
SELECT Name, Code
FROM cte
WHERE rn = 1;
```
[SQLfiddle demo](http://sqlfiddle.com/#!3/d6b45/1)
If you have multiple values of code that share the same length, the choice will be arbitrary,... | Try this
```
select clothes.name, MIN(code)
from clothes
inner join
(
SELECT
Name, Min(Len(Code)) as CodeLen
FROM
clothes
GROUP BY
Name
) results
on clothes.name = results.name
and LEN(clothes.code) = results.CodeLen
group by clothes.name
``` | Removing duplicate rows by selecting only those with minimum length value | [
"",
"sql",
"sql-server",
""
] |
I have a 2D list, for example `mylist =[[1,2,3],[4,5,6],[7,8,9]]`.
Is there any way I can use `len()` function such that I can calculate the lengths of array indices? For example:
```
len(mylist[0:3])
len(mylist[1:3])
len(mylist[0:1])
```
Should give:
```
9
6
3
``` | `length = sum([len(arr) for arr in mylist])`
```
sum([len(arr) for arr in mylist[0:3]]) = 9
sum([len(arr) for arr in mylist[1:3]]) = 6
sum([len(arr) for arr in mylist[2:3]]) = 3
```
Sum the length of each list in `mylist` to get the length of all elements.
This will only work correctly if the list is 2D. If some el... | You can flatten the list, then call `len` on it:
```
>>> mylist=[[1,2,3],[4,5,6],[7,8,9]]
>>> import collections
>>> def flatten(l):
... for el in l:
... if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
... for sub in flatten(el):
... yield sub
... ... | Length of 2d list in python | [
"",
"python",
"python-2.7",
""
] |
I am reading the book "*Python Programming for the Absolute Beginner (3rd edition)*". I am in the chapter introducing custom modules and I believe this may be an error in the coding in the book, because I have checked it 5 or 6 times and matched it exactly.
First we have a custom module *games.py*
```
class Player(ob... | I actually have this book myself. And yes, it is a typo. Here is how to fix it:
```
# SimpleGame.py
import games, random
print("Welcome to the world's simplest game!\n")
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for... | You have an infinite loop here:
```
again = None
while again != "n":
players = []
``` | Python custom modules - error with example code | [
"",
"python",
"python-3.x",
"module",
""
] |
First, all relevant code
**main.py**
```
import string
import app
group1=[ "spc", "bspc",",","."]#letters, space, backspace(spans mult layers)
# add in letters one at a time
for s in string.ascii_lowercase:
group1.append(s)
group2=[0,1,2,3,4,5,6,7,8,9, "tab ","ent","lAR" ,"rAR" , "uAR", "dAR"]
group3= []
for s in... | You have a module named `app` that contains a class named `app`. If you just do `import app` in main.py then `app` will refer to the module, and `app.app` will refer to the class. Here are a couple of options:
* Leave your import statement alone, and use `myApp = app.app({"testFKey":[3,2,2]})` inside of main.py
* Repl... | In `main.py` change second line to:
```
from app import app
```
The issue is you have `app` module and `app` class within it. But you are importing module, not the class from it:
```
myApp = app({"testFKey": [3, 2, 2]})
```
(you can also instead replace "`app`" inside line above into "`app.app`") | Why am I getting 'module' object is not callable in python 3? | [
"",
"python",
"python-3.x",
"tkinter",
"runtime-error",
""
] |
```
SELECT
Stockmain.VRNOA,
item.description as item_description,
party.name as party_name,
stockmain.vrdate,
stockdetail.qty,
stockdetail.rate,
stockdetail.amount,
ROW_NUMBER() OVER (ORDER BY VRDATE) AS RowNum
FROM StockMain
INNER JOI... | It looks like you're trying to perform a paging operation, or at least a query that is greatly simplified using the new paging operators in SQL Server 2012, OFFSET and FETCH:
```
SELECT
Stockmain.VRNOA,
item.description as item_description,
party.name as party_name,
stockmain.vrdate... | Put it in a subquery, the `ROW_NUMBER()` can't be used in the `WHERE` clause, not to mention you can't use aliases created in the `SELECT` list in the `WHERE` clause:
```
SELECT *
FROM (SELECT
Stockmain.VRNOA,
item.description as item_description,
party.name as party_name,
... | SQL Error of Undefined Column | [
"",
"sql",
"sql-server",
"database",
""
] |
I have an application which uses Hibernate to support Oracle and MySQL databases. After an update I have to manually delete some columns with indexes/constraints on it. These indexes have Hibernate generated random names.
In Oracle I can do this:
```
ALTER TABLE table_name DROP (column_name) CASCADE CONSTRAINTS;
```
... | You can select indexes for a table form information\_schema:
```
SELECT DISTINCT INDEX_NAME, TABLE_NAME, TABLE_SCHEMA FROM information_schema.STATISTICS;
``` | To get all indexes for a particular database (replace **<Database\_Name>** with your database name), use:
```
SELECT DISTINCT INDEX_NAME
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA LIKE '<Database_Name>';
```
To get all indexes for a table (replace **<Table\_Name>** with your table name) of a particular d... | Delete MySQL column index without knowing its name | [
"",
"mysql",
"sql",
"database",
"hibernate",
"indexing",
""
] |
I am trying to debug a python code using pdb. I have a variable that called c and when I press c to print this variable the pdb get confused and continue debugging to the next break point. How can I avoid such confusion given that it would be very difficult to change the name of the variable. | Your confusion is about what the various commands in PDB do. I think of it a bit like a [MUD](https://en.wikipedia.org/wiki/MUD) and that works fairly often:
Use **p** to print out the contents of a variable (or **pp** to pretty-print (or handle your character's basic needs)):
```
(Pdb) p df
Empty DataFrame
Columns: ... | You can tell pdb not to evaluate things like that using the `!` prefix:
```
>>> !c
... <value of c>
``` | Debugging Python using pdb | [
"",
"python",
"python-2.7",
"pdb",
""
] |
relatively new to Django and trying to piece together standard practice for dealing with M2M relationships in a form. I already have the model and db squared away.
For this example, I've written an app in my project for Articles, and I'm attempting to add Categories. To keep it simple an Article has a title, body, tim... | Comments per file...
# models.py
```
class Category(models.Model):
category = models.CharField(max_length=100)
```
The category's name should be named `name`. A field named `category` I'd expect to be something like `models.ForeignKey("Category")`.
```
class Article(models.Model):
title = models.CharField(m... | I'd start by renaming `category` in the model to `categories`, and updating the related code accordingly - the singular naming is just going to be a continuous headache.
At that point, you're pretty close. In your success branch when submitting an article, assign the categories as a separate statement.
```
article = ... | Django Forms - Many to Many relationships | [
"",
"python",
"django",
"forms",
""
] |
I have written a mysql query to retrieve data from two tables with subquery and join.
The query works fine but I want to avoid subquery because of some performance issues.
It should be ordered by date time before group.
```
SELECT a.value1, a.value2, b.value1 FROM (SELECT * FROM A ORDER BY datetime DESC, id DESC) AS ... | There appears to be no purpose to your subquery in the first place. All you are doing is performing an `ORDER BY`, which will be lost the instant you join to the other table. You should be able to do this:
```
SELECT a.value1, a.value2, b.value1 FROM
A as a
INNER JOIN
B AS b
ON b.a_id=a.id
WHERE a.v... | You haven't got any filter on A table, so you can directly join the table:
```
SELECT b.value2, b.value3 FROM A AS a
INNER JOIN B AS b ON b.a_id=a.id
WHERE a.value4='value'
GROUP BY b.value2, b.value3;
```
Note you have to select columns that were grouped by. | Avoid sub query | [
"",
"mysql",
"sql",
""
] |
I have two tables. A and B. I'm trying to figure out a way to add a column in my select query that returns true or false as to whether or not there exists a record in B.
```
Table A
ID Title
1 A
2 B
3 C
4 D
5 E
Table B
ID Detail
3 foo
4 foo
4 bar
4 barfood
```
I w... | If you're adding a column named 'Exists' temporary then try this
```
select a.id, a.title,case when a.id=b.id then 'True' else 'False' end as Exists
from A a left outer join B b
on a.id = b.id
```
If you've alredy added Exists column to table then
```
select a.id, a.title,Exists=(case when a.id=b.id then 'Tru... | There are probably more efficient ways to accomplish it, but a combination of count and a case statement will do the trick:
```
select ID, Title,
case when
(select count(1) from B where ID = A.ID) = 0 then 'False'
else 'True'
end as 'Exists'
from A
```
[SQLFiddle link](http://sqlfiddle.com/#!3/81d94/1/0) | SQL alter a column if exists | [
"",
"sql",
"if-statement",
"exists",
""
] |
I'm using CXFreeze with PySide (QT). I get an error:
cx\_Freeze: Python error in main script.
myscript.py line 33, in
File ExtensionLoader\_Pyside\_QtGUI.py, line 11, in
Import Error: DLL load failed: The specified module could not be found
When running a fresh install of Windows server 2008.
I'm running the frozen EX... | **I used Py2exe instead of CXFreeze and it worked perfectly.**
Also, apparently Python requires the MS Visual C++ Dependency Files:
<http://www.microsoft.com/en-us/download/details.aspx?id=29>
So any bundling needs that as well, if it's a fresh install. (Although I think they are now bundled with newer Windows version... | Based on your `Import Error: DLL load failed` it is most likely an installation issue causing the missing DLL. To figure our exactly which DLL you are missing, use <http://www.dependencywalker.com/> Run the .exe and open the .pyd file for File ExtensionLoader\_Pyside\_QtGUI.py and it will show you exactly which DLL's a... | pySide: ExtensionLoader_Pyside_QtGUI.py specified module could not be found | [
"",
"python",
"qt",
"pyside",
"cx-freeze",
""
] |
If I have a frame like this
```
frame = pd.DataFrame({
"a": ["the cat is blue", "the sky is green", "the dog is black"]
})
```
and I want to check if any of those rows contain a certain word I just have to do this.
```
frame["b"] = (
frame.a.str.contains("dog") |
frame.a.str.contains("cat") |
frame.a.st... | ```
frame = pd.DataFrame({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']})
frame
a
0 the cat is blue
1 the sky is green
2 the dog is black
```
The [`str.contains`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html) method accepts a regu... | For list should work
```
print(frame[frame["a"].isin(mylist)])
```
See [`pandas.DataFrame.isin()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html). | Check if a string in a Pandas DataFrame column is in a list of strings | [
"",
"python",
"python-2.7",
"pandas",
""
] |
How can I get the SQL Server server and instance name of the current connection, using a T-SQL script? | Just found the answer, in [this SO question](https://stackoverflow.com/questions/129861/how-can-i-query-the-name-of-the-current-sql-server-database-instance) (literally, inside the question, not any answer):
```
SELECT @@servername
```
returns servername\instance as far as this is not the default instance
```
SELECT... | How about this:
```
EXECUTE xp_regread @rootkey='HKEY_LOCAL_MACHINE',
@key='SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQl',
@value_name='MSSQLSERVER'
```
This will get the instance name as well. `null` means default instance:
```
SELECT SERVERPROPERTY ('InstanceName... | How to get current instance name from T-SQL | [
"",
"sql",
"sql-server",
"database",
"t-sql",
"sql-server-2008r2-express",
""
] |
The R `qchisq` function converts a p-value and number of degrees of freedom to the corresponding chi-squared value. Is there a Python library that has an equivalent?
I've looked around in SciPy without finding anything. | It's `scipy.stats.chi2.ppf` - Percent point function (inverse of cdf).
E.g., in R:
```
> qchisq(0.05,5)
[1] 1.145476
```
in Python:
```
In [8]: scipy.stats.chi2.ppf(0.05, 5)
Out[8]: 1.1454762260617695
``` | As @VadimKhotilovich points out in his answer, you can use `scipy.stats.chi2.ppf`. You can also use the function `chdtri` from `scipy.special`, but use 1-p as the argument.
R:
```
> qchisq(0.01, 7)
[1] 1.239042
> qchisq(0.05, 7)
[1] 2.16735
```
scipy:
```
In [16]: from scipy.special import chdtri
In [17]: chdtri(7... | Is there a python equivalent of R's qchisq function? | [
"",
"python",
"r",
"statistics",
"scipy",
"chi-squared",
""
] |
I've been trying to fit the amplitude, frequency and phase of a sine curve given some generated two dimensional toy data. (Code at the end)
To get estimates for the three parameters, I first perform an FFT. I use the values from the FFT as initial guesses for the actual frequency and phase and then fit for them (row b... | I've tried to distill the important parts of your question into this answer.
1. First of all, try fitting a *single* block of data, not an array. Once you are confident that your model is sufficient you can move on.
2. Your fit is only going to be as good as your model, if you move on to something not "sine"-like you'... | The problem is due to a bad initial guess of the phase, not the frequency. While cycling through the rows of genSine (inner loop) you use the fit result of the previous line as initial guess for the next row which does not work always. If you determine the phase from an fft of the current row and use that as initial gu... | Failure of non linear fit to sine curve | [
"",
"python",
"scipy",
"curve-fitting",
""
] |
Suppose I have two lists of any, but equal length, for example:
```
['a','b','c','d']
['r','t','y','h']
```
For these two lists, I would want output to be:
```
'ar', 'bt', 'cy', 'dh'
```
Basically, the first element of the first list to the first element of the second list and so on. How would I do that? And note, ... | [`zip`](http://docs.python.org/3/library/functions.html#zip) the lists to combine them, then [`join`](http://docs.python.org/3/library/stdtypes.html#str.join) each pair of strings into a single string:
```
>>> list1 = ['a','b','c','d']
>>> list2 = ['r','t','y','h']
>>> [''.join(pair) for pair in zip(list1, list2)]
['a... | You can use `map` and `zip` to do the job:
```
>>> l1=['a','b','c','d']
>>> l2=['r','t','y','h']
>>> map(lambda(x,y): x+y, zip(l1,l2))
['ar', 'bt', 'cy', 'dh']
```
What `zip` does is it creates a list of tuples, where the i-th tuple contains the i-th element from each list. Then you can transform each tuple into a st... | Combining two lists in python3 | [
"",
"python",
"list",
"python-3.x",
""
] |
I have the following select:
```
SELECT TOP 1000 [ObjectiveId]
,[Name]
,[Text]
FROM [dbo].[Objective]
```
It gives me
```
Name Text
0100 Header1
0101 Detail1
0102 Detail2
0200 Header2
0201 Detail1a
0202 Detail1b
```
Is there a way I could make a string like this with a ||| divider... | ```
; WITH headers AS (
SELECT Name
, Text
FROM dbo.Objective
WHERE Right(Name, 2) = '00'
)
, details AS (
SELECT Name
, Text
FROM dbo.Objective
WHERE Right(Name, 2) <> '00'
)
SELECT headers.Text + ' ||| ' + details.Text
FROM headers
LEFT
JOIN details
ON Left(details.name, 2) = ... | Query:
**[SQLFIDDLEExample](http://sqlfiddle.com/#!6/01adf/6)**
```
SELECT t1.Text + ' ||| ' + t2.Text AS clm
FROM Objective t1
LEFT JOIN Objective t2
ON SUBSTRING(t2.Name, 1, 2) = SUBSTRING(t1.Name, 1, 2)
AND t2.Name not like '%00'
WHERE t1.Name like '%00'
```
Result:
```
| CLM |
-------... | Can I flatten out header and detail records with a SQL Statement in Sql Server 2012 | [
"",
"sql",
"sql-server",
""
] |
I added a facebook button to my page by copying/pasting the code they supply on their website.
It looks like this:
```
"http://www.facebook.com/dialog/feed?app_id={{fbapp_id}}&link={{link_url}}&message={{share_message|urlencode}}&display=popup&redirect_uri={{link_url}}
```
As you can see, it's got the `{}` in there ... | You can usually find that information [in the documentation, under "Escaping"](http://jinja.pocoo.org/docs/templates/#escaping) or similar. In this case, you can either output the delimiter with a variable expression:
```
{{ '{{' }}
```
Or you can use the `raw` block, for longer stretches of code:
```
{% raw %}
... | This question is old but I recently had the same issue. If you setup Jinja2 Environment to use undefined=jinja2.DebugUndefined it will ignore missing parameters and leave them as if a new Jinja template. Useful for say multi-stage parsing and u can run logging as well to know when variables have not been defined:
```
... | How to disable Jinja2 for sections of template with {}? | [
"",
"python",
"jinja2",
""
] |
I am trying to display a list in vertically sorted columns with number of columns decided by the user. I want to use `zip()` but I can't seem to figure out how to tell it to go through `n` no of lists.
```
#!/usr/bin/env python
import random
lst = random.sample(range(100), 30)
lst = sorted(lst)
col_size = int(raw_i... | Use [the grouper recipe](http://docs.python.org/2/library/itertools.html#itertools.izip) `IT.izip_longest(*[iterable]*n)` to collect the items in `lst` into groups of size `n`. (See [this page](https://stackoverflow.com/a/17516752/190597) for a more detailed explanation of how the grouper recipe works.)
```
import ran... | Zip doesn't do what you're after because the rows are different sizes. Map will transpose when rows are uneven.
See the following with code help from [Create nice column output in python](https://stackoverflow.com/questions/9989334/create-nice-column-output-in-python).
## PROGRAM
import random
lst = random.sample(r... | Zip together n number of lists | [
"",
"python",
"list",
""
] |
```
>>> list=[None]
>>> def list[0](x,y):
File "<stdin>", line 1
def list[0](x,y):
^
SyntaxError: invalid syntax
```
How can I define a function as an element of a list? | Python's `def` isn't flexible enough to handle generic [lvalues](http://dictionary.reference.com/browse/lvalue) such as `list[0]`. The language only allows you to use an *identifier* as function name. Here are the relevant parts of the [grammar rule for the def-statement](http://docs.python.org/2.7/reference/compound_s... | ```
def f(whatever):
do_stuff()
l[0] = f
```
The function definition syntax doesn't allow you to define a function directly into a data structure, but you can just create the function and then assign it wherever it needs to go. | Define function as list element | [
"",
"python",
""
] |
I have a computer on my LAN that I would like to run an IPython Notebook server on. The computer is headless, so I can only access this computer using SSH. I tried to start IPython Notebook through screen, then detach, but the kernel restarts with X server errors.
Specifically, I did the following:
* SSH into remote ... | It appears as though these kernel restarts only occur when I import traitsui modules in a notebook. Specially, the following imports cause the error.
```
from traitsui.api import *
from traitsui.menu import *
```
The solution is to change the backend for traitsui, *before* importing any traitsui modules,
```
from tr... | Ipython is creating your plots (or any other X-graphics such as `traitsui` UI elements) in the X session you created with `ssh -X`. When you log out, the ssh tunnel closes along with that X session, thus the errors. Without the ssh tunnel, the plots have no way to get to you.
Assuming you don't have a physical termina... | Start IPython remotely using SSH+screen, then detach and log out | [
"",
"python",
"ssh",
"ipython",
"enthought",
"jupyter-notebook",
""
] |
Let us say I have a python method to get last synced changelist in p4. (The question itself is not related to p4 but only a basic python question)
```
def get_last_synced_changelist(p4port, client_name, p4 = None):
with P4Connection(p4port) as p4:
last_change_list = p4.run_changes("-m1", "@%s" % client_nam... | You can create a dummy context manager:
```
import contextlib
@contextlib.contextmanager
def dummyctx(x):
yield x
def get_last_synced_changelist(p4port, client_name, p4=None):
if p4 is None:
ctx = P4Connection(p4port)
else:
ctx = dummyctx(p4)
with ctx as p4:
last_change_list = ... | It's not directly possible, `with` is a compound statement and can't be embedded in expressions like this. But you can make use of the fact that your function also supports "borrowing" a resource:
```
def get_last_synced_changelist(p4port, client_name, p4 = None):
if p4 is None:
with P4Connection(p4port) a... | Python handling parameters in "with" context | [
"",
"python",
"python-2.7",
""
] |
I have to write a programme where a turtle takes 90 degree turns, chosen randomly as left or right, around the screen, until it hits a wall, takes a 180 degree turn and goes back to walking around the screen. When it's hit the wall 4 times, the loop terminates. The problem I'm having is that when it bounces off the wal... | Your `counter = counter + 1` is wrong. When your `isInScreen` returns `False`, the while loop breaks and the code ends, since, the counter is being incremented but you don't loop over again. See the following code -
```
import turtle
import random
def isInScreen(w,t):
leftBound = w.window_width() / -2.0
right... | As an alternative to the nested loops and to avoid some redundant statements, the following should produce the same result as Sukrit's answer.
```
def randomWalk(t,w):
counter = 0
while counter < 4:
if not isInScreen(w,t):
t.left(180)
counter += 1
else:
coin... | Randomly walking turtle function not doing what I want it to | [
"",
"python",
"python-3.x",
"turtle-graphics",
""
] |
I wanted to have a look at the python deque class. When I checked [the source code](http://hg.python.org/cpython/file/791034a0ae1e/Lib/collections/__init__.py) , I found the following at line 10
```
from _collections import deque, defaultdict
```
where exactly can I find this \_collections module? I searched on my c... | `_collections` is builtin extension module.
You can find source for \_collection module [here](http://hg.python.org/cpython/file/tip/Modules/_collectionsmodule.c).
[Setup.dist](http://hg.python.org/cpython/file/tip/Modules/Setup.dist) contains mapping between builtin extension module name to source file. | `_collections` is a private implementation of a class according to this answer: ["Private" (implementation) class in Python](https://stackoverflow.com/questions/551038/private-implementation-class-in-python).
Being private, I don't think that you will be able to access its Python source but you can check out the C imp... | finding _collections in python source | [
"",
"python",
""
] |
I have two dates: a `StartDate` and a `CreatedDate`
If I say
```
CreatedDate < StartDate
```
what will happen if `StartDate` is `NULL`?
Should I use
```
isnull(startdate,0)
```
or will it just return a `NULL` or will it always be less than `StartDate` as `StartDate` is `NULL`? | Any ordinary comparisons (>, <, >=, <=, =, <>, like, in) return null if at least one of their arguments is null; so CreatedDate < StartDate returns null if StartDate is null. You can test for null explicitly:
```
((CreatedDate < StartDate) or (StartDate is null))
```
Or you can transform the StartDate value
```
... | You have to check for `null`.
If you don't check for `null` then your compare will result in `unknown` which is `false`. | Calculate Nulls with a date | [
"",
"sql",
"null",
""
] |
after a simple query...
```
SELECT Col_ID, datetime1, datetime2, datetime3
FROM TABLE_DATETIME
WHERE datetime1 LIKE '20130805%'
OR datetime2 LIKE '20130805%'
OR datetime3 LIKE '20130805%'
```
... I have this scenario
```
Col_ID |datetime1 |datetime2 |datetime3 |
----------|--------------|--... | You can use [`COALESCE()`](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce) function for this:
```
SELECT Col_ID
, COALESCE(datetime1,datetime2,datetime3) AS ALL_DATETIME
FROM TABLE_DATETIME
WHERE ...
ORDER BY COALESCE(datetime1,datetime2,datetime3)
```
Output:
```
| COL_ID... | Use `NULL` handling function
```
SELECT Col_ID, ifnull(datetime1, ifnull(datetime2, datetime3 )) as ALL_DATETIME
FROM TABLE_DATETIME
WHERE datetime1 LIKE '20130805%'
OR datetime2 LIKE '20130805%'
OR datetime3 LIKE '20130805%'
order by 2
``` | Union different column in one and then order by this | [
"",
"mysql",
"sql",
""
] |
I have a jsp file that looks like this:
```
<font color="#121212">
<br>
Text 1
<br>
Text 2
<br>
</font>
```
Does anyone know a quick sed/awk command I could invoke in my shell script to replace "Text 1" and "Text 2" with predefined variables? Text1/2 are just placeholders for this question, the space inbetween those... | Try this awk command:
```
awk '/<font /{intag=1}
/<\/font>/{intag=0 ;br=0}
intag==1 && /<br>/{br++}
{print}
br==1{print "Foo"; getline}
br==2{print "Bar"; getline}' file
```
This command will replace line just after 1st `<br>` with `Foo` and line just after 2nd `<br>` with `Bar`. | If you have some separator you can use between your blocks of replacement text, e.g. newline:
```
$ awk -v text="foo
bar" '
BEGIN {
split(text,t,/\n/)
}
/<br>/ {
if (++c in t) {
print $0 ORS t[c]
f = 1
}
else {
f = 0
}
}
!f... | Change text inbetween tags - shell script | [
"",
"python",
"regex",
"bash",
"sed",
"awk",
""
] |
Lets have a look at the next snippet -
```
@event.listens_for(Pool, "checkout")
def check_connection(dbapi_con, con_record, con_proxy):
cursor = dbapi_con.cursor()
try:
cursor.execute("SELECT 1") # could also be dbapi_con.ping(),
# not sure what is better
except exc.OperationalErr... | There was a talk about this, and this doc describes the problem pretty nicely, so I used their recommended approach to handle such errors: <http://discorporate.us/jek/talks/SQLAlchemy-EuroPython2010.pdf>
It looks something like this:
```
from sqlalchemy import create_engine, event
from sqlalchemy.exc import Disconnec... | Try the `pool_recycle` argument to `create_engine`.
From [the documentation](http://docs.sqlalchemy.org/en/rel_0_9/dialects/mysql.html#connection-timeouts):
> Connection Timeouts
>
> MySQL features an automatic connection close behavior, for connections
> that have been idle for eight hours or more. To circumvent hav... | Python SQLAlchemy - "MySQL server has gone away" | [
"",
"python",
"mysql",
"sqlalchemy",
""
] |
I have the following query:
```
with cte as
(SELECT top 10 [1],[2]
FROM [tbl_B] where [2] > '2000-01-01' and Status_7 = 0 and Status_8 = 1
ORDER BY [2])
,
CTE1 AS
( select [1], row_number() over (order by [2]) as rn
from CTE
)
select [1] from CTE1 where rn = '10'
```
how can I put this into a variable to com... | ```
with cte as
(
SELECT top 10 [1],[2]
FROM [tbl_B]
where [2] > '2000-01-01' and Status_7 = 0 and Status_8 = 1
ORDER BY [2]
)
,CTE1 AS
(
select [1], row_number() over (order by [2]) as rn
from CTE
)
select @123 = [1] from CTE1 where rn = '10'
``` | ```
with cte as
(SELECT top 10 [1],[2]
FROM [tbl_B] where [2] > '2000-01-01' and Status_7 = 0 and Status_8 = 1
ORDER BY [2])
,
CTE1 AS
( select [1], row_number() over (order by [2]) as rn
from CTE
)
select @123 = [1] from CTE1 where rn = '10'
``` | How to store result of sql query in variable? | [
"",
"sql",
""
] |
I have a file that has a list of files but it adds `\n` at the end how can I have python just write the info I need on a new line without getting `\n` in the way so that way my info will be called `X.acc` not `x.acc\n`? Here is my code that writes the file
```
def add(x):
nl = "\n"
acc = ".acc"
xy = x + ac... | Your question doesn't actually make sense, because of what a "line" actually is and what that `'\n'` character means.
Files don't have an intrinsic concept of lines. A file is just a sequence of bytes. `'\n'` is the line separator (as Python represents it with universal newlines). If you want your data to show up on d... | Just change add:
```
def add(x):
nl = "\n"
acc = ".acc"
xy = x + acc
exyz = xy
xyz = exyz
xxx = str(xyz)
tf = open('accounts.dat',"a+")
tf.writelines(xxx)
tf.writelines(nl) # Write the newline AFTER instead of before the output
tf.close() # close is a function so needs to be c... | how to add a new line in a text file using python without \n | [
"",
"python",
"python-3.x",
""
] |
This happens in the python build:
```
#is it executable
print os.access("support/d8/d8", os.X_OK)
#is it there in the shell
os.system("test -f support/d8/d8 && echo \"found\" || echo \"not found\"")
```
and then:
```
#run it
os.system("support/d8/d8 --trace_exception with a bunch of files");
```
which outputs:
```... | You're running an x86\_32 bit executable [`d8`](https://github.com/albertjan/skulpt/raw/master/support/d8/d8) (despite the [comment](https://github.com/albertjan/skulpt/blob/master/support/d8/skulpt_readme.txt), by the way). If the (Travis) system is x64, and/or does not have all of the x86\_32 libraries
* `linux-gate... | Why don't you try this:
```
os.system("./support/d8/d8 --trace_exception with a bunch of files");
```
I had a similar issue, while executing the ./ is some how required. | os.system not finding file that is really there | [
"",
"python",
"travis-ci",
""
] |
i have to sum element in a column(SCENARIO1) that is varchar and contain data like (1,920, 270.00, 0, NULL) but when i try to convert data into int or decimal i get this error :
"he command is wrong when converting value "4582014,00" to int type"
here is my request :
```
select sum( convert( int, SCENARIO1) )
from Mn... | try this
```
select sum(cast(replace(SCENARIO1, ',', '.') as decimal(29, 10)))
from Mnt_Scenario_Exercice
where code_pere = '00000000';
```
If you couldn't convert your `'4582014,00'` into decimal, there's a chance you have different decimal separator on your server. You could look what it is or just try `'.'` | 4582014,00 should be a decimal
try this (I assume that youre query is working) and changed convert(int into decimal)
> select sum(convert(decimal(20,2),replace(SCENARIO1, ',', '.'))) from Mnt\_Scenario\_Exercice where code\_pere='00000000' | Sum of data in varchar column | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I have the following table
```
Name | Subject | Marks
--------------------------
a M 20
b M 25
c M 30
d C 44
e C 45
f C 46
g H 20
```
Here I have a "Student" table I want to get the Name of ... | You can use the ROW\_NUMBER function to return only the "best" row per subject:
[SQL Fiddle](http://sqlfiddle.com/#!3/db6d8/7)
**MS SQL Server 2008 Schema Setup**:
```
CREATE TABLE Student
([Name] varchar(1), [Subject] varchar(1), [Marks] int)
;
INSERT INTO Student
([Name], [Subject], [Marks])
VALUES
('... | You can use other functions and cte also to get the result..
eg : 1
```
select B.Name,
A.Subject,
B.Marks
from ( select Subject,
max(Marks) as High_Marks
from Student
group by Subject
) a
join Student b
on a.subject = b.subject
and a.high_Marks = b.Marks
```
... | How to get the name of a the student who got max marks in each subject? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2005",
"sql-server-2008-r2",
""
] |
We have several own Python packages and want to create local PyPI repository for them using simple interface like <https://pypi.python.org/simple/>
This repository I want to create for local only without any mirrors due to security reason, and it will be put under [Apache](https://en.wikipedia.org/wiki/Apache_HTTP_Ser... | Take a look at [`pip2pi`](https://github.com/wolever/pip2pi). It seems to be exactly what you are looking for. | We had a similar need at my company. Basically how can we upload "closed source" packages to an index while being able to install them as if they were on PyPI?
We have sponsored a project called [devpi](https://pypi.python.org/pypi/devpi) which acts as a PyPI cache (packages you access from PyPI will be cached on your... | How can I create a local own PyPI repository index without a mirror? | [
"",
"python",
"pip",
"pypi",
""
] |
I'm trying to Convert a Decimal DateTime value to DateTime datatype and check a condition in a select query
```
SELECT * FROM CLBALTRNTBL WHERE CONVERT(DATETIME,LSTDAT) >= @sDt
AND CONVERT(DATETIME,LSTDAT) <= @eDt
```
but the following error Occurs
```
Arithmetic overflow error converting expression to data t... | Try this :
```
SELECT *
FROM CLBALTRNTBL
WHERE CONVERT(DATETIME, CONVERT(VARCHAR(8), LSTDAT), 112) >= @sDt
AND CONVERT(DATETIME, CONVERT(VARCHAR(8), LSTDAT), 112) <= @eDt
``` | It's way more efficient to convert your variables and compare to column - than to convert your column.
```
SELECT *
FROM CLBALTRNTBL
WHERE LSTDAT >= CONVERT(INT,CONVERT(NVARCHAR(8),@sDt,112))
AND LSTDAT <= CONVERT(INT,CONVERT(NVARCHAR(8),@eDt,112))
```
**[SQLFiddle DEMO](http://sqlfiddle.com/#!3/30803/1)** | How to Convert Decimal to DateTime in where clause | [
"",
"sql",
"sql-server",
"datetime",
"decimal",
"converters",
""
] |
I have a cursor with values from a select and i want to do something after depending if i had any row found or none.
```
recs_Table SYS_REFCURSOR;
begin
open recs_Table for
select * from table1, table2;
if recs_Table%found then
--do this
else
--do that
end if;
end;
```
This... | You need to execute a FETCH against the cursor prior to using the %FOUND attribute. Change your code to something like
```
DECLARE
recs_Table SYS_REFCURSOR;
nTable_1_value NUMBER;
nTable_2_value NUMBER;
begin
open recs_Table for
select * from table1, table2;
FETCH recs_Table INTO nTable_1_val... | we use two procedures to execute the result
```
create or replace procedure pro_sample(recs_Table out SYS_REFCURSOR) is
begin
open recs_Table for
select * from table1, table2;
end;
```
this above procedure will be used to open a cursor
```
create or replace procedure pro_sample(recs_Table ... | Best way to check if SYS_REFCURSOR is empty | [
"",
"sql",
"oracle",
"plsql",
"sys-refcursor",
""
] |
This next behaviour befuddles me, any explanation would be appreciated.
```
>>> a = (0.1457164443693023, False)
>>> print a
(0.1457164443693023, False)
>>> print a[0]
0.145716444369
```
Using python 2.7 | The only difference is the `print`. The number doesn't change, just its representation. You can reduce your problem to:
```
>>> 0.1457164443693023
0.1457164443693023
>>> print 0.1457164443693023
0.145716444369
```
(I guess (and this is only and merely a guess) this boils down to `__repr__` vs `__str__` or something a... | The first calls \_\_ repr \_\_ , the second \_\_ str \_\_
```
a = (0.1457164443693023, False)
print a
>>> (0.1457164443693023, False)
print a[0]
>>> 0.145716444369
print repr(a[0])
>>> 0.1457164443693023
print str(a[0])
>>> 0.145716444369
```
For some design reason Double.\_\_ str \_\_() returns fewer decimals. | Python float numbers lose accuracy out of a tuple? | [
"",
"python",
"floating-accuracy",
""
] |
I have two tables to store addresses as follows:
I want to get every address, city, name and area name (cityId,Areaid maybe null)
I tried:
```
SELECT [Details]
,[AddressId]
,[CityId]
,[PlaceName] as CityName
,[AreaId]
,... | You need to join twice with the Places table. Once for the cities and once for the Areas.
```
SELECT [Details]
,[AddressId]
,[CityId]
,C.[PlaceName] as CityName
,[AreaId]
,A.[PlaceName] as AreaName
FROM [MyDB].[dbo].[Address]
LEFT OUTER JOIN [MyDB].[dbo].[Places] C
ON [City... | Add another join
```
SELECT [Details]
,[AddressId]
,[CityId]
,p1.[PlaceName] as CityName
,[AreaId]
,p2.[PlaceName] as AreaName
FROM [MyDB].[dbo].[Address]
LEFT OUTER JOIN [MyDB].[dbo].[Places] p1 ON [CityId] = p1.[PlaceId]
LEFT OUTER JOIN [MyDB].[dbo].[Places] p2 ON [AreaId] = p2... | Two joins between two tables | [
"",
"sql",
"sql-server",
""
] |
I want to split a string using python. I have successfully done it for one variable, but finding it hard to do it for 2.
The String :
```
Paragraph 4-2 says. i am going home$ early- Yes.
```
I need the output to be
```
Paragraph 4-2 says
i am going home
early
Yes
```
The sentence should split from `.`, `$` and `-... | You can do this:
```
>>> import re
>>> st='Paragraph 4-2 says. i am going home$ early- Yes.'
>>> [m.group(1) for m in re.finditer(r'(.*?[.$\-])(?:\s+|$)',st)]
['Paragraph 4-2 says.', 'i am going home$', 'early-', 'Yes.']
```
If you are not going to modify the match group at all (with strip or something) you can also ... | ```
>>> import re
>>> s = 'Paragraph 4-2 says. i am going home$ early- Yes'
>>>
>>> re.split(r'(?<!\d)\s*[.$-]\s*(?!\d)', s)
['Paragraph 4-2 says', 'i am going home', 'early', 'Yes']
```
* `\s*[.$-]\s*` matches any of `.`,`$` or `-` surrounded by 0 or more spaces (`\s*`).
* `(?<!\d)` is a negative-lookbehind to ensure... | Splitting a String using multiple delimiters | [
"",
"python",
"regex",
""
] |
How do I modify a table with SQL Server 2012 in design view? I am not able to alter the table in design view, when I'm done with my changes it gives me the error on the image:
 | The message error is self explanatory :)
* Check the Allow nulls checkbox.
* Fill this column with data
* then edit the table again and uncheck the allow nulls checkbox | You try to add a new column that must have a value by your definition. But you are not giving a value. Ask yourself: *What should the existing records have for that column?*
If you can think of a value then add this as `default`. If not then `allow nulls` for that column. | How can I modify a table using SQL Server 2012 in design view | [
"",
"sql",
"sql-server-2012-express",
""
] |
I'm trying to find the best way to switch between the two python compilers, 2.7 to 3.3.
I ran the python script from the cmd like this:
> `python ex1.py`
Where do I set the "python" environment in the window's environment variable to point to either python 3.3 or 2.7?
I am wondering if there is an easy way to switch... | For Windows 7, I just rename the `python.exe` from the Python 3 folder to `python3.exe` and add the path into the environment variables. Using that, I can execute `python test_script.py` and the script runs with Python 2.7 and when I do `python3 test_script.py`, it runs the script in Python 3.
To add `Python 3` to the... | No need for "tricks". Python 3.3 comes with PyLauncher "py.exe", installs it in the path, and registers it as the ".py" extension handler. With it, a special comment at the top of a script tells the launcher which version of Python to run:
```
#!python2
print "hello"
```
Or
```
#!python3
print("hello")
```
From the... | How to switch between python 2.7 to python 3 from command line? | [
"",
"python",
"windows",
"command-line",
"cmd",
""
] |
So, to start, this is finding our top 20% of highest spenders in 2010:
```
select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2010-01-01'
and o.OrderD... | You have an interesting question. Fundamentally, it is about migration in spending quintiles from one year to the next. I would solve this by looking at all quintiles for the three years, to see where people move.
This starts with a summary of the data by year and email. The key function is `ntile()`. To be honest, I ... | Try this:
```
;WITH top_2010 AS
(
select top (20)percent o.BillEmail,SUM(o.total) as TotalSpent,
count(o.OrderID) as TotalOrders
from dbo.tblOrder o with (nolock)
where o.DomainProjectID=13
and o.BillEmail not like ''
and o.OrderDate >= '2010-01-01'
and o.OrderDate < '2011-... | Top 20% Spender's Retention Rate | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am trying to implement a trigger to auto increment a field on the row update. Each time an existing row in PERSON table is updated, i want consistency\_version to be incremented by one automatically.
My table:
```
CREATE TABLE PERSON (
id INT NOT NULL AUTO_INCREMENT,
consistency_version INT NOT NULL DEFAULT 0,
name... | My best guess is that '@version' is returning NULL. This would cause @version + 1 to result in null, and then attempt to set the not-nullable consistency\_version column to null, resulting in an error.
Have you tried using OLD instead?
`CREATE TRIGGER consistency_version_trigger BEFORE UPDATE ON PERSON`
`FOR EACH ... | @VERSION is a session variable. It exists and is visible only during the session which created it. So you are basically saying `SET NEW.VERSION = NULL + 1` which is NULL.
*Assuming the builtin autoincrement feature doesn't fit your needs for some reason:*
To create an global auto incrementing value you need to use a ... | MySQL - Trigger error on row update | [
"",
"mysql",
"sql",
"triggers",
""
] |
I'm using urllib3 against private services that have self signed certificates. Is there any way to have urllib3 ignore the certificate errors and make the request anyways?
```
import urllib3
c = urllib3.HTTPSConnectionPool('10.0.3.168', port=9001)
c.request('GET', '/')
```
When using the following:
```
import urllib... | Try following code:
```
import urllib3
c = urllib3.HTTPSConnectionPool('10.0.3.168', port=9001, cert_reqs='CERT_NONE',
assert_hostname=False)
c.request('GET', '/')
```
See [Setting assert\_hostname to False will disable SSL hostname verification](https://github.com/shazow/urllib3/pull/... | In this question I see many answers but, IMHO, too much unnecessary information that can lead to confusion.
**Just add the `cert_reqs='CERT_NONE'` parameter**
```
import urllib3
http = urllib3.PoolManager(cert_reqs='CERT_NONE')
``` | Ignore certificate validation with urllib3 | [
"",
"python",
"python-3.x",
"urllib3",
""
] |
HI i have a field in database whose **value** is **null = true** but i need to update it timely with the integers .I am running this script on terminal
```
getW = get_HomeTeam_myworld.w
getL = get_HomeTeam_myworld.l
if winloss == "w":
getW = getW + 1
#getW.save()
print getW
```
but it gives the fol... | It seems like getW value is None. Add some check:
```
if winloss == "w":
getW = getW + 1 if getW else 1
#getW.save()
print getW
``` | tis is right can you also please tell me how can i save this update this value in db
this is the whole process
```
get_HomeTeam_myworld = myworld.objects.get(team_id=gethome_teamID)
get_HomeTeam_myworld = myworld.objects.get(team_id=getaway_teamID)
getW = get_HomeTeam_myworld.w
getL = get_HomeTeam_myw... | update null field with integer in django Python | [
"",
"python",
"mysql",
"django",
"null",
"integer",
""
] |
Can someone explain me what's wrong with the following script?
I have started learning programming in Python very recently so this might be very trivial for the experienced out here but please look into it and let me know what's wrong with it. The idea is to write a script that reverses a given string. I understand th... | First, from you recent comment I deduce that your python program is executed as a bash script. To have it execute properly, add this line to the top:
```
#!/usr/bin/env python
```
Then there's the reverse function. The others have all pointed out that you need to use the assignment operator (`=`) and not the equality... | You used double "=" which return True or False for comparison. you should use "=".
i highly recommend you to read about the operators because it will save you a lot of time when coding:
<http://www.tutorialspoint.com/python/python_basic_operators.htm> | What is wrong with the following Python Script? | [
"",
"python",
""
] |
I have created table using this create command as:
> CREATE TABLE test\_table(id INT PRIMARY KEY,name
> VARCHAR(50),price INT)
i want to insert into this table wherein values are stored already in variable
```
bookdb=# name = 'algorithms'
bookdb-# price = 500
bookdb-# INSERT INTO test_table VALUES(1,'name',price);
`... | don't have postgres installed here, but you can try this
```
import psycopg2
import file_content
try:
conn = psycopg2.connect(database='bookdb',user='v22')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS book_details")
cur.execute("CREATE TABLE book_details(id INT PRIMARY KEY,name VARCHAR(50),pri... | [SQL](https://en.wikipedia.org/wiki/SQL) does not support the concept of variables.
To use variables, you must use a programming language, such as [Java](http://en.wikipedia.org/wiki/Java), [C](http://en.wikipedia.org/wiki/C_%28programming_language%29), [Xojo](http://en.wikipedia.org/wiki/Xojo). One such language is [... | How do I insert data into table? | [
"",
"python",
"database",
"postgresql",
""
] |
I have been using selenium for automatic browser simulations and web scraping in python and it has worked well for me. But now, I have to run it behind a proxy server. So now selenium open up the window but could not open the requested page because of proxy settings not set on the opened browser. Current code is as fol... | You need to set desired capabilities or browser profile, like this:
```
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", "proxy.server.address")
profile.set_preference("network.proxy.http_port", "port_number")
profile.update_preferences()... | The official Selenium documentation (<http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp#using-a-proxy>) provides clear and helpful guidelines about using a proxy.
For Firefox (which is the browser of choice in your sample code) you should do the following:
```
from selenium import webdriver
from selenium.webdr... | Running selenium behind a proxy server | [
"",
"python",
"selenium",
"selenium-webdriver",
"proxy",
"web-scraping",
""
] |
Is there a pythonic way to convert a structured array to vector?
For example:
I'm trying to convert an array like:
```
[(9,), (1,), (1, 12), (9,), (8,)]
```
to a vector like:
```
[9,1,1,12,9,8]
``` | ```
In [15]: import numpy as np
In [16]: x = np.array([(9,), (1,), (1, 12), (9,), (8,)])
In [17]: np.concatenate(x)
Out[17]: array([ 9, 1, 1, 12, 9, 8])
```
Another option is `np.hstack(x)`, but for this purpose, `np.concatenate` is faster:
```
In [14]: x = [tuple(np.random.randint(10, size=np.random.randint(10... | You don't need to use any `numpy`, you can use `sum`:
```
myList = [(9,), (1,), (1, 12), (9,), (8,)]
list(sum(myList, ()))
```
result:
```
[9, 1, 1, 12, 9, 8]
``` | Python array to 1-D Vector | [
"",
"python",
"numpy",
""
] |
The below is returning a syntax error issue.
Having searched thoroughly online, I cannot see why. Any ideas?
```
delete Tracks
from tracks ... | If I remember correctly Postgres doesn't allow joins in `DELETE`, but you can use the `USING`keyword instead like [described in the documentation](http://www.postgresql.org/docs/current/static/sql-delete.html):
```
DELETE FROM Tracks
USING releases
WHERE tracks.label_id=releases.label_id
AND tracks.label_id = 185... | ```
delete from tracks
left join releases ... | SQL Deleting from a join table not working | [
"",
"sql",
"postgresql",
""
] |
I would like to access the result of the following shell command,
```
youtube-dl -g "www.youtube.com/..."
```
to print its output `direct url` to a file, from within a python program. This is what I have tried:
```
import youtube-dl
fromurl="www.youtube.com/..."
geturl=youtube-dl.magiclyextracturlfromurl(fromurl)
``... | It's not difficult and [actually documented](https://github.com/rg3/youtube-dl/blob/master/README.md#embedding-youtube-dl):
```
import youtube_dl
ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s.%(ext)s'})
with ydl:
result = ydl.extract_info(
'http://www.youtube.com/watch?v=BaW_jenozKc',
download=F... | For simple code,
may be i think
```
import os
os.system('youtube-dl [OPTIONS] URL [URL...]')
```
Above is just running command line inside python.
Other is mentioned in the documentation [Using youtube-dl on python](https://github.com/ytdl-org/youtube-dl/blob/master/README.md#embedding-youtube-dl)
Here is the way
`... | How to use youtube-dl from a python program? | [
"",
"python",
"youtube-dl",
""
] |
How efficient are iterations over slice operations in Python? And if a copy is inevitable with slices, is there an alternative?
I know that a slice operation over a list is O(k), where k is the size of the slice.
```
x[5 : 5+k] # O(k) copy operation
```
However, when iterating over a part of a list, I find that the... | You can use `itertools.islice` to get a sliced iterator from the list:
Example:
```
>>> from itertools import islice
>>> lis = range(20)
>>> for x in islice(lis, 10, None, 1):
... print x
...
10
11
12
13
14
15
16
17
18
19
```
# Update:
As noted by @user2357112 the performance of `islice` depends on the sta... | Use:
```
for elem in x[5 : 5+k]:
```
It's Pythonic! Don't change this until you've *profiled* your code and determined that this is a bottleneck -- though I doubt you will ever find this to be the main source of a bottleneck.
---
In terms of speed it will probably be your best choice:
```
In [30]: x = range(100)
... | Efficient iteration over slice in Python | [
"",
"python",
"performance",
"iteration",
"slice",
""
] |
I read the docs from python.org, but is still confused about this problem. In one project, I have the following script structure:
dir a:
```
math.py containing func c()
main.py containing main()
```
What should I do in main.py in order to import math under dir a rather than stdlib?
import math just does not... | ***Edit:***
Sorry my mistake... This will never work. You can choose either to give your top level package a name that doesn't conflicts with a name in the standard library. Or the main script cannot be in the package directory. So basically you can either:
Rename your module to `my_math.py` and then `main.py` can be... | This CAN work.
```
sys.path.insert(0,'path/to/math.py')
import math
```
This will make python check at the specified directory BEFORE stdlibs. This is a risky method for the same reason. I would recommend putting math.py in its OWN directory and using that path, so nothing else is changed.
I would also recommend imp... | What should I do to import math.py that is not stdlib | [
"",
"python",
"python-import",
""
] |
I need to read from a file several integers written line by line and separated by line feed and insert them into a list.
```
1
2
3
4
5
```
Currently I was able to read it using the following code, but I need also to optimize my code:
```
import sys
fd = open(sys.argv[1], 'r')
for line in fd:
line = line.rstrip(... | `int()` automatically removes the white-space characters,so there's no need of `str.rstrip`.
```
>>> int('10\r\n')
10
>>> int('10\n')
10
>>> int('10 \n')
10
```
You can also use a list comprehension here, it is faster than `list.append`:
```
import sys
with open(sys.argv[1]) as fd:
L = [int(line) for line in f... | You don't actually need to strip the line because `int()` already gets rid of trailing whitespace:
```
L = []
with open('nums.txt') as myfile: # With statements are more pythonic!
for line in myfile:
L.append(int(line))
print L
```
Returns:
```
[1, 2, 3, 4, 5]
```
As a result, you can then use [`map()`... | How to optimize the reading of a file removing all the line feed \n characters | [
"",
"python",
"performance",
""
] |
I've got two tables:
* tags
* tags\_news(binding)
I need to delete data which not contains `id` from `tags table`.
**Example**:
tags: 1, 2
tags\_news: 2
There is no data with id=1 in tags\_news. And I need to delete this. I don't know how. Please, help me. | You can use `NOT EXISTS`
```
DELETE tn FROM dbo.TagsNews tn
WHERE NOT EXISTS(
SELECT 1 FROM dbo.Tags t
WHERE t.ID = tn.ID
)
``` | ```
delete from tags where id not in(select id from tags_new)
``` | Special delete query | [
"",
"sql",
"sql-delete",
""
] |
This request might seem slightly ridiculous, unfortunately however, it is direly needed by my small company and because of this I will be awarding the maximum bounty for a good solution.
We have a set of legacy order information stored in a .txt file. In order to import this order information into our new custom datab... | If you are open to using a database and importing these files (which should not be very difficult), then you do not need a "complicated function to append the two together". All you need is a simple cross join like this ... `select t1.*, t2.* from t1, t2`
See for yourself at... <http://sqlfiddle.com/#!2/0c584/1> | Here is a solution in C#. You run it like:
```
joinfiles a.txt b.txt c.txt
```
where a.txt is the first file, b.txt the second one, and c.txt the output file that will be created. It generates the output at 100 MB/s on my machine so that is probably fast enough.
```
using System;
using System.IO;
using System.Text;
... | Elegantly appending a set of strings (.txt file) to another set of strings (.txt also)? | [
"",
"sql",
"string",
"algorithm",
"text",
"append",
""
] |
I am writing like this in Django:
```
writer.writerow(['VideoName ', 'Director ', 'Cameraman ', 'Editor ', 'Reporter ', 'Tag '])
```
It is writing in CSV like this:
```
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="report.csv"'
Video, Director, Cameraman
`... | Set a `delimiter` when you are initializing your `csv.writer`:
```
writer = csv.writer(buffer, delimiter=" ")
``` | Specify [delimiter](http://docs.python.org/2/library/csv#csv.Dialect.delimiter) when create csv.writer.
In addition to that trim field values. (`'videoName '` -> `'videoName'`)
```
>>> import csv
>>> import sys
>>>
>>> writer = csv.writer(sys.stdout, delimiter=' ')
>>> writer.writerow(['VideoName', 'Director', 'Came... | Don't include comma while writing to CSV in Django? | [
"",
"python",
"django",
"csv",
""
] |
First time writing a class here and I need a little help.
I've been trying to write a class in which the first takes a tab-delimited csv file and outputs a list of dictionaries. Each of the keys in the dictionary is a column title in the csv.
So far, this is what my class looks like:
```
import csv
class consolidat... | ## Problem
You did not supply second argument for `__init__()`:
```
class consolidate(object):
def __init__(self, file):
self.file = file
# rest of the code
```
while you are instantiating it like this:
```
c = consolidate()
```
## Solution
This should work. Change class definition to this:
```
i... | You should pass the file as a parameter to `__init__`.
```
c = consolidate ('abilities.txt')
```
Then inside `create_master_list` you should open `self.file`.
```
with (open (self.file, 'rU') ) as f:
```
Now you can call
```
a = c.create_master_list ()
``` | Passing a file to a class | [
"",
"python",
"class",
""
] |
I have a program that opens an account and there are several lines but i want it to update this one line `credits = 0` Whenever a purchase is made I want it to add one more to the amount this is what the file looks like
```
['namef', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = 0
... | The below code snippet should give you an idea on how to go about. This code updates, the value of the counter variable present within a file **counter\_file.txt**
```
import os
counter_file = open(r'./counter_file.txt', 'r+')
content_lines = []
for line in counter_file:
if 'counter=' in line:
... | You can create a general text file replacer based on a dictionary containing what to look for as keys and as corresponding values what to replace:
In the template text file put some flags where you want variables:
```
['<namef>', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = <cred... | how to update a variable in a text file | [
"",
"python",
"file",
"variables",
"python-3.x",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.