Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a variable call hex\_string. The value could be '01234567'. Now I would like to get a hex value from this variable which is 0x01234567 instead of string type. The value of this variable may change. So I need a generic conversion method. | I think you might be mixing up numbers and their representations. `0x01234567` and `19088743` are the exact same thing. `"0x01234567"` and `"19088743"` are not (note the quotes).
To go from a string of hexadecimal characters, to an integer, use [`int(value, 16)`](http://docs.python.org/2/library/functions.html#int).
... | ```
>>> int('01234567', 16)
19088743
```
This is the same as:
```
>>> 0x01234567
19088743
``` | Hex string variable to hex value conversion in python | [
"",
"python",
"string",
"hex",
""
] |
Two tables, brand\_gifts bg, giftcode gc:
**Table 1: brand\_gifts**
```
id brand_id name
```
**Table 2: giftcode**
```
id gift_id code usesleft
```
The value I use to retrieve my data is the brand\_id from brand\_gifts table. What I need is a list of elements that on table one brand\_id = 1, the two tables are rel... | ```
SELECT gc.gift_id
FROM brand_gifts bg, giftcode gc
WHERE (
bg.brand_id =1
AND gc.gift_id = gc.id <==
AND gc.usesleft >0
)
LIMIT 0 , 30
```
your error looks in the marked line, the condition should be "gc.gift\_id = bg.id"
```
SELECT gc.gift_id
FROM brand_gifts bg, giftcode gc... | try this
```
SELECT gc.gift_id
FROM brand_gifts bg, giftcode gc
WHERE (
bg.brand_id =1
AND gc.gift_id = bg.id
AND gc.usesleft >0
)
LIMIT 0 , 30
``` | JOIN issues on mySql | [
"",
"mysql",
"sql",
""
] |
I'm packaging some python packages using a well known third party packaging system, and I'm encountering an issue with the way entry points are created.
When I install an entry point on my machine, the entry point will contain a shebang pointed at whatever python interpreter, like so:
in **/home/me/development/test/s... | You can customize the console\_scripts' shebang line by setting 'sys.executable' (learned this from a [debian bug report](http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=548392)). That is to say...
```
sys.executable = '/bin/custom_python'
setup(
entry_points={
'console_scripts': [
... etc...
]
}
... | For future reference for someone who wants to do this at runtime without modifying the `setup.py`, it's possible to pass the interpreter path to `setup.py build` via `pip` with:
```
$ ./venv/bin/pip install --global-option=build \
--global-option='--executable=/bin/custom_python' .
...
$ head -1 ./venv/bin/some-entry-... | Changing console_script entry point interpreter for packaging | [
"",
"python",
"setuptools",
"distutils",
""
] |
I have two list as below:
```
latt=[42.0,41.978567980875397,41.96622693388357,41.963791391892457,...,41.972407378075879]
lont=[-66.706920989908909,-66.703116557977069,-66.707351643324543,...-66.718218142021925]
```
now I want to plot this as a line, separate each 10 of those 'latt' and 'lont' records as a period and ... | There are several different ways to do this. The "best" approach will depend mostly on how many line segments you want to plot.
If you're just going to be plotting a handful (e.g. 10) line segments, then just do something like:
```
import numpy as np
import matplotlib.pyplot as plt
def uniqueish_color():
"""Ther... | Copied from [this example](http://matplotlib.org/examples/pylab_examples/multicolored_line.html):
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
x = np.linspace(0, 3 * np.pi, 500)
y = np.sin(x)
z = np.... | How to plot one line in different colors | [
"",
"python",
"matplotlib",
""
] |
If i have this dictionary:
`a = {'alpha':12,'beta':13,'gamma':14}`
and this one:
`b = {'andora':19,'beta:14','gamma':19}`
and this one:
`c = {'beta':11,'gamma':20}`
how do i intersect the keys such that the resultant dictionary would have values as the average of the values in the given dictionaries.
for example... | ```
def intersect(dicts):
common_keys = reduce(set.intersection, map(set, dicts))
num = float(len(dicts))
return {k: sum(d[k] for d in dicts)/num for k in common_keys}
```
Example:
```
>>> a = {'alpha':12,'beta':13,'gamma':14}
>>> b = {'andora':19,'beta':14,'gamma':19}
>>> c = {'beta':11,'gamma':20}
>>> i... | Use a dict comprehension:
```
>>> keys = a.viewkeys() & b.viewkeys() & c.viewkeys()
>>> keys
set(['beta', 'gamma'])
>>> {k: (a[k]+b[k]+c[k])/3.0 for k in keys}
{'beta': 12.666666666666666, 'gamma': 17.666666666666668}
```
Function:
```
>>> def get_keys(*args):
... return reduce(set.intersection,map(set,args))
.... | Intersect dictionaries with keys averaged | [
"",
"python",
"dictionary",
"intersect",
""
] |
I am attempting to use BeautifulSoup to parse an html table which I uploaded to <http://pastie.org/8070879> in order to get the three columns (0 to 735, 0.50 to 1.0 and 0.5 to 0.0) as lists. To explain why, I will want the integers 0-735 to be keys and the decimal numbers to be values.
From reading many of the other p... | HTML parsers like BeautifulSoup presume that what you want is an object model that mirrors the input HTML structure. But sometimes (like in this case) that model gets in the way more than helps. Pyparsing includes some HTML parsing features that are more robust than just using raw regexes, but otherwise work in similar... | I think the above answer is better than what I would offer, but I have a BeautifulSoup answer that can get you started. This is a bit hackish, but I figured I would offer it nevertheless.
With BeautifulSoup, you can find all the tags with certain attributes in the following way (assuming you have a soup.object already... | Parse HTML Table with Python BeautifulSoup | [
"",
"python",
"html",
"beautifulsoup",
""
] |
I was doing [this practice problem](http://www.codechef.com/problems/SUMTRIAN) on codechef. I have already [solved this in C](http://www.codechef.com/status/SUMTRIAN,anshbansal) and was trying to do the same in Python 2.7. I am getting NZEC error on codechef judge which is "Non Zero Exit Code". I don't understand why t... | Don't mix using the file object as an iterator, and calling `.readline()` on the object.
By using `islice()` on `sys.stdin` you are treating the object as an iterator, calling `file.next()` under the hood. From the [`.next()` documentation](http://docs.python.org/2/library/stdtypes.html#file.next):
> In order to make... | change this line:
```
triangle = [map(int, i.split()) for i in islice(sys.stdin,height)]
```
to this:
```
triangle = [map(int, sys.stdin.readline().split()) for _ in xrange(height)]
```
From the [docs](http://docs.python.org/2/library/stdtypes.html#file.next):
> As a consequence of using a read-ahead buffer, combi... | What causes the NZEC (Non Zero Exit Code) error in my Sums in a Triangle solution? | [
"",
"python",
"python-2.7",
""
] |
I have a database table in sql server 2008. My query is breaking for a reason that is unknown to me:
```
select release_id, url_id,tt_projectid, release_title, tech_area, current_state, dateadd(ss,last_built,'12/31/1969 20:00:00') as recent_Date,
autobuild_count, manualbuild_count, bcm_build_count, config_... | The reason is because `last_auto_integ` is being stored as a string rather than as a date. These lines in the `where` clause are not being executed with the `and` -- by happenstance -- because none occur when `release_id > 360000`.
From what I can see, there are no other places in the query where you might be converti... | Because when you change `AND` to `OR` you are getting a lot more rows returned, and one of these other expressions is failing:
```
dateadd(ss,integ_complete_date,'12/31/1969 20:00:00')
MONTH(last_auto_integ)
YEAR(last_auto_integ)
``` | sql - conversion error when changing 'and' to 'or' | [
"",
"sql",
"sql-server-2008",
""
] |
I've been getting the most weird error ever. I have a Person model
```
class Person(models.Model):
user = models.OneToOneField(User, primary_key=True)
facebook_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
twitter_id = models.CharField(max_length=225, unique=True, null=True, bla... | Since you have `null=True, blank=True` and `unique=True`, django is considering `None` or blank as a unique entry. Remove the unique constraint and handle the uniqueness part in the code. | None of the answers clearly describe the root of the problem.
Normally in the *db* you can make a field `null=True, unique=True` and it will work... because `NULL != NULL`. So each blank value is still considered unique.
But unfortunately for `CharField`s Django will save an empty string `""` (because when you submit... | Django unique, null and blank CharField giving 'already exists' error on Admin page | [
"",
"python",
"django",
"django-admin",
"django-models",
""
] |
I wrote some code that can search through a large csv file and, based on the search parameters, find a computer name.
Now, I would like to pass this string(computer name) along as a command-line parameter and automatically run RealVNC (located in `C:\Program Files\RealVNC\VNC4\vncviewer.exe`) with it. So, after the co... | You can use a subprocess like this:
```
from subprocess import call
call(["appname", "arguments"])
```
In case you don't have it, here's a [manual page](http://www.realvnc.com/products/open/4.1/man/vncviewer.html) for the command line arguments and their options. | Have a look at the [subprocess](http://docs.python.org/2/library/subprocess.html) module (and more specifically `call` or `Popen`) | Pass a string to the command line | [
"",
"python",
"command-line",
""
] |
I have stored procedure like this:
```
alter procedure [dbo].[delivary] @dedate nvarchar(100),
@carid nvarchar(100),
@transid integer as
begin
select t.transactID
from Transaction_tbl t
where t.TBarcode = @carid
update Transaction... | It should be
```
alter procedure [dbo].[delivary]
(@dedate nvarchar(100),
@carid nvarchar(100))
AS
begin
DECLARE @transactID int;
SET @transactID = (select t.transactID
from Transaction_tbl t
where t.TBarcode = @carid);
update Transaction_tbl
... | There is 2 ways you can do it :
First Retrieving and storing your transactID in a variable :
```
alter procedure [dbo].[delivary] @dedate nvarchar(100),
@carid nvarchar(100)as
begin
declare @transid int
select @transid = t.transactID
from Transaction_tbl t
where ... | stored procedure updating two tables with different id | [
"",
"sql",
"sql-server",
""
] |
Having two simple classes; one with only `parent` attribute, and one with both `parent` and `children` attributes.
This means that the one with both `parent` and `children` inherits from the one with only `parent`.
Here's the class with only `parent` attribute.
Let's call it `Child` since it can only be a child, not a... | What you're doing is nonsense.
Just make them one class and use *either* `add_child()` and `remove_child()` *or* `set_parent()`, but not both. | This problem, which is called a "Two-Way Association", is described in book "Refactorization: Improving the Design of Existing Code" by Martin Fowler, Kent Beck, and few more authors. The way the problem is solved in the book is by assigning one of the classes a complete control over another class. First, you need to d... | How to link parent and children to each other? | [
"",
"python",
"parent-child",
"parent",
"children",
""
] |
I'm a self-learning and newbie in SQLite. I have three tables (person, pet, person\_pet) and the .schema is:
```
CREATE TABLE person (
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
age INTEGER,
dead INTEGER,
phone_number INTEGER,
salary FLOAT,
dob DATETIME
);
CREATE TABLE person_pet (
person_id INTEGER... | You don't need a sub-query. You need joins:
```
SELECT p.id, p.first_name, p.last_name, p2.id as pet_id, p2.name as pet_name
FROM person as p
INNER JOIN person_pet as pp on pp.person_id = p.id
INNER JOIN pet as p2 on p2.id = pp.pet_id
WHERE
p2.purchased_on > '2004/01/01 0:0:0 AM'
``` | ```
SELECT a.id, a.first_name, a.last_name, c.id pet_id, c.name pet_name
FROM person a, person_pet b, pet c
WHERE b.person_id =a.id
and c.id = b.pet_id
and c.purchased_on > '2004/01/01'
```
see [DEMO HERE](http://sqlfiddle.com/#!7/cd524/2) | How to receive two values from a subquery SQLite | [
"",
"sql",
"database",
"sqlite",
""
] |
I have four tables that I want to join and display the output all together. I'm not sure how the syntax works for Oracle SQL Developer. I know this is an easy question for a programmer and I was hoping someone can make a suggestion on how the code might look like.
The **tables** are:
```
JNL1
JNL2
JNL3
JNL4
```
The ... | It really depends on what kind of join you want (outer or not) but you can use default SQL syntax.
For example, joining without the `JOIN` keyword:
```
select * from JNL1, JNL2, JNL3, JNL4,
where
JNL1.ItemID = JNL2.ItemID AND
JNL2.ItemID = JNL3.ItemID AND
JNL3.ItemID = JNL4.ItemID;
```
Additionally you can make use... | It works in Oracle as it would in other DB engines :
```
SELECT *
FROM JNL1 j1
INNER JOIN JNL2 j2 ON j1.ItemID = j2.ItemID
INNER JOIN JNL3 j3 ON j1.ItemID = j3.ItemID
INNER JOIN JNL4 j4 ON j1.ItemID = j4.ItemID
```
One typical Oracle syntax exists when you want to `LEFT JOIN` :
Standard SQL:
```
SELECT *
FROM JNL1 ... | Joining Tables in Oracle SQL Developer | [
"",
"sql",
"oracle",
"join",
""
] |
I have looked here: [Selecting all corresponding fields using MAX and GROUP BY](https://stackoverflow.com/questions/1305056/selecting-all-corresponding-fields-using-max-and-group-by) and similar pages on SO but I cannot seem to get all my fields to line up properly.
I feel like I'm at the cusp of figuring this out but... | In general, unless you're trying to perform some sort of MySQL "magic" you should always group by *every* non-aggregate, non-constant column in your `SELECT` list.
In your case, the best approach is to get a list of (name, # bedrooms, minimum rent), and then find all the rows that match these values - in other words, ... | ```
SELECT min(ru.id) as id, run.name, ru.rent, ru.rent AS min_rent, ru.bedrooms
FROM rental_units AS ru
JOIN rental_unit_names AS run
on run.id = ru.name_id
WHERE run.merge = 1
and ru.rent =
(select min(ru1.rent) from rental_units AS ru1
JOIN rental_unit_names AS run1
on run1.id = ru1.name_id
where run.name = run1.na... | MySQL GROUP BY with MIN - incorrect column data | [
"",
"mysql",
"sql",
"group-by",
"min",
""
] |
I am tying to make a python program that will generate the sum of primes for a number, but the program is not giving the correct result,please tell me why.
```
b=1
#generates a list of numbers.
while b<100:
b=b+1
x = 0.0
a = 0
d = 0
#generates a list of numbers less than b.
while x<b:
... | Your `d` variable is being reset during each iteration of your outer loop. Move the initialization out of that loop.
Additionally, the `a == 2` check should only occur once per iteration of the outer loop. Move it out of the inner loop.
```
b=1
d = 0
#generates a list of numbers.
while b<100:
b=b+1
x = 0.0
... | Kevin properly answered the question you asked. Permit me to answer the question you *didn't* ask, but should have: What is the best way to compute the sum of the primes less than *n*. The answer is to use a sieve:
```
def sumPrimes(n):
sum = 0
sieve = [True] * (n+1)
for p in range(2, n):
if sieve[... | python sum of primes | [
"",
"python",
"sum",
"primes",
""
] |
All the matplotlib [examples](http://matplotlib.org/examples/pylab_examples/histogram_demo_extended.html) with `hist()` generate a data set, provide the data set to the `hist` function with some bins (possibly non-uniformly spaced) and the function automatically calculates and then plots the histogram.
I already have ... | Perhaps the weight parameter would be of help in your problem.
```
import matplotlib.pyplot as plt
a= [1,2,3,4,5,6,7,8,9]
b= [5,3,4,5,3,2,1,2,3]
plt.hist(a,9, weights=b)
plt.show()
```
Or, as tcaswell said, you could just make a bar plot and change the x-axis.
[Using matplotlib how could I plot a histogram with giv... | Also, as an alternative (similar to Matlab), you can use `bar`:
```
import matplotlib.pyplot as plt
a= [1,2,3,4,5,6,7,8,9]
b= [5,3,4,5,3,2,1,2,3]
plt.bar(a,b)
```
[](https://i.stack.imgur.com/VQBiL.png)
Then, you can also add the title and other st... | Histogram from data which is already binned, I have bins and frequency values | [
"",
"python",
"matplotlib",
"histogram",
""
] |
This feels like it should be very simple, but I haven't been able to find an answer..
In a python script I am reading in data from a USB device (x and y movements of a USB mouse). it arrives in single ASCII characters. I can easily convert to unsigned integers (0-255) using ord. But, I would like it as signed integers... | Subtract 256 if over 127:
```
unsigned = ord(character)
signed = unsigned - 256 if unsigned > 127 else unsigned
```
Alternatively, repack the byte with the `struct` module:
```
from struct import pack, unpack
signed = unpack('B', pack('b', unsigned))[0]
```
or directly from the character:
```
signed = unpack('B', ... | ```
from ctypes import c_int8
value = c_int8(191).value
```
use ctypes with your ord() value - should be -65 in this case
ex. from string data
```
from ctypes import c_int8
data ='BF'
value1 = int(data, 16) # or ord(data.decode('hex'))
value2 = c_int8(value1).value
```
value1 is 16bit integer representation of hex ... | convert ascii character to signed 8-bit integer python | [
"",
"python",
"integer",
"ascii",
"signed",
""
] |
To do some testing on a new table field, I'd like to fake-up some values on existing records in my test database. I want to assign a value to every 8th record in a table. I can easily select every 8th record using this syntax:
```
select *
from
(select rownum rn
, jeffs_field_to_update
from jeff)
where mod(rn... | You need to join this to UPDATE statement on any key in the table. For example, if you have an unique id column, update statement will look like this:
```
update jeff
set jeffs_field_to_update = value
where id in
(select id
from
(select rownum rn
, jeff.id
from jeff)
where mod(rn, 8) = 0)
``` | A shorter answer:
```
UPDATE jeff
SET jeffs_field_to_update = value
WHERE mod(DBMS_ROWID.ROWID_ROW_NUMBER(ROWID), 8)=0;
``` | Oracle SQL update every nth row | [
"",
"sql",
"oracle",
"sql-update",
""
] |
As the title says, in Python (I tried in 2.7 and 3.3.2), why `int('0.0')` does not work? It gives this error:
```
ValueError: invalid literal for int() with base 10: '0.0'
```
If you try `int('0')` or `int(eval('0.0'))` it works... | Simply because `0.0` is not a valid integer of base 10. While `0` is.
Read about `int()` [here.](http://docs.python.org/2/library/functions.html#int)
> int(x, base=10)
>
> Convert a number or string x to an integer, or return
> 0 if no arguments are given. If x is a number, it can be a plain
> integer, a long integer... | From the docs on `int`:
```
int(x=0) -> int or long
int(x, base=10) -> int or long
```
If x is **not a number** or if base is given, then x must be a string or Unicode object representing an integer literal in the given base.
So, `'0.0'` is an invalid integer literal for base 10.
You need:
```
>>> int(float('0.0')... | Python 2.7 and 3.3.2, why int('0.0') does not work? | [
"",
"python",
"string",
"integer",
"type-conversion",
""
] |
Suppose I have a database of athletic meeting results with a schema as follows
```
DATE,NAME,FINISH_POS
```
I wish to do a query to select all rows where an athlete has competed in at least three events without winning. For example with the following sample data
```
2013-06-22,Johnson,2
2013-06-21,Johnson,1
2013-06-... | I think this can be even simpler / faster:
```
SELECT day, place, athlete
FROM (
SELECT *, min(place) OVER (PARTITION BY athlete
ORDER BY day
ROWS 3 PRECEDING) AS best
FROM t
) sub
WHERE best > 1
```
[**->SQLfiddle**](http://sqlfiddle.com/#!1/e9... | Here's an alternative formulation that does the work in two scans without subqueries:
```
SELECT
"date", athlete, place
FROM (
SELECT
"date",
place,
athlete,
1 <> ALL (array_agg(place) OVER w) AS include_row
FROM Table1
WINDOW w AS (PARTITION BY athlete ORDER BY "date" ASC ROWS BETWEEN 3 PRECE... | Select finishes where athlete didn't finish first for the past 3 events | [
"",
"sql",
"postgresql",
"window-functions",
""
] |
Sorry for the confusing title. I was having trouble searching for the solution I am looking for because I do not know how to summarize it in a few words.
I have a single table, table\_name, with columns Indicator, ID, and Num. The Indicator is either 0 or 1 and the ID can exist up to 2 times. If the ID number exists t... | This is tricky, because you want to be sure not to lose any rows. For that reason, I'm doing this with a nested `select` statement:
```
select (case when indicator = 0 then 0
else (select t2.num from table_name t2 where t2.id = t.id and t2.indicator = 0)
end) as Val
from table_name t
```
Here is ... | ```
select case when oneId.id is null the 0 else zero.num end case
from table1 zero
left join table1 oneId
on zero.id = oneId.id
and 1 = oneId.indicator
where zero.indicator = 0
``` | select a field from one row as a field from another SQL | [
"",
"sql",
""
] |
I want to print list of list in python 3.x with below code, but it is giving an error.
```
lol=[[1,2],[3,4],[5,6],['five','six']]
for elem in lol:
print (":".join(elem))
# this is the error I am getting-> TypeError: sequence item 0: expected str instance, int found
```
I am expecting this output:
```
1:2
3:4
5... | One can't join `int`'s only strings. You can Explicitly cast to `str` all your data
try something like this
```
for elem in lol:
print (":".join(map(str, elem)))
```
or with generator
```
for elem in lol:
print (":".join(str(i) for i in elem))
```
or You can use `format` instead of casting to string (this a... | I'd go for:
```
for items in your_list:
print (*items, sep=':')
```
This takes advantage of `print` as a function and doesn't require joins or explicit string conversion. | Python How to print list of list | [
"",
"python",
"python-3.x",
""
] |
I am trying to access the following data structure inside a template in Django. But its too difficult for me too figure out how.
```
{ Day1 : { Room1 : [(datetime.date(), (totalTime1, Flag1)),
(datetime.date(), (totalTime2, Flag2)),
(datetime.date(), (totalTime3, Flag3)),
... | It can't be done in a single loop, but you can do it with some nesting:
```
{% for day, rooms in mydict.items %}
{% for room, dates_and_flags in rooms.items %}
{% for date, time_and_flags in dates_and_flags %}
{{ date }}:{{ time_and_flags }}
{% endfor %}
{% endfor %}
{% endfor %}
```
Because `time... | I was able to do it with a single loop - although maybe I misunderstood the previous answers or initial question. Regardless, this might be helpful to anyone else looking into working with nested dictionaries in Django
Combine
* the .items() method to loop over the dictionary in Django
* the .value syntax for the att... | How do I read a nested dictionary in a Django template? | [
"",
"python",
"django",
"django-templates",
""
] |
A table with 2 columns ordered by group, number:
```
group_id | number
---------+--------
1 | 101
1 | 102
1 | 103
1 | 106
2 | 104
2 | 105
2 | 107
```
What SQL query should I write to get the following output:
```
group_id | number_from | number_to | total
--... | [Here is SQL Fiddel Demo](http://sqlfiddle.com/#!1/0eaa6/70)
Below is the script
```
create table Temp(A int,B int);
insert into temp values (1,101);
insert into temp values (1,102);
insert into temp values (1,103);
insert into temp values (1,106);
insert into temp values (2,104);
insert into temp values (2,105);
in... | ```
WITH RECURSIVE rope AS (
SELECT i1.id AS low
, i1.id AS high
, i1.grp AS grp
, 1::integer AS cnt
FROM islands i1
-- no left neighbor
WHERE NOT EXISTS ( SELECT * FROM islands x WHERE x.grp = i1.grp AND x.id = i1.id-1)
UNION ALL
SELECT ch.low AS low
, i2.id AS high
... | Detect range and count from a table | [
"",
"sql",
"postgresql",
"range",
"detect",
""
] |
I'm iterating over a list of tuples, and was just wondering if there is a smaller notation to do the following:
```
for tuple in list:
(a,b,c,d,e) = tuple
```
or the equivalent
```
for (a,b,c,d,e) in list:
tuple = (a,b,c,d,e)
```
Both of these snippits allow me to access the tuple per item as well as as a w... | The pythonic way is the first option you menioned:
```
for tup in list:
a,b,c,d,e = tup
``` | This might be a hack that you could use. There might be a better way, but that's why it's a hack. Your examples are all fine and that's how I would certainly do it.
```
>>> list1 = [(1, 2, 3, 4, 5)]
>>> for (a, b, c, d, e), tup in zip(list1, list1):
print a, b, c, d, e
print tup
1 2 3 4 5
(1, 2, 3, 4, 5... | iterate over list of tuples in two notations | [
"",
"python",
"tuples",
""
] |
I'm constructing a dictionary in Python from many elements, some of which are nan's and I don't want to add them to the dictionary at all (because then I'll be inserting it into database and I don't want to have fields which don't make sense).
At the moment I'm doing something like this:
```
data = pd.read_csv("data.... | ```
>>> fields = [float('nan'),2,3,float('nan'),5]
>>> {"field%d"%i:v for i,v in enumerate(fields) if not math.isnan(v)}
{'field2': 3, 'field1': 2, 'field4': 5}
```
Or an ordered dict:
```
>>> OrderedDict(("field%d"%i,v) for i,v in enumerate(fields) if not math.isnan(v))
OrderedDict([('field1', 2), ('field2', 3), ('f... | Is this what you were looking for?
```
data = pd.read_csv("data.csv")
for i in range(len(data)):
mydict = OrderedDict([("type", "mydata"), ("field2", data.ix[i,2]), ("field5", data.ix[i,5])])
# field numbers
fields = [3,4,8]
for f in fields:
if not math.isnan(data.ix[i,f]):
mydict[... | Conditionally add multiple items to dictionary in Python | [
"",
"python",
"dictionary",
""
] |
I hope this is a easy one.
Is there any possiblity to call itertools.product with a yet (not hardcoded) not knwon number of arguments?
Something like this:
`itertools.product(x[0],x[1],x[2],....)`
and the dimension of x can't be hardcoded
Thanks! | Try:
```
itertools.product(*x)
```
i.e. we [unpack the argument list](http://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists). | You can use
```
itertools.product(*x)
``` | Calling itertools.product with unkown number of args | [
"",
"python",
""
] |
In Python, these two examples do the same thing:
```
from tkinter import Label
widget = Label(None, text='Hello')
widget.pack()
widget.mainloop()
from tkinter import Label
widget = Label(None,'Hello')
widget.pack()
widget.mainloop()
```
I think `Label` is a class, and when I try to create an instance of that class, ... | `text='Hello'` means you're explicitly passing the value `'Hello'` to a **keyword argument** `text` in the function arguments.
`Label(None,'Hello')` means `'Hello'` is passed to the second positional argument in the function definition(no matter what the name of that variable is)
```
>>> def func(first, second):
... ... | > I feel strange about the meaning of text='Hello'. Could anyone please tell me about that?
It is a [named argument](http://www.diveintopython.net/power_of_introspection/optional_arguments.html) or [keyword argument](http://docs.python.org/3/tutorial/controlflow.html#keyword-arguments).
Named arguments allow to pass ... | What is the difference between these two ways of passing arguments? | [
"",
"python",
""
] |
Is there a way to "capture" the error message printed out by `sys.exit()` during testing and compare it to another string?
Some background: in the Python script I'm working on, I've been using `sys.exit()` to print out a more specific error message (and avoid the traceback which usually arises).
```
try:
do_somet... | [`sys.exit`](http://docs.python.org/3/library/sys#sys.exit) dosn't do anythin else then raising `SystemExit`, which you can catch like any other exception.
The example about the context manager just shows you how you can use it to get the exception which was thrown in the with block if you need to perform checks on it... | `assertEqual` is part of unittest's TestCase, so won't help you if you're not using it. You would have to shell off the process to see what happens. Why not write some unit tests instead? | Capture error message from sys.exit() during testing | [
"",
"python",
"python-2.7",
"python-3.3",
""
] |
I have a small script that will check to see if a list of devices are either ssh or telnet enable.
Here is my code:
```
import socket
import sys
file = open('list', 'r')
file = file.readlines()
list = []
for i in file:
i=i.replace('\n','')
list.append(i)
for i in list:
s = socket.socket(socket.AF_INET, s... | did you try adding a [timeout](https://stackoverflow.com/questions/3432102/python-socket-connection-timeout)?
```
import socket
import sys
with open('list', 'r') as f:# file is a global class
# per default it reads the file line by line,
# readlines() loads the whole file in memory at once, using more memory... | I cannot really run the code because I don't have the `list` file you open on my machine. Still made few edits, any difference?
```
import socket
import sys
file = open('list', 'r')
file = file.readlines()
list = []
for i in file:
i=i.replace('\n','')
list.append(i)
for i in list:
s = socket.socket(socke... | Python Try and Except - The script get hung on the except | [
"",
"python",
""
] |
I am trying to count the number of values in a column that meet a certain condition (for example, are greater than 0.75). The column I have is made up of 2000+ decimals.
This is what I have tried,
```
a = len(fs)
c = np.zeros(a)
for i in fs[0:a]:
if i >= 0.75:
print = 1
elif i < 0.75:
print ... | In numpy you could do something like:
```
np.where(fs >= 0.75)[0].size
```
or
```
np.count_nonzero(fs >= 0.75)
```
Both are equivalent, but I probably prefer the second. See the docs for an explanation:
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.count_nonzero.html>
but basically `fs >= 0.75` creat... | It is not clear if you want to compute the number of 1 in the *same* loop, in which case vaggelas answer is correct.
If you want a separate loop to count the number of values `>= 0.75`, you can use:
```
>>> sum(1 for i in fs[0:a] if i >= 0.75)
``` | Want to count the number of values in a column that meet a condition | [
"",
"python",
"numpy",
""
] |
I have a pandas dataframe:
```
import pandas as pnd
d = pnd.Timestamp('2013-01-01 16:00')
dates = pnd.bdate_range(start=d, end = d+pnd.DateOffset(days=10), normalize = False)
df = pnd.DataFrame(index=dates, columns=['a'])
df['a'] = 6
print(df)
a
2013-01-01 16:00:00 6
2013-01-02 16:00:00 6
2013... | You're looking for the index method `get_loc`:
```
In [11]: df.index.get_loc(ds)
Out[11]: 1
``` | **Get dataframe integer index given a date key:**
```
>>> import pandas as pd
>>> df = pd.DataFrame(
index=pd.date_range(pd.datetime(2008,1,1), pd.datetime(2008,1,5)),
columns=("foo", "bar"))
>>> df["foo"] = [10,20,40,15,10]
>>> df["bar"] = [100,200,40,-50,-38]
>>> df
foo bar
2008-01-01 10 ... | Finding label location in a DataFrame Index | [
"",
"python",
"pandas",
""
] |
In the code below instead of active age I need to do a calculation with Open\_time and the current time.
In other words i need to do if current time minus open\_time is between 0 and 30, or 31 and 60, or over 60.
```
SELECT COUNT(CASE WHEN Assignment = 'Crosby' AND Severity = 4 AND CloseTime-OpenTime = 0-30 THEN P_NU... | <http://msdn.microsoft.com/en-us/library/ms189794.aspx> datediff..
```
SELECT
COUNT(CASE WHEN Assignment = 'Crosby' AND Severity = 4 AND datediff('day',getdate(), OpenTime) between 0 and 30 THEN P_NUMBER END) as crosby_sev4_030,
COUNT(CASE WHEN Assignment = 'Crosby' AND Severity = 5 AND datediff('day',getdate(), Open... | How about this?
```
WITH Assignments AS (
SELECT
Grp = Assignment + '_Sev' + Convert(varchar(11), Severity) + '_' + Label
FROM
dashboard.dbo.SmThings
CROSS APPLY (
SELECT Age = DateDiff(OpenTime, GetDate())
) A
INNER JOIN (
SELECT '030', 0, 30, '030'
... | SQL Timestamp Subtraction to get number of days | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I want to rewrite [yEnc](http://www.yenc.org/) code to make it compilable on Win32 with Visual Studio 2008.
The issue is that yEnc uses *unistd.h* (UNIX) functions *fcntl* to check if a file is readable or writable. It is of course not compatible with MS Visual Studio.
Here's what I want to be remove:
```
static Boo... | Finally, I think the following checks will be sufficient:
```
infile == NULL
outfile == NULL
fread != read_count
fwrite != write_count
ferror
```
This should be sufficient. Moreover, the file have been opened in Python first and I presume this file open has been tested for exceptions. | You don't have to convert it just install windows POSIX.
<http://www.cygwin.com/> | How to properly handle file read/write errors in C? | [
"",
"python",
"c",
""
] |
Is there a way to exchange between child and parent functions a variable that is not a list?
```
#parent
list=[0]*1
singlevalue = 0
#child - 0
def test():
list[0]= list[0]+1
return list
#parent
test() #>>1
test() #>>2
#child - 1
def test():
singlevalue = singlevalue +1
return singlevalue
#parent... | Both answers so far suggest a solution, which was not the point of the post. The difference is that regarding the list, you are working with a reference and are not manipulating a "bound" variable, as you would do with `singlevalue`.
As soon as you would try to do: `l = l + [1]` for example, you would try to modify the... | Would it be helpful to have a look at [defining functions](http://docs.python.org/2/tutorial/controlflow.html#defining-functions) on how to pass arguments?
Passing arguments might be more reliable than manipulating a "variable" of which you're hoping it is globally accessible and **mutable**.
Actually, the "variables... | python single integer variable between function | [
"",
"python",
"list",
"function",
"share",
""
] |
How can I get the index or column of a DataFrame as a NumPy array or Python list? | To get a NumPy array, you should use the `values` attribute:
```
In [1]: df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c']); df
A B
a 1 4
b 2 5
c 3 6
In [2]: df.index.values
Out[2]: array(['a', 'b', 'c'], dtype=object)
```
This accesses how the data is already stored, so there isn't... | You can use `df.index` to access the index object and then get the values in a list using `df.index.tolist()`. Similarly, you can use `df['col'].tolist()` for Series. | How do I convert a Pandas series or index to a NumPy array? | [
"",
"python",
"pandas",
""
] |
Imagine I have a numpy array and I need to find the spans/ranges where that condition is True. For example, I have the following array in which I'm trying to find spans where items are greater than 1:
```
[0, 0, 0, 2, 2, 0, 2, 2, 2, 0]
```
I would need to find indices (start, stop):
```
(3, 5)
(6, 9)
```
The faste... | How's one way. First take the boolean array you have:
```
In [11]: a
Out[11]: array([0, 0, 0, 2, 2, 0, 2, 2, 2, 0])
In [12]: a1 = a > 1
```
Shift it one to the left (to get the next state at each index) using [`roll`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html):
```
In [13]: a1_rshifted = n... | If you have access to the scipy library:
You can use [scipy.ndimage.measurements.label](http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.measurements.label.html#scipy.ndimage.measurements.label) to identify any regions of non zero value. it returns an array where the value of each element is the id of... | Find span where condition is True using NumPy | [
"",
"python",
"arrays",
"search",
"numpy",
""
] |
Let's say I have a database of Amazon customers who made purchases in the last year. It is pretty detailed and has columns like name, age, zip code, income level, favorite color, food, music, etc. Now, let's say I run a query such that I return all Amazon customers who bought Book X.
```
SELECT NAME, AGE, ZIPCODE, INC... | If i understood your requirement correctly then a nested quesry should do the job. SOmething like this:
```
SELECT distinct NAME, AGE, ZIPCODE, INCOME, FAVECOLOR, FAVEFOOD, FAVEMUSIC
FROM [Amazon].[dbo].[Customers] a, (SELECT NAME, AGE, ZIPCODE, INCOME, FAVECOLOR, FAVEFOOD, FAVEMUSIC
FROM [Amazon].[dbo].[Customers]
WH... | I think you need two separate queries. First one to bring back the customers, once a customer such as Bob is selected a second query is performed based on Bob's attributes.
A simple example would be a forms application that has two grids. The first displays a list of the users. When you select one of the users the sec... | How to run multiple SQL queries whose values change? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a query that I am trying to understand. Can someone shed light on to the details of what this query does?
I've only ever used one `ON` clause in a join condition. This one has multiple conditions for the `LEFT JOIN`, making it tricky to understand.
```
INSERT INTO nop_tbl
(q_date, community_id, news... | You have your explanation:
The objective of the query is to count subscriptions per `(q_date, community_id, newsletter_t)` in `newsletter_subscribers_main` and write the result to `nop_tbl`.
The `LEFT JOIN` prevents that rows are added multiple times.
But I also think, the query is inefficient and **probably wrong*... | The short short version is:
1. `insert ... select ...`
-> the query is filling `nob_tbl`
2. `from ...`
-> based on data in `newsletter_subscribers_main`
3. `left join ... where ... is null`
-> that are not already present in `nob_tbl` | Need help understanding a complex query with multiple join conditions | [
"",
"sql",
"postgresql",
"left-join",
""
] |
I have a PySide GUI app (written in Python 3, running on Windows 7 Pro) in which I’m setting the application icon as follows:
```
class MyGui(QtGui.QWidget):
def __init__(self):
super(MyGui, self).__init__()
...
self.setWindowIcon(QtGui.QIcon('MyGui.ico'))
if os.name == 'nt':
... | PySide needs access to a special DLL to read .ico files. I think it's qico4.dll.
You could try changing the call to setWindowIcon to open the icon as a .png and put a .png of it in the ./dist directory and see if that works. If so, then your code is fine and I'm pretty sure it's the .dll problem. You'll need to tell c... | I found another solution that doesn't require having the icon in both PNG and ICO formats. As Simon mentions in his answer, *qico4.dll* is required to read the .ico files. Also, this file needs to be placed in a directory named `imageformats` that is a subdirectory of your app directory. The folder structure should loo... | Application icon in PySide GUI | [
"",
"python",
"qt",
"qt4",
"pyside",
"python-3.3",
""
] |
I have a view in SQL which is bringing together some data in which I need to eliminate duplicate values. I have tried using DISTINCT and GROUP BY's without success. Basically what we have going on is a series of Uploaded Files which are attached to a Provider based upon the Type of document it is. They will upload mult... | Simply put, given a DocumentID, you want a list of (ProviderID, FilePath) where the FilePath is the most recent for that DocumentID and ProviderID combination.
I would rank all of your FilePaths partitioning by ProviderID and ordering by Date:
```
SELECT outerF.FileName, outerF.FilePath,
outerD.ProviderID, o... | You can use a ROW\_NUMBER() to solve this:
```
SELECT *
FROM (SELECT UploadedFiles.FileName, UploadedFiles.FilePath,
ReqDocuments.ProviderID, Providers.CompanyName,
dbo.ReqDocuments.ID AS RequiredDocumentID, dbo.UploadedFiles.aDate,
dbo.UploadedFiles.aUser
, ROW_NUMBER () OVER (PARTITION BY ReqDocuments.Pr... | duplicate items in SQL view/query | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am crazy confused about this for some reason.
Basically, I'm looking for a query that will find the number of new customers per month, since 2010.
I have the customer's email address(email), all orders placed(OrderID), and what date it was placed on(OrderDate). The table is tblOrder.
I know that a "new customer" i... | Try:
```
select yr, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]
from
(select datepart(month,minDate) mth, datepart(year,minDate) yr, count(*) cnt
from (select min(OrderDate) minDate, max(OrderDate) maxDate
from tblOrder
group by email) sq
where datediff(month, minDate, maxDate) > 0
g... | Start by defining a new customer
```
select distinct FirstTimer.customer_id
from
(select customer_id,min(order_date) as FirstOrderDate
from tblOrder
group by customer_id
having Month(min(order_date))=month(TargetDate) and
year(min(order_date))=year(targetDate)
) FirstTimer
join tblOrder ot on ot.customer_id=F... | Counting new Customers per Month | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am creating a database based on a sporting game to store matches and each player involved in each match. I am having trouble resolving a many to many relationship. I currently have the following tables:
**Player**
```
id
name
```
**Match**
```
id
date
```
**PlayerMatch**
```
player_id
match_id
home_team
goals_f... | I would recommend a sticking with a many to many relationship. This allows you to change the specifications of how many players you can have in a game easily while not complicating the data model much.
**Player**
```
id
name
```
**Match**
```
id
date
```
**PlayerMatch**
```
player_id
match_id
is_home
goals_for
go... | That is a valid option, though I would suggest a naming convention where you use the same column name in both tables (i.e. use match\_id in both Match and PlayerMatch; same for player\_id). This helps make your SQL a bit more clear and when doing joins in some databases (MySQL) you can then use the 'using (col1, col2, ... | SQL Database Design Many to Many | [
"",
"sql",
"database-design",
""
] |
I have this form field:
```
area = forms.DecimalField(max_digits=20)
```
When I post it I get unicode data:
```
raise Exception(type(a.get('area',))
```
the result is
> `<type 'unicode'>`
How can I convert that to float? I want to perform an arithmetic operation on the result.
If I do this:
```
float(a.get('are... | If the form is processed and you get your `area` as `<type 'unicode'>` then this should suffice to convert it and perform arithmetic on it.
```
area = form.data['area']
#area should be <type 'unicode'>
area_float = float(area)
```
Consider the following example
```
a = u'1.34'
a_float = float(a)
type(a_float)
>> <ty... | Form submissions are strings (excepted when files are being uploaded, I think.) In Django, the form is automatically converted to the appropriate Python type if the form is valid (how convenient!) You access the data using via `cleaned_data` (see [Processing the data from the form](https://docs.djangoproject.com/en/dev... | How can i convert DecimalField to float in Python Django? | [
"",
"python",
"django",
""
] |
Consider the following function:
```
def fun(lst):
for item in lst:
cmp = 0
for other in lst:
if item < other:
cmp -= 1
elif item > other:
cmp += 1
if not cmp:
return item
nums = [1,3,2,2]
print("fun({0}) = {1}".format... | First, there's wrong alignment in your code ("if not cmp:" should be one position left,
and last two lines should be on the same column as the first line is) like this:
```
def fun(lst):
for item in lst:
cmp = 0
for other in lst:
if item < other:
cmp -= 1
el... | > Does anyone have any tips on how to make interpreting a block of code easier...
Write it out. Give each name its own space on the page and track changes to the values while running through the code. After some practice you'll be able to track the simple values easily, only needing to write out the non-scalar values. | Working out why a block of code gives a certain output | [
"",
"python",
"output",
""
] |
I would like to draw graphs like this (Sorry, I was not able to upload the picture)
<http://www.organizationview.com/wp-content/uploads/2011/01/Stacked-distribution.jpg>
Which software can do this? Is there any python utilities that can do this? | I made you a working matplotlib example. I only made three components per bar-chart. Adding two more for the five total in your example is left as an exercise to the reader. :) The code is quoted down below. You can also see it live or download my IPython notebook: <http://nbviewer.ipython.org/5852773>
```
import nump... | The matplotlib library can be used for generating graphs in Python.
<http://matplotlib.org/> | Stacked distribution graph (possibly in python) | [
"",
"python",
"graph",
"charts",
""
] |
I'm looking for the simplest way to determine the weekday number for the `DATE` value in oracle independent of the `NLS` settings.
```
Monday -> 1
Tuesday -> 2
…
Sunday -> 7
```
Any ideas? | ISO weeks start on Monday; they don't use NLS settings. I *think* this expression is reliable.
```
1 + trunc(your_date) - trunc(your_date, 'IW')
```
To show how the arithmetic works . . . current\_date is a Wednesday.
```
select current_date as cur_date
, trunc(current_date) as trunc_cur
, trunc(current_da... | One option is to use the remainder of the difference in days between the date in question and the date of a known Monday (eg 1900-01-01).
```
mod(my_date-date '1900-01-01',7)+1 day_of_week
```
You'd have to choose a suitably ancient Monday such that all the dates you'd use are greater than or equal to it. | Weekday number regardless of the NLS settings | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I have a small issue when I'm trying to import data from CSV files with numpy's loadtxt function. Here's a sample of the type of data files I have.
Call it 'datafile1.csv':
```
# Comment 1
# Comment 2
x,y,z
1,2,3
4,5,6
7,8,9
...
...
# End of File Comment
```
The script that I thought would work for this situation l... | Skip comment line manually using generator expression:
```
import numpy as np
with open('datafile1.csv') as f:
lines = (line for line in f if not line.startswith('#'))
FH = np.loadtxt(lines, delimiter=',', skiprows=1)
``` | Create your own custom filter function, such as:
```
def skipper(fname):
with open(fname) as fin:
no_comments = (line for line in fin if not line.lstrip().startswith('#'))
next(no_comments, None) # skip header
for row in no_comments:
yield row
a = np.loadtxt(skipper('your_file'... | numpy loadtxt skip first row | [
"",
"python",
"bash",
"csv",
"numpy",
"import-from-csv",
""
] |
How can i sum or add (PDetail.DETAIL\_FOR\_QTY) on the current query?
```
SELECT PDetail.PLU, PDetail.DETAIL_FOR_QTY, PLU.PLU_DESC, PLU.LAST_PRICE
FROM PDetail INNER JOIN
PLU ON PDetail.PLU = PLU.PLU_NUM
WHERE (PDetail.DEPT = 26) AND (PDetail.StoreNumber IN (1, 2, 3, 4, 7,... | this did the trick:
```
SELECT PDetail.PLU, SUM(PDetail.DETAIL_FOR_QTY) AS DETAIL_FOR_QTY, PLU.PLU_DESC, PLU.LAST_PRICE
FROM PDetail INNER JOIN
PLU ON PDetail.PLU = PLU.PLU_NUM
WHERE (PDetail.DEPT = 26) AND (PDetail.StoreNumber IN (1, 2, 3, 4, 7, 8, 10, 12, 14, 16)) ... | Based on the comments to the questions, you simply want
```
select PDetail.PLU,
sum(DETAIL_FOR_QTRY) as [QUANTITY SUM],
PLU.PLU_Description,
MAX(PLU.Last_Price)
FROM PDetail
INNER JOIN PLU
ON PDetail.PLU = PLU.PLU_NUM
WHERE (PDetail.DEPT = 26)
AND (PDetail.StoreNumber IN (1, 2, 3, 4,... | sum aggerate in sql query | [
"",
"sql",
"t-sql",
"sql-server-2008-r2",
""
] |
I have a large data set of urls and I need a way to parse words from the urls eg:
```
realestatesales.com -> {"real","estate","sales"}
```
I would prefer to do it in python. This seems like it should be possible with some kind of english language dictionary. There might be some ambiguous cases, but I feel like there ... | This is a problem is word segmentation, and an efficient dynamic programming solution exists. [This](http://thenoisychannel.com/2011/08/08/retiring-a-great-interview-problem/) page discusses how you could implement it. I have also answered this question on SO before, but I can't find a link to the answer. Please feel f... | Ternary Search Trees when filled with a word-dictionary can find the most-complex set of matched terms (*words*) rather efficiently. This is the solution I've previously used.
You can get a C/Python implementation of a tst here: <http://github.com/nlehuen/pytst>
**Example:**
```
import tst
tree = tst.TST()
#note th... | Python parse words from URL string | [
"",
"python",
"string",
"parsing",
"url",
"nlp",
""
] |
Which of the following two approaches is considered best practice? The both achieve the same result.
```
class Foo():
LABELS = ('One','Two','Three')
class Bar():
def __init__(self):
self.__labels = ('One','Two','Three')
@property
def labels(self):
return self.__labels
``` | If you don't need custom getting or setting behavior, there's no point in making something a property. The first version is better.
Also, these are not quite identical in their behavior. In `Foo`, there's a class-level attribute for labels. In `Bar`, there isn't. Referencing `Foo.LABELS` will work fine, referencing `B... | The [PEP 8 Style Guide for Python Code](http://legacy.python.org/dev/peps/pep-0008/#constants) offers a 3rd way, and the [Zen of Python](http://legacy.python.org/dev/peps/pep-0020/) agrees.
They suggests adding a very simple module, that creates a namespace to define the constants.
Entire of contents of e.g. `package... | Python: Should I use a Constant or a Property? | [
"",
"python",
"syntax",
"constants",
""
] |
I am looking for a query to for each row to find the column (YYY.) with the highest/most recent date and would like to find the corresponding column (XXXX.)
Finding the column with the most recent date was possible, but getting the corresponding column left me clueless... All suggestions are welcome!!
So from the tabl... | ```
SELECT id,
CASE
WHEN YYYY0 > YYY1 AND YYY0 > YYY2 ... AND YYY0 > YYY9 THEN XXX0
WHEN YYY1 > YYY2 ... AND YYY0 > YYY9 THEN XXX1
...
ELSE XXX9 AS LabelX,
CASE
WHEN YYYY0 > YYY1 AND YYY0 > YYY2 ... AND YYY0 > YYY9 THEN YYY0
WHEN YYY1 > YYY2 ... AND YYY0 > YYY9 THEN YYY1
...
ELSE YYY9 AS LabelY,
...
```
and replace > ... | If it's a SQL Server 2005 and above you can do it this way (it assumes that dates are unique in each column for specific id):
```
;with cte as (
select id, xxxx0 as LabelX, yyy0 as LabelY from tab union all
select id, xxxx1, yyy1 from tab union all
select id, xxxx9, yyy9 from tab
)
select t.id, x.LabelX, t... | SQL get data from column(YYY0) with same number as different column(XXXX0) with the maximum date | [
"",
"sql",
""
] |
I need to create a tally dictionary of time stamps on our server log files with the hours as keys
I dont want to do the long-winded case by case check regular expression and append (its python..there is a better way)
e.g. say I have a list:
```
times = ['02:49:04', '02:50:03', '03:21:23', '03:21:48', '03:24:29', '0... | something like:
```
from collections import Counter
counts = Counter(time[:2]+'00' for time in times)
``` | ```
from collections import defaultdict
countDict = defaultdict(int)
for t in times:
countDict[t[:2]+"--"] += 1
print countDict
``` | count occurrences of timeframes in a list | [
"",
"python",
""
] |
Ahoy, I'm writing a Python script to filter some large CSV files.
I only want to keep rows which meet my criteria.
My input is a CSV file in the following format
> ```
> Locus Total_Depth Average_Depth_sample Depth_for_17
> chr1:6484996 1030 1030 1030
> chr1:6484997 14 ... | Use list comprehension.
```
import csv
with open("filepath", 'rb') as f:
reader = csv.DictReader(f)
rows = [row for row in reader if row['Total_Depth'] != '0']
for row in rows:
print row
```
[DictReader](http://docs.python.org/2/library/csv.html#csv.DictReader) | If you store the full result of the zip, you can check the appropriate header before assigning:
```
...
for row in reader: #for each row in the reader object
r = zip(headers, row):
if r['Total_Depth'] == 0:
for h, v in r:
column[h].append(v)
``` | Returning a row from a CSV, if specified value within the row matches condition | [
"",
"python",
"csv",
"python-2.7",
"dictionary",
""
] |
I am very new a Python
I want to change sentence if there are repeated words.
**Correct**
* Ex. "this just so so so nice" --> "this is just so nice"
* Ex. "this is just is is" --> "this is just is"
Right now am I using this reg. but it do all so change on letters.
Ex. "My friend and i is happy" --> "My friend and i... | ```
text = re.sub(r'\b(\w+)( \1\b)+', r'\1', text) #remove duplicated words in row
```
The `\b` matches the empty string, but only at the beginning or end of a word. | Non- regex solution using `itertools.groupby`:
```
>>> strs = "this is just is is"
>>> from itertools import groupby
>>> " ".join([k for k,v in groupby(strs.split())])
'this is just is'
>>> strs = "this just so so so nice"
>>> " ".join([k for k,v in groupby(strs.split())])
'this just so nice'
``` | python regular expression to remove repeated words | [
"",
"python",
"regex",
""
] |
How do I go about running a bash script using the subprocess module, to which I must give several arguments?
This is what I'm currently using:
```
subprocess.Popen(['/my/file/path/programname.sh', 'arg1 arg2 %s' % arg3], \
shell = True)
```
The bash script seems not to be taking any of the parameters in. Any ins... | Pass arguments as a list, see [the very first code example in the docs](http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module):
```
import subprocess
subprocess.check_call(['/my/file/path/programname.sh', 'arg1', 'arg2', arg3])
```
If `arg3` is not a string; convert it to string before passing... | ```
subprocess.Popen(['/my/file/path/programname.sh arg1 arg2 %s' % arg3], shell = True).
```
If you use `shell = True` the script and its arguments have to be passed as a string. Any other elements in the `args` sequence will be treated as arguments to the shell.
You can find the complete docs at <http://docs.python... | Python: subprocess and running a bash script with multiple arguments | [
"",
"python",
"bash",
"arguments",
"subprocess",
"popen",
""
] |
How can I import variables from one file to another?
example: `file1` has the variables `x1` and `x2` how to pass them to `file2`?
How can I import **all** of the variables from one to another? | ```
from file1 import *
```
will import all objects and methods in file1 | Import `file1` inside `file2`:
To import all variables from file1 without flooding file2's namespace, use:
```
import file1
#now use file1.x1, file2.x2, ... to access those variables
```
To import all variables from file1 to file2's namespace( not recommended):
```
from file1 import *
#now use x1, x2..
```
From t... | Importing variables from another file? | [
"",
"python",
"file",
"variables",
"import",
""
] |
I made myself a little module which I happen to use quite a lot. Whenever I need it I simply copy it to the folder in which I want to use it. Since I am lazy I wanted to install it so that I can call it from anywhere, even the interactive prompt. So I read a bit about installing here, and concluded I needed to copy the... | There are methods to install Python modules system-wide. You may want to take a look at [distutils](http://docs.python.org/2/library/distutils.html). A good tutorial for distutils2 (the current version) can be found [here](http://wiki.python.org/moin/Distutils/Tutorial).
You basically have to write a file `setup.py` w... | The answer is: **it's all about permissions**.
It's not enough to place the file in the correct location, like, such instance: */usr/local/lib/python2.7/dist-packages*, you also need to ensure that the file can be read by the process you're running, in this case, python.
Be sure that "other" users have read access to... | How to make my Python module available system wide on Linux? | [
"",
"python",
"linux",
"module",
"installation",
""
] |
I am just new to python.
as i know in python multi-line comments are made like this
```
"""
this is a comments
"""
```
but consider this code
```
somevariable="""this is a variable"""
print somevariable
```
it prints ***this is a variable***
are comments and strings are same in python or they are different? | The first one isn't a comment, it's a string. But since you're not *doing* anything with that string (printing it, assigning it to a variable etc.) all the interpreter does is say "Yup, that's a string alright!" and ignore it entirely. Effectively making it the same as a comment, since it's an arbitrary bunch of text t... | There are no multi-line comments in Python. They're both just strings. The former is typically used as a docstring and will be associated with the function/class/module, while the other gets assigned to a variable. | Comments compared to string in python | [
"",
"python",
""
] |
The XML:
```
<?xml version="1.0"?>
<pages>
<page>
<url>http://example.com/Labs</url>
<title>Labs</title>
<subpages>
<page>
<url>http://example.com/Labs/Email</url>
<title>Email</title>
<subpages>
<page/>
... | Used `lxml.html`.
```
import lxml.html
rexml = ...
def depth(node):
d = 0
while node is not None:
d += 1
node = node.getparent()
return d
tree = lxml.html.fromstring(rexml)
for node in tree.iter('page'):
print depth(node)
for url in node.iterfind('url'):
print url.text
... | The Python `ElementTree` API provides iterators for depth-first traversal of a XML tree - unfortunately, those iterators don't provide any depth information to the caller.
But you can write a depth-first iterator that also returns the depth information for each element:
```
import xml.etree.ElementTree as ET
def dep... | xml.etree.ElementTree get node depth | [
"",
"python",
"xml",
"xml-parsing",
""
] |
I have the following example table:
```
ID Type Price Code Date
1 1 .99 Null 6/1
2 2 1.99 Null 5/1
3 1 .99 1234 4/1
4 3 1.99 Null 5/1
5 2 3.99 Null 6/1
6 1 1.30 1234 5/1
7 1 1.64 5673 6/... | ```
Select
ID, Type, Price, Code, Date
from
tblPRODUCT tbpr
where
(Code = '1234' AND Date IN (Select MAX(Date) from tblPRODUCT where type= tbpr.type
and code = '1234'))
OR Date IN (Select MAX(Date) from tblPRODUCT where type= tbpr.type
and not exists(select code from tblPRODUCT where type= ... | Belated and similar to a deleted answer, but just to show a slightly simpler approach than the accepted answer;
```
WITH cte AS (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY Type ORDER BY Code DESC, Date DESC) rn
FROM tblPRODUCT WHERE Code='1234' OR Code IS NULL
)
SELECT ID, Type, Price, Code, Date
FROM cte WHERE ... | Return one value if true, return another value if not true | [
"",
"sql",
"sql-server",
"select",
"if-statement",
""
] |
I am new to Python and I started studying the basics. I am a C++ guy so the // operator was something new. According with a book that I am reading:
```
>> 4/2
2.0
>> 2/4
0.5
>> 5//4
2
>> 2//4
0
```
The problem is that when I write `5//4` the result is 1,when I write `4/2` the result is 2 and not 2.0 and when I write ... | In Python 2.x, the default division operator is "Classic division". This means that `/`, when used with integer operators will result in integer division similar to C++ or java [i.e. `4/3 = 1`].
In Python 3.x, this is changed. There, `/` refers to "True division" [`4/3 = 1.3333..`], whereas `//` is used to request "Cl... | The difference occurs in case of `Python 3.x` .
In Python 3.0, `7 / 2` will return **3.5** and `7 // 2` will return **3**. The operator `/` is `floating point division`, and the operator `//` is `floor division` or `integer division`.
But in case of `Python 2.x` there won't be any difference and the text is wrong I be... | Python's / and // operators on 2.7.4 | [
"",
"python",
"operators",
""
] |
I have a stored procedure and the select statement is:
```
SELECT { fn MONTHNAME(OrderDate) } AS MonthName, YEAR(OrderDate) AS Year, SUM(TotalValue) AS Profits
FROM [Order]
WHERE (YEAR(OrderDate) = @year)
GROUP BY { fn MONTHNAME(OrderDate) }, YEAR(OrderDate)
```
this shows the sum total for every mont... | Try this:
```
SELECT { fn MONTHNAME(OrderDate) } AS MonthName, YEAR(OrderDate) AS Year, SUM(TotalValue) AS Profits
FROM [Order]
WHERE (YEAR(OrderDate) = @year)
GROUP BY { fn MONTHNAME(OrderDate) }, MONTH(OrderDate), YEAR(OrderDate)
order by Year(orderDate),month(OrderDate)
```
Note you need to add any... | Just add
```
Order by max(OrderDate)
```
at the end.
```
SELECT { fn MONTHNAME(OrderDate) } AS MonthName, YEAR(OrderDate) AS Year, SUM(TotalValue) AS Profits
FROM [Order]
WHERE (YEAR(OrderDate) = @year)
GROUP BY { fn MONTHNAME(OrderDate) }, YEAR(OrderDate)
Order by max(OrderDate)
```
Now about h... | Order By month and year in sql with sum | [
"",
"sql",
"sql-server",
""
] |
For example if I have a string of numbers and a list of word:
```
My_number = ("5,6!7,8")
My_word =["hel?llo","intro"]
``` | Using `str.translate`:
```
>>> from string import punctuation
>>> lis = ["hel?llo","intro"]
>>> [ x.translate(None, punctuation) for x in lis]
['helllo', 'intro']
>>> strs = "5,6!7,8"
>>> strs.translate(None, punctuation)
'5678'
```
Using `regex`:
```
>>> import re
>>> [ re.sub(r'[{}]+'.format(punctuation),'',x ) fo... | Assuming you meant for `my_number` to be a string,
```
>>> from string import punctuation
>>> my_number = "5,6!7,8"
>>> my_word = ["hel?llo", "intro"]
>>> remove_punctuation = lambda s: s.translate(None, punctuation)
>>> my_number = remove_punctuation(my_number)
>>> my_word = map(remove_punctuation, my_word)
>>> my_nu... | How to remove the punctuation in the middle of a word or numbers? | [
"",
"python",
"punctuation",
""
] |
Can `not x` and `x==None` give different answers if `x` is a class instance ?
I mean how is `not x` evaluated if `x` is a class instance ? | yes it **can** give different answers.
```
x == None
```
will call the [`__eq__()`](http://docs.python.org/2/reference/datamodel.html#object.__eq__) method to valuate the operator and give the result implemented compared to the `None` singleton.
```
not x
```
will call the [`__nonzero__()`](http://docs.python.org/2... | ```
class A():
def __eq__(self, other): #other receives the value None
print 'inside eq'
return True
def __nonzero__(self):
print 'inside nonzero'
return True
...
>>> x = A()
>>> x == None #calls __eq__
inside eq
True
>>> not x #calls __nonzero__
inside no... | Difference between 'not x' and 'x==None' in python | [
"",
"python",
""
] |
I can't figure out if this is an acceptable operation. I need to select records from the SQL Server 2008 database and then delete them, all as a single transaction from an ASP.NET code. Note that the .NET code must be able to retrieve the data that was first selected.
Something as such:
```
SELECT * FROM [tbl] WHERE ... | This will do the select and delete simultanious:
```
delete from [tbl] output deleted.* WHERE [id] > 6
``` | It is possible to select and delete in the same transaction as long as both operations are enlisted in the same transaction.
Look at this post
[Transactions in .net](https://stackoverflow.com/questions/224689/transactions-in-net) | Can I first SELECT and then DELETE records in one t-SQL transaction? | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I have seen a few questions that want the same except in my situation the time format isn't always hh:mm:ss, sometimes it's just mm:ss
I understand the idea mentioned here [How to convert an H:MM:SS time string to seconds in Python?](https://stackoverflow.com/questions/6402812/how-to-convert-an-hmmss-time-string-to-se... | ```
def getSec(s):
l = map(int, s.split(':')) # l = list(map(int, s.split(':'))) in Python 3.x
return sum(n * sec for n, sec in zip(l[::-1], (1, 60, 3600)))
getSec('20') # 20
getSec('1:20') # 80
getSec('1:30:01') # 5401
``` | It's pretty much the same for all time formats. Check out the [datetime](http://docs.python.org/2/library/datetime.html) module:
```
>>> s = "15:34:23"
>>> datetime.datetime.strptime(s, "%H:%M:%S")
datetime.datetime(1900, 1, 1, 15, 34, 23)
>>> s = "34:23"
>>> datetime.datetime.strptime(s, "%M:%S")
datetime.datetime... | Another converting hh:mm:ss to seconds | [
"",
"python",
""
] |
I just wrote a python script to get rid of some annoying suffixes in filenames,
here's my code:
```
import os
for root, dirs, files in os.walk("path"):
for filename in files:
if filename.endswith("[AnnoyingTag].mov"):
os.rename(filename, filename[:-18]+'.mov')
```
but I got the error in t... | You can replace
```
os.rename(filename, filename[:-18]+'.mov')
```
with
```
os.rename(root + os.sep + filename, root + os.sep + filename[:-18]+'.mov')
``` | The preferred way to join paths is to use `os.path.join`, change this line:
```
os.rename(filename, filename[:-18]+'.mov')
```
Replace it with this:
```
os.rename(os.path.join(root, filename), os.path.join(root, filename[:-18]+'.mov'))
``` | Python os.rename and os.walk together | [
"",
"python",
"filenames",
"os.walk",
""
] |
**What I intended to do:**
> Implement a function called my\_pop(), which is similar to the list
> pop() method. Take a list as input, remove the last object from the
> list and return it.
**What I came up with:**
```
# take an input of list;
# if not last item(determined by comparing index number): loop through the... | Your problem is that the last element's index (the result of l.index(i) where i is the last element of your list), does not equal -1.
This is a potential fix:
```
def my_pop(l):
new = []
l = list(l)
for i in l:
if l[-1] == i:
pass
else:
new.append(i)
return new
... | There are a few problems with your code:
1. The `pop` function returns not the new list, but the last element of the old list - it looks like your function is returning the new list.
2. The index function always returns a positive index - remember that why you can access the last element of a list as -1, its real inde... | Stuck when trying to manually implement the pop method for lists | [
"",
"python",
"list",
""
] |
I am quite new to PyQt. Does anyone tell me how to get the background color of a button or label (QPushButton, QLabel) in PyQt. | I haven't used PyQt, but I think API should be very similar to C++. To get background color of QWidget-based class, first get its [palette](http://qt-project.org/doc/qt-5.0/qtwidgets/qwidget.html#palette-prop) and then call [QPalette::color()](http://qt-project.org/doc/qt-5.0/qtgui/qpalette.html#color-2) with [QPalette... | Here is a sample code. This will help you.
```
QPushButton button1, button2;
button1.setStyleSheet("background-color:#ff0000;");
//To get Background color
QColor color = button1.palette().button().color();
//To set fetched color
button2.setStyleSheet("background-color:" + color.name() +";");
``` | How to get the background color of a button or label (QPushButton, QLabel) in PyQt | [
"",
"python",
"qt",
"pyqt",
"uibackgroundcolor",
""
] |
I have the following project structure
```
SampleProject
com
python
example
source
utils
ConfigManager.py
conf
constants.cfg
```
How to access constants.cfg from ConfigManager.py.
I have a limitation
1. I can not give full path(absol... | If `conf` is a Python package then you could use [`pkgutil.get_data()`](http://docs.python.org/2/library/pkgutil.html):
```
import pkgutil
data = pkgutil.get_data("conf", "constants.cfg")
```
Or if `setuptools` is installed – [`pkg_resources.resource_string()`](http://packages.python.org/distribute/pkg_resources.htm... | If you had some module in the root of the project tree, say config\_loader.py that looked like this:
```
import os
def get_config_path():
relative_path = 'conf/constants.cfg'
current_dir = os.getcwd()
return os.join(current_dir, relative_path)
```
And then in ConfigManager.py or any other module that nee... | Python : How to access file from different directory | [
"",
"python",
"python-2.7",
"import",
"python-import",
"pythonpath",
""
] |
I have a multi-index DataFrame created via a groupby operation. I'm trying to do a compound sort using several levels of the index, but I can't seem to find a sort function that does what I need.
Initial dataset looks something like this (daily sales counts of various products):
```
Date Manufacturer Product... | A hack would be to change the order of the levels:
```
In [11]: g
Out[11]:
Sales
Manufacturer Product Name Product Launch Date
Apple iPad 2010-04-03 30
iPod 2001-10-23 34
Samsung Galaxy 2009-04-27 ... | This one liner works for me:
```
In [1]: grouped.sortlevel(["Manufacturer","Product Launch Date"], sort_remaining=False)
Sales
Manufacturer Product Name Product Launch Date
Apple iPod 2001-10-23 34
iPad 2010-04-03 ... | Multi-Index Sorting in Pandas | [
"",
"python",
"sorting",
"pandas",
"multi-index",
""
] |
Assuming that you already have pip or easy\_install installed on your python distribution, I would like to know how can I installed a required package in the user directory from within the script itself.
From what I know pip is also a python module so the solution should look like:
```
try:
import zumba
except Im... | Updated for newer pip version (>= 10.0):
```
try:
import zumba
except ImportError:
from pip._internal import main as pip
pip(['install', '--user', 'zumba'])
import zumba
```
Thanks to @Joop I was able to come-up with the proper answer.
```
try:
import zumba
except ImportError:
import pip
... | As of pip version >= 10.0.0, the above solutions will not work because of internal package restructuring. The new way to use pip inside a script is now as follows:
```
try: import abc
except ImportError:
from pip._internal import main as pip
pip(['install', '--user', 'abc'])
import abc
``` | How to install a missing python package from inside the script that needs it? | [
"",
"python",
"pip",
""
] |
Say if I have:
```
list1 = [1,6]
list2 = [1]
```
I want to do something if list values match!
Compare it and do stuff after that | Mmm, like this?
```
if list1 == list2: # compare lists for equality
doStuff() # if lists are equal, do stuff after that
```
Of course, you need to clarify what do you mean by "if lists values match". The above will check to see if both lists have the same elements, in the same position - that is, if they're ... | Use [`any()`](http://docs.python.org/2/library/functions.html#any):
```
>>> L1 = [1,6]
>>> L2 = [1]
>>> any(i in L1 for i in L2)
True
```
Pretty much, it loops through each item in `L2` and if any item in L2 is in `L1`, then it will return `True`.
If you want to see whether each item is in the other list, and print ... | how to compare two list ,object instances in python | [
"",
"python",
"python-2.7",
""
] |
I have opened the file I want to write to using:
```
data = open('input','a')
```
using a loop, I want to write some words to the file in the same line. And after every loop iteration I want to add a newline character.
```
while loop:
for loop:
/* do something */
if some_condition:
da... | Remove the newline at the end of `tag` before writing it.
```
data.write(str(tag).rstrip('\n'))
``` | ```
while loop:
for loop:
/*do something
*/
if some_condition:
data.write(str(tag)+"")
data.write(" ")
```
In other words, remove the data.write("\n"); | Continue writing in same line of file | [
"",
"python",
"file-io",
""
] |
I've found various detailed explanations on how to pass long lists of arguments into a function, but I still kinda doubt if that's proper way to do it.
In other words, I *suspect* that I'm doing it wrong, but I can't see how to do it *right*.
The problem: I have (not very long) recurrent function, which uses quite a ... | You could wrap up all your parameters in a class, like this:
```
class FooParameters:
alpha = 1.0
beta = 1.0
gamma = 1.0
zeta = 1.0
alphaList = []
betaList = []
gammaList = []
zetaList = []
```
and then your function takes a single parameter instance:
```
def myFunction(params):
o... | This is commonly used in `matplotlib`, for example, where a large number of arguments can be conveniently passed using `*` or `**`:
```
def function(*args, **kwargs):
do something
```
Calling the function:
```
function(1,2,3,4,5, a=1, b=2, b=3)
```
where the listed arguments `1,2,3,4,5` will go to `args` wherea... | Python: Best way to deal with functions with long list of arguments? | [
"",
"python",
"list",
"python-2.7",
"dictionary",
"arguments",
""
] |
How can i enable pretty print on the REPL by default?
Currently I do it by using `pprint.pprint()` function.
```
>>> pprint.pprint(data)
{'SHIP_CATEGORY': '',
'SHIP_QUANTITY': 1,
'SHIP_SEPARATELY': 0,
'SHIP_SUPPLEMENT': 0,
'SHIP_SUPPLEMENT_ONCE': 0,
'THUMBNAIL': ''}
```
But I want pretty print by default
```
>... | Use [sys.displayhook](http://docs.python.org/2/library/sys#sys.displayhook)
```
import pprint
import sys
orig_displayhook = sys.displayhook
def myhook(value):
if value != None:
__builtins__._ = value
pprint.pprint(value)
__builtins__.pprint_on = lambda: setattr(sys, 'displayhook', myhook)
__buil... | Use [IPython](http://ipython.org/) shell:
```
In [10]: data = {'SHIP_CATEGORY': '', 'SHIP_QUANTITY': 1, 'SHIP_SEPARATELY': 0, 'SHIP_SUPPLEMENT': 0, 'SHIP_SUPPLEMENT_ONCE': 0,}
In [11]: data
Out[11]:
{'SHIP_CATEGORY': '',
'SHIP_QUANTITY': 1,
'SHIP_SEPARATELY': 0,
'SHIP_SUPPLEMENT': 0,
'SHIP_SUPPLEMENT_ONCE': 0}
... | Pretty print by default in Python REPL | [
"",
"python",
"read-eval-print-loop",
""
] |
Is the following piece of SQL Query a normal query or a Correlated Subquery ??
```
SELECT UserID,
FirstName,
LastName,
DOB,
GFName,
GLName,
LoginName,
LoginEffectiveDate,
LoginExpiryDate,
Password,
Email,
ReportingTo,
Mobile,
Co... | Correlated Subquery is a sub-query that uses values from the outer query. In this case the inner query has to be executed for every row of outer query.
See example here <http://en.wikipedia.org/wiki/Correlated_subquery>
Simple subquery doesn't use values from the outer query and is being calculated only once:
```
SE... | Above example is not Co-related Sub-Query. It is Derived Table / Inline-View since i.e, a Sub-query within FROM Clause.
A Corelated Sub-query should refer its parent(main Query) Table in it. For example See find the Nth max salary by Co-related Sub-query:
```
SELECT Salary
FROM Employee E1
WHERE N-1 = (SELECT COUNT(... | Difference between Subquery and Correlated Subquery | [
"",
"sql",
"sql-server",
"subquery",
"correlated-subquery",
""
] |
my problem is that I have to encode a dict to make a couchdb design:
I have this dict:
```
params = {'descending': 'true', 'startkey': 'Mexico', 'endkey': 'Mexico'}
```
I want a URL like this:
```
http://localhost:5984/hello-world/_design/precios/_view/precios?descending=true&startkey=%22Mexico%22&endkey=%22Mexico%... | Couch parameter values are JSON literals, so should be created by JSON-encoding the values. *Then* you need to URL-encode the results of that to fit in a standard URL, as well.
Example:
```
import urllib, json
def to_json_query(params):
return urllib.urlencode({p: json.dumps(params[p]) for p in params})
>>> qs =... | I would suggest writing your own urlencode function. Here's a basic example :
```
params = {"startkey":"Mexico","endkey":"Mexico"}
def myencode(params):
return "&".join(['%s="%s"' %(key,value) for key,value in params.iteritems()])
print myencode(params)
## chaouche@karabeela ~/CODE/TEST/PYTHON $ python test_exe... | CouchDB urlencode Python | [
"",
"python",
"python-2.7",
"couchdb",
"urllib",
"couchrest",
""
] |
```
TABLEA
MasterCategoryID MasterCategoryDesc
1 Housing
1 Housing
1 Housing
2 Car
2 Car
2 Car
3 Shop
TABLEB
ID Description
1 Home
2 ... | Use a CURSOR to do the work. The cursor loops through each row of TableA and the MasterCategoryID increases if it is not found in TableB. This happens before the next row of TableA is loaded into the cursor ...
```
DECLARE @ID int
DECLARE @Description VARCHAR(MAX)
DECLARE my_cursor CURSOR FOR
SELECT ID, Descriptio... | Create a new table your\_table with fields `x_MasterCategoryDesc` ,`x_SubCategoryDesc`
Insert all your values in that table and the run the below **`SP`**.
```
CREATE PROCEDURE x_experiment
AS
BEGIN
IF object_id('TEMPDB..#TABLES') IS NOT NULL
BEGIN
DROP TABLE #TABLES
END
DECLARE @ROWCOUNT INT
... | Insert rows in table while maintaining IDs | [
"",
"sql",
"t-sql",
""
] |
I'm trying to create a program that assigns whatever the person types in response to a certain prompt, it takes up more than two lines and I'm afraid that it's not recognizing the string because it is on separate lines. It keeps popping up with an "Incorrect Syntax" error and keeps pointing to the line below. Any way I... | You need to use [multi-line strings](http://docs.python.org/2/tutorial/introduction.html#strings), or else parentheses, to wrap a string in Python source code. Since your string is already within parentheses, I'd use that fact. The interpreter will automatically join strings together if they appear next to each other w... | I would use multi-line strings, but you also have the following option:
```
>>> print "Hello world, how are you? \
... Foo bar!"
Hello world, how are you? Foo bar!
```
A backslash tells the interpreter to treat the following line as a continuation of the previous one. If you care how your code blocks look, you could ... | Incorrect syntax with a string that takes up more than 1 line Python | [
"",
"python",
"python-2.7",
""
] |
My question seems simple, but for a novice to python like myself this is starting to get too complex for me to get, so here's the situation:
I need to take a list such as:
```
L = [(a, b, c), (d, e, d), (etc, etc, etc), (etc, etc, etc)]
```
and make each index an individual list so that I may pull elements from each... | I might be misreading your question, but I'm inclined to say that you don't actually have to do anything to be able to index your tuples. See my comment, but: `L[0][0]` will give `"a"`, `L[0][1]` will give `"b"`, `L[2][1]` will give `"etc"` etc...
If you really want a clean way to turn this into a list of lists you co... | What you have there is a list of tuples, access them like a list of lists
```
L[3][2]
```
will get the second element from the 3rd tuple in your list L | Python list index splitting and manipulation | [
"",
"python",
"arrays",
"list",
""
] |
This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives 0... | Indexing starts at `0`. So battleships contains items at indexes `0`, `1`, `2`, `3`.
First `len(bships)` gets the length of the list of lists `battleships`, which is 4.
`bships[c-b][a-1]` accesses items in a list through their index value. So with your first call to the function:
```
print(fun(1,1,battleships))
```
... | You can work it out easily by replacing the calculations with the actual values:
In the first call, you are indexing:
```
bships[c-b][a-1] == bships[4-1][1-1] == bships[3][0]
```
Counting from 0, that's the last row, `['0','0','0','0']`, first element, `'0'`.
The second call evaluates to:
```
bships[c-b][a-1] == b... | How does list indexing work? | [
"",
"python",
"list",
"indexing",
""
] |
I do not understand where the value for "line\_count" is passed to this variable. If you can explain it to me I would really appreciate it!! The output prints each successive line. I understand how it increments the line numbers (1, 2, 3, 4), but how it is actually knowing where to get the data to print each string is ... | After rewinding, the file pointer is back at the start of the file.
Each call to `f.readline()` will read one line from `f`.
After this the `f`'s file pointer will be at the start of the next line.
Therefore, the program reads the lines consecutively. | `line_count` is a *parameter* of the function; it gets its value by a caller passing an *argument* when calling the function. In this case, the argument is the value of the `current_line` global variable. | learn python the hard way exercise 20 | [
"",
"python",
""
] |
I need to fix some security issues in a non-IT app that we were assigned to maintain. It's in Microsoft Access front-end (SQL Server back-end).
Does anyone know if SQL Injection can be done via the RecordSource or RowSource property of Microsoft Access controls? For example, if I set a listbox's recordsource to
`Me.S... | If you're doing string concatenation, you're vulnerable. | Could use VBA to eliminate the obvious use of the field name in the WHERE condition.
```
Sub btnLogin_OnClick()
If instr(0, me.txtBox, someFieldName) > 0 Then
Msgbox("Foo Bar!")
Else
Login
End If
End Sub
``` | Microsoft Access SQL Injection | [
"",
"sql",
"vba",
"ms-access",
"sql-injection",
"ms-access-2010",
""
] |
I get some rather unexpected behavior on an expression that works with `==` but not with `is`:
```
>>> (True == False) is False
True
>>> True == (False is False)
True
>>> True == False is False
False
>>> id(True)
8978640
>>> id(False)
8978192
>>> id(True == False)
8978192
>>> id(False is False)
8978640
``` | Because in fact that's a [chained comparison](http://docs.python.org/2/reference/expressions.html#not-in), so
```
True == False is False
```
is equivalent to
```
(True == False) and (False is False)
```
This can be surprising in this case, but lets you write `1 <= x < 4` unlike in other languages like C. | From the [docs](http://docs.python.org/2/reference/expressions.html#not-in):
> x < y <= z is equivalent to x < y and y <= z, except that y is
> evaluated only once (but in both cases z is not evaluated at all when
> x < y is found to be false).
In your case `True == False is False` is equivalent to `True == False and... | Why does `True == False is False` evaluate to False? | [
"",
"python",
""
] |
So I am currently trying to define a function that looks at two strings and tells the user if one string is located in the other, it looks like this:
```
def isIn(x, y):
for x in y:
if x == y:
print "True"
print "x in y"
else:
print "False"
for y in x:
... | I think you're confusing `for ... in` with just plain `in`;
```
def isIn(x,y):
if x in y:
print "True"
print "x in y"
else:
print "False"
if y in x:
print "True"
print "y in x"
else:
print "False"
isIn('5','1')
``` | How about something simpler?
```
def isIn(x, y):
return x in y or y in x
```
If we're dealing with whole strings and we're interested in knowing if one is part of the other, there's no need to iterate over each of their chars - that will only tell you if some char is in both strings.
Now If you really need to kn... | I'm having trouble with the for(x) in (y) function | [
"",
"python",
"python-2.7",
""
] |
How can I get the value from the following strings using one regular expression?
```
/*##debug_string:value/##*/
```
or
```
/*##debug_string:1234/##*/
```
or
```
/*##debug_string:http://stackoverflow.com//##*/
```
The result should be
```
value
1234
http://stackoverflow.com/
``` | Trying to read behind your pattern
```
re.findall("/\*##debug_string:(.*?)/##\*/", your_string)
```
Note that your variations cannot work because you didn't escape the `*`. In regular expressions, `*` mean a repetition of the previous character/group. If you really mean the `*` character, you must use `\*`.
```
impo... | Use this regex:
```
[^:]+:([^/]+)
```
And use capture group #1 for your value.
### Live Demo: <http://www.rubular.com/r/FxFnpfPHFn> | How can I extract two values from a string like this using a regular expression? | [
"",
"python",
"regex",
""
] |
I have an integer list in Python that should correspond to the following int values (which can be changed to hex byte values):
```
[10, 145, 140, 188, 212, 198, 210, 25, 152, 20, 120, 15, 49, 113, 33, 220, 124, 67, 174, 224, 220, 241, 241]
```
However, when I convert that list to a bytearray (using bytearray(nameOfLi... | ```
>>> x = bytearray(b'\n\x91\x8c\xbc\xd4\xc6\xd2\x19\x98\x14x\x0f1q!\xdc|C\xae\xe0
\xdc\xf1\xf1')
>>> import binascii
>>> print(binascii.hexlify(x))
0a918cbcd4c6d2199814780f317121dc7c43aee0dcf1f1
```
Use [binascii](https://docs.python.org/3/library/binascii.html) if you want all of it to be printed as a hex string | Use bytes.hex()
```
>>> x = bytearray([0x01,0x02,0xff])
>>> print(x.hex())
0102ff
``` | Python Bytearray Printing | [
"",
"python",
"python-3.x",
""
] |
I would like to know which is the difference between a query with a join and a query with several tables at the FROM clause.
For example:
```
SELECT *
FROM table1 NATURAL JOIN table2.
```
or
```
SELECT *
FROM table1, table2
WHERE table1.field=table2.field.
```
Thank you so much. | `NATURAL JOIN` compares all columns of both tables and equals those who have the same name and the same type.
So basically, these two SQL statements will do the same operation if and only if the `table1` and `table2` have only one column with the same name and type, and that column is `field`. | An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN return all rows from multiple tables where the join condition is met.
You can do also with WHERE but is to logical with JOIN. Use t... | SQL table combination methods | [
"",
"mysql",
"sql",
"database",
"join",
""
] |
I'm trying to find the number of occurrences of a word in a string.
```
word = "dog"
str1 = "the dogs barked"
```
I used the following to count the occurrences:
```
count = str1.count(word)
```
The issue is I want an exact match. So the count for this sentence would be 0.
Is that possible? | If you're going for efficiency:
```
import re
count = sum(1 for _ in re.finditer(r'\b%s\b' % re.escape(word), input_string))
```
This doesn't need to create any intermediate lists (unlike `split()`) and thus will work efficiently for large `input_string` values.
It also has the benefit of working correctly with punc... | You can use [`str.split()`](http://docs.python.org/2/library/stdtypes.html#str.split) to convert the sentence to a list of words:
```
a = 'the dogs barked'.split()
```
This will create the list:
```
['the', 'dogs', 'barked']
```
You can then count the number of exact occurrences using [`list.count()`](http://docs.p... | Finding occurrences of a word in a string in python 3 | [
"",
"python",
"string",
"count",
"match",
""
] |
I am interested in moving a materialized view from one db to the other, regardless, I also need to change one of the columns. How can I view the original script that build the MV? I am running TOAD, but cannot seem to find the original script.
Thanks in advance! | You can use the function `dbms_metadata.get_ddl`:
```
select dbms_metadata.get_ddl('MATERIALIZED_VIEW', 'MVIEW_NAME') from dual;
``` | I ended up running:
```
select * from all_mviews where mview_name = ‘YOUR_MV_NAME’;
``` | How to view the original script of a materialized view? | [
"",
"sql",
"oracle",
"view",
"materialized",
""
] |
I am trying to add ' at the end and beginning of the string.
I have
```
str1 = 'abc'
str2 = 'def'
strf = str1 + str2
print strf
```
It gives output
```
abcdef
```
I need `'abcdef'`
I have tried join
```
'''.join(strf)
```
what I am trying to achieve here is the variable will be passed to parse an xml, where s... | A string always has quotes around it, without quotes it's not a string.
Use `repr` to see the quotes, `print` always shows the string without quote:
```
>>> str1 = 'abc'
>>> str2 = 'def'
>>> print str1 + str2
abcdef #just a human friendly output, the string still have quotes
>>> print repr(str1 + ... | Why not just:
```
print "'%s'" % strf
```
Or even:
```
print "'" + strf + "'"
``` | How can I concatenate ' in a string using python | [
"",
"python",
"append",
"concatenation",
""
] |
Consider the following simple MySQL query:
```
SELECT date, count(*) cnt, ip
FROM fwlog
GROUP BY ip, date
HAVING cnt>100
ORDER BY date DESC, cnt DESC
```
It gives me something like:
```
date cnt src
2013-06-20 14441 172.16.a
2013-06-20 8887 172.16.b
....
2013-06-19 14606 172.16.b
2013-0... | Try:
```
SELECT a.`date`, count(*) cnt, a.ip
FROM fwlog a
JOIN (SELECT ip, count(*) today_count
FROM fwlog
where `date` = date(now())
group by ip) t
ON a.ip = t.ip and t.today_count > 100
GROUP BY a.ip, a.date
ORDER BY t.today_count DESC, a.ip, a.`date` DESC
``` | You need to add a count for the current date into your `order by` clause. Getting the current date differs among databases. Here is the version for SQL Server:
```
SELECT date, count(*) cnt, ip
FROM fwlog
GROUP BY ip, date
HAVING cnt > 100
ORDER BY SUM(case when date = cast(GETDATE() as date) then 1 else 0 end) desc,... | SQL sort by count with condition, show history | [
"",
"mysql",
"sql",
""
] |
I am trying to parse the following JSON using Python / Django:
```
[
{
"street": "KEELER",
":id": 1421
}
]
```
Within my Django templates, I can successfully access the street key like:
```
{{ obj.street }}
```
but cannot access the id. I have tried the following (all taken from various SO questions):
... | So as @Aya recommended, what I did was dump the JSON to a string, replace all instances of ":id" with "id", then convert it back to JSON. At that point, I was able to access the ID like:
```
{{ obj.id }}
``` | Your object is wrapped in an array.
```
obj = [
{
"street": "KEELER",
":id": 1421
}
]
```
`:id` should be accessed like `obj[0][':id']`. | Parse JSON with colon in key | [
"",
"python",
"django",
"json",
"django-templates",
""
] |
I've got a macro that I'd like a bunch of existing spreadsheets to use. The only problem is that there are so many spreadsheets that it would be too time consuming to do it by hand!
I've written a Python script to access the needed files using pyWin32, but I can't seem to figure out a way to use it to add the macro in... | This is the code converted. You can use either the [win32com](http://sourceforge.net/projects/pywin32/%20pywin32) or [comtypes](http://sourceforge.net/projects/comtypes/?source=dlp%20comtypes) packages.
```
import os
import sys
# Import System libraries
import glob
import random
import re
sys.coinit_flags = 0 # comt... | As I also struggled some time to get this right, I will provide another example which is supposed to work with Excel 2007/2010/2013's `xlsm` format. There is not much difference to the example provided above, it is just a little bit more simple without the looping over different files and with more comments included. B... | Use Python to Inject Macros into Spreadsheets | [
"",
"python",
"excel",
"vbe",
"vba",
""
] |
I have this table:
```
video_id tag_id
10 7
6 7
10 5
6 5
9 5
9 4
10 4
```
I want to write a query which will give me `video_id` which have both `tag_id` 7 and 5. So `video_id` 10 and 6 should be selected, but not 9.
I tried `where tag_id IN (7, 5)` condition but ... | Will it work for you?
```
SELECT video_id
FROM table1
WHERE tag_id iN (7,5)
GROUP BY video_id
HAVING COUNT(DISTINCT tag_id) =2;
```
**Update**.
If you have a unique constraint on (video\_id,tag\_id), no need for `COUNT(DISTINCT)`; `COUNT(*)` will work as well | Arbitrary solution -
Below is an answer for sql server, with mysql you would need a count() on video\_id and then look for rows with the value needed.
I don't have mysql to test but feel free to add an edit of a correct mysql solution.
---
With a table called neededtag with one column (tag) that has the list of wha... | How Do I Write This IN Query | [
"",
"mysql",
"sql",
""
] |
I'm doing a machine learning computations having two dataframes - one for factors and other one for target values. I have to split both into training and testing parts. It seems to me that I've found the way but I'm looking for more elegant solution. Here is my code:
```
import pandas as pd
import numpy as np
import r... | If you make `rows` a boolean array of length `len(df)`, then you can get the `True` rows with `df[rows]` and get the `False` rows with `df[~rows]`:
```
import pandas as pd
import numpy as np
import random
np.random.seed(2013)
df_source = pd.DataFrame(
np.random.randn(5, 2), index=range(0, 10, 2), columns=list('AB... | Below you can find my solution, which doesn't involve any extra variables.
1. Use `.sample` method to get sample of your data
2. Use `.index` method on sample, to get indexes
3. Apply `slice()`ing by index for second `dataframe`
E.g.
Let's say you have X and Y and you want to get 10 pieces sample on each. And it shou... | Sample two pandas dataframes the same way | [
"",
"python",
"pandas",
""
] |
I wanted to have a temporary table that will insert values using select statements. But every time I ran the query, I always got error
> Subquery returns more than 1 value. This is not permitted when the query follows =, !=, <, <=, >, >=, or when the subquery is used as an expression. The statement has been terminated... | In SQLServer2005+ You can use option with [common table expression](http://msdn.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx)
```
DECLARE @tblKeywords TABLE (Keyword1 VARCHAR(MAX), Keyword2 VARCHAR(MAX), Keyword3 VARCHAR(MAX))
;WITH cte AS
(
SELECT Keyword, ROW_NUMBER() OVER (ORDER BY KeywordID) ... | try this
```
DECLARE @tblKeywords TABLE
(
Keyword1 VARCHAR(MAX) ,
Keyword2 VARCHAR(MAX) ,
Keyword3 VARCHAR(MAX)
)
INSERT INTO @tblKeywords
( Keyword1 ,
Keyword2 ,
Keyword3
)
SELECT k ,
( SELECT kk
FROM ( ... | Subquery returns more than 1 value SQL error on multiple selection | [
"",
"sql",
"sql-server",
"database",
"select",
"insert",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.