Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am reading serial data like this:
```
connected = False
port = 'COM4'
baud = 9600
ser = serial.Serial(port, baud, timeout=0)
while not connected:
#serin = ser.read()
connected = True
while True:
print("test")
reading = ser.readline().decode()
```
The problem is that it prevents anythi... | Put it in a separate thread, for example:
```
import threading
import serial
connected = False
port = 'COM4'
baud = 9600
serial_port = serial.Serial(port, baud, timeout=0)
def handle_data(data):
print(data)
def read_from_port(ser):
while not connected:
#serin = ser.read()
connected = True
... | Using a separate thread is totally unnecessary. Just follow the example below for your infinite while loop instead.
*I use this technique in my [eRCaGuy\_PyTerm](https://github.com/ElectricRCAircraftGuy/eRCaGuy_PyTerm) serial terminal program [here (search the code for `inWaiting()` or `in_waiting`)](https://github.co... | PySerial non-blocking read loop | [
"",
"python",
"python-3.x",
"nonblocking",
"pyserial",
""
] |
```
select colA, colB from car
where car.id in (select id from make) and
car.id in (select id from model);
```
The above query works perfectly file as is, say there is a case that the make table has not been popluated with anything. just an empty table. is there a way to make the join not take place on that table?
B... | ```
SELECT colA, colB
FROM car
WHERE ((SELECT COUNT(*) FROM make) = 0) OR id IN (SELECT id FROM make))
AND id IN (SELECT id from model)
```
With a LEFT JOIN:
```
SELECT DISTINCT colA, colB
FROM car
JOIN (SELECT COUNT(*) c FROM make) mcount
LEFT JOIN make ON car.id = make.id
JOIN model ON car.id = model.id
WHERE mco... | You would have to do this with a more complicated join:
```
select c.colA, c.colB
from car c cross join
(select count(*) as num from make) m
where num = 0 or
(c.id in (select id from make) and
c.id in (select id from model)
)
``` | Conditional Where clause in sql | [
"",
"mysql",
"sql",
"left-join",
""
] |
I am trying to write a python script which will execute a bash command line program for me. This program asks for user input twice, and I want my script to automatically enter "1" each time.
I've heard of something like this:
```
os.system("program < prepared_input")
```
How do I write prepared\_input? Thanks. | Create file with two lines:
```
1
1
```
And use `read` in the bash script to get the input:
**Demo:**
```
$ cat abc
1
1
$ cat so.sh
#!/bin/bash
read data
echo "You entered $data"
read data
echo "Now you entered $data"
$ bash so.sh <abc
You entered 1
Now you entered 1
```
Python :
```
>>> import os
>>> os.system("... | Use of pexpect will work for you...
Here is the solution - <http://pypi.python.org/pypi/pexpect/> | Automate Input Into Python Prompts | [
"",
"python",
"bash",
""
] |
I have an email form where I'm trying to save the user's email address to the database. The model looks like this:
```
class EmailForm(db.Model):
email_address = db.EmailProperty
```
I've been using a few tutorials like [this](http://f.souza.cc/2010/08/flying-with-fla... | You are attempting to use a Model as a Form, which are two different things.
You need another step
```
from flaskext import wtf
from flaskext.wtf import validators
class EmailModel(db.Model):
email_address = db.EmailProperty
class EmailForm(wtf.Form):
email = wtf.TextField('Email Address', validators=[valid... | I guess this is what you are looking for:
<https://developers.google.com/appengine/docs/python/datastore/typesandpropertyclasses#Email>
email\_address = db.EmailProperty()
email\_address = db.Email("larry@example.com") | How to properly save form data in Google App Engine | [
"",
"python",
"flask",
""
] |
With `distutils`, `setuptools`, etc. a package version is specified in `setup.py`:
```
# file: setup.py
...
setup(
name='foobar',
version='1.0.0',
# other attributes
)
```
I would like to be able to access the same version number from within the package:
```
>>> import foobar
>>> foobar.__version__
'1.0.0'
```
---
... | Set the version in `setup.py` only, and read your own version with [`pkg_resources`](http://pythonhosted.org/setuptools/pkg_resources.html), effectively querying the `setuptools` metadata:
file: `setup.py`
```
setup(
name='foobar',
version='1.0.0',
# other attributes
)
```
file: `__init__.py`
```
from p... | I don't believe there's a canonical answer to this, but my method (either directly copied or slightly tweaked from what I've seen in various other places) is as follows:
**Folder heirarchy (relevant files only):**
```
package_root/
|- main_package/
| |- __init__.py
| `- _version.py
`- setup.py
```
**`main_pa... | What is the correct way to share package version with setup.py and the package? | [
"",
"python",
"setuptools",
"distutils",
""
] |
If I have a customer respond to the same survey in 30 days more than once, I only want to count it once. Can someone show me code to do that please?
```
create table #Something
(
CustID Char(10),
SurveyId char(5),
ResponseDate datetime
)
insert #Something
select 'Cust1', '100', '5/6/13' union all
sel... | Going on the theory that you want your periods calculated as 30 days from the first time a survey is submitted, here is a (gross) solution.
```
declare @Something table
(
CustID Char(10),
SurveyId char(5),
ResponseDate datetime
)
insert @Something
select 'Cust1', '100', '5/6/13' union all
select 'Cust1', ... | I'm not a SQL Server guy, but in Oacle if you subtract integer values from a 'date', you're effectively subtracting "days," so something like this could work:
```
SELECT custid, surveyid
FROM Something a
WHERE NOT EXISTS (
SELECT 1
FROM Something b
WHERE a.custid = b.custid
AND a.surveyid = b.surveyid
... | Count Response once in 30 days SQL | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I should preface this by saying the following: I know this functionality is not supported by default - what I'm attempting is a hacky workaround that has very little practical application, and is a complete practice in mental masturbation as a result of boredom and curiosity. That said, I'm trying to do the following:
... | Python doesn't have a portable way to trace frames… but the CPython implementation does: [`sys._getframe`](http://docs.python.org/3/library/sys.html#sys._getframe) returns you a frame object.
What can you do with a frame object? See the handy chart in the [`inspect`](http://docs.python.org/3/library/inspect.html) docs... | Actually you can perform similar trick like this:
```
>>> from contextlib import contextmanager
>>> @contextmanager
def override_new_vars(locs):
old_locals = locs.copy()
yield
new_locals_names = set(locs) - set(old_locals)
for name in new_locals_names:
locs[name] = '%s = %r' % (name, locs[name]... | Getting name of local variable at runtime in Python | [
"",
"python",
"debugging",
""
] |
I have numpy matrices collected in the list. I need to built an array which contains particular entry from each matrix, for example second entry from each matrix. I would like to avoid loop.
The data is already in this shape, I don't want to change the structure or change matrices into something else.
Example code - ... | Using list comprehension:
```
>>> x = [i[1] for i in L]
>>> x
[2, 5, 8, 11, 14]
>>>
``` | You could also do
```
>>> M = np.column_stack([m1,m2,m3,m4,m5])
```
and then access the rows via
```
>>> M[1]
matrix([[ 2, 5, 8, 11, 14]])
```
If you've got larger vectors, and want to access multiple rows, this might be faster in the long run. | accessing position from numpy matrices in the list | [
"",
"python",
"numpy",
""
] |
I Need to Search "WAM" in below `/var/log/messages` and Export complete time stamp value to Excel sheet / Text document
```
2013-07-09T02:22:18.535639Z user.info WebAppMgr WAM
2013-07-09T02:22:21.817372Z user.info sam SAM ^Icom.palm.app.calculator
2013-07-09T02:22:21.818442Z user.info sam SAM ^Icom.palm.app.settings... | Try this:
```
awk 'BEGIN{print "WAM"}/\<WAM\>/{print $1}' /home/santosh/messages > text.file
``` | try this one-liner:
```
awk 'BEGIN{v="WAM";print v}$NF==v&&$0=$1' yourfile
```
with your example:
```
kent$ echo "2013-07-09T02:22:18.535639Z user.info WebAppMgr WAM
2013-07-09T02:22:21.817372Z user.info sam SAM ^Icom.palm.app.calculator
2013-07-09T02:22:21.818442Z user.info sam SAM ^Icom.palm.app.settings
2013-0... | Shell script to Search and Export to csv file/Excel sheet | [
"",
"python",
"performance",
"bash",
"shell",
""
] |
When trying to create a database running a script generated by Visual Studio (Entity Framework, "Generate Database From Model..." link), I'm running into an error with a Primary Key.
The command giving me an issue is
```
ALTER TABLE tablename
ADD CONSTRAINT constraintname
PRIMARY KEY NONCLUSTERED (col1, col2 ASC)... | [`nchar`](http://msdn.microsoft.com/en-us/library/ms186939.aspx) is unicode, which takes up two bytes per character.
If you don't need unicode, switch to `char`. Or shorten your columns, or add separate column(s) to use as a key. Two 512 character strings is a pretty large primary key! | Switch to `nvarchar`. `nchar` is a fixed-space data type. You'll probably waste 90% of your storage space. If you want to store a string of 10 chars you will need space for 256 which is an unnecessary waste.
Consider going to `varchar` to space a further 50%. But you loose Unicode that way.
Next todo for you: read th... | SQL Server seems to calculate key length incorrectly | [
"",
"sql",
"sql-server-2005",
""
] |
Following [document](http://doc.scrapy.org/en/0.16/topics/practices.html#run-scrapy-from-a-script), I can run scrapy from a Python script, but I can't get the scrapy result.
This is my spider:
```
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from items import DmozItem
class Dmoz... | Terminal prints the result because the default log level is set to `DEBUG`.
When you are running your spider from the script and call `log.start()`, the default log level is set to `INFO`.
Just replace:
```
log.start()
```
with
```
log.start(loglevel=log.DEBUG)
```
UPD:
To get the result as string, you can log e... | I found your question while asking myself the same thing, namely: "How can I get the result?". Since this wasn't answered here I endeavoured to find the answer myself and now that I have I can share it:
```
items = []
def add_item(item):
items.append(item)
dispatcher.connect(add_item, signal=signals.item_passed)
`... | Confused about running Scrapy from within a Python script | [
"",
"python",
"web-scraping",
"scrapy",
""
] |
I want to add two list of different length start from the right
Here's an example
```
[3, 0, 2, 1]
[8, 7]
```
Expected result:
```
[3, 0, 10, 8]
```
These list represent coefficient of polynomials
Here is my implementation
```
class Polynomial:
def __init__(self, coefficients):
self.coeffs = coefficie... | Edit (2020-18-03):
```
>>> P = [3, 0, 2, 1]
>>> Q = [8, 7]
>>> from itertools import zip_longest
>>> [x+y for x,y in zip_longest(reversed(P), reversed(Q), fillvalue=0)][::-1]
[3, 0, 10, 8]
```
Obviously, if you choose a convention where the coefficients are ordered the opposite way, you can just use
```
P = [1, 2, 0... | I believe a simple for loop is far simpler than a comprehension with zip\_longest...
```
P = [3, 0, 2, 1]
Q = [8, 7]
A, B = sorted([P, Q], key=len)
for i, x in enumerate(reversed(A), 1):
B[-i] += x
#print(B)
```
If you need to keep `P` unchanged, copy it first. Also, if `Q` is much smaller than `P`, this will b... | Add two lists of different lengths in python, start from the right | [
"",
"python",
"coding-style",
""
] |
I have a table of sales with fields: product,date,qty. I need to extract the Product wise sales in day wise format like this
```
Product 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 .............. 31 Total Sale
Rice X X X X X X X X X XX XX XX XX XX XX XX............... XX
Tea X X X X X X X X X XX XX XX XX XX XX X... | you can use following statment in oracle
```
SELECT
product
, sum( CASE WHEN TO_CHAR(date, 'dd') = '01' THEN qty ELSE 0 END ) as 1
, sum( CASE WHEN TO_CHAR(date, 'dd') = '02' THEN qty ELSE 0 END ) as 2
, sum( CASE WHEN TO_CHAR(date, 'dd') = '03' THEN qty ELSE 0 END ) as 3
, sum( CASE WHEN TO_CHAR(date, 'dd') = ... | You will have to use [PIVOT](http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx), I have only put upto 6 day here, include upto 31
```
WITH base AS (
SELECT product, day(date) AS DAY, sum(qty) AS tot
FROM product GROUP BY product, date)
SELECT product, [1], [2], [3], [4], [5], [6]
FROM base pivot(sum(tot... | Data extraction day wise | [
"",
"sql",
"sql-server",
"oracle",
""
] |
Is there any possibility to delete the entire Data in table and insert new rows with id starts from 1
Delete Command helps to remove the data from table when we trying to insert new row that id will be Last inserted row id+1(if last inserted id is 5 then new id should be 6) but i want to store that id as 1
any sugges... | After deleteing all records do
```
ALTER TABLE tablename AUTO_INCREMENT = 1
```
**Note**
**From MySQL Docs** : [Link](http://dev.mysql.com/doc/refman/5.1/en/alter-table.html)
> You cannot reset the counter to a value less than or equal to any that
> have already been used. For MyISAM, if the value is less than or e... | I presume from your description, that "id" is an identity column?
In that case,
```
TRUNCATE TABLE tablename;
```
with both delete all rows, and reset the identity field to populate from 1 again. | Insert new row with id 1 | [
"",
"mysql",
"sql",
""
] |
I'm having trouble understanding just why I would want to use bitwise operators in a high-level language like Python. From what I have learned of high- vs low-level languages is that high-level ones are typically designed to that you don't have to worry too much about the machine code going into a computer. I don't see... | If you want a concrete example of bitwise operators being used in the standard library, just look at the `re` library. [According to the API](http://docs.python.org/2/library/re.html#re.compile), the flags are supposed to be bitwise `OR`ed together.
This allows you to pass a large number of options in a single argumen... | There's definitely a use for bitwise operations in Python. Aside from `or`-ing flags, like mgilson mentions, I used them myself for composing packet headers for CAN messages. Very often, the headers for a lower-level message protocol are composed of fields that have a length that is not a multiple of 8 bits, so you wou... | What are the advantages to using bitwise operations over boolean operations in Python? | [
"",
"python",
"bit-manipulation",
"low-level",
"high-level",
""
] |
I have made two tables. The first table holds the metadata of a file.
```
create table filemetadata (
id varchar(20) primary key ,
filename varchar(50),
path varchar(200),
size varchar(10),
author varchar(50)
) ;
+-------+-------------+---------+------+---------+
| id | filename | path | size | author |
+-... | Use `JOIN` (from the top of my head, no checks done):
```
SELECT filemetadata.id, filename, path, size, author, GROUP_CONCAT(favouritedby)
FROM filemetadata
LEFT JOIN filefav ON filemetadata.id=filefav.id GROUP BY filemetadata.id
``` | `Select A.*,B.favouritedby FROM filemetadata A Left join (Select id,Group_Concat(favouritedby) from filefav group by id) B ON A.`Id=B.Id | Combining two tables in a database | [
"",
"mysql",
"sql",
"database",
"database-design",
"database-schema",
""
] |
Ok I have searched SO and Google but haven't really found a definitive answer so throwing it out there for the SO community.
Basically I have a table of longitudes and latitudes for specific points of interest, the sql query will know which location you are currently at (which would be one of those in the table, passe... | I wrote a blog a couple years ago that explains how this can be done without using the spatial data types. Since it appears as though you have a table of longitude/latitude values, this blog will likely help a lot.
[SQL Server Zipcode Latitude Longitude Proximity Search](http://blogs.lessthandot.com/index.php/DataMgmt... | Let's look at a simple example of using the `STDistance` function in SQL Server 2008 (and later).
I'm going to tell SQL Server that I'm in London, and I want to see how far away each of my offices are. Here's the results that I want SQL Server to give me:
[](https://i.st... | Get the nearest longitude and latitude from MSSQL database table? | [
"",
"sql",
"sql-server",
"database",
"t-sql",
"sql-server-2012",
""
] |
I am learning from the book: "Learning Android" (Marko Gargenta - O'REILLY) I am in chapter 9 (The Database).
I am trying to show anything useful using sqlite3. I opened the emulator. I opened the File Explorer in eclipse, I found that I have a database in my emulator which has the path
`data/data/saleh.yamba/databas... | `adb shell` is not a SQLite command.
I guess what your are trying to do is:
```
$ adb shell sqlite3 /data/data/saleh.yamba/databases/timeline.db
```
to start sqlite3 and open the database | You can't select directly from the db - you would need to select from a table inside the db.
As you most likely don't know the insides of this db try creating one on your own, I guess that shouldn't be much further in your book. | SQLite3 doesn't show anything | [
"",
"android",
"sql",
"eclipse",
"sqlite",
"emulation",
""
] |
I am very new to programming and started learning python. Might look very stupid question, so please pardon my ignorance.
Consider the following snippet of code :
```
class Test1:
bar = 10
def display(self,foo):
self.foo=foo
print "foo : ",self.foo #80
def display1(self):
print ... | `bar` is a class attribute. Since classes in Python are objects, they too can have attributes. `bar` just happens to live on that `Test` object, not an instance thereof.
Because of the way Python resolves attribute lookups, it looks like `test1` has a `bar` attribute, but it doesn't.
`foo` on the other hand lives on ... | `bar` is a class attribute and `foo` is an instance attribute. The main difference is that `bar` will be available to all class instances while `foo` will be available to an instance only if you call display on that instance
```
>>> ins1 = Test1()
```
`ins1.bar` works fine because it is a class attribute and is share... | Understanding python class attributes | [
"",
"python",
"python-2.7",
"python-3.x",
""
] |
I do have a list as given below -
```
keyList1 = ["Person", "Male", "Boy", "Student", "id_123", "Name"]
value1 = "Roger"
```
How can I generate dynamic dictionary which can be retrieved as below -
```
mydict["Person"]["Male"]["Boy"]["Student"]["id_123"]["Name"] = value
```
The list could be anything; Variable Lengt... | I'm just learning python, so my code could be not very pythonic, but here's my code
```
d = {}
keyList1 = ["Person", "Male", "Boy", "Student", "id_123", "Name"]
keyList2 = ["Person", "Male", "Boy", "Student", "id_123", "Age"]
value1 = "Roger"
value2 = 3
def insert(cur, list, value):
if len(list) == 1:
cu... | You can do this by making nested `defaultdict`s:
```
from collections import defaultdict
def recursive_defaultdict():
return defaultdict(recursive_defaultdict)
def setpath(d, p, k):
if len(p) == 1:
d[p[0]] = k
else:
setpath(d[p[0]], p[1:], k)
mydict = recursive_defaultdict()
setpath(myd... | Python Generate a dynamic dictionary from the list of keys | [
"",
"python",
"dictionary",
""
] |
I have created a simple multi threaded tcp server using python's threding module. This server creates a new thread each time a new client is connected.
```
#!/usr/bin/env python
import socket, threading
class ClientThread(threading.Thread):
def __init__(self,ip,port):
threading.Thread.__init__(self)
... | You should pass the client sock to the thread like you do with the ip address and the port:
```
class ClientThread(threading.Thread):
def __init__(self, ip, port, socket):
threading.Thread.__init__(self)
self.ip = ip
self.port = port
self.socket = socket
print "[+] New thre... | I have created this nice class you can override
```
import socket
import thread
class SocketServer(socket.socket):
clients = []
def __init__(self):
socket.socket.__init__(self)
#To silence- address occupied!!
self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.bind... | Multi Threaded TCP server in Python | [
"",
"python",
"sockets",
"tcpserver",
""
] |
I have two different tables FirewallLog and ProxyLog. There is no relation between these two tables. They have four common fields :
LogTime ClientIP BytesSent BytesRec
I need to Calculate the total usage of a particular ClientIP for each day over a period of time (like last month) and display it like belo... | First, create a Calendar table. One that has, at the very least, an `id` column and a `calendar_date` column, and fill it with dates covering every day of every year you can *ever* be interested in . *(You'll find that you'll add flags for weekends, bankholidays and all sorts of other useful meta-data about dates.)*
T... | If you don't have a calendar table, you can create one using a recursive CTE:
```
declare @startdate date = '2013-02-01';
declare @enddate date = '2013-03-01';
with dates as (
select @startdate as thedate
union all
select dateadd(day, 1, thedate)
from dates
where thedate < @enddate
)... | Summing up columns from two different tables | [
"",
"sql",
"sql-server",
""
] |
I'm learning Python Tuple, and feeling a bit overwhelmed. I'm working with a tuple about 20 times the size of what I've put together below.
```
{u'0UsShTrY': {u'a': {u'n': u'Backups'}, u'h': u'0UsShTrY', u'k': (16147314, 17885416, 1049370661, 902515467), u'ts': 13734967, u'p': u'5RtyGQwS', u'u': u'xpz_tb-YDUg', u't': ... | You can extract some of the data with comprehensions, like this:
```
[d[k]['a']['n'] for k in d]
# => [u'Backups', 'Rubbish Bin', u'Test3', u'Abandon All Ships - 5 - Stange Love.mp3']
```
(assuming you have your dict (and it's a dict, as Dan and David say, not a tuple) in `d`). | What you appear to have showed is not in fact a tuple but a dictionary which is made of of key/value pairs, and some of those values are themselves dictionaries with key/value pairs some of which contain tuples.
If this Dict is called MusicDict for example you would access the information you need like this:
To acces... | Python Tuple Issue | [
"",
"python",
"tuples",
""
] |
I'm pretty new with Python and programming in general, so excuse the lack of "fu". :)
I'm having trouble understanding this class call:
# snippet
```
class bar:
def __init__(self, a):
self.a = a
def __add__(self, b):
s = self.a + b.a
return s
```
# end snippet
So, from the interpret... | When you call `x + y` it is actually translated to:
```
x.__add__(y)
```
Therefore, this method is called:
```
__add__(self, b) # __add__(x, y)
```
Which results in:
```
s = x.a + y.a # 30
return 30
``` | In this code, b.a isn't being created, it is being accessed. You're basically passing in y as the argument b, which already has an `a` attribute associated with it since it is an object of type `bar`. If you want to step through your code go to <http://www.pythontutor.com> | Need help walking through logic of this code | [
"",
"python",
""
] |
I am a newbie in python, so may be this is a silly question. I want to write simple c program with embedded python script. I have two files:
call-function.c:
```
#include <Python.h>
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue;
if (argc < 3)
... | I have resolved this issue by setting PYTHONPATH to `pwd`. Also module name (without .py) should be set for argv[1].
Thank you! | I ran into this issue also after struggling for a while.After searching the web I found that is was a system path issue. After adding the two lines after Py\_Initialize(); it worked.
OS: Windows 7, Compiler: Embarcadero C++ Builder XE6, Python: Version 2.7
Reference: [C++ With Python](https://sites.google.com/site/ja... | PyImport_Import fails (returns NULL) | [
"",
"python",
"c",
""
] |
I am a complete beginner with Python and am trying to do something in a single line of code.
```
resourceProperties = 'test test token test'
rpAttrs = [ ['ajgagag', 'knkagga'], ['token', 'knkagga'], ['ajgagag', 'knkagga'] ]
for value in rpAttrs if not list(re.finditer(value[0], resourceProperties)) : print value[0]
`... | ```
list_comp = [value[0] for value in rpAttrs if not list(re.finditer(value[0], resourceProperties))]
>> ['ajgagag', 'ajgagag']
```
would be the correct way to do the comprehension | Based on the OP's confirmation that only a "containment" check is needed
```
>>> print [value[0] for value in rpAttrs if not value[0] in resourceProperties]
['ajgagag', 'ajgagag']
``` | Print search term that does not exist in list comprehension of a list comprension | [
"",
"python",
"jython",
""
] |
I was wondering if anyone had any suggestions for lazy loading imports in an **init** file? I currently have the following folder structure:
```
/mypackage
__init__.py
/core
__init__.py
mymodule.py
mymodule2.py
```
The **init**.py file in the core folder with the following imports:
``... | You can't. Remember that when python imports it executes the code in the module. The module itself doesn't know how it is imported hence it cannot know whether it has to import `MyModule(2)` or not.
You have to choose: allow `from mypackage.core import A, B` *and* `from core.exc import E` does the non-needed imports (... | Unless I'm mistaking your intentions, this is actually possible but requires some magic.
Basically, subclass `types.ModuleType` and override `__getattr__` to import on demand.
Check out the Werkzeug [\_\_init\_\_.py](https://github.com/pallets/werkzeug/blob/71eab19be2c83fb476de51275e2f9bdf69d5cc10/src/werkzeug/__init... | Lazy loading module imports in an __init__.py file python | [
"",
"python",
"lazy-loading",
"import",
""
] |
Hi I'm making a program on python and I'm having trouble adding a global variable to my program so I'm just going to post my code and show you how I tried to do it.
So this is my class:
```
import globalvariables
class Bus :
def __init__(self, Number, Capacity, Destination, Seats):
self.Bus_Number = Number
... | The variable `Seats` is local to `__init__` function and can't be accessed outside of it.
So,
```
self.Seats_taken = Seats + 1
```
Should be :
```
self.Seats_taken = self.Seats_taken + 1
```
or :
```
self.Seats_taken += 1
```
Instead of using global variables inside class you should use class attributes:
```
c... | Globals should be avoided. In case you still want it to be :
```
def Book(self):
self.Seats_taken = globalvariables.Seats + 1
``` | Global variables in Python aa | [
"",
"python",
""
] |
I saw an example of code that where `hash` function is applied to a tuple. As a result it returns a negative integer. I wonder what does this function do? Google does not help. I found a page that explains how hash is calculated but it does not explain why we need this function. | [A hash is an fixed sized integer that identifies a particular value](http://en.wikipedia.org/wiki/Hash_function). Each value needs to have its own hash, so for the same value you will get the same hash even if it's not the same object.
```
>>> hash("Look at me!")
4343814758193556824
>>> f = "Look at me!"
>>> hash(f)
... | ## TL;DR:
Please refer to [the glossary](https://docs.python.org/3/glossary.html#term-hashable): `hash()` is used as a shortcut to comparing objects, an object is deemed hashable if it can be compared to other objects. That is why we use `hash()`. It's also used to access `dict` and `set` elements which are implemente... | What does hash do in python? | [
"",
"python",
"hash",
""
] |
Say I have an option menu `network_select` that has a list of networks to connect to.
```
import Tkinter as tk
choices = ('network one', 'network two', 'network three')
var = tk.StringVar(root)
network_select = tk.OptionMenu(root, var, *choices)
```
Now, when the user presses the refresh button, I want to update the... | I modified your script to demonstrate how to do this:
```
import Tkinter as tk
root = tk.Tk()
choices = ('network one', 'network two', 'network three')
var = tk.StringVar(root)
def refresh():
# Reset var and delete all old options
var.set('')
network_select['menu'].delete(0, 'end')
# Insert list of ... | In case of using ttk, there is a convenient `set_menu(default=None, values)` method on the OptionMenu object. | Changing the options of a OptionMenu when clicking a Button | [
"",
"python",
"python-2.7",
"tkinter",
"onclick",
"optionmenu",
""
] |
I am storing a timestamp field in a SQLite3 column as `TIMESTAMP DATETIME DEFAULT CURRENT_TIMESTAMP` and I was wondering if there was any way for it to include milliseconds in the timestamp as well? | Instead of `CURRENT_TIMESTAMP`, use `(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW'))` so that your column definition become:
```
TIMESTAMP DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW'))
```
For example:
```
CREATE TABLE IF NOT EXISTS event
(when_ts DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')));
``` | To get number of milliseconds since epoch you can use `julianday()` with some additional calculations:
```
-- Julian time to Epoch MS
SELECT CAST((julianday('now') - 2440587.5)*86400000 AS INTEGER);
``` | SQLite Current Timestamp with Milliseconds? | [
"",
"sql",
"sqlite",
""
] |
I created this function in Python 2.7 with `ipython`:
```
def _(v):
return v
```
later if I call `_(somevalue)`, I get `_ = somevalue`.
```
in[3]: _(3)
out[3]: 3
in[4]: print _
out[4]: 3
```
The function has disappeared! If I call `_(4)` I get:
```
TypeError: 'int' object is not callable
```
Why? What's wrong... | The Python interpreter assigns the last expression value to `_`.
This behaviour is limited to the [REPL interpreter](http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) only, and is intended to assist in interactive coding sessions:
```
>>> import math
>>> math.pow(3.0, 5)
243.0
>>> result = _
>>> resu... | `_` is a special variable in interpreter, it is always assigned to the result of previous expression. So, you shoudn't use it like that.
BTW the problem seems to be related to IPython shell, because your code works fine in normal python shell:
In normal python shell when you assign anything to the variable `_` then i... | Assigning a value to single underscore _ in Python/IPython interpreter | [
"",
"python",
"function",
"ipython",
"interpreter",
"read-eval-print-loop",
""
] |
I Have requirement in Oracle 10g:
I need to select using an `in` clause.
The problem is the string which I want to use in the database is comma separated values product codes like `4435D,4436E,5656F, 5670L` in a single column.
What I want is something like `'4435D','4436E','5656F', '5670L'` which I can use as
```
Se... | You can use the hierarchical query to separate the values in the string.
```
with str as (
select '4435D,4436E,5656F,5670L' s from dual)
select regexp_substr(s,'[^,]+',1,level) from str
connect by regexp_substr(s,'[^,]+',1,level) is not null;
```
output:
```
4435D
4436E
5656F
5670L
```
You can use this as subquer... | How about using like?
```
Select * from sub_products
where product_code like '%4435D%' or product_code like '%5656F%' or product_code like '%5670L%';
``` | Separate/Organize string values in Oracle | [
"",
"sql",
"string",
"oracle",
"oracle10g",
""
] |
I have a database that contains articles with pre-calculated quality scores ranging from 0 to 10 (with 10 being best quality) and each article has a published date.
Here is an example database schema.
```
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`conte... | You'll need some weighting for this. This one is based on the [Hacker News Algorithm](http://amix.dk/blog/post/19574).
```
SELECT *,
(score/power(((NOW()-published)/60)/60,1.8)) as rank
FROM posts ORDER BY rank DESC;
``` | You need to calculate a relevance score based on those two parameters. How such a relevance score is calculated will depend on how you wish for the two metrics to relate (e.g. the rate at which older articles become less interesting).
Suppose one defined a [stored function](http://dev.mysql.com/doc/en/stored-routines.... | How to order articles by both quality score and publish date? | [
"",
"mysql",
"sql",
"algorithm",
""
] |
I have exported an Access table into a .csv file and am importing that .csv file into a MySql table.
After importing everything, I currently have a column in MySQL called **Time** that contains string data (VARCHAR):
```
7/29/2008 10:28:38
```
Importing this timestamp data from Access using a .csv file would work co... | The correct format is `%c/%e/%Y`:
```
UPDATE members SET Time2 = STR_TO_DATE(Time, '%c/%e/%Y')
```
where
* %c is the month, numeric, without leading zeros
* %e is the day of the month, numeric, probably without leading zeros
* %Y is the year
Here you can find a reference of the [format string](http://dev.mysql.com/... | I couldn't get `STR_TO_DATE` to work when doing a `SELECT`, changed `STR_TO_DATE` to `DATE_FORMAT` and I have `mm/dd/yyyy` -
```
SELECT DATE_FORMAT(Time, '%c/%e/%Y') FROM the_table_name
```
> e.g. DATE\_FORMAT('2013-08-14 09:42:05')
>
> gives 8/14/2013 | How to convert a string containing a timestamp to a simple Date in MySql | [
"",
"mysql",
"sql",
"ms-access",
"csv",
""
] |
The users dynamically generate queries in a form, and the results are shown in a listbox on the same form. The listbox can have anywhere from 1 to 12 columns.
The users want the results of this query to be able to be exported to Excel. I believe not saving the file is preferred but whatever works will work.
I have cu... | You could make a ListObject in excel with an external data source that's the same as the RowSource of the Listbox.
```
Private Sub Command2_Click()
Dim xlApp As Excel.Application
Dim xlWb As Excel.Workbook
Dim xlWs As Excel.Worksheet
Dim xlLo As Excel.ListObject
Set xlApp = GetObject(, "Excel.App... | Please refer to this site for all possible methods as well as advantages/disadvantages of them.
For your problem , I would prefer to use DAO method. The example codes are also in this site.
[Way to transer data from access to excel](http://zmey.1977.ru/Access_To_Excel.htm)
While you import Cell by Cell, you can forma... | Most Efficient Way To Export Access 2003 Listbox RowSource (query) To Excel 2003 | [
"",
"sql",
"excel",
"vba",
"ms-access",
"export-to-excel",
""
] |
Selecting rows from table1 which do not exists in table2 and inserting it in table2
like
**Images**
```
id type name
502 1 summer.gif
```
**SEOImages**
```
id idimage ... ...
1000 501 ... ...
```
Now I want to select all the rows from `Images` table whose id does not match idimage `SEOImages... | **Approach :**
```
Insert into Table2
select A,B,C,....
from Table1
Where Not Exists (select *
from table2
where Your_where_clause)
```
**Example :**
[**SQLFiddelDemo**](http://sqlfiddle.com/#!3/a527d/2)
```
Create table Images(id int,
type int,
... | ```
INSERT INTO SeoImages
(IdImage)
SELECT ID
FROM Images
WHERE ID NOT IN (SELECT IDIMAGE FROM SEOImages)
``` | selecting row from one table and insert into other table | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
In my program I'm working with various numpy arrays of varying sizes. I need to store them into XML files for later use. I did not write them to binary files so I have all my data in one place (the XML file) and not scattered through 200 files.
So I tried to use numpy's array\_str() method to transform an array into a... | Numpy provides an easy way to store many arrays in a compressed file:
```
a = np.arange(10)
b = np.arange(10)
np.savez_compressed('file.npz', a=a, b=b)
```
You can even change the array names when saving, by doing for example: `np.savez_compressed('file.npz', newa=a, newb=b)`.
To read the saved file use `np.load()`,... | Unfortunately there is no easy way to read your current output back into numpy. The output won't look as nice on your xml file, but you could create a readable version of your arrays as follows:
```
>>> import cStringIO
>>> a = np.array([[ 0.99845902, -0.70780512, 0.26981375, -0.6077122, 0.09639695], [ 0.61856711, -0.... | Storing and loading numpy arrays as files | [
"",
"python",
"arrays",
"string",
"serialization",
"numpy",
""
] |
I'm taking user inputted strings continuously and then trying to remove any character that is not a character or digit.
The method that I developed involves splitting a string by the white space and then analyzing each word to find invalid characters.
I'm having a hard time putting the words back together with spaces... | Of course, @Ashwini's answer is better than this, But if you still want to do it just with loops
```
strings = raw_input("type something")
while(True):
MyString = ""
if strings == "stop": break
for string in strings.split():
for char in string:
if(char.isalnum()): MyString += char
... | # Simple loop based solution:
```
strs = "foo12 #$dsfs 8d"
ans = []
for c in strs:
if c.isalnum():
ans.append(c)
elif c.isspace(): #handles all types of white-space characters \n \t etc.
ans.append(c)
print ("".join(ans))
#foo12 dsfs 8d
```
# One-liners:
Use `str.translate`:
```
>>> from st... | Converting a list into a string | [
"",
"python",
"string",
"list",
"function",
"join",
""
] |
I have a dictionary item from which I would like to get the maximum value. This dictionary consists of 2 dictionaries. The following is the dictionary
```
new_f_key: {'previous_f_key': {'1g': ['33725.7', '-70.29'],
'2g': ['35613.3', '108.83'],
'3g': ['32080... | ```
dic = {'previous_f_key': {'1g': ['33725.7', '-70.29'],
'2g': ['35613.3', '108.83'],
'3g': ['32080.9', '-69.86']},
'f_key': {'1g': ['8880.8', '-66.99'],
'2g': ['6942.6', '114.79'],
'3g': ['12300.3', ... | Do this. It will handle arbitrary nesting, and it's short.
```
def weird_max(d, key=float):
vals = []
for item in d.itervalues():
if isinstance(item, dict):
vals.append(weird_max(item))
else: # should be a list
vals.extend(item)
return max(vals, key=key)
```
That sa... | Get Maximum Value based upon Multiple Dictionary Objects using Python | [
"",
"python",
"dictionary",
""
] |
I am trying to do something like (psuedo - of course):
```
SELECT
city,
CASE WHEN COUNT( [group] ) > 1 THEN 'Multiple' ELSE [group] END AS Type
FROM
offices
GROUP BY
city
```
Where offices contains rows like:
```
ID | group | city
----------------------
1 | 'A' | 'Houston'
2 | 'B' | 'H... | You can find the `MIN` and `MAX` of the column and then act if they are not identical:
```
declare @t table (ID int not null,[group] char(1) not null,city varchar(20) not null)
insert into @t(ID,[group],city) values
(1,'A','Houston'),
(2,'B','Houston'),
(3,'C','Houston'),
(4,'S','Boston' ),
(5,'R','Detroit')
select c... | [@Damien\_The\_Unbeliever's answer](https://stackoverflow.com/a/17588061/1369235) is perfect. This one is an alternative. If you want to check for more than one (e.g. `COUNT(GROUP) > 2`). Just use `MIN` or `MAX` in `ELSE` like this:
```
SELECT
city,
CASE WHEN COUNT([group]) > 2
THEN 'Multiple'
ELS... | Using GROUP BY clause to replace dissimilar rows with single value | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a schema which looks as follows (simplified):
```
CREATE TABLE MyTable (
DateTimeOffset HitDate NOT NULL,
IpAddress varchar(15)
)
```
A sample row might look as follows:
`'7/10/2013 8:05:29 -07:00' '111.222.333.444'`
I'm trying to work out a query that will give me, for each day (e.g., 7/10/2013) the n... | The easiest way to do this (in my opinion) is to find the earliest date when an IP address appeared, and then use that for aggregation:
```
select cast(minHitDate as Date), count(*) as FirstTimeVisitors
from (select IpAddress, min(HitDate) as minHitDate
from MyTable t
group by IpAddress
) i
group by c... | ```
CREATE TABLE #MyTable (
HitDate DateTimeOffset NOT NULL,
IpAddress varchar(15))
insert #mytable values
('7/10/2013 8:05:29 -07:00', '111.222.333.444'),
('7/10/2013 12:05:29 -07:00', '111.222.333.222'),
('7/9/2013 9:05:29 -07:00' ,'111.222.333.444'),
('7/9/2013 10:05:29 -07:00', '111.222.333.555'),
('7/8/2013 11:05... | SQL Query - Determining new visitors each day | [
"",
"sql",
"t-sql",
""
] |
I'm somewhat new to SQL and I am trying to figure out the best way of doing this without hardcoding update statements in SQL Server 2012.
Basically I have a hierarchical table of companies (think of a supply chain) with columns (`CompanyID, ParentID, ParentPriceAdj, CompanyPriceAdj`). Each company gets assigned a pric... | Recursive CTE can be used to walk hierarchy, something like:
```
ALTER PROCEDURE [dbo].[UpdatePricing]
(
@companyID int,
@PriceAdj decimal
)
as
begin
set nocount on
update CompanyInfo
set CompanyPriceAdj = @PriceAdj
where CompanyID = @companyID
;with Hierarchy(CompanyID, ParentID, InPrice... | You can use WITH expression in t-sql to get all parent records for given child record. And can update each record in record set accordingly with your logic.
Here are links for WITH expression --
*<http://msdn.microsoft.com/en-us/library/ms175972.aspx>*
*<http://msdn.microsoft.com/en-us/library/ms186243(v=sql.105).as... | SQL Server : recursive update statement | [
"",
"sql",
"sql-server",
"recursion",
"sql-update",
"sql-server-2012",
""
] |
I'm creating a select statement that combines two tables, `zone` and `output`,
based on a referenced `device` table and on a mapping of `zone_number` to `output_type_id`.
The mapping of `zone_number` to `output_type_id` doesn't appear
anywhere in the database, and I would like to create it "on-the-fly" within the selec... | You can use `VALUES` as an inline table and JOIN to it, you just need to give it an alias and column names:
```
join (values (1, 101), (2, 202), (3, 303), (4, 304)) as map(zone_number, output_type_id)
on ...
```
From the [fine manual](http://www.postgresql.org/docs/current/interactive/sql-values.html):
> `VALUES` ca... | So just to complement the accepted answer, the following code is a valid, **self-contained** Postgresql expression which will evaluate to an 'inline' relation with columns `(zone_number, output_type_id)`:
```
SELECT * FROM
(VALUES
(1, 101),
(2, 202),
(3, 303),
(4, 304)
) as i(zone_number, output_type_id)
... | How to create an "on-the-fly" mapping table within a SELECT statement in Postgresql | [
"",
"sql",
"postgresql",
"postgresql-8.4",
""
] |
I have an issue where in my data I will have a record returned where a column value will look like
-- query
```
Select col1 from myTable where id = 23
```
-- result of col1
111, 104, 34, 45
I want to feed these values to an in clause. So far I have tried:
-- Query 2 -- try 1
```
Select * from mytableTwo
where myf... | You don't want an `in` clause. You want to use `like`:
```
select *
from myTableTwo t2
where exists (select 1
from myTable t
where id = 23 and
', '+t.col1+', ' like '%, '+t2.myfield+', %'
);
```
This uses `like` for the comparison in the list. It uses a su... | If you observe closely, Query 2 -- try 1 & Query 2 -- try 2 are considered as single value.
like this :
```
WHERE myfield in ('111, 104, 34, 45')
```
which is not same as :
```
WHERE myfield in ('111', '104', '34', '45')
```
So, If you intend to filter myTable rows from MyTableTwo, you need to extract the values o... | T-SQL Comma delimited value from resultset to in clause in Subquery | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I have a function where, based on different case, I'm changing the parameters sent to a function whose result I'm returning. I would like to just decide parameters in the middle of the method, and only have one return call at the bottom of my function. Please be aware this is not what my code looks like, it's just an e... | Use `*` to [unpack the parameter tuple](http://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists):
```
func(*parameters)
```
**Demo:**
```
def func(x,y,z):
print x,y,z
>>> params = (1,2,3)
>>> func(*params)
1 2 3
>>> params = (4,5,6)
>>> func(*params)
4 5 6
``` | Just do
`return func(*parameters)`
It unpacks the parameters and passes it to the `func`. Read the [Python Docs](http://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists) entry on this.
For example -
```
>>> def test(a, b, c):
print a, b, c
>>> testList = [2, 3, 4]
>>> test(*testList)
2... | Storing Python function parameters as a variable to call later | [
"",
"python",
"django",
"parameters",
""
] |
I have a directory `bar` inside a directory `foo`, with file `foo_file.txt` in directory `foo` and file `bar_file.txt` in directory `bar`; i.e.
```
computer$ ls
foo/
computer$ ls foo/
bar/ foo_file.txt
computer$ ls foo/bar/
bar_file.txt
```
Using the python [os.path.relpath](http://docs.python.org/2/library/os.path.... | `os.path.relpath()` assumes that its arguments are directories.
```
>>> os.path.join(os.path.relpath(os.path.dirname('foo/bar/bar_file.txt'),
os.path.dirname('foo/foo_file.txt')),
os.path.basename('foo/bar/bar_file.txt'))
'bar/bar_file.txt'
``` | ```
os.path.relpath(arg1, arg2)
```
will give the relative path of arg2 from the directory of arg1. In order to get from arg2 to arg1 in your case, you would need to cd up one directory(..), go the bar directory(bar), and then the bar\_file.txt. Therefore, the relative path is
```
../bar/bar_file.txt
``` | Python os.path.relpath behavior | [
"",
"python",
"path",
"os.path",
""
] |
My data file looks like this:
```
3.6-band
6238
Over
0.5678
Over
0.6874
Over
0.7680
Over
0.7834
```
What I want to do is to pick out the smallest float and the word directly above it and print those two values. I have no idea what I'm doing. I've tried
```
df=open('filepath')
for line in df:
df1=line.split()
... | Store the items in a list of lists,`[word,num]` pairs and then apply `min` on that list of list. Use `key` parameter of `min` to specify the which item must be used for comparison of item.:
```
with open('abc') as f:
lis = [[line.strip(),next(f).strip()] for line in f]
minn = min(lis, key = lambda x: float(x[1... | You could use the [grouper recipe](http://docs.python.org/2/library/itertools.html#itertools.izip), `izip(*[iterator]*2)` to cluster the lines in `df` into groups of 2. Then, to find the minimum *pair* of lines, use [`min` and its `key` parameter](http://docs.python.org/2/library/functions.html#min) to specify the prox... | Finding smallest float in file then printing that and line above it | [
"",
"python",
"python-2.7",
"min",
""
] |
Here is what I'm trying to do:
I have a long string:
```
s = asdf23rlkasdfidsiwanttocutthisoutsadlkljasdfhvaildufhblkajsdhf
```
I want to cut out the substring: iwanttocutthisout
I will be iterating through a loop and with each iteration the value of s will change. The only thing that will stay the same with each i... | You can do a slice between the index of occurance of `iwant` (`+len(iwant)` to dis-include `iwant`) and `thisout` respectively, like so:
```
>>> s = "asdf23rlkasdfidsiwanttocutthisoutsadlkljasdfhvaildufhblkajsdhf"
>>> s[s.index("iwant")+len("iwant"):s.index("thisout")]
'tocut'
```
Diagramatically:
```
"asdf23rlkasdf... | Use the `sub()` function in the `re` module like this:
`clean_s = re.sub(r'iwant\w+thisout','',s)`
Substitute \w+ for .+ if you're expecting non-word characters in your string and use \* instead of + if there is a chance that there won't be any extra characters between the start and end tags (i.e. 'iwantthisout') | Find and cut out a python substring | [
"",
"python",
"string",
"find",
"substring",
"cut",
""
] |
I need to remove extra spaces in a sentences. The sentence is `"I like python"` and I need to make `"I like python"`. So I used replace like this:
```
>>>
>>> sentence="I like python"
>>> def checkio(element):
newelement=element.replace(" ", " ") and element.replace(" ", " ")
return newelement... | This is probably what you wanted to do:
```
def checkio(element):
newelement = element.replace(" ", " ").replace(" ", " ")
return newelement
```
You could even shorten this to
```
def checkio(element):
return element.replace(" ", " ").replace(" ", " ")
```
However, what if you wanted to replace an... | How about using this to remove extra whitespace:
```
" ".join(sentence.split())
```
If you want, you can package this as a function:
```
def checkio(element):
return " ".join(element.split())
```
### The reason why your approach fails is in your `and` statement.
Python first evaluates `element.replace(" ", " "... | Can someone explain why replace isn't working for me | [
"",
"python",
"replace",
""
] |
In python classes, the @property is a nice decorator that avoids using explicit setter and getter functions. However, it comes at a cost of an overhead 2-5 times that of a "classical" class function. In my case, this is quite OK in the case of setting a property, where the overhead is insignificant compared to the proc... | Don't use a `property` in this case. A `property` object is a data descriptor, which means that any access to `instance.var` will invoke that descriptor and Python will never look for an attribute on the instance itself.
You have two options: use the [`.__setattr__()`](http://docs.python.org/2/reference/datamodel.html... | `property` python docs: <https://docs.python.org/2/howto/descriptor.html#properties>
```
class MyClass(object):
def __init__(self):
self._var = None
# only setter
def var(self, newValue):
self._var = newValue
var = property(None, var)
c = MyClass()
c.var = 3
print ('ok')
print (c.va... | Python class @property: use setter but evade getter? | [
"",
"python",
"class",
"properties",
"timing",
""
] |
I've been searching all over but wasn't able to fig this thing out.
I'm from a Java background, if that helps, trying to learn python.
```
a = [
(i,j,k) for (i,j,k) in [
(i,j,k) for i in {-4,-2,1,2,5,0}
for j in {-4,-2,1,2,5,0}
for k in {-4,-2,1,2,5,0} if ... | You are using the wrong operator. You want [boolean `and`](http://docs.python.org/2/reference/expressions.html#boolean-operations); [`&` is a *bitwise* operator](http://docs.python.org/2/reference/expressions.html#binary-bitwise-operations):
```
[(i,j,k) for (i,j,k) in [(i,j,k) for i in {-4,-2,1,2,5,0} for j in {-4,-... | In python, `&` is a bit operator. For your need, you should use `and`. | A list comprehension returns wrong result | [
"",
"python",
"list-comprehension",
""
] |
I'm using SQL (SQL Server, PostgreSQL) over 10 years and still I'm never used `ANY/SOME` and `ALL` keywords in my production code. All situation I've encountered I could get away with `IN`, `MAX`, `MIN`, `EXISTS`, and I think it's more readable.
For example:
```
-- = ANY
select * from Users as U where U.ID = ANY(sele... | I find ANY and ALL to be very useful when you're not just testing equality or inequality. Consider
```
'blah' LIKE ANY (ARRAY['%lah', '%fah', '%dah']);
```
[as used my answer to this question](https://stackoverflow.com/q/16854442/398670).
`ANY`, `ALL` and their negations can greatly simplify code that'd otherwise re... | No, I've never used the `ANY`, `ALL`, or `SOME` keywords either, and I've never seen them used in other people's code. I assume these are vestigal syntax, like the various optional keywords that appear in some places in SQL (for example, `AS`).
Keep in mind that SQL was defined by a committee. | SQL: do we need ANY/SOME and ALL keywords? | [
"",
"mysql",
"sql",
"sql-server",
"postgresql",
"ansi-sql",
""
] |
I want to design a table which contain a friend Relationship between two person, so I Designed a table contain the following fields : `FriendId` , `Friend_L`, `Friend_R`
this mean that the person `Frind_L` is a friend to the person `Friend_R`
but this design have a problem that I must add every Friend Relationship Tw... | Try using a different query?
```
SELECT
Friend_R as Friend
FROM
Friends
WHERE
Friend_L = :x
UNION
SELECT
Friend_L as Friend
FROM
Friends
WHERE
Friend_R = :x
```
The first is identical to yours, but the UNION with the other query should return all the alternative results. UNION (without the ALL) take... | You don't have to do that. Assume you are looking for relations to a user with id of 20.
```
SELECT *
FROM friends
WHERE left_id = 20 or right_id = 20;
``` | Designing a Table to hold Friend Relationship | [
"",
"sql",
"database",
"database-design",
""
] |
Here is what I want. If I have 6 A's and 2 B's, how do I get all of the possible combinations?
EX:
`AAAAAABB, AAAAABAB, AAAABAAB, AAABAAAB, AABAAAAB, ABAAAAAB, BAAAAAAB, etc`
I am really looking to do this with 60 A's and 20 B's and then find the number of times that there is BB somewhere in the results. I would post... | Use `itertools.permutations`:
```
>>> from itertools import permutations
for p in permutations('AAAAAA'+'LL'):
print ("".join(p))
...
```
Use `sets` if you want unique items:
```
unique=set(i for i in permutations('AAAAAA'+'LL'))
```
To get the number of items that contain 'LL' anywhere use `sum` and a generat... | Rather than calculating permutations of `'A' * 60 + 'B' * 20` (which will return a lot of duplicates), you can represent the possible strings as combinations of 20 integers (representing the positions of the B's) taken from `range(80)`. These combinations can be calculated using [`itertools`](http://docs.python.org/2.7... | Permutations of a string with two distinct characters (60 of one value and 20 of another) | [
"",
"python",
""
] |
I am working on a project. I have been able to do everything asked for as far as total line count, separated and sorted, and total letter count. The issue I am having is listing the length of each individual word. Example: the: 3, it: 2, and etc... I am not trying to find how many times it appears in the text file.
``... | This should be what you're looking for:
```
string = open('file.txt').read()
for word in string.split():
print len(word)
``` | This assumes each line has numerous words, split by a space.
```
with open('words.txt') as my_file:
words = []
for line in my_file:
words.extend(line.split())
print {w: len(w) for w in words)}
```
Alternatively:
```
with open('words.txt') as my_file:
print {w: len(w) for w in words.split() for wo... | Python word length count from a text file | [
"",
"python",
""
] |
```
class Inventory(object):
def __init__(self):
self.inventory = {
'cash': 500,
'paycheck': 1,
'savings': 1000,
'current_car': 0,
'possible_cars': ['Chevy', 'Honda', 'BMW'],
'car_cost': [0, 100, 200],
'current_house': 0,
... | First, that isn't the error that your code produces. In your version you have `'status': status()` but on SO you wrote `'status': self.status()`. In any case, if you fix that you still have a problem,
```
AttributeError: 'Inventory' object has no attribute 'inventory'
```
The reason you get that error is because Pyth... | I got a different error, but I believe the solution would be the same:
```
class Inventory(object):
def __init__(self):
self.inventory = {
'cash': 500,
'paycheck': 1,
'savings': 1000,
'current_car': 0,
'possible_cars': ['Chevy', 'Honda', 'BMW'],
... | Using method as a dictionary value | [
"",
"python",
"python-2.7",
""
] |
How would I go about making a special singleton, like `None`? (I'm new to python.)
I want to be able to do this sort of thing:
```
def create_mutations(d):
return [
Mutation(c, v)
if v is not CellAction.Delete else
Mutation(c, isDelete=True)
for (c, v) in d
]
```
Used like... | You can just instantiate an `object` somewhere in your module or class like this:
```
Delete = object()
```
This is enough for most cases. | Simply make some object and give it a name. An empty class will do:
```
class Delete:
pass
```
Or, as Michael notes, an `object` instance.
Whatever object you use should be mutable if you plan to test for it using `is`; Python has a habit of sharing instances of immutable objects. (For example, all empty tuples ... | Special Singleton (like None) | [
"",
"python",
""
] |
I have a subquery in my SELECT statement that returns more than one row, but I need both values. Is there anyway to concatenate the multiple values with a comma to make the outside query think the subquery is only returning one value?
Example of my query:
```
select o.id,
(select v.value v from values v join attri... | Try with this query, maybe will be useful (click [here](http://sqlfiddle.com/#!4/54346/1) to test the query):
```
CREATE TABLE TEST1(
ID INT);
CREATE TABLE TEST2(
ID INT,
TXT VARCHAR2(100));
INSERT INTO TEST1 VALUES(1);
INSERT INTO TEST1 VALUES(2);
INSERT INTO TEST1 VALUES(3);
INSERT INTO TEST2 VALUES(1,'A'... | Just add the `GROUP BY a.att_id` or limit your query
```
select o.id,
(select v.value val from values v join attributes a on v.att_id=a.att_id
where a.att_id='100' and v.id=o.id GROUP BY a.att_id)
from objects o
where o.class_id='GGzX';
OR
select o.id,
(select v.value val from values v join attributes a on v... | Sub-Query Returns More than one row | [
"",
"sql",
"oracle",
""
] |
I am writing lines one by one to an external files. Each line has 9 columns separated by Tab delimiter. If i split each line in that file and output last column, i can see \n being appended to the end of the 9 column. My code is:
```
#!/usr/bin/python
with open("temp", "r") as f:
for lines in f:
hashes = ... | Because each line has 9 columns, the 8th index (which is the 9th object) has a line break, since the next line starts. Just take that away:
```
print hashes[8][:-1]
``` | Try using [strip](http://docs.python.org/2/library/stdtypes.html#str.strip) on the lines to remove the `\n` (the new line character). `strip` removes the leading and trailing whitespace characters.
```
with open("temp", "r") as f:
for lines in f.readlines():
if lines.strip():
hashes = lines.spl... | \n appending at the end of each line | [
"",
"python",
""
] |
This is not a technical question at all really. However, I can not locate my .HTML report that is supposed to be generated using:
> py.test --cov-report html pytest/01\_smoke.py
I thought for sure it would place it in the parent location, or the test script location. Does neither and I have not been able to locate. S... | I think you also need to specify the directory/file you want coverage for like `py.test --cov=MYPKG --cov-report=html` after which a `html/index.html` is generated. | if you do not specify --cov=/path/to/code then it will not generate the html at all.
```
$ py.test --cov-report html test_smoke.py
== test session starts ==
platform linux2 -- Python 2.7.12, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 rootdir: /home/someuser/somedir, inifile: plugins: xdist-1.22.0, forked-0.2, cov-2.5.1 col... | Py.Test : Reporting and HTML output | [
"",
"python",
"reporting",
"pytest",
""
] |
I am getting an error when trying to open Firefox using Selenium in ipython notebook. I've looked around and have found similar errors but nothing that exactly matches the error I'm getting. Anybody know what the problem might be and how I fix it? I'm using Firefox 22.
The code I typed in was as follows:
```
from sel... | Try specify your Firefox binary when initialize `Firefox()`
```
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
binary = FirefoxBinary('path/to/binary')
driver = webdriver.Firefox(firefox_binary=binary)
```
The default path FirefoxDriver looking for is at `%PROGRAMF... | Problem is ocuring because you don't have **geckodriver**
Solution:
1. Go to [this website](https://github.com/mozilla/geckodriver/releases "geckodriver official website") and download appropriate version for you machine, make sure that you have .exe file inside the archieve.
2. Then unpack and copy .exe file to your... | Python selenium error when trying to launch firefox | [
"",
"python",
"selenium",
"selenium-webdriver",
"web-scraping",
""
] |
EDIT: Here is a more complete set of code that shows exactly what's going on per the answer below.
```
libname output '/data/files/jeff'
%let DateStart = '01Jan2013'd;
%let DateEnd = '01Jun2013'd;
proc sql;
CREATE TABLE output.id AS (
SELECT DISTINCT id
FROM mydb.sale_volume AS sv
WHERE sv.category IN ('a', 'b',... | The most critical thing to understand when using SAS to access data in Teradata (or any other external database for that matter) is that the SAS software prepares SQL and submits it to the database. The idea is to try and relieve you (the user) from all the database specific details. SAS does this using a concept calle... | If ID is unique and a single value, then you can try constructing a format.
Create a dataset that looks like this:
`fmtname, start, label`
where fmtname is the same for all records, a legal format name (begins and ends with a letter, contains alphanumeric or \_); start is the ID value; and label is a 1. Then add one... | Writing Efficient Queries in SAS Using Proc sql with Teradata | [
"",
"sql",
"sas",
"teradata",
""
] |
I have a 2-D numpy array of shape `(256,128)` and I would like to average every 8 rows of the 256 together so I end up with a numpy array of shape `(32,128)` Is there any way to average just the one dimension? | You can `reshape` and then average over an axis:
```
averaged = a.reshape((32,8,128)).mean(axis=1)
```
The result is an (32,128) array. | Using the `axis` parameter of the `np.average`. If not provide, the average of the flatten array will be calculated.
```
In [19]: a
Out[19]:
array([[1, 2, 3],
[2, 3, 4]])
In [20]: np.average(a)
Out[20]: 2.5
In [22]: np.average(a, axis=1)
Out[22]: array([ 2., 3.])
In [23]: np.average(a, axis=0)
Out[23]: ar... | How to average over a 2-D array? | [
"",
"python",
"arrays",
"numpy",
"multidimensional-array",
"indexing",
""
] |
Hi guys I am new to python and would appreciate some help!
I have multiple strings like this:
```
21357.53 84898.10 Mckenzie Meadows Golf Course 80912.48 84102.38
```
And I am trying to figure out how to split the line based on a group of words (ie. `"Mckenzie Meadows Golf Course"`) with quotes around it and the dou... | This is the way I would do that:
```
import re
tgt='21357.53 84898.10 Mckenzie Meadows Golf Course 80912.48 84102.38'
nums=[m.group() for m in re.finditer(r'[\d\.]+',tgt)]
words=[m.group() for m in re.finditer(r'[a-zA-Z]+',tgt)]
print '"{}" {}'.format(' '.join(words),' '.join(nums))
```
Prints:
```
"Mckenzie Meado... | You can try this:
```
s = "21357.53 84898.10 Mckenzie Meadows Golf Course 80912.48 84102.38"
sList = s.split(' ')
words = []
nums = []
for l in sList:
if l.isalpha():
words.append(l)
elif l.isdigit():
nums.append(l)
wordString = "\"%s\"" % " ".join(words)
row = [wordString] + nums
```
At thi... | How do you split a string into quoted sentence and numbers using python | [
"",
"python",
"string",
"split",
""
] |
It is a basic question.
I have written the following code:
```
class Point:
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __str__(self):
return '({0} , {1})'.format(self.x,self.y)
def reflect_x(self):
return Point(self.x,-self.y)
p1=Point(3,4)
p2=p1.reflect_x
print... | > I just want p2 as a point which is the reflected point of p1 from x-axis. How can I do it?
Well, then you should call the method `reflect_x` on `p1` and store the result in `p2`, like this:
```
p2 = p1.reflect_x()
```
In your sample code, you did something different:
```
p2 = p1.reflect_x
```
which means you wan... | FYI:
If you want to access `reflect_x` as a member instead of as a method. add `@property` decorator to `reflex_x` method.
like:
```
class Point:
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __str__(self):
return '({0} , {1})'.format(self.x,self.y)
@property
def reflect... | Why did I get a wrong result from code like `instance.method`? | [
"",
"python",
"class",
"methods",
""
] |
I posses a class called `Collatz` and a function `collatz_it` which creates an object of the class, I'm trying to generate the number of steps for a number to reach 1 using the [collatz conjucture](https://en.wikipedia.org/wiki/Collatz_conjecture) and their corresponding steps till 1 million using a generator
```
impo... | The default representation of any Python container is to use the `repr()` output of the contents, not `str()`.
The solution would be for you to either give the `collatz.Collatz()` instance a `__repr__` method (you can monkey-patch that in), or to use a subclass of `dict` that uses `str()` instead of `repr()` when disp... | Store the value that you want on this line:
`values[count] = i`
Do something like
`values[count] = i.value`
or
`values[count] = str(i)`
In the last case this assumed that you have written a `__str__` method for the class:
```
class Collatz:
...
def __str__(self):
return str(self.value)
``` | Retrieving data from a class without the str method | [
"",
"python",
"python-2.7",
""
] |
Say I have the following HTML script:
```
<head>$name</head>
```
And I have the following shell script which replaces the variable in the HTML script with a name
```
#/bin/bash
report=$(cat ./a.html)
export name=$(echo aakash)
bash -c "echo \"$report\""
```
This works.
Now I have to implement the shell script in P... | ```
with open('a.html', 'r') as report:
data = report.read()
data = data.replace('$name', 'aakash')
with open('out.html', 'w') as newf:
newf.write(data)
``` | It looks like you're after a templating engine, but if you wanted a straight forward, no thrills, built into the standard library, here's an example using [string.Template](http://docs.python.org/2/library/string.html#string.Template):
```
from string import Template
with open('a.html') as fin:
template = Templat... | Conversion of shell script to python script | [
"",
"python",
"shell",
""
] |
One minor annoyance with `dict.setdefault` is that it always evaluates its second argument (when given, of course), even when the first argument is already a key in the dictionary.
For example:
```
import random
def noisy_default():
ret = random.randint(0, 10000000)
print 'noisy_default: returning %d' % ret
... | No, evaluation of arguments happens before the call. You can implement a `setdefault`-like function that takes a callable as its second argument and calls it only if it is needed. | This can be accomplished with `defaultdict`, too. It is instantiated with a callable which is then called when a nonexisting element is accessed.
```
from collections import defaultdict
d = defaultdict(noisy_default)
d[1] # noise
d[1] # no noise
```
The caveat with `defaultdict` is that the callable gets no argument... | How to implement a lazy setdefault? | [
"",
"python",
"lazy-evaluation",
""
] |
I'm calling a REST API with requests in python and so far have been successful when I set `verify=False`.
Now, I have to use client side cert that I need to import for authentication and I'm getting this error everytime I'm using the `cert (.pfx). cert.pfx` is password protected.
```
r = requests.post(url, params=pay... | I had this same problem. The `verify` parameter refers to the server's certificate. You want the `cert` parameter to specify your client certificate.
```
import requests
cert_file_path = "cert.pem"
key_file_path = "key.pem"
url = "https://example.com/resource"
params = {"param_1": "value_1", "param_2": "value_2"}
cer... | I had the same problem and to resolve this, I came to know that we have to send RootCA along with certificate and its key as shown below,
```
response = requests.post(url, data=your_data, cert=('path_client_certificate_file', 'path_certificate_key_file'), verify='path_rootCA')
``` | Python Requests - SSL error for client side cert | [
"",
"python",
"certificate",
"python-requests",
""
] |
When I delete a record in a table using SQL Server 2008 and its Management Studio, and then insert a new record, sequence of primary key column is not in order.
Suppose I delete Record5 with `record_id = 5`. Table is left with 4 records i.e., `Record1,Record2,Record3,Record4`.
Now when I insert a new record .. its `I... | This may sound unbelievable, but if you want an incrementing record number, SQL Server has no support for you. A transaction that is rolled back or a server restart can leave holes in the numbers.
For a strictly increasing order, you have to roll your own implementation. One common solution is to create a table with a... | There is no guarantee that the IDENTITY values will not have gaps. In fact is very likely to encounter such gaps. You must design your application in a way that accommodates and expects such gaps in identity values. To display a row number in a grid the best option, by far, is to use a local client-side (ASP.Net or eve... | Table ID (PrimaryKey) does not increment in a proper sequence when a new record is inserted | [
"",
"sql",
"sql-server-2008",
""
] |
I'm new to both R and mySQL and would like to run the following mysql command in R
```
query = "select x, y from table where z in ('a', 'b');"
sqlQuery(connection, query)
```
Suppose I have a very long vector of variable length. Is it possible to do
```
vector = c('a','b', .....)
query = "select x, y from table wher... | You need to use `shQuote`
```
query <- paste("select x, y from table where z in (", paste(shQuote(vector, type = "sh"),
collapse = ', '), ");")
query
[1] "select x, y from table where z in ( 'a', 'b', 'c', 'd' );"
``` | Put your vector in quotes before pasting it into your query.
```
vector <- paste0("'", vector, "'", collapse=", ")
query <- paste("select ....", vector, <etc>)
```
`shQuote` does this for you, but this is an abuse of its purpose. It's meant for quoting strings for the *OS shell*, and there's no guarantee that its de... | R vector into String of Strings | [
"",
"sql",
"r",
"paste",
""
] |
I have a table as follows:
```
DECLARE @tmp TABLE
(
userID int,
testID int,
someDate datetime
)
```
Within it I store dates along with two ID values, e.g.
```
INSERT INTO @tmp (userID, testID, someDate) VALUES (1, 50, '2010-10-01')
INSERT INTO @tmp (userID, testID, someDate) VALUES (1, 50, '2010-... | ```
SELECT userID, testID, MAX(someDate)
FROM @tmp
GROUP BY testId,userID;
```
[fiddle](http://www.sqlfiddle.com/#!6/d41d8/5209) | Try
```
SELECT t1.* FROM @tmp t1
INNER JOIN (SELECT userId, MAX(someDate) someDate
FROM @tmp
GROUP BY userId) t2
ON t1.userId = t2.userId
AND t1.someDate = t2.someDate
``` | Select top dates grouped by ID's | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
I was wondering if it was possible to do the following. I have a database of first and last names, I'd like to query it so that the results are firstname.lastname or in the case of firstname.lastname already being returned, it should be firstname.lastname1 (or 2 if firstname.lastname1 was already returned, etc). So que... | ```
SELECT
FirstName + '.' + LastName
+ IsNull(cast(NullIf(ROW_NUMBER() OVER(PARTITION BY FirstName + '.' + LastName ORDER BY ID) - 1, 0) as varchar(10)), '')
FROM
TableName
``` | Like this
```
SELECT FirstName + '.' + LastName +
CAST(ROW_NUMBER() OVER(PARTITION BY FirstName, LastName ORDER BY ID) As Varchar(9))
FROM YourTable
``` | Auto Increment Value on SQL SELECT when duplicate | [
"",
"sql",
"sql-server",
"select",
""
] |
While browsing codegolf, I found [this](https://codegolf.stackexchange.com/a/12007/8558) :
```
g=input();print("Approved","Summer School","Failed")[(g<7)+(g<3)]
```
I don't understand what the [] means after print()... Any clarification ? | ```
>>> print("Approved","Summer School","Failed")[0]
Approved
>>> print("Approved","Summer School","Failed")[1]
Summer School
>>> print("Approved","Summer School","Failed")[2]
Failed
```
See the pattern? It's just simple indexing.
By the way we always know `(g<7)+(g<3)` will be `>= 0` (`False + False`) and `<= 2` (`... | It's just tuple indexing. No different from this:
```
x = (1, 2, 3)[1]
```
which assigns `2` to `x`.
In your more complex variant, an element of the tuple is selected and then passed to `print`.
The confusion is that the code makes it look like you are calling a function named `print`. This confusion was removed in... | What is the meaning of print()[] in Python? | [
"",
"python",
"python-2.7",
""
] |
```
def manualReverse(list):
return list[::-1]
def reverse(list):
return list(reversed(list))
list = [2,3,5,7,9]
print manualReverse(list)
print reverse(list)
```
I just started learning `Python`. Can anyone help me with the below questions?
1.How come `list[::-1]` returns the `reversed` list?
... | `[::-1]` is equivalent to `[::1]`, but instead of going left to right, the negative makes it go right to left. With a negative step of one, this simply returns all the elements in the opposite order. The whole syntax is called the [Python Slice Notation](https://stackoverflow.com/questions/509211/the-python-slice-notat... | `list[::-1]` utilizes a slice notation and returns all the elements but in reversed order.
[Explain Python's slice notation](https://stackoverflow.com/questions/509211/the-python-slice-notation)
Here is a detailed explanation with examples - it will answer this and more similar questions.
Indentation of `def reverse(l... | Reversing a list in Python | [
"",
"python",
"list",
"reverse",
""
] |
I am querying a table (my table has NULL values) using this sql code:
```
SELECT x.f1,Count(x.f1) FROM
(SELECT p1 As F1 FROM table
UNION ALL
SELECT p2 As F1 FROM table
UNION ALL
SELECT p3 As F1 FROM table) x
GROUP BY x.f1
```
This code achieves the question this user asked:
[SQL, count in multiple columns then gr... | First there really is no reason to think that the two queries would return similar results. The one with the `where` clause is counting rows, regardless of the number of matches. The one with `union all` could count each row up to three times, depending on the values in `p1`, `p2`, and `p3`.
To count rows with the `un... | `col1 or col2 or col3, etc = 'entry name'` is not the right syntax. It just checks if `col1` and `col2` have any value. Only the last one in the list is checked against the actual value `'entry name'`. | Why is my SQL Union Query Returning Different Values than my manual SELECT WHERE query? | [
"",
"sql",
"database",
"t-sql",
"sql-server-2012",
""
] |
In test.txt:
```
1 a
2 b
3 c
4 a
5 d
6 c
```
I want to remove duplicate and save the rest in test2.txt:
```
2 b
5 d
```
I tried to start with the codes below.
```
file1 = open('../test.txt').read().split('\n')
#file2 = open('../test2.txt', "w")
word = set()
for line in file1:
if line:
s... | You can use `collections.Orderedict` here:
```
>>> from collections import OrderedDict
with open('abc') as f:
dic = OrderedDict()
for line in f:
v,k = line.split()
dic.setdefault(k,[]).append(v)
```
Now `dic` looks like:
```
OrderedDict([('a', ['1', '4']), ('b', ['2']), ('c', ['3', '6']), ('d... | I tried to keep it as similar to your stlye as possible:
```
file1 = open('../test.txt').read().split('\n')
word = set()
test = []
duplicate = []
sin_duple = []
num_lines = 0;
num_duplicates = 0;
for line in file1:
if line:
sline = line.split(' ')
test.append(" ".join([sline[0], sline[1]]))
... | Delete and save duplicate in another file | [
"",
"python",
""
] |
I have a question
If I have one row that looks like this
```
|ordernumber|qty|articlenumber|
| 123125213| 3 |fffff111 |
```
How can I split this into three rows like this:
```
|ordernumber|qty|articlenumber|
| 123125213| 1 |fffff111 |
| 123125213| 1 |fffff111 |
| 123125213| 1 |fffff111 |
```
/J | You can use recursive CTE:
```
WITH RCTE AS
(
SELECT
ordernumber, qty, articlenumber, qty AS L
FROM Table1
UNION ALL
SELECT
ordernumber, 1, articlenumber, L - 1 AS L
FROM RCTE
WHERE L>0
)
SELECT ordernumber,qty, articlenumber
FROM RCTE WHERE qty = 1
```
**[SQLFiddle... | Here's a quick hack using an additional table populated with a number of rows suitable for the `qty` values you are expecting:
```
-- helper table
CREATE TABLE qty_splitter (qty int)
INSERT INTO qty_splitter VALUES (1)
INSERT INTO qty_splitter VALUES (2)
INSERT INTO qty_splitter VALUES (3)
INSERT INTO qty_splitter VA... | Split a row on 2 or more rows depending on a column | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I have a string which looks like this when I print it:
```
RT @HHRoadGuy: It's that time again! Time to tune in for the latest #fortheloveofmusic episode. Catch it now on @CMT!
http://t.co/VatlhGq9…
```
I tried to get rid of the linespacing with:
```
tweet = tweet.rstrip('\r\n')
```
But it does not work. Probabl... | ```
tweet = tweet.replace('\n','')
```
Is the answer. I just had a tiny error in my code and after trying all these different methods and things I got blind. Sorry! | Are you sure that the line delimeters are indeed '\r\n' and not just '\n'?
Because `replace()` should work just fine:
```
>>> s = 'hello\r\n\r\nhi'
>>> print(s)
hello
hi
>>> s2 = s.replace('\r\n\r\n', '\r\n')
>>> print(s2)
hello
hi
```
Indeed, the `rstrip()` will not work, since that function only strips on the righ... | Delete linespacing in multiline string Python | [
"",
"python",
"formatting",
"line-breaks",
""
] |
Trying to find a good way to set a maximum time limit for command execution latency in Selenium Python WebDriver. Ideally, something like:
```
my_driver = get_my_driver()
my_driver.set_timeout(30) # seconds
my_driver.get('http://www.example.com') # stops / throws exception when time is over 30 seconds
```
would w... | In python, the method to create a timeout for a page to load is:
**Firefox, Chromedriver and undetected\_chromedriver**:
```
driver.set_page_load_timeout(30)
```
**Other**:
```
driver.implicitly_wait(30)
```
This will throw a `TimeoutException` whenever the page load takes more than 30 seconds. | The best way is to set preference:
```
fp = webdriver.FirefoxProfile()
fp.set_preference("http.response.timeout", 5)
fp.set_preference("dom.max_script_run_time", 5)
driver = webdriver.Firefox(firefox_profile=fp)
driver.get("http://www.google.com/")
``` | How to set Selenium Python WebDriver default timeout? | [
"",
"python",
"firefox",
"selenium",
"timeout",
"selenium-webdriver",
""
] |
I have an app that will show images from reddit. Some images come like this <https://i.stack.imgur.com/LKuXA.jpg>, when I need to make them look like this <https://i.stack.imgur.com/yfiH1.jpg>. Just add an (i) at the beginning and (.jpg) at the end. | This function should do what you need. I expanded on @jh314's response and made the code a little less compact and checked that the url *started* with `http://imgur.com` as that code would cause issues with other URLs, like the google search I included. It also only replaces the first instance, which could causes issue... | You can use a string replace:
```
s = "http://imgur.com/Cuv9oau"
s = s.replace("//imgur", "//i.imgur")+(".jpg" if not s.endswith(".jpg") else "")
```
This sets s to:
```
'http://i.imgur.com/Cuv9oau.jpg'
``` | how do I modify a url that I pick at random in python | [
"",
"python",
"flask",
""
] |
Lets say I have a table that has the following columns:
customerId, productId
What I want to see is if I have 100,000 customers I want to group them so I can see X number of customers have Y number of products. For example 2,000 customers may have 5 purchases, 1,000 customers have 4 products, 10 customers might have ... | ```
SELECT
COUNT(CustomerID) AS number_customers,
number_products
FROM (
SELECT CustomerID,
COUNT(ProductID) AS number_products
FROM tableName
GROUP BY customerID
) subquery
GROUP BY number_products
``` | ```
Select CustomerID, count(ProductID)
FROM tableName
group by customerID
having count(ProductID) > 25
```
now if you want to only count distinct products...
```
Select CustomerID, count(distinct ProductID)
FROM tableName
group by customerID
having count(ProductID) > 25
```
Assuming your data contain... | SQL - Group By Query | [
"",
"sql",
"oracle",
"group-by",
""
] |
I'm really new to coding, programming, Python, and just computers in general, so I need some help with Canopy. I've been having pretty consistent troubles installing any packages to Canopy; some stuff is in the internal package manager,but whenever it isn't, it's really confusing. I guess I'll list a specific installat... | The way I installed `astropy` is as follows.
1. Open Windows Terminal
2. Change Directory to `C:\Users\<USER NAME>\AppData\Local\Enthought\Canopy32\User\Scripts`
3. Type `easy_install.exe astropy`
4. Wait until the download completes, and restart Enthought.
 | sometimes installing packages can be hard for enthought canopy . You could install all python packages using `pip install mrjob` command on the its own **canopy command prompt**
1. Go to tools tab on the canopy editor ,
2. Left click on the canopy command prompt ,
3. Finally `pip install <package name>` and hit Enter ... | Installing a package to Canopy | [
"",
"python",
"installation",
"package",
"enthought",
"canopy",
""
] |
I have a program that queries an API every few seconds. Each response triggers a few functions which themselves make some calls to websites and such -- calls that I don't want to blindly trust to succeed. If I catch an exception in `foo()`, for example, or even in a function that `foo()` calls, is it possible to restar... | To restart anything, just use a `while` loop *outside* the `try`. For example:
```
def foo():
while True:
try:
foo2()
except:
pass
else:
break
```
---
And if you want to pass the exception up the chain, just do this in the outer function instead of the ... | Refactor this - you'll get a stackoverflow error sooner or later if you have enough failures.
`queryRepeatedly` should just be `query`. It should return `void` and throw exceptions on failures.
Wrap in something that looks like this, your true `queryRepeatedly` function?
```
while True:
try:
query()
... | Restarting a program after exception | [
"",
"python",
"function",
""
] |
I'm working on a small project where I need to control a console player via python. This example command works perfectly on the Linux terminal:
```
mplayer -loop 0 -playlist <(find "/mnt/music/soundtrack" -type f | egrep -i '(\.mp3|\.wav|\.flac|\.ogg|\.avi|\.flv|\.mpeg|\.mpg)'| sort)
```
In Python I'm doing the follo... | Your default user shell is probably `bash`. Python's `os.system` command calls `sh` by default in linux.
A workaround is to use `subprocess.check_call()` and pass [`shell=True`](http://docs.python.org/2/library/subprocess.html#frequently-used-arguments) as an argument to tell `subprocess` to execute using your default... | Your python call 'os.system' is probably just using a different shell than the one you're using on the terminal:
**[os.system() execute command under which linux shell?](https://stackoverflow.com/questions/905221/os-system-execute-command-under-which-linux-shell)**
The shell you've spawned with os.system may not suppo... | Problems running terminal command via Python | [
"",
"python",
"linux",
"bash",
""
] |
I have the following procedure:
```
def myProc(invIndex, keyWord):
D={}
for i in range(len(keyWord)):
if keyWord[i] in invIndex.keys():
D.update(invIndex[query[i]])
return D
```
But I am getting the following error:
```
Traceback (most recent call last):
File "<stdin>", line... | `D = {}` is a dictionary not set.
```
>>> d = {}
>>> type(d)
<type 'dict'>
```
Use `D = set()`:
```
>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])
``` | ```
>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>
```
What you've made is a dictionary and not a Set.
The `update` method in dictionary is used to update the new dictionary from a previous one, like so,
```
>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}
```
Whereas in sets, it is used... | How can I add items to an empty set in python | [
"",
"python",
"set",
""
] |
I would like to be able to do greater than and less than against dates. How would I go about doing that? For example:
```
date1 = "20/06/2013"
date2 = "25/06/2013"
date3 = "01/07/2013"
date4 = "07/07/2013"
datelist = [date1, date2, date3]
for j in datelist:
if j <= date4:
print j
```
If I run the ab... | You can use the [`datetime`](http://docs.python.org/2/library/datetime.html) module to convert them all to datetime objects. You are comparing strings in your example:
```
>>> from datetime import datetime
>>> date1 = datetime.strptime(date1, "%d/%m/%Y")
>>> date2 = datetime.strptime(date2, "%d/%m/%Y")
>>> date3 = dat... | You are comparing strings, not dates. You should use a date-based object-type, such as [datetime](http://docs.python.org/2/library/datetime.html).
[How to compare two dates?](https://stackoverflow.com/questions/8142364/how-to-compare-two-dates) | greater than 'date' python 3 | [
"",
"python",
"python-3.x",
""
] |
I have created a script in Python which notifies me at a given event.
I am using the following function to produce the warning window:
```
def window_warn():
'''
This function will throw up a window with some text
'''
#These two lines get rid of tk root window
root = Tkinter.Tk()
root.withdraw(... | Try calling `root.update()` before returning from the function. That will process all pending Tk/X window events.
(ideally, you'd establish a main event loop before displaying the window, but that assumes that your entire program is event driven, which may not always work.) | You have to call `root.mainloop()` to enable the program to respond to events. | Tkinter TkMessageBox not closing after click OK | [
"",
"python",
"python-2.7",
"tkinter",
"xfce",
""
] |
I'm currently trying to make a GET request to YouTube, to search for a video on it (using Python, as well as the *Requests* module). The following is what I'm doing to make a request:
```
r = requests.get("http://www.youtube.com/",
params={
"search_query": "Test"
}).text
```
However, when... | Looking at youtube, the url to the search page seems to be
```
http://www.youtube.com/results?search_query=test
```
You're missing the `results` part, which is the page you are looking for. | Use the Youtube API to get the data.
```
# Import the modules
import requests
import json
# Make it a bit prettier..
print "-" * 30
print "This will show the Most Popular Videos on YouTube"
print "-" * 30
# Get the feed
r = requests.get("http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?v=2&alt=jsonc")
r.te... | How to send parameters with a GET request? | [
"",
"python",
"get",
"request",
""
] |
I'm operating on an *SQLite3* database in my android app. I just read from the pre populated database that has 200k rows and 14 columns. Entries are words. Datatype of all columns is text. Querying for words up to 11 letters (eg. ABANDONMENT) works fine. But for 12 or greater (eg. ABANDONMENTS), the app crashes. Here i... | I was quering in a loop. And closing the cursor inside the loop and not outside solved the problem. | Error -12 means cursor leak.
Try to close it:
```
try {....} finally { cursor.close();}
``` | Could not allocate CursorWindow | [
"",
"android",
"sql",
"database",
"sqlite",
"android-cursor",
""
] |
I have an auto-increment transactionID `type=MEDIUMINT(9)` in my table. I want to also display a unique 4-character (which can grow over time, but 4 for now) alphabetical Redemption Code to my users. What is the best way to derive this alphabetical code from my transactionID, preferably straight from the `SELECT statem... | That mostly depends on what alphabet you want to use.
You may use [TO\_BASE64](http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_to-base64) to convert it it to base64 encoded string or simply do something like:
```
select REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
REP... | I was just looking for something like this and I found a way to do it with the [CONV](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_conv) function.
```
CONV(9+your_number, 10, 36)
```
This converts 1 to A, 2 to B etc.
The way it works is by adding 9 and then converting to base 36, in w... | MySQL Convert Numbers to letters | [
"",
"mysql",
"sql",
""
] |
I have a text file where each line has a bunch of text. (in the actual file there are no line numbers) like this:
```
line#: text:
0 This is some text
1 More text
2 whats for lunch
```
I want a function that returns a dictionary mapping each word to its line number occurrence essentiall... | You can get the line numbers using `enumerate` when you scan the file initially, and add line numbers to the dict of `set`s as you go.
myfile.txt:
```
a b c
b x y
a c b
```
index it:
```
index = {}
with open('myfile.txt') as F:
for line_num, line in enumerate(F):
for word in line.split():
in... | The line responsible for the slowdown is this one:
```
l = {a for a, b in enumerate(wordLoc) if w in b}
```
Every time you find a word you haven't seen yet, you re-enumerate every single line and see if contains the word. This is going to contribute O(NumberOfUniqueWords \* NumberOfLines) operations overall, which is... | my inverse index is very slow any suggestions? | [
"",
"python",
"algorithm",
""
] |
Suppose I have a table `STUDENT` with columns including `ID`, `name`, `email`, and `advisorID`. And I have a second table `ADVISOR` with fields including `ID` and `name`. `STUDENT.AdvisorID` is a foreign key. When inserting a student, you must have a key pointing toward an `ADVISOR`.
When inserting a student from the ... | One possible way:
```
insert into student (name, email, advisorID)
values (
'Fred Smith',
'fred@example.com',
(select id from advisor where name = 'Lord Voldemort'))
``` | First of all, you don't have to use `INSERT INTO SELECT` to do that. You can simply insert `Advison` first, check the `ID` that was assigned and then use it while inserting `Student` entity.
If you'd like to use `INSERT INTO SELECT` anyway, you can do it like that:
```
INSERT INTO Student (name, email, advisorID)
SEL... | How does INSERT INTO ... SELECT ... FROM ... WHERE work? | [
"",
"mysql",
"sql",
"database",
"sqlite",
""
] |
I need a small help with a SQL query.
I have two tables: `tbltrans` and `tbltrans_temp`. I want to select the maximum of tbltrans\_temp `max(tbltrans_temp.transid)`.
If `tbltrans_temp` is empty and it returns null, it should then take the max of `tbltrans.transid`.
If both tables are empty, it should just return 0.
... | This works using `COALESCE`:
```
select coalesce(maxtemptrans, maxtrans, 0)
from (select max(transid) maxtemptrans from tbltrans_temp) t,
(select max(transid) maxtrans from tbltrans ) t2
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!3/89841/1) | Try:
```
select coalesce((select max(transid) from tbltrans_temp),
(select max(transid) from tbltrans),
0)
``` | Simple SQL query to select a max | [
"",
"sql",
"sql-server",
"sqlite",
"join",
""
] |
I need to compare values from different rows. Each row is a dictionary, and I need to compare the values in adjacent rows for the key 'flag'. How would I do this? Simply saying:
```
for row in range(1,len(myjson))::
if row['flag'] == (row-1)['flag']:
print yes
```
returns a TypeError: `'int' object... | Your exception indicates that `list_of_rows` is not what you think it is.
To look at other, adjacent rows, provided `list_of_rows` is indeed a list, I'd use `enumerate()` to include the current index and then use that index to load next and previous rows:
```
for i, row in enumerate(list_of_rows):
previous = list... | For comparing adjacent items you can use `zip`:
**Example:**
```
>>> lis = [1,1,2,3,4,4,5,6,7,7]
for x,y in zip(lis, lis[1:]):
if x == y :
print x,y,'are equal'
...
1 1 are equal
4 4 are equal
7 7 are equal
```
For your list of dictionaries, you can do something like :
```
from itertools impor... | Removing duplicate entries? | [
"",
"python",
""
] |
I want to read messages from either a Queue.Queue or a TCP socket, whichever comes first.
How can it be achieved without resorting to 2 threads ?
Platform is CPython 2.7.5 on Windows | To do it in a single thread, you'll have to use non-blocking methods, and merge them into a single event loop. I'm actually using `select` instead of non-blocking socket I/O here, since it's slightly cleaner if you need to read from multiple sockets...
```
import socket
import select
import Queue
import time
TIMEOUT ... | There is a very nice trick to do this [here](http://chimera.labs.oreilly.com/books/1230000000393/ch12.html#_solution_209) that applies to your problem.
```
import queue
import socket
import os
class PollableQueue(queue.Queue):
def __init__(self):
super().__init__()
# Create a pair of connected soc... | Python - How to wait on both queue and a socket on same time | [
"",
"python",
""
] |
i am using "add" and "set" to enter list as value to a dictionary key. The thing is, my dictionary key is a string. So, i cannot have list as value using "append". Hence, i used "add" and "set" to append to the values. But they will not allow duplicates in the list. How can i change my code to allow duplicates? My part... | > my dictionary key is a string. So, i cannot have list as value using
> "append"
That is not so. You can have strings as keys and lists as values:
```
myDict = {}
myDict.setdefault(myKey, []).append(value)
```
The second argument in `myDict.setdefault(myKey, [])` is a default value. If `myKey` is not in `myDict`, t... | You can't store duplicate values in a `set`. That's kind of the whole point.
You also seem to be expecting the `set` to preserve order. It doesn't do that. It may seem to for small cases, but if you write code that depends on it, it will break.
So, what's a type that's kind of like `set`, but allows duplicate values ... | How can duplicate values be allowed in dictionary when using set | [
"",
"python",
""
] |
So I'm trying to write a query to pull some data and I have one condition that needs to be met and I can't seem to figure out how to actually execute it. What I'm trying to achieve is that if a column is not null in one table, then I want to check another table and see if there is a specific value in one those columns.... | At first I thought you wanted the `CASE` statement from the wording of your question, but I think you're just looking for an `OUTER JOIN` with an `OR` statement:
```
SELECT DISTINCT a.id, a.user_name, a.created_date, a.transaction_number
FROM TableA A
LEFT JOIN TableB B ON A.response_id = B.Id
WHERE A.response_id ... | where TableA.Response\_id is null or (select count(1) from TableB WHERE (type\_id NOT IN ('4)) AND (id = TableA.response\_id)) = 0
provided that your subquery is logically correct. | SQL Where Condition with IF Statement | [
"",
"sql",
"if-statement",
"where-clause",
""
] |
I had a code below in Python 3.2 and I wanted to run it in Python 2.7. I did convert it (have put the code of `missing_elements` in both versions) but I am not sure if that is the most efficient way to do it. Basically what happens if there are two `yield from` calls like below in upper half and lower half in `missing_... | If you don't use the results of your yields,\* you can *always* turn this:
```
yield from foo
```
… into this:
```
for bar in foo:
yield bar
```
There might be a performance cost,\*\* but there is never a semantic difference.
---
> Are the entries from the two halves (upper and lower) appended to each other i... | Replace them with for-loops:
```
yield from range(L[start] + 1, L[end])
==>
for i in range(L[start] + 1, L[end]):
yield i
```
The same about elements:
```
yield from missing_elements(L, index, end)
==>
for el in missing_elements(L, index, end):
yield el
``` | Converting "yield from" statement to Python 2.7 code | [
"",
"python",
"generator",
"python-2.x",
"yield",
"yield-from",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.