Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
**Context**: I needed to randomly erase some precise element of a few lists of numbers, extracting some random indexes and saving them in a set called *aleaindex* (done, it properly works, thanks to some SO users' help). Now, I'd like to substitute the old lists *a*, *b*, etc with the new, eventually shorter ones *newa...
This line: ``` a=new_a[:] ``` overwrites the variable `a` with a new object. Outside the function or module, the old object is still pointed at by `a` (or whatever it was called there). Try: ``` new_a = [v for i, v in enumerate(a) if i not in aleaindex] while a: a.pop() a[:] = new_a[:] ``` ### Explanation ...
I do not know what you are trying to do but from your snippets you are clearly lost. Your code does not make much sense and there are more more than one problem. Nonetheless, the problem you asked about - why the list is not fully changed? - seems to be related to this loop: ``` while a: a.pop() a = new_a[:] ``` ...
Why function-modified lists don't change when seen in the main file?
[ "", "python", "list", "function", "" ]
**Context:** I want to replace an object with another: ``` x = [] r = [2] replace(x, r) assert x == [2] assert x is r ``` In Smalltalk this would be called `become` . **Question:** How would I do that? Would I need to create a C-extension or is there already something like this? **I tried:** [This](https://gist.git...
If you want to be able to do this... ``` import pylung pylung.deutsch() import os # I want to preserve object identity with the original os os.ERREICHE_SETZEN os.durchlaufe(...) ``` ...and retain compatibility with existing libraries (which will use the English names), it's probably easiest to add additional attrib...
A simple `=` does what you want: ``` x = [] r = [2] x = r assert x == [2] assert x == r assert x is r ```
Replace object with another in the entire process / become in Python
[ "", "python", "reference", "" ]
I am trying to select the rows from a table by 'group by' and ignoring the first row got by sorting the data by date. The sorting should be done by a date field, to ignore the newest entry and returning the old ones for the group. The table looks like ``` +----+------------+-------------+-----------+ | id | updated o...
Something like the following to get only the rows that are the minimum date for a specific row: ``` select a.ID, a.updated_on, a.group_name, list_name from data a where a.updated_on < ( select max(updated_on) from data group by group_name having group_name = a.group_name ); ``` SQL Fiddle: <http://www.sqlfiddle.co...
You could try using the following query (yes, it has a nested join, but maybe it helps). ``` SELECT ID FROM (select d1.ID FROM data d1 LEFT JOIN data d2 ON (d1.group_name = d2.group_name AND d1.list_name=d2.list_name AND d1.updated_on > d2.updated_on) WHERE d2.ID IS NULL) data_tmp; ``` **CORRECTION:** ``` SELECT ...
Mysql to select rows group by with order by another column
[ "", "mysql", "sql", "" ]
I'm launching a program with `subprocess` on Python. In some cases the program may freeze. This is out of my control. The only thing I can do from the command line it is launched from is `Ctrl``Esc` which kills the program quickly. Is there any way to emulate this with `subprocess`? I am using `subprocess.Popen(cmd, ...
``` p = subprocess.Popen("echo 'foo' && sleep 60 && echo 'bar'", shell=True) p.kill() ``` Check out the docs on the `subprocess` module for more info: <http://docs.python.org/2/library/subprocess.html>
Well, there are a couple of methods on the object returned by `subprocess.Popen()` which may be of use: [`Popen.terminate()`](http://docs.python.org/2/library/subprocess.html#subprocess.Popen.terminate) and [`Popen.kill()`](http://docs.python.org/2/library/subprocess.html#subprocess.Popen.kill), which send a `SIGTERM` ...
Kill a running subprocess call
[ "", "python", "multithreading", "subprocess", "" ]
earlier this week i posted a question on how to change specific words to numbers in a file. As part of my sentiment analysis work. This was not the right method for me unfortunately, i interpreted my data wrong. So i will re ask the question using the right method. I have a specific word list that contains tokens, for...
Here: ``` wordlist = [':)', ':(', 'happy', 'sad'] tweets = ['I find python cool, it makes me happy :)', 'today is a sad day :('] for tweet in tweets: print(' '.join(['1' if word in tweet else '0' for word in wordlist])) ``` Output: ``` 1 0 1 0 0 1 0 1 ```
# Description If you have to do this with regular expressions I'd do this in two parts. **Part 1** would find and replace all the known words with a `1`. Read your known word file into an array, then join the array with the regex or symbol `|`. Then nest that string into the regex. `(?<=^|\s)(\b(?:happy|kittens|[:][...
Changing lines of text into binary type pattern
[ "", "python", "regex", "" ]
I think the question is clear enough. I want to make a hidden Markov model in Python and draw a vizualization model of it. So, it's something like this picture: ![model](https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/HMMGraph.svg/708px-HMMGraph.svg.png) Is there any module to do that? I've googled it and f...
Though I've never worked with Hidden Markov Models, when I need to visualize a graph (directed, with labels, colors, etc.), I use [Gephi](https://gephi.org/), a GUI graph browser/editor and generate the graphs programmatically as [GraphML](http://graphml.graphdrawing.org/) files, which is an XML-based format. Python ha...
The `dot` package from [graphviz](http://www.graphviz.org) is the best I've found. The syntax is simple, simpler than xml.
How to visualize a hidden Markov model in Python?
[ "", "python", "graphics", "hidden-markov-models", "" ]
I have a table `Student` in SQL Server with these columns: ``` [ID], [Age], [Level] ``` I want the query that returns each age value that appears in `Students`, and finds the level value that appears most often. For example, if there are more `'a'` level students aged 18 than 'b' or 'c' it should print the pair `(18, ...
One more option with ROW\_NUMBER ranking function in the ORDER BY clause. WITH TIES used when you want to return two or more rows that tie for last place in the limited results set. ``` SELECT TOP 1 WITH TIES age, level FROM dbo.Student GROUP BY age, level ORDER BY ROW_NUMBER() OVER(PARTITION BY age ORDER BY COUNT(*) ...
You can do this using window functions: ``` select t.* from (select age, level, count(*) as cnt, row_number() over (partition by age order by count(*) desc) as seqnum from student s group by age, level ) t where seqnum = 1; ``` The inner query aggregates the data to count the number of l...
sql query finding most often level appear
[ "", "sql", "sql-server", "" ]
In my data.txt file, there are 2 types of lines. 1. Normal data: 16 numbers separated by spaces with a '\n' appended at the end. 2. Incomplete data: In the process of writing the data into data.txt, the writing-in of the last line is always interrupted by the STOP command. Thus, it is always incomplete, e.g.it can hav...
To answer your 'b' question. Assume you have this file (called '/tmp/lines.txt'): ``` line 1 2013:10:15 line 3 line 4 2010:8:15 line 6 ``` You can use the [linecache](http://docs.python.org/2/library/linecache.html?highlight=linecache) module: ``` >>> import linecache >>> linecache.getline('/tmp/lines.txt', 2) '201...
You can try [pandas](http://pandas.pydata.org/) which provides a use function [read\_csv](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html) to load the data more easily. Example data: ``` a b c d e f g h i j k l m n o p a b c d e f g h i j k l m n o p a b c d e f g h i j k l m n o...
numpy - Python - Selectively import parts of the .txt file
[ "", "python", "numpy", "analysis", "" ]
I'm using python 2.6 current output ``` mylist = [('log:A', '1009.2'), ('log:B', '938.1'), ('log:C', '925.7'), ('log:C', '925.7')] ``` I'am trying to add the values to produce the follow: Ranked highest to lowest. The problem I'am having is adding everthing with a log:C tag together. and not outputting it twice. ```...
Using `collections.defaultdict`: ``` >>> strs = "log:A 22 log:B 44 log:C 74 log:D 24 log:B 10" >>> from collections import defaultdict >>> dic = defaultdict(int) >>> it = iter(strs.split()) >>> for k in it: ... dic[k] += int(next(it)) ... >>> for k,v in sorted(dic.items(), key = lambda x: x[1], reverse = Tru...
``` mystr = 'log:A 22 log:B 44 log:C 74 log:D 24 log:B 10' li=mystr.split() res={} for k,v in zip(li[::2],li[1::2]): res.setdefault(k,[]).append(int(v)) print res ``` Prints: ``` {'log:D': [24], 'log:A': [22], 'log:C': [74], 'log:B': [44, 10]} ``` Then just sum them: ``` for k in sorted(res): print k, sum...
python matching list items
[ "", "python", "string", "parsing", "dictionary", "" ]
So I have this function. ``` def test(fourBits): binaryDigits = fourBits if binaryDigits[1] == 1: print 'test' ``` If I enter `test('1111')` it won't print `test`. I don't understand why it is not?
Use this: ``` if int(binaryDigits[1]) == 1: ``` or this: ``` if binaryDigits[1] == '1': ``` so that the types match, i.e., compare two characters or two numbers.
binaryDigits[1] is a string, 1 is an integer
Why won't my function print
[ "", "python", "printing", "" ]
I need to do something like this, but in Python instead of Bash: ``` i=1 while [ $i <= 10 ] ; do wget http://somewebsite.net/shared/fshared_$i.7z $i = $i + 1 done ``` In Python I tried with the following: ``` import urllib, os i = 0 while i <= 3: os.system('wget http://somewebsite.net/shared/fshared_',i,...
Try ``` os.system('wget http://somewebsite.net/shared/fshared_%s.7z'%i) ``` use `%s` instead of `,`
You **can** increment in Bash. You have to do something like: ``` i=3 (( i++ )) echo $i ``` That last like should print 4. So your script would be: ``` i=1 while [ $i -le 10 ] ; do wget http://somewebsite.net/shared/fshared_$i.7z (( i++ )) done ``` Edit: fixed code to use `-le` instead of `<=` since `<=` do...
How to download with wget in Python using variables?
[ "", "python", "bash", "wget", "" ]
Is there a way in python such that given a python class: ``` class Foo(object): apple = None orange = None def __init__(self, apple=None, orange=None) super(Foo, self).__init__() self.apple = apple self.orange = orange ``` after a Foo object is **init**, one of the two attributes (...
In the constructor, it's simple enough to `raise` a `ValueError` if they are both `None` or both set. The problem is later on in the code. Following the principle of least surprise, I think you should mark the variables private and use setter methods (not property setter, plain old methods). This clearly suggests you'...
Something like ``` if !((self.apple==None)^(self.orange==None)) // some error ``` Might do the trick... ^ is the XOR operator, which returns true if one, but not both, of the operands are true.
Force one of two python class attributes to be always be assigned a value?
[ "", "python", "" ]
I know, that ``` map(function, arguments) ``` is equivalent to ``` for argument in arguments: function(argument) ``` Is it possible to use map function to do the following? ``` for arg, kwargs in arguments: function(arg, **kwargs) ```
You can with a lambda: ``` map(lambda a: function(a[0], **a[1]), arguments) ``` or you could use a generator expression or list comprehension, depending on what you want: ``` (function(a, **k) for a, k in arguments) [function(a, **k) for a, k in arguments] ``` In Python 2, `map()` returns a list (so the list compre...
For the case of positional arguments only, you can use `itertools.starmap(fun, args)`: > Return an iterator whose values are returned from the function evaluated with a argument tuple taken from the given sequence. Example: ``` from itertools import starmap def f(i, arg): print(arg * (i+1)) for _ in starmap(f,...
Python `map` and arguments unpacking
[ "", "python", "map-function", "" ]
I'm having a fairly difficult time using `mock` in Python: ``` def method_under_test(): r = requests.post("http://localhost/post") print r.ok # prints "<MagicMock name='post().ok' id='11111111'>" if r.ok: return StartResult() else: raise Exception() class MethodUnderTestTest(TestCase):...
You need to use [`return_value`](https://docs.python.org/3/library/unittest.mock.html?highlight=return_value#unittest.mock.Mock.return_value) and [`PropertyMock`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.PropertyMock): ``` with patch('requests.post') as patched_post: type(patched_post.ret...
A compact and simple way to do it is to use `new_callable` `patch`'s attribute to force `patch` to use `PropertyMock` instead of `MagicMock` to create the mock object. The other arguments passed to `patch` will be used to create `PropertyMock` object. ``` with patch('requests.post.ok', new_callable=PropertyMock, retur...
Mock attributes in Python mock?
[ "", "python", "unit-testing", "testing", "mocking", "python-mock", "" ]
I have 2 tables in my database: `BusLines` & `BusStops`. Each instance of `BusLines` can have many stops associated with it, in a particular order. To make the associations easier to manage (delete or add new stops in an existing line), the associative table has been designed with the following structure: `id_BusLine ...
**Solutions for SQL Server 2008-2012, PostgreSQL 9.1.9, Oracle 11g** Actually, recursive CTE is a solution for almost all current RDBMS, including PostgreSQL (explanations and example shown below). However there is another better solution (optimized) for Oracle DBs: hierarchical queries. NOCYCLE instructs Oracle to r...
If using sql server then I think a recursive cte like this works ``` ;WITH route AS ( SELECT BusLineId, BusStopId, NextBusStopId FROM BusLine_BusStop WHERE IsFirstStop = 1 UNION ALL SELECT b.BusLineId, b.BusStopId, b.NextBusStopId FROM BusLine_BusStop b INNER JOIN route r ON r.BusLineId = b.Bus...
Order SQL request when each row contains id of the next one
[ "", "sql", "postgresql", "request", "" ]
I have written some code in Python that checks for an MD5 hash in a file and makes sure the hash matches that of the original. Here is what I have developed: ``` # Defines filename filename = "file.exe" # Gets MD5 from file def getmd5(filename): return m.hexdigest() md5 = dict() for fname in filename: md5...
In regards to your error and what's missing in your code. `m` is a name which is not defined for `getmd5()` function. No offence, I know you are a beginner, but your code is all over the place. Let's look at your issues one by one :) First, you are not using `hashlib.md5.hexdigest()` method correctly. Please refer ex...
In Python [3.8+](https://docs.python.org/whatsnew/3.8.html#assignment-expressions) you can do ``` import hashlib with open("your_filename.png", "rb") as f: file_hash = hashlib.md5() while chunk := f.read(8192): file_hash.update(chunk) print(file_hash.digest()) print(file_hash.hexdigest()) # to get a...
How do I calculate the MD5 checksum of a file in Python?
[ "", "python", "md5", "md5sum", "" ]
Reading "Learn Python the Hard Way", I am playing with Exercise 10 ``` tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ print tabby_cat print persian_cat print backslash_cat print f...
``` fat_cat = """ <-- here? I'll do a list: ``` That is, ``` fat_cat = """I'll do a list: ... ``` removes it.
Because `print` always puts a newline (by default), the reason you've got another new line between the 3rd and fourth is that it contains an explicit `\n` ``` print fat_cat, ``` The above suppresses the implicit newline for the final output.
Where do this new line come from?
[ "", "python", "python-2.7", "" ]
[Using Python 3.x] I'm trying to create a CSV file with two columns, one containing fake e-mail addresses, the second column should contain a certain country code as specified in the respective function. I would like the country codes to be - at least - uniformly distributed assigned to each e-mail address. But it wou...
If you have percentages per country code, simply expand the countries list until you have enough elements, then shuffle the list: ``` cc = [('us', .2), ('gb', .2), ('de', .1), ('fr', .05), ('it', .05)] distribution = n / sum(dist for c, dist in cc) countries = [] for c, dist in cc: countries.extend([c] * int(round...
You are trying to **abuse** the `zip` function. In your case using a genexp or dict-comprehension is straightforward: ``` def gen_email_dict(n): return {get_email(): choice(cc) for _ in range(n)} #return dict((get_email(), choice(cc)) for _ in range(n)) # python2 ``` The `zip` function should be used only wi...
Zip two lists of unequal length to form a dictionary. Values to be randomly picked from one of the lists
[ "", "python", "python-3.x", "" ]
I have a Pandas data frame and one of the columns, have dates in string format of `YYYY-MM-DD`. For e.g. : `'2013-10-28'` At the moment the `dtype` of the column is `object`. How do I convert the column values to Pandas date format?
Use [astype](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html) ``` In [31]: df Out[31]: a time 0 1 2013-01-01 1 2 2013-01-02 2 3 2013-01-03 In [32]: df['time'] = df['time'].astype('datetime64[ns]') In [33]: df Out[33]: a time 0 1 2013-01-01 00:00:00...
Essentially equivalent to @waitingkuo, but I would use `pd.to_datetime` here (it seems a little cleaner, and offers some additional functionality e.g. `dayfirst`): ``` In [11]: df Out[11]: a time 0 1 2013-01-01 1 2 2013-01-02 2 3 2013-01-03 In [12]: pd.to_datetime(df['time']) Out[12]: 0 2013-01-01 0...
How to convert Pandas Series of dates string into date objects?
[ "", "python", "pandas", "date", "time-series", "" ]
i am running a flask project and i am looking for a way to create a directory ABOVE the path from which the current App is running. For example: ``` dirA --> dirBinA --> peter.py griffin.sh dirCinA --> index.py <--------- this is the flask app that's running tom.css dick...
In order to create a new 2-level-depth directory, you need to create it in ***TWO*** steps. For instance, if `../dirDinA` doesn't yet exist, then the following command fails. ``` os.mkdir("../dirDinA/anotherDir") ``` It produces the `OSError: No such file or directory`, misleadingly, showing you the ***FULL*** path t...
You can use [os.makedirs](https://docs.python.org/3/library/os.html?highlight=makedir#os.makedirs) to create multiple directory levels in a single call: ``` os.makedirs("../dirDinA/anotherDir") ```
how to os.mkdir() above current root path in python
[ "", "python", "path", "flask", "mkdir", "" ]
I have a number of classes and corresponding feature vectors, and when I run predict\_proba() I will get this: ``` classes = ['one','two','three','one','three'] feature = [[0,1,1,0],[0,1,0,1],[1,1,0,0],[0,0,0,0],[0,1,1,1]] from sklearn.naive_bayes import BernoulliNB clf = BernoulliNB() clf.fit(feature,classes) clf....
Just use the `.classes_` attribute of the classifier to recover the mapping. In your example that gives: ``` >>> clf.classes_ array(['one', 'three', 'two'], dtype='|S5') ``` And thanks for putting a minimalistic reproduction script in your question, it makes answering really easy by just copy and pasting in a ...
``` import pandas as pd test = [[0,1,1,0],[1,1,1,0]] pd.DataFrame(clf.predict_proba(test), columns=clf.classes_) Out[2]: one three two 0 0.542815 0.361876 0.095309 1 0.306431 0.612863 0.080706 ```
How to find the corresponding class in clf.predict_proba()
[ "", "python", "machine-learning", "scikit-learn", "" ]
I have a table with the points `X` and `Y`. I need to find the `X` and `Y` point closest to the origin `(0, 0)`. I am trying this way: ``` SELECT * FROM `line` WHERE xi < yi and 0 < xi and 0 < yi and yi < xi ORDER BY yi and xi ASC Limit 100 ``` But I am not getting the desired values.
The distance to the origin is given by `sqrt(xi^2 +yi^2)`. Since a square root is strictly ascending, you can omit it for the purpose of ordering. That gives: ``` SELECT * FROM `line` ORDER BY xi*xi + yi*yi Limit 100 ```
You need to calculate the distance `d = sqrt(x²+y²)` to get the nearest point from the origin ``` select x, y, sqrt(x*x + y*y) as distance from `line` order by distance asc limit 1 ```
Closest two values from certain value
[ "", "mysql", "sql", "" ]
After some searching and trawling through the IPython [documentation](http://ipython.org/ipython-doc/rel-0.12/config/ipython.html) and some [code](https://github.com/ipython/ipython), I can't seem to figure out whether it's possible to store the command history (*not* the output log) to a **text file** rather than an S...
You can emulate bash's behavior by adding this in one of your startup scripts (e.g. `$(ipython locate profile)/startup/log_history.py`: ``` import atexit import os ip = get_ipython() LIMIT = 1000 # limit the size of the history def save_history(): """save the IPython history to a plaintext file""" histfile =...
You can export all of your history in IPython to a text file with the [**%history**](https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-history) magic like this: ``` %history -g -f filename ``` One way of getting what you want might be to do that export in a [git hook](https://git-scm.com/book/en/...
How to log IPython history to text file?
[ "", "python", "configuration", "ipython", "" ]
I have a Django application with a Publication model and a Tag model. Each publication has one or more Tags associated with it. I want to query the database with a set of two Tags and have returned only publications that have BOTH of those tags. I cannot seem to find the syntax for this although I am certain it is rea...
``` pubs_for_tags = Publication.objects.filter(tags__title__istartswith=q).filter( tags__title__istartswith=q2) ``` or ``` pubs_for_tags = Publication.objects.filter(Q(tags__title__istartswith=q), Q( tags__title__istartswith=q2)) ```
I know this is old, but I just ran into the same problem and realized it points at an (as far as I know) undocumented aspect of using Django filters across one-to-many or many-to-many relations. Two conditions made within the same filter apply to the *same* related object. Two conditions made in separate filters can ma...
And Condition Django Query Using Same Keyword
[ "", "sql", "django", "django-filter", "" ]
I am attempting to write a quick piece of code that will check to see if a directory exists, if it does it will print that it does, if it does request permission to overwrite, and if not prompt to make the directory. Here is what I have so far: ``` def mk_prjDir(): print "Checking to see if", prjDir, "exists.." ...
Firstly `prjDir` must be a full path to `prjDir`, i.e "\home\my\_direc\", othwerise `os.listdir` will try to find `prjDir` in the current working directory of the script. Secondly as `os.listdir` returns only file/directory names not the full path, so to get the full path you can use `os.path.join(prjDir,d)`. ``` imp...
`os.listdir(dir)` returns you a list of files found in the directory `dir`. As the error says, this directory does not exists, so, obviously, `listdir` can't list its contents. Why are you doing this loop? Just use `os.path.isdir` to test if your directory exists.
Python: If statement with exception using os.path.isdir?
[ "", "python", "scripting", "os.path", "" ]
So I've got this to find out if a process is running or not: ``` os.system("ps aux | grep [my]process") ``` I use the square brackets so I don't get back the grep command too. Altho when I try to do something like ``` 'yes' if os.system("ps aux | grep [my]process") else 'no' ``` I always get no, even if in fact py...
Use `subprocess.call()` or `subprocess.check_call()`
You have the logic the wrong way round. `grep` is returning `0` when there are some matching lines using the `subprocess` module is a better idea anyway. You can get the output of `ps aux` and examine it in your program. Although parsing the output of ps is always going to be fairly fragile eg: ``` import subprocess...
python: output of os.system is not considered for a true/false check?
[ "", "python", "" ]
I am 2 result sets from the below query which I want to 'combine' the results into 1 single table but not sure how to proceed from here, can someone please kindly provide some guidance: ``` SELECT userid, vehicleId, count(vehicleId) As SearchCount FROM MemberSearches GROUP BY userid, vehicleId ORDER BY count(vehicle...
Not efficient, just test its working... ``` SELECT userid, vehicleId, SUM(SearchCount) As SearchCount FROM (SELECT userid, vehicleId, count(vehicleId) As SearchCount FROM MemberSearches GROUP BY userid, vehicleId UNION ALL SELECT f.UserId, v.AutoId AS VehicleId, count(v.AutoId) AS SearchCount FROM Favorites f LEF...
``` SELECT userid, vehicleId, count(*) As SearchCount FROM ( SELECT userid, vehicleId FROM MemberSearches UNION ALL SELECT f.UserId, v.AutoId FROM Favorites f LEFT JOIN [SellPost] sp ON (f.PostId = sp.AutoId) LEFT JOIN [Vehicle] v ON (sp.CarId = v.AutoId) ) AS X GROUP BY userid, vehic...
SQL Server + 'Merging results'
[ "", "sql", "sql-server", "" ]
I am doing a report whereby I can't construct the SQL programatically. I have two values that are fed into the report. The values that can be one of the following three options: 1. redeem 2. purchase 3. redeem AND purchase The query needs to have a WHERE clause. If "redeem" is fed in, it must have: ``` ... WHERE bal...
Yep. You're almost there. ``` WHERE (param='redeem' and balance <=0) or (param='purchase' and balance>=0) or (param='redeem AND purchase ') ```
Use `CASE` statements in your `WHERE` clause. You can find examples [here](http://www.devx.com/tips/Tip/15633). I tried the following code in MySQL and it works: ``` SET @param = 'purchase'; SELECT * FROM TEST.ACCOUNT WHERE CASE WHEN @param = 'redeem' THEN BALANCE < 0 WHEN @param = 'purchase' THEN BALANCE >=...
Conditional where in SQL based on Value?
[ "", "mysql", "sql", "" ]
I've got functions, which sometimes return NaNs with `float('nan')` (I'm not using numpy). How do I write a test for it, since ``` assertEqual(nan_value, float('nan')) ``` is just like `float('nan') == float('nan')` always false. Is there maybe something like `assertIsNan`? I could not find anything about it…
I came up with ``` assertTrue(math.isnan(nan_value)) ```
`math.isnan(x)` will raise a `TypeError` if `x` is neither a `float` nor a `Real`. It's better to use something like this : ``` import math class NumericAssertions: """ This class is following the UnitTest naming conventions. It is meant to be used along with unittest.TestCase like so : class MyTest...
How to check if value is nan in unittest?
[ "", "python", "unit-testing", "assert", "nan", "" ]
i'm using oracle 11 and i need to display the "orders" from last month, where the date of each order has already been set. tables are: name: Store order ``` OrderNo OrderDate ------- ---------- ST1 03-MAY-12 ST2 03-APR-13 ST3 15-APR-13 ``` so ideally, what it should return is both ST2 and ST3, as ...
using @Grisha's answer ``` select * from orders where to_char(OrderDate,'MM') = to_char(add_months(sysdate,-1),'MM') ```
This should be able to use indexes well since it does no per row calculations on the rows in orders; ``` WITH cte AS ( SELECT MAX(OrderDate) orderdate FROM orders ) SELECT * FROM orders o, cte WHERE o.OrderDate >= TRUNC(cte.orderdate,'MM') AND o.OrderDate < LAST_DAY(cte.orderdate)+1 ``` [An SQLfiddle to test with]...
SQL pull values from "last month" when dates have already been declared
[ "", "sql", "oracle", "" ]
I want to write a function that takes a file as a string, and returns True if the file has duplicate words and False otherwise. So far I have: ``` def double(filename): infile = open(filename, 'r') res = False l = infile.split() infile.close() for line in l: #if line is in l twice ...
Use a set to detect duplicates: ``` def double(filename): seen = set() with open(filename, 'r') as infile: for line in l: for word in line.split(): if word in seen: return True seen.add(word) return False ``` You could shorten that t...
The [*str.split()*](http://docs.python.org/2.7/library/stdtypes.html#str.split) method doesn't work well for splitting words in natural English text because of apostrophes and punctuation. You usually need the power of [regular expressions](http://docs.python.org/2.7/library/re.html) for this: ``` >>> text = """I ain'...
How to determine if word in string is a double word?
[ "", "python", "python-3.x", "" ]
I am learning bash script and python for my project, I wants to Kill the terminal after completion of its execution. I run my process on one terminal and when I execute it it open a new terminal and do requested operation and later after completion new terminal have to be closed which is not happening. My code is: ```...
A terminal closes when its last child process exits. This will do what I think you want: ``` os.system("xfce4-terminal -e 'bash -c \"echo hello ; /bin/bash ; exit 0\"'") ``` which I tested. **Added in response to comment** There is a shell script in Ubuntu `/usr/bin/usb-devices` which prints to stdout and then exit...
Let's back up and look carefully at the one main line of code you posted: ``` os.system(""xfce4-terminal -e 'bash -c \"./testing.sh; exec bash\"'") ``` What does it do? * It uses Python to invoke a shell (`os.system`), which is usually not a great idea for a host of reasons. * Inside that shell, it launches xfce4-te...
How to kill a terminal after completion of process
[ "", "python", "bash", "shell", "ubuntu", "" ]
[**get()**](https://docs.python.org/3/library/queue.html#queue.Queue.get) removes and returns an item from **Queue** in Python. ``` import queue q = queue.Queue() # Here q.put("Apple") q.put("Orange") q.put("Banana") print(q.get()) print(q.get()) print(q.get()) ``` Output: ``` Apple Orange Banana ``` Now, I want...
> The `Queue` module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. As you can see, the `Queue` module was created specifically for use with threads, providing only *FIFO*, *LIFO* and *priority queues...
queue\_object.queue will return copy of your queue in a deque object which you can then use the slices of. It is of course, not syncronized with the original queue, but will allow you to peek at the queue at the time of the copy. There's a good rationalization for why you wouldn't want to do this explained in detail i...
How to get the items in Queue without removing the items?
[ "", "python", "data-structures", "queue", "" ]
Two's complement is when you inverse bits then add a binary 1 digit. So for example... ``` 0011001 apply two's complement 1. inverse the bits, 1100110 2. add a binary digit, 1100110 + 1 = 1100111 ``` Another example to show overflow situation... ``` 1001100 apply two's complement 1. inverse the bits, 0110011 2. add ...
``` x=int(a,2) num_bits = 10 print x - (1 << num_bits) ``` I think this should solve the problem
Try this: ``` x = 0b11001100 complement = abs(~x) + 0b1 print bin(complement) ```
Python - Most effective way to implement two's complement?
[ "", "python", "performance", "twos-complement", "" ]
I have a table (n2m) that contains authors' ids and their articles' ids. I'm counting number of authors who have just one article in the table. I'm using the following query: ``` select count(*) from authors_articles where AutID in ( select AutID from authors_articles group by AutID having co...
Your query can be simplified to: ``` select count(*) from ( select AutID from authors_articles group by AutID having count(distinct articleID) = 1 ) x ```
I think it can be even simpler: ``` SELECT count(*) num_articles FROM authors_articles GROUP BY AutID HAVING num_articles = 1 ```
Counting authors with just one article
[ "", "mysql", "sql", "" ]
I am trying to do the following, in a clear pythonic way: ``` def remove_prefix(str, prefix): return str.lstrip(prefix) print(remove_prefix('template.extensions', 'template.')) ``` This gives: ``` xtensions ``` Which is not what I was expecting (`extensions`). Obviously (stupid me), because I have used [lstrip...
For Python 3.9+: ``` text.removeprefix(prefix) ``` For older versions, the following provides the same behavior: ``` def remove_prefix(text, prefix): if text.startswith(prefix): return text[len(prefix):] return text ```
Short and sweet: ``` def remove_prefix(text, prefix): return text[text.startswith(prefix) and len(prefix):] ```
Remove a prefix from a string
[ "", "python", "" ]
I'm fairly new to Python, and think this should be a fairly common problem, but can't find a solution. I've already looked at [this page](https://stackoverflow.com/questions/3459098/create-list-of-single-item-repeated-n-times-in-python) and found it helpful for one item, but I'm struggling to extend the example to mult...
You can use `zip` and a list comprehension here: ``` >>> a = ['x','y','z'] >>> b = [1,2,3] >>> [[x]*y for x,y in zip(a,b)] [['x'], ['y', 'y'], ['z', 'z', 'z']] ``` or: ``` >>> [[x for _ in xrange(y)] for x,y in zip(a,b)] [['x'], ['y', 'y'], ['z', 'z', 'z']] ``` `zip` will create the whole list in memory first, to g...
The fastest way to do it is with [*map()*](http://docs.python.org/2.7/library/functions.html#map) and [*operator.mul()*](http://docs.python.org/2.7/library/operator.html#operator.mul): ``` >>> from operator import mul >>> map(mul, [['x'], ['y'], ['z']], [1, 2, 3]) [['x'], ['y', 'y'], ['z', 'z', 'z']] ```
Creating list of individual list items multiplied n times
[ "", "python", "arrays", "list", "loops", "emcee", "" ]
``` table : metrics ``` columns: ``` 1. name : Name 2. instance: A name can have several instances (Name: John, Instances: John at work, John at concert) 3. metric: IQ, KQ, EQ 4. metric_value: Any numeric ``` Objective of the query Find out the metrics whose `metric_value` is 0 for all instances for all names. Na...
Are you looking for something like this? ``` SELECT metric FROM metrics GROUP BY metric HAVING SUM(metric_value) = 0 ``` Here is **[SQLFiddle](http://sqlfiddle.com/#!2/f0e3a5/1)** demo **UPDATE** If metric\_value can have negative values then use this one ``` SELECT metric FROM metrics GROUP BY metric HAVING ...
Even though this looks suspiciously like homework.... see if this gives you what you're after: ``` SELECT DISTINCT M1.Metric FROM METRICS M1 WHERE NOT EXISTS ( SELECT * FROM METRICS M2 WHERE M2.Metric <> 0 AND M1.Metric = M2.Metric ) ```
SQL Help: Complex query
[ "", "sql", "" ]
I'm getting this error on a SQL user defined function: > An expression of non-boolean type specified in a context where a > condition is expected, near ')'. For this: ``` UPDATE LMI_Contact SET Phone = NULL WHERE dbo.LMI_IsSingleCharacterRepeated(Phone, '0') ``` where the function can be created using: ``` -- ***t...
You must use comparison operators against functions even if the return type is `bit`. ``` UPDATE LMI_Contact SET Phone = NULL WHERE dbo.LMI_IsSingleCharacterRepeated(Phone, '0') = 1 ```
Try This ``` CREATE FUNCTION LMI_IsSingleCharacterRepeated (@str varchar(max), @char char(1)) RETURNS BIT AS BEGIN DECLARE @indx int DECLARE @len int DECLARE @currentChar char(1) SET @indx = 1 SET @len= LEN(@str) WHILE @indx <= @len BEGIN SET @currentChar = SUBSTRING(@str, @indx, ...
SQL User Defined Function Generates a Non-Boolean Type Error
[ "", "sql", "function", "boolean", "where-clause", "" ]
I have a character (eg. "a") and I need to check a string (eg. "aaaabcd") for the number of occurances of "a" in a row (processing stops at "b" in this case and returned value is 4). I have something like this: ``` def count_char(str_, ch_): count = 0 for c in str_: if c == ch_: count += 1 else: ...
The `re.match` function will start looking in the beginning of the string ``` m = re.match(r'[%s]+' % ch_, str_) return m.end() if m else 0 ``` If you want the biggest number of chars in any part of the string: ``` max(len(x) for x in re.findall(r'[%s]+' % ch_, str_)) ```
One option using [`itertools.takewhile`](http://docs.python.org/2/library/itertools.html#itertools.takewhile), ``` >>> from itertools import takewhile >>> str_ = 'aaaabcd' >>> ch_ = 'a' >>> sum(1 for _ in takewhile(lambda x: x == ch_, str_)) 4 ```
Number of the same characters in a row - python
[ "", "python", "string", "" ]
How can I return records where I did not have sales for a month e.g July 2004? User will supply a date say July 2004 then I need to see the products where there was no sales. ``` SELECT DP.ProductID ,DP.Name ,FS.OrderDate ,FS.OrderQty ,FS.OrderAmount FROM dbo.DimProduct AS DP LEFT JOIN dbo.FactSales as FS on FS....
``` SELECT DP.* FROM dbo.DimProduct AS DP LEFT JOIN dbo.FactSales as FS ON FS.ProductID = DP.ProductID AND DATENAME(month, FS.OrderDate) = 'July' AND YEAR(FS.OrderDate) = 2004 WHERE FS.ProductID IS NULL ```
Maybe this solve your problem: ``` SELECT DP.ProductID ,DP.Name ,FS.OrderDate ,FS.OrderQty ,FS.OrderAmount FROM dbo.DimProduct AS DP LEFT JOIN dbo.FactSales as FS on FS.ProductID = DP.ProductID WHERE FS.OrderAmount == 0 ```
Return products where there was no sales for month
[ "", "sql", "t-sql", "" ]
How can I do a search AND REPLACE a string. To be more specific. I have a text file with ``` SAMPLE AB CD .. TYPES AB QP PO .. RUNS AB DE ZY ``` I want to replace `AB` with `XX`, only under lines `SAMPLE` and `RUNS`. I've already tried multiple ways of using `replace()`. I tried something lik...
A file is an iterator over lines in Python: ``` for line in file: output.write(line) # save as is if 'SAMPLE' in line or 'RUNS' in line: line = next(file, "") # move to the next line output.write(line.replace('AB', 'XX')) # save replacing AB with XX ``` To support SAMPLE/RUNS lines that follows ...
The easiest way will be to iterate your file line by line, and each time you see a `SAMPLE` or `RUNS` line to save a flag meaning “the previous line was the one I was looking for”. Any other line will reset this flag. Now on every iteration you check if the flag was set during the previous iteration, and if it was you ...
Search and replace string under specific line
[ "", "python", "replace", "find", "" ]
I have two MySQL tables that are relational based on an ID number. I need to select the count of the IDs in the first table that do NOT match any ID in the second table. This is what I tried: ``` SELECT COUNT(DISTINCT(ask_questions.id)) FROM ask_questions INNER JOIN ask_answers ON ask_questions.id != ask_answers.que...
use `LEFT JOIN` since you want to get `ID` that do not have atleast a match on the other table. ``` SELECT COUNT(DISTINCT(ask_questions.id)) FROM ask_questions LEFT JOIN ask_answers ON ask_questions.id = ask_answers.question_id WHERE ask_answers.question_id IS NULL ``` To further gain mor...
Use `NOT IN` ``` SELECT COUNT(ask_questions.id) FROM ask_questions WHERE ask_questions.id NOT IN(SELECT question_id FROM ask_answers) ```
How to select COUNT of one table column where there are no matches in another table column
[ "", "mysql", "sql", "" ]
My actual example is more involved so I boiled the concept down to a simple example: ``` l = [1,2,3,4,5,6,7,8] for number in l: calc = number*10 print calc ``` For each iteration of my loop, I end up with a variable (`calc`) I'd like to use to populate a new list. My actual process involves much more than mu...
Here's how to do it without jumping straight into list comprehensions. It's not a great idea to use `l` as a variable name because it is identical to `1` in some fonts, so I changed it (althought `l1` isn't really much better :) ) ``` l1 = [1,2,3,4,5,6,7,8] l2 = [] for number in l1: calc = number*10 print calc...
There are several options... ## List comprehensions Use [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions), if short enough: ``` new_list = [number * 10 for number in old_list] ``` ## `map()` You could also use `map()`, if the function exists before (or you will eg. use...
How to generate new list from variable in a loop?
[ "", "python", "" ]
I want to read a .xlsx file using the Pandas Library of python and port the data to a postgreSQL table. All I could do up until now is: ``` import pandas as pd data = pd.ExcelFile("*File Name*") ``` Now I know that the step got executed successfully, but I want to know how i can parse the excel file that has been re...
I usually create a dictionary containing a `DataFrame` for every sheet: ``` xl_file = pd.ExcelFile(file_name) dfs = {sheet_name: xl_file.parse(sheet_name) for sheet_name in xl_file.sheet_names} ``` --- Update: In pandas version 0.21.0+ you will get this behavior more cleanly by passing [`sheet_name=None`...
``` pd.read_excel(file_name) ``` sometimes this code gives an error for xlsx files as: `XLRDError:Excel xlsx file; not supported` instead , you can use `openpyxl` engine to read excel file. ``` df_samples = pd.read_excel(r'filename.xlsx', engine='openpyxl') ```
How to read a .xlsx file using the pandas Library in iPython?
[ "", "python", "pandas", "ipython", "jupyter-notebook", "dataframe", "" ]
I have a list of filenames as follows ``` files = [ '/dl/files/4j55eeer_wq3wxxpiqm.jpg', '/home/Desktop/hjsd03wnsbdr9rk3k', 'kd0dje7cmidj0xks03nd8nd8a3', ... ] ``` The problem is most of the files do not have an extension in the filenames, what would be the best way to get file extension of these file...
Once you use `magic` to get the MIME type, you can use [`mimetypes.guess_extension()`](http://docs.python.org/2/library/mimetypes.html#mimetypes.guess_extension) to get the extension for it.
It can be done if you have an oracle that determines file types from their content. Happily at least one such oracle is already implemented in Python: <https://github.com/ahupp/python-magic>
How can i get a file extension from a filetype?
[ "", "python", "file", "" ]
I'm working on the GUI for a simple quiz app using Tkinter in Python 2.7. Thus far, I have begun to set up my frame. I've put a scrollbar inside of a Text widget named `results_txtbx` to scroll up and down a list noting the player's performance on each question. I've been using `grid` since it's easier for me to manage...
You don't want to use a text widget as the master for a scrollbar. Like any other widget, if you pack or grid the scrollbar in the text widget, the text widget will shrink or expand to fit the scrollbar. That is the crux of your problem. Instead, create a separate frame (which you're already doing), and use that frame...
Set `results_scrbr.grid(row = 3, column = 2)` next to `results_txtbx.grid(row = 3,column = 1, padx = 4)`, `sticky` is not needed because window is not resizable, and i lowered the padx so scrollbar is closer to text. Also to make the results\_txtbx vertically scrollable, add `results_scrbr.config(command=results_txtbx...
Tkinter - Text widget shrinks when Scrollbar is added
[ "", "python", "python-2.7", "tkinter", "" ]
I need your help, I have a structure like this: ``` myList = [(1,2,3),(2,4,4),(1,5,6)] ``` It's a list of tuples. Now I need to get every first element of each tuple in the list to e.g. replace each `1` with a `3`. The output should be: `myList = [(3,2,3),(2,4,4),(3,5,6)]` I know I can make it like: ``` for item i...
``` >>> myList = [(1,2,3,4,5,6),(4,5,6,7,8)] >>> dic = {1:3} >>> [ (dic.get(x[0],x[0]),) + x[1:] for x in myList] [(3, 2, 3, 4, 5, 6), (4, 5, 6, 7, 8)] ``` If `myList` is a list of lists: ``` >>> myList = [[1,2,3,4,5,6],[4,5,6,7,8]] >>> [ [dic.get(x[0],x[0]) ] + x[1:] for x in myList] [[3, 2, 3, 4, 5, 6], [4, 5, 6, 7...
> *But is there a other way to do this? without iterating over the whole list?* No. Not without iterating over the whole list. Since you wish to examine each tuple to see if the element you wish to change is a certain number, you *have* to iterate over the whole list *somehow*. So the only remaining consideration is ...
Possible to modify every first tuple element in a list of tuples?
[ "", "python", "list", "tuples", "" ]
Suppose I have a table with column which takes values from 1 to 10. I need to select columns with all values except for 9 and 10. Will there be a difference (performance-wise) when I use this query: ``` SELECT * FROM tbl WHERE col NOT IN (9, 10) ``` and this one? ``` SELECT * FROM tbl WHERE col IN (1, 2, 3, 4, 5, 6,...
When it comes to performance you should always profile your code (i.e. run your queries few thousand times and measure each loops performance using some kind of `stopwatch`. [Sample](http://ideone.com/WbNnJT)). But here I highly recommend using the first query for better future maintaining. The logic is that you need ...
Use "IN" as it will most likely make the DBMS use an index on the corresponding column. "NOT IN" could in theory also be translated into an index usage, but in a more complicated way which DBMS might not "spend overhead time" using.
SQL - IN vs. NOT IN
[ "", "sql", "" ]
I am trying this question from CodingBat > Given three ints, a b c, return True if one of b or c is "close" (differing by > at most 1), while the other is "far", differing from both other values by 2 or > more. Note: abs(num) computes the absolute value of a number. ``` close_far(1, 2, 10) → True close_far(1, 2, 3) →...
This problem can be greatly simplified, without loss of generality, by sorting: ``` def close_far(a, b, c): x, y, z = sorted([a, b, c]) delta_close, delta_far = sorted([y - x, z - y]) return delta_close <= 1 and delta_far >= 2 ```
``` def close_far(a, b, c): def close(x, y): return abs(x - y) <= 1 def far(x, y): return abs(x - y) >= 2 return (close(b, a) and far(c, a) and far(c, b) or close(c, a) and far(b, a) and far(b, c)) >>> close_far(1, 2, 10) True >>> close_far(1, 2, 3) False >>> close_far(4, 1, 3) True ```
Alternative approaches to comparing values
[ "", "python", "algorithm", "" ]
**I'm using SQL 2000. A string column 'Password' is there in a table 'Users'. It has around 3k rows. My requirement is to encrypt all the values of the 'Password' column. Also, I should be able to decrypt those encrypted password fields whenever it is needed.** I know, from SQL 2005 onward, there are in-built function...
You could use undocumented `PWDENCRYPT` and `PWDCOMPARE` functions available in SQL Server 2000 - ``` CREATE TABLE #USER ( LOGIN_ID varchar(20), UserPassword nvarchar(256) ) -- Encrypt & Insert Password -- Note: You will have to write UPDATE on existing records INSERT #USER VALUES ( 'my_loginid', PWDENCRYPT(...
Passwords are usually stored with a 1 way hash (for example SHA1), meaning they are encrypted and never need to be decrypted. When the user enters the password, your code would hash it and check if the hashed value matched the hashed value in the database. However, it sounds like you have a requirement to also be able...
Encrypt a column in SQL 2000 via code or SQL script
[ "", "sql", "encryption", "sql-server-2000", "" ]
I have a program to generate dynamic query string based on input. This query may select from any tables or joined tables in my DB, and the column names and number of columns are unknown. Now with this query string as the only input, I want to fetch all data from the result and output them line by line, is there any wa...
You can do that with [`DBMS_SQL`](http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/dynamic.htm#BHCIBJBG) package. *Update* To get more detailed reference about DBMS\_SQL go [here](http://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_sql.htm#ARPLS058).
``` <PRE> DECLARE RUN_S CLOB; IGNORE NUMBER; SOURCE_CURSOR NUMBER; PWFIELD_COUNT NUMBER DEFAULT 0; L_DESCTBL DBMS_SQL.DESC_TAB2; Z_NUMBER NUMBER; BEGIN RUN_S := ' SELECT 1 AS VAL1, 2 AS VAL2, ...
Oracle : how to fetch data from dynamic query?
[ "", "sql", "oracle", "plsql", "" ]
I have a list of words, let's say it's ``` ['a', 'b', 'c', 'd'] ``` I have a document where I've already pre-processed a text file into a matrix, and it goes like this: ``` a,b,c,d 0,1,1,0 1,1,0,0 1,1,1,1 ``` Where 1 is the presence of the word in a sentence, and 0 is the absence of that word in a sentence. I would...
All you have to do is `sum` each column since it's just 0s and 1s! ``` import numpy as np array = numpy.array((matrix)) answer = np.apply_along_axis(sum,0,array[1::]) my_dict = dict(zip(matrix[0],answer)) ``` now you have a dictionary where the keys are the words and the values is the total number of appearances!
You can use [*collections.Counter*](http://docs.python.org/2.7/library/collections.html#collections.Counter) to tally the word counts: ``` >>> from collections import Counter >>> filedata = '''\ 0,1,1,0 1,1,0,0 1,1,1,1 ''' >>> counter = Counter() >>> for line in filedata.splitlines(): a, b, c, d = map(int, line.sp...
I have a list of words. I want to add a counter variable associated with each word. How do I do this?
[ "", "python", "arrays", "list", "" ]
I am a MSSQL user now I am converting my database to MySQL, I am writing following query in MySQL. ``` select col1 as [My Column] from table1 ``` > Error : You have an error in sql syntax
You have a syntax error because the escape character (*delimiter*) is different from `MSSQL`. You need to use `backtick` instead of brackets. eg, ``` select col1 as `My Column` from table1 ``` MySQL => backtick MSSQL => bracket
Remove `[]` ``` select col1 as MyAliasName from table1 ``` Or ``` select col1 as `My Alias Name` from table1 ```
Alias in mysql select query
[ "", "mysql", "sql", "sql-server", "alias", "" ]
I have a bunch of product data in my DB. Each product has a certain ShopID which tells me to which shop it belongs. **I want all products with ShopID 1,4,7 appear last in the results.** How can I do that? Sample Code ``` SELECT * FROM Tablename WHERE Name LIKE %red% ORDER BY ShopID ASC ``` Best Regards, D.
Another alternative option would be to use a `CASE` statement in your `ORDER BY` clause: ``` SELECT * FROM Tablename WHERE Name LIKE '%red%' ORDER BY CASE WHEN ShopID IN (1,4,7) THEN 1 ELSE 0 END, ShopID ``` * [SQL Fiddle Demo](http://www.sqlfiddle.com/#!2/4147eb/1)
if `ShopID` is not saved as comma separated value, you can use MySQL's `FIELD()` ``` ORDER BY FIELD(ShopID, 1,4,7) ASC, ShopID ASC ``` * [SQLFiddle Demo](http://www.sqlfiddle.com/#!2/1fb5d/1) the reason why `1,4,7` appears on the last part of the result list is because `FIELD()` returns the index that was specified ...
MySQL: Show rows with certain content last
[ "", "mysql", "sql", "" ]
I have two arrays: ``` a=np.array((1,2,3,4,5)) b=np.array((2,3,4,5,6)) ``` What I want is to use the values of a and b for the limits of linspace e.g. ``` c=np.linspace(a,b,11) ``` I get an error when I use this code. The answer should be for the first element of the array: ``` c=np.linspace(a,b,11) print c c=[1 1...
You can do this: ``` c = np.array([np.linspace(i,j,5) for i,j in zip(a,b)]) #array([[ 1. , 1.25, 1.5 , 1.75, 2. ], # [ 2. , 2.25, 2.5 , 2.75, 3. ], # [ 3. , 3.25, 3.5 , 3.75, 4. ], # [ 4. , 4.25, 4.5 , 4.75, 5. ], # [ 5. , 5.25, 5.5 , 5.75, 6. ]]) ```
If you want to avoid explicit Python loops, you can do the following: ``` >>> a = np.array([1, 2, 3, 4, 5]).reshape(-1, 1) >>> b = np.array([2, 3, 4, 5, 6]).reshape(-1, 1) >>> c = np.linspace(0, 1, 11) >>> a + (b - a) * c array([[ 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. ], [ 2. , 2.1, 2...
Python linspace limits from two arrays
[ "", "python", "arrays", "numpy", "" ]
In my database project, I had to build a database regarding some data from the Olympic games. I have to build the following query as well : *Compute medal table for the specific Olympic Games supplied by the user. Medal table should contain country’s IOC code followed by the number of gold, silver, bronze and total m...
The data are not the problem - the fact that you have an implicit cartesian join between each of q1, q2 and q3 *is* a problem. Try: ``` SELECT c.countryName as country, count(case m.idMedal when 'Gold medal' then 1 end) as cntG, count(case m.idMedal when 'Silver medal' then 1 end) as cntS, count(...
Sorry but your query is a real mess. You can't simply join the 3 subqueries that way. However, you can have what you want in one query. I'll give you the pseudo code and leave you the details :) ``` SELECT [countryName], SUM(color like '%Gold%') as total_gold, SUM(color like '%Silver%') as total_silver, ...
SQL: count from same table/field, but different values
[ "", "sql", "subquery", "" ]
I have a dictionary where the value elements are lists: ``` d1={'A': [], 'C': ['SUV'], 'B': []} ``` I need to concatenate the values into a single list ,only if the list is non-empty. Expected output: ``` o=['SUV'] ``` Help is appreciated.
``` from itertools import chain d1={'A': [], 'C': ['SUV'], 'B': []} print list(chain.from_iterable(d1.itervalues())) ```
You can use `itertools.chain`, but the order can be arbitrary as dicts are unordered collection. So may have have to sort the dict based on keys or values to get the desired result. ``` >>> d1={'A': [], 'C': ['SUV'], 'B': []} >>> from itertools import chain >>> list(chain(*d1.values())) # or use d1.itervalues() as it ...
Concatenate lists together
[ "", "python", "" ]
I'm running Python3.3 on Win64 and am having trouble following the installation instructions for Jinja2. I followed the suggestion here ([Jinja install for python](https://stackoverflow.com/questions/6726983/jinja-install-for-python)) but my installation of Python 3.3 doesn't have a easy\_install.exe as described. I do...
To use easy install and pip: use windows setuptools : <https://pypi.python.org/pypi/setuptools> Python for windows extensions is also very helpfull :
Please go to <http://www.lfd.uci.edu/~gohlke/pythonlibs/#setuptools> 1. Download and install appropriate setuptool.exe for your Computer. 2. Download and install appropriate jinja2.exe for your Computer. 3. From your command prompt install C:\Python27\Lib\Jinja2(version)>setup.py install 4. A jinja2 folder should be c...
Trouble installing Jinja2 on Windows
[ "", "python", "installation", "jinja2", "python-3.3", "" ]
I am looking for all the functions that have a parameter called *adjustable*. One of these function is **matplotlib.pyplot.figure ().add\_axes**. help(matplotlib.pyplot.figure ().add\_axes) describes that parameter, that can be present in *kwargs* dictionary. I tried pydoc.apropos ``` from pydoc import apropos In [...
I just noticed you're using IPython, if so, there's an extension called [grasp](https://pypi.python.org/pypi/grasp/0.3.2) which implements its own version of apropos that may be useful here. The documentation even uses `matplotlib` in its example.
Here is a quickly written function that walks all current packages in the specified path, using `ast` to find matching parameters, and returning `(filename, funcname, line_no)` for each match. ``` import ast import pkgutil import os.path class FindParameter(ast.NodeVisitor): def __init__(self, parameter): ...
Python *apropos* command
[ "", "python", "matplotlib", "" ]
I'm looking for the equivalent to the vlookup function in excel. I have a script where I read in a csv file. I would like to be able to query an associated value from another column in the .csv. Script so far: ``` import matplotlib import matplotlib.mlab as mlab import glob for files in glob.glob("*.csv"): print ...
I think this solves your problem quite directly: ``` import numpy import glob for f in glob.glob("*.csv"): print f r = numpy.recfromcsv(f) print numpy.interp(5, r.depth, r.temp) ``` I'm pretty sure numpy is a prerequisite for matplotlib.
Not sure what that `r` object is, but since it has a member called `cols`, I'm going to assume it also has a member called `rows` which contains the row data. ``` >>> r.rows [[16.1309, 5], [16.1476, 94.4007], ...] ``` In that case, your pseudocode very nearly contains a valid generator expression/list comprehension. ...
basic python vlookup equivalent
[ "", "python", "" ]
Using `.read()` to read a file, how would I split on two objects at once? I'm trying to split on commas, and `"\n"` simultaneously, but when I split on commas first, it turns my string into a list, in which I cannot split again. Here is the string I'm trying to split: `'States, Total Score, Critical Reading, Mathemat...
You can use a list comprehension: ``` >>> strs = 'States, Total Score, Critical Reading, Mathematics, Writing, Participation (%)\nWashington,1564,524,532,508,41.2000\nNewHampshire,1554,520,524,510,64.0000\nMassachusetts,1547,512,526,509,72.1000\nOregon,1546,523,524,499,37.1000\nVermont,1546,519,512,506,64.0000\nArizon...
Don't read the whole file in one go, read *per line*, then split: ``` with open(filepath) as f: for line in f: print line.strip().split(',') ``` You could also first split on newlines, then loop and split on commas: ``` lines = [line.split(',') for line in somestring.splitlines()] ``` But for comma-sepa...
How to split on two items in a string?
[ "", "python", "string", "list", "split", "" ]
I'm trying to get `python` to return, as close as possible, the **center** of the most obvious clustering in an image like the one below: ![image](https://i.stack.imgur.com/iE0C3.png) In my [previous question](https://stackoverflow.com/questions/16822334/find-peak-of-2d-histogram) I asked how to get the global maximu...
I'm adding this answer because it's the solution I ended up using. It's a combination of Bi Rico's comment here (May 30 at 18:54) and the answer given in this question: [Find peak of 2d histogram](https://stackoverflow.com/questions/16822334/find-peak-of-2d-histogram). As it turns out using the peak detection algorith...
Answering the last part of your question, always you have points in an image, you can find their coordinates by searching, in some order, the local maximums of the image. In case your data is not a point source, you can apply a mask to each peak in order to avoid the peak neighborhood from being a maximum while perform...
Peak detection in a noisy 2d array
[ "", "python", "image-processing", "numpy", "matplotlib", "" ]
I noticed something very weird. I tried to look at where it was going wrong and realised that for some reason, the `nest[0]` list keeps changing midway through the loop. ``` >>> nest = [['prefix'],['line 1'],['line 2']] >>> for part in nest[1:]: ... list = nest[0] ... list += part ... print list ``` The o...
EDIT: with explanation of pointers, as requested Your problem is that when you assign list to nest[0], you are not creating a new list, your just assigning a pointer. Your pointer is directed to the list containing ['prefix'] On your first iteration, you add something to this list On your second iteration, you don't...
`list = nest[0]` mean you assign pointer to nest[0] to variable name `list` If you want your expected output, you need to create a new list to make sure it will not effect the original. ``` nest = [['prefix'],['line 1'],['line 2']] for part in nest[1:]: list = nest[0] + part print list ``` `nest[0] + part` w...
For loop through a nested-list
[ "", "python", "nested-lists", "" ]
I'm modifying a query I have that pulls news items from my database. These news items have tags, which, in the database, is stored in a single column as a string separated by commas. For example: ``` 'content,video,featured video,foo' ``` What I'm trying to do is grab all the items in the table but **not** the items...
I'm offering horrible thing, but if you want to stick to your table structure, you may try following: ``` SELECT * FROM posts WHERE STATUS=2 AND INSTR(tags,'featured video')>0 OR INSTR(tags,'video')=0 ``` At least use `FULLTEXT` index on that field, so it won't be this painful to use.
I would use a query like this: ``` SELECT * FROM posts WHERE status = 2 AND (CONCAT(',', tags, ',') LIKE '%,featured video,%' OR CONCAT(',', tags, ',') NOT LIKE '%,video,%') ORDER BY postDate ```
SQL Query - Don't grab this unless this
[ "", "sql", "" ]
I have this php mysql statement ``` SELECT a.*, p.filename, m.`first name`, m.`last name`, m.`mobile number`, m.`status`, m.`email address` FROM map a join members m on a.members_id = m.id join pictures p on m.pictures_id = p.id WHERE a.active = 1 GROUP BY a.members_id order by a.`date added` DESC limit 1; ``` Howeve...
Try: ``` select * from (SELECT a.*, p.filename, m.`first name`, m.`last name`, m.`mobile number`, m.`status`, m.`email address` FROM map a join members m on a.members_id = m.id join pictures p on m.pictures_id = p.id WHERE a.active = 1 order by a.members_id, a.`date added` DESC) sq GROUP BY memb...
If you want to get one result per map, you have to select it in two steps - so with a subquery. The inner query gets the newest map per member and the outer query gets all the data. Be careful with the indices, otherwise it will be very slow. I think it will be something like: ``` SELECT a.*, p.filename, m.`first...
How to order group by and get first row?
[ "", "mysql", "sql", "select", "" ]
I have some code that is meant to convert CSV files into tab delimited files. My problem is that I cannot figure out how to write the correct values in the correct order. Here is my code: ``` for file in import_dir: data = csv.reader(open(file)) fields = data.next() new_file = export_dir+os.path.basename(f...
The `csv` module contains methods for writing as well as reading, making this pretty trivial: ``` import csv with open("test.csv") as file, open("test_tab.csv", "w") as out: reader = csv.reader(file) writer = csv.writer(out, dialect=csv.excel_tab) for row in reader: writer.writerow(row) ``` No ne...
Extract the code that writes the headers *outside* the main loop, in such a way that it only gets written exactly once at the beginning. Also, consider using the [CSV module](http://docs.python.org/2/library/csv.html) for writing CSV files (not just for reading), don't reinvent the wheel!
Trouble with Python order of operations/loop
[ "", "python", "" ]
I'm building a MongoDB database and the problem is that I want to avoid duplicate entries. At the moment I'm doing this (inserting document only after checking if entry doesn't exist): ``` from pymongo import Connection import pandas as pd from time import strftime from collections import OrderedDict connection = Co...
You can build a [unique index](http://docs.mongodb.org/manual/core/indexes/#index-type-unique) on the fields you are searching (mongo shell syntax): ``` db.mycollection.ensureIndex({_id:1, date1:1, date2:1, number:1, type:1}, {unique: true}); ``` And capture the constraint violation exception (and ignore it if approp...
Checking before inserting is not good way to prevent it. To prevent duplication of keys , use primary key. see [how to set a primary key in mongodb](https://stackoverflow.com/questions/3298963/how-to-set-a-primary-key-in-mongodb) Also if it's not good for you , at least add [mongo index](http://docs.mongodb.org/manual...
Checking if record exists in MongoDB
[ "", "python", "performance", "mongodb", "pymongo", "" ]
I have a string (it could be an integer too) in Python and I want to write it to a file. It contains only ones and zeros I want that pattern of ones and zeros to be written to a file. I want to write the binary directly because I need to store a lot of data, but only certain values. I see no need to take up the space o...
Alright, after quite a bit more searching, I found an answer. I believe that the rest of you simply didn't understand (which was probably my fault, as I had to edit twice to make it clear). I found it [here](http://www.linuxquestions.org/questions/programming-9/writing-binary-data-under-python-718165/). The answer was...
To write out a string you can use the file's `.write` method. To write an integer, you will need to use the `struct` module ``` import struct #... with open('file.dat', 'wb') as f: if isinstance(value, int): f.write(struct.pack('i', value)) # write an int elif isinstance(value, str): f.write(v...
Write a binary integer or string to a file in python
[ "", "python", "file", "file-io", "binary", "" ]
``` True and "asdf" or "qwer" ``` result => "asdf" ``` False and "asdf" or "qwer" ``` result => "qwer" I can't understand how those things work. I thought that boolean operator on string would make type error, but it didn't. Is it something like predefined statement, for instance "a if b else c"?
Python *and* and *or* operations stop when the answer is determined and return the value of the last object scanned. They do not return *True* or *False*. I love this feature and find myself using it all the time. Since non-empty strings count as True ``` True and "asdf" or absolutely_anything_here_or_following ``` ...
`and` and `or` work just like the familiar boolean operators - they return true if both of their operands are true and false if one of their operands are true, respectively. They also short circuit, just like `&&` and `||`. However, in Python, where anything can be interpreted as being `True` or `False` in a boolean ...
How does boolean operator work on string in python
[ "", "python", "" ]
I have a table with two columns ID,DESCRIPTION the ID column in not unique. I would like a DELETE query that will make the table have unique values in the ID column. For example, if this is my current table **ID DESCRIPTION** ``` - 5 ABC - 5 DEF - 6 XDX - 6 KKK - 7 AAA ``` I would like to modi...
> *"I would like a query that will make the table have unique values in the ID column."* This will give you one record for each `ID`. ``` SELECT ID, MIN(Description) Description FROM tableName GROUP BY ID ``` * [SQLFiddle Demo](http://www.sqlfiddle.com/#!2/397bb/1) --- Here's a delete statement to remove duplic...
Uthe most elegant way is to use mysql's multiple-table delete syntax and join the table to itself: ``` delete d from mytable t join mytable d on d.id = t.id and d.description > t.description ``` The key part of this query is the greater-than comparison of `description`, which not only stops same-row joins but also ...
SQL unique query
[ "", "mysql", "sql", "" ]
I'm using Scrapy to crawl some pages. I fetch the start\_urls from an excel sheet and I need to save the url in the item. ``` class abc_Spider(BaseSpider): name = 'abc' allowed_domains = ['abc.com'] wb = xlrd.open_workbook(path + '/somefile.xlsx') wb.sheet_names() sh = wb.sheet_by_name(u'Sheet1...
You can find what you need in `response.request.meta['redirect_urls']`. Quote from [docs](http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#std:reqmeta-redirect_urls): > The urls which the request goes through (while being redirected) can > be found in the redirect\_urls Request.meta key. Hope that h...
This gave me the original 'referer URL', i.e. which of my start\_urls led to the URL corresponding to this request object being scraped: ``` req = response.request req_headers = req.__dict__['headers'] referer_url = req_headers['Referer'].decode('utf-8') ```
how to get the original start_url in scrapy (before redirect)
[ "", "python", "redirect", "web-scraping", "scrapy", "" ]
Sorry for the beginner question. But how can I put these queries into one data set rather than multiple queries? They are all being taken out of the same table. Also as you can see there is an "Open\_Time" This is a DATE format. How can I write that to say AND open\_date is within the last 60 days? ``` SELECT COUNT(P_...
Try this sql. ``` SELECT COUNT(CASE WHEN Assignment = 'Crosby' AND Severity = 4 AND DATEDIFF(CURDATE(),Open_Time)<=60 THEN P_NUMBER END) as p1, COUNT(CASE WHEN Assignment = 'Crosby' AND Severity = 5 AND DATEDIFF(CURDATE(),Open_Time)<=60 THEN P_NUMBER END) as p2, COUNT(CASE WHEN Assignment = 'Crosby' AND Sever...
One way of doing this: ``` SELECT SUM(CASE WHEN Assignment = 'Crosby' AND Severity=4 AND Open_Time<=60 THEN 1 ELSE 0 END) AS P_number1 ,SUM(CASE WHEN Assignment = 'Crosby' AND Severity=5 AND Open_Time<=60 THEN 1 ELSE 0 END) AS P_number2 ,SUM(CASE WHEN Assignment = 'Crosby' AND Severity=4 AND close_time<=60 THEN 1 ELS...
SQL combine separate queries
[ "", "sql", "" ]
I am working with [this tutorial](https://www.kaggle.com/c/titanic-gettingStarted/details/getting-started-with-python). On the example ``` import csv as csv import numpy as np csv_file_object = csv.reader(open('train.csv', 'rb')) header = csv_file_object.next() data = [] for row in csv_file_object: data.append(r...
Check your indentation. If `data = np.array(data)` is in your for loop (ie indented the same amount as `data.append(row)`), you'll turn `data` into a Numpy array before you've finished appending items to a list. This will cause the error you see because lists have an `append()` method, while numpy arrays do not. Your ...
Have a look at the example at the [linked location](https://www.kaggle.com/c/titanic-gettingStarted/details/getting-started-with-python): ``` #The first thing to do is to import the relevant packages # that I will need for my script, #these include the Numpy (for maths and arrays) #and csv for reading and writing csv...
Python code not running
[ "", "python", "python-2.7", "numpy", "" ]
I am trying to create a VIEW where I should have the following columns: **Clinic\_id | Result\_month\_id | AVF | AVC | AVG | Other | Total\_Days** Total\_Days should be calculated dynamically using (AVF+AVC+[AVG]+Other). The SQL Query is: ``` CREATE VIEW Rate AS SELECT clinic_id, result_month_id, sum(case v_id...
You can use a subquery for this: ``` CREATE VIEW Rate AS select t.*, AVC + [AVG] + Other as TotalDays from (SELECT clinic_id, result_month_id, sum(case v_id when 'ula' then [days] else 0 end) as AVF, sum(case v_id when 'ter' then [days] when 'thet...
Simplest way is going to be to use a CTE. ``` CREATE VIEW Rate AS WITH CalculatedValues AS ( SELECT clinic_id, result_month_id, sum(case v_id when 'ula' then [days] else 0 end) as AVF, sum(case v_id when 'ter' then [days] when 'theter' then [days] ...
Dynamic SUM() while using Sum(Case) on a VIEW in MSSQL
[ "", "sql", "sql-server", "dynamic", "" ]
Consider the following class: ``` class MyObject(object): __slots__ = ('_att1', '_att2') def __init__(self): self._att1 = None self._att2 = None @property def att1(self): """READ-ONLY property. """ return self._att1 @property def att2(self): """att2 p...
Python doesn't have a formal distinction between private and protected class members. Even the distinction between private and public is pretty weak, since anything can be accessed if a user tries hard enough. If a private versus protected distinction would make sense for your application, you can simply document that ...
Attributes with underscore are not “protected”, but “private”—they are subject to change. Even if your class is derived from it. You should use parent property to access this data. Speaking about performance. Of course, property access is a bit slower than attribute access, simply because it involves a function call, ...
Faster attribute access in python
[ "", "python", "pylint", "" ]
The SQL below contains some DDL and a simple query. The result I am getting is ``` a1|b1|c1 a1|b2|c3 a3|b3|c2 a3|b3|c3 a3|b3|c4 a3|b3|c5 a3|b5|c6 a3|b5|c7 ``` The result I want is ``` a1 |b1 |c1 a1 |b2 |c3 a3 |b3 |c2 null |null |c4 null |null |c5 a3 |b5 |c6 null |null |c7 ...
something like this should work (I have tested it on PostgreSql, should work on Oracle too) ``` SELECT case when row_number = 1 then a_id end as a_id, case when row_number = 1 then b_id end as b_id, c_id FROM ( SELECT a.a_Id, b.b_Id, c.c_Id, row_number() OVER (partition by a.a_id, b.b_id o...
``` select t1.a_id, t1.b_id, table_c.c_id from table_c left join ( select a_Id, b_Id, c_Id from ( select a.a_Id as a_id, b.b_Id as b_id, c.c_Id as c_id, ROW_NUMBER() OVER (PARTITION BY a.a_ID, b.b_id ORDER BY C_ID) as aNum from table_A as a join table_B as b on a.a_Id = b.a_Id join...
Restrict many - many results in SQL join
[ "", "sql", "" ]
I have three database tables: `routes`, `trips`, and `stoptimes` that contain transit information. They're related with foreign keys as follows: ``` routes -> ROUTE_ID -> trips -> TRIP_ID -> stoptimes ``` i.e. there are some routes, lots of trips per route, and even more stoptimes per trip. For each route i...
You can do this with a trick in MySQL, involving group concatenation. Here is the query: ``` select t.route_id, substring_index(group_concat(t.trip_id order by NumStops desc), ',', 1), max(NumStops) as Length from trips t join (select st.trip_id, count(*) as NumStops from stoptimes st g...
If you join all the tables together correctly, you'll get one row for each stop time, so a `COUNT(*)` will give you the total stops. As for the count by direction, I'll assume the direction values are `1, 2, 3, ...`. I can't tell which table `direction_id` is in so I've left it unaliased in the query: ``` SELECT rout...
SQL help - select table with the greatest number of related rows
[ "", "mysql", "sql", "database", "" ]
I am trying to learn python and for that purpose i made a simple addition program using python 2.7.3 ``` print("Enter two Numbers\n") a = int(raw_input('A=')) b = int(raw_input('B=')) c=a+b print ('C= %s' %c) ``` i saved the file as *add.py* and when i double click and run it;the program run and exits instantenously ...
add an empty `raw_input()` at the end to pause until you press `Enter` ``` print("Enter two Numbers\n") a = int(raw_input('A=')) b = int(raw_input('B=')) c=a+b print ('C= %s' %c) raw_input() # waits for you to press enter ``` Alternatively run it from `IDLE`, command line, or whichever editor you use.
It's exiting because you're not telling the interpreter to pause at any moment after printing the results. The program itself works. I recommend running it directly in the terminal/command line window like so: ![screenshot of it working](https://i.stack.imgur.com/fFTGm.png) Alternatively, you could write: ``` import...
Simple addition program in python
[ "", "python", "math", "python-2.7", "" ]
``` IF object_id('tempdb..#A') IS NOT NULL DROP TABLE #A IF object_id('tempdb..#B') IS NOT NULL DROP TABLE #B CREATE TABLE #A (fname varchar(20), lname varchar(20)) CREATE TABLE #B (fname varchar(20), lname varchar(20)) INSERT INTO #A SELECT 'Kevin', 'XP' UNION ALL SELECT 'Tammy', 'Win7' UNION ALL SELECT 'Wes', 'XP'...
This would create rows with unique fname and take Win7 if both Win7 and XP existed. ``` INSERT INTO #B SELECT a.fname, MIN(a.lname) FROM #A a GROUP BY a.fname ```
Answering your question, why don't your queries work? ``` INSERT INTO #B SELECT a.fname, a.lname FROM #A a WHERE a.fname NOT IN (SELECT fname from #B) ``` This operation is evaluated in two different operations. In the first, the SELECT part of the query is executed. It returns a table. At such point #B is empty, hen...
Copy records from one table to another without duplicates
[ "", "sql", "sql-server-2008", "" ]
How can I decode a pem-encoded (base64) certificate with Python? For example this here from github.com: ``` -----BEGIN CERTIFICATE----- MIIHKjCCBhKgAwIBAgIQDnd2il0H8OV5WcoqnVCCtTANBgkqhkiG9w0BAQUFADBp MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMSgwJgYDVQQDEx9EaWdpQ2VydCBIaWdoI...
Python's standard library, even in the latest version, does not include anything that can decode X.509 certificates. However, the add-on [`cryptography`](https://cryptography.io/) package does support this. Quoting an [example from the documentation](https://cryptography.io/en/latest/x509/reference/#loading-certificate...
You can use [`pyasn1`](https://github.com/etingof/pyasn1) and [`pyasn1-modules`](https://github.com/etingof/pyasn1-modules) packages to parse this kind of data. For instance: ``` from pyasn1_modules import pem, rfc2459 from pyasn1.codec.der import decoder substrate = pem.readPemFromFile(open('cert.pem')) cert = decod...
How can I decode a SSL certificate using python?
[ "", "python", "ssl", "cryptography", "certificate", "pem", "" ]
I have a list of lookup fields: ``` >>> l = ['A', 'C', 'Z', 'M'] ``` I would need to test the equality of 2 dictionaries on this lookup list: ``` >>> d1 = {'A': 3,'F': 4,'Z': 1} >>> d2 = {'B': 0,'A': 3,'C': 7} ``` The equality test for any field 'x' in the list succeeds if any of the following conditions are satisf...
This is probably the shortest and most elegant: ``` all( d1.get(x) == d2.get(x) for x in l ) ``` Note that if x is not in both dictionary, we are comparing None with None. EDIT: - Following comments, using generator (not list comprehension). - Ashwini comment is correct. Will not work if one of the dictionaries ...
Try this: ``` success = True for x in l: if not (((x not in d1) and (x not in d2)) or (d1.get(x) == d2.get(x))): success = False ```
Equality of dictionaries
[ "", "python", "" ]
I am trying to manipulate my sql select result. I stored the variable in the database in this way `<p>asd</p>` so it will be recognized as a paragraph in my application, but I want to use it in my app's other function. I want to show it in this way 'asd'. Is there any way to do it in sql? any help will be appriciated ...
If you are running [MySQL 5.1.5 or above](http://ftp.nchu.edu.tw/MySQL/tech-resources/articles/mysql-5.1-xml.html), then you could use the [XPath](http://www.w3schools.com/xpath/) function [`ExtractValue()`](http://dev.mysql.com/doc/refman/5.1/en/xml-functions.html#function_extractvalue), like this... ``` SELECT Extra...
Yes, you can use select replace, like so: ``` select replace(replace("<p>asd</p>",'<p>',''),'</p>','') ``` [See it in action: SQL fiddle](http://sqlfiddle.com/#!2/d41d8/13613/0)
How to manipulate the result of select query in SQL?
[ "", "mysql", "sql", "" ]
I am having a difficult time summing a column of distinct values based on a column of values, which also needs to be distinct. For example, I have: ``` Index PaymentID PaymentAmt PartPmtApplied 1 35 50 26 2 35 50 24 3 36 50 38 4 36 ...
If you need to sum distinct values you can just simply sum everything from a subquery that would hold only distinct values ( or distinct pairs of values ). So you probably need ``` SELECT SUM( PaymentAmt ) FROM ( SELECT PaymentAmt FROM tabl_a GROUP BY PaymentId, PaymentAmt ) distinct_payments; ``` This will g...
You can actually do it without any subquery. Just use `GROUP BY` in your query. ``` SELECT PaymentID, SUM(PaymentAmount) TotalPayment FROM tabl_a GROUP BY PaymentID ``` This will give you unique value of `PaymentID` with its calculated total amount of `PaymentAmount`. * [SQLFiddle Demo](http://www.sqlfiddle.co...
How to correctly sum a 2 column query in MySQL
[ "", "mysql", "sql", "" ]
I am trying to install GDAL in virtual environment based on the various [solutions](https://stackoverflow.com/questions/11336153/python-gdal-package-missing-header-file-when-installing-via-pip) out there. However the download itself already fails: ``` $ pip install --no-install GDAL ``` Here is the pip.log ``` ----...
A workaround to that problem is to 1. Download [GDAL Complete](http://www.kyngchaos.com/files/software/frameworks/GDAL_Complete-1.10.dmg) from [this site](http://www.kyngchaos.com/software/frameworks) 2. Install GDAL Complete.pkg 3. Go to `/Library/Frameworks/GDAL.framework/Versions/1.10/` and copy all files in there ...
The workaround given by @user1738154 didn't work as expected for me so went ahead and installed GDAL using [HomeBrew](http://brew.sh) then using pip into my Virtual environment. ``` $ brew install gdal (venv)$ pip install GDAL ``` Everything compiled and ran like a charm.
Python GDAL: pip install --no-install GDAL fails
[ "", "python", "virtualenv", "gdal", "" ]
I want a function to refer to itself. e.g. to be recursive. So I do something like that: ``` def fib(n): return n if n <= 1 else fib(n-1)+fib(n-2) ``` This is fine most of the time, but `fib` does not, actually, refer to itself; it refers to the the binding of `fib` in the enclosing block. So if for some reason ...
Like [abamert](https://stackoverflow.com/questions/16821879/is-there-a-way-to-refer-to-the-current-function-in-python#comment24252510_16821975) said "..there is no way around the problem from inside ..". Here's my approach: ``` def fib(n): def fib(n): return n if n <= 1 else fib(n-1)+fib(n-2) return f...
I'd make a decorator for this ``` from functools import wraps def selfcaller(func): @wraps(func) def wrapper(*args, **kwargs): return func(wrapper, *args, **kwargs) return wrapper ``` And use it like ``` @selfcaller def fib(self, n): return n if n <= 1 else self(n-1)+self(n-2) ``` --- This...
Is there a way to refer to the current function in python?
[ "", "python", "" ]
I'm trying to build a list of domain names from an Enom API call. I get back a lot of information and need to locate the domain name related lines, and then join them together. The string that comes back from Enom looks somewhat like this: ``` SLD1=domain1 TLD1=com SLD2=domain2 TLD2=org TLDOverride=1 SLD3=domain3 TLD...
this works for you example, ``` >>> sld_list = re.findall("^.*SLD[0-9]*?=(.*?)$", enom, re.M) >>> tld_list = re.findall("^.*TLD[0-9]*?=(.*?)$", enom, re.M) >>> map(lambda x: x[0] + '.' + x[1], zip(sld_list, tld_list)) ['domain1.com', 'domain2.org', 'domain3.co.uk', 'domain4.net'] ```
**Edit:** Every time I see a question asking for regular expression solution I have this bizarre urge to try and solve it without regular expressions. Most of the times it's more efficient than the use of regex, I encourage the OP to test which of the solutions is most efficient. Here is the naive approach: ``` a = "...
Regular Expression in Python
[ "", "python", "regex", "" ]
after a computer fix my python projects dir (windows) changed (say from d: to f:). now all my virtualenvs are broken. after activating the env the project inside the virtualenv can't find the dependencies and the custom scripts (from the env\scripts folder)won't work tried running: ``` virtualenv --relocateble ENV_NA...
Seems like your system and local environments create a mix of libraries and binaries from different versions of python. Chances are you would need to delete `Lib`, `Scripts` and `Include` and start again with `virtualenv .`. You might be able to save the `site-packages` folder, but if you have `requirements.txt` files...
Correcting python directory path in `ENV_FOLDER\Lib\orig-prefix.txt` helped me
changing virtualenv folder on windows
[ "", "python", "virtualenv", "virtualenv-commands", "" ]
For example I have a dataset as below: ``` id Date 1 2000/01/01 1 2001/01/01 1 2002/01/01 2 2003/01/01 ``` By datastep or sql, how could I get the record with id = 1 and latest Date 2002/01/01? Help is appreciated and thanks in advance.
Try this sql. ``` select id,max(Date) from yourtable group by id; ```
If you want the entire record and the data is sorted as shown (BY id and DESCENDING date), you can use this data step: ``` data want; set have; by id; /* you don't need to specify date here */ if last.id; run; ``` This give you the most recent record for each id.
SAS datastep/SQL select latest record from multiple records with same ID
[ "", "sql", "sas", "proc-sql", "datastep", "" ]
Can't we yield more than one value in the python generator functions? Example, ``` def gen(): for i in range(5): yield i, i+1 k1, k2 = gen() ``` --- ``` Traceback (most recent call last) ----> 1 k1, k2 = a() ValueError: too many values to unpack ``` This works as follows: ``` >>> b = a()...
Because `gen()` returns a generator (a single item - so it can't be unpacked as two), it needs to be advanced *first* to get the values... ``` g = gen() a, b = next(g) ``` It works with `list` because that implicitly consumes the generator. Can we further make this a generator? Something like this: ``` g = gen(); d...
Your function `gen` returns a generator and not values as you might expect judging from the example you gave. If you iterate over the generator the pairs of values will be yielded: ``` In [2]: def gen(): ...: for i in range(5): ...: yield i, i+1 ...: In [3]: for k...
Yield multiple values
[ "", "python", "generator", "" ]
I have just started learning Django. I was wondering if Django app can have more than one views file? Let's say, I have two separate classes. Should I keep them in one views file or can I make two views files? Thanks in advance!
Views are just python modules, you can do whatever you want, for instance you can change their names to `whatever.py` as long as your `imports` are correct :) And as suggested: find more info here [Django: split views.py in several files](https://stackoverflow.com/questions/1921771/django-split-views-py-in-several-fil...
Yes, you can. A modular way of splitting would be to create a package - `views/` ``` - views/ - first.py - second.py - __init__.py ``` and in your `__init.py__` add the following: ``` from .first import * from .second import * ``` This way, all your views would be available for `urls.py`.
Can a django app have more than one views.py?
[ "", "python", "django", "django-views", "" ]
Say I have a select box with some values such as 'RED', 'BLUE' and 'GREEN' and I want to use those strings as references to constants called the same thing, but containing tuples, as so: ``` RED = ('x234114','z8765667') ``` The code I am looking for would look something like this in my mind's eye :) ``` globals_look...
Once you have defined the variable with the tuple you can access it by using locals. ``` >>> RED = ('x234114','z8765667') >>> locals()["RED"] ('x234114', 'z8765667') ``` But the right way to do it would be using a dictionary ``` >>> select_data = {"RED" :('x234114','z8765667'),"BLUE":('x934587','z943657')} >>> selec...
Using eval: ``` RED = ('x234114','z8765667') def globals_lookup(ident): return eval(ident) t=globals_lookup('RED') ``` But a better way would be using a hash table: ``` colors={'RED':('x234114','z8765667')} t=colors['RED'] ```
How to convert a string into a constant tuple in Python
[ "", "python", "string", "tuples", "" ]
I'm trying to calculate the GC content (in %) of a DNA sequence for a Rosalind question. I have the following code, but it returns 0, or only the number of G's alone or C's alone (no percentage). ``` x = raw_input("Sequence?:").upper() total = len(x) c = x.count("C") g = x.count("G") gc_total = g+c gc_content = gc_t...
Shouldn't: > print cg\_content read > print gc\_content? As for the other snippet of code, your loop says > if i == "C" or "G": This is evaluating "G" to true every time and thus running the if statement as true. Instead, it should read > if i == "C" or i=="G": Also, you don't need that else statement. Hope t...
Your problem is that you are performming integer division, not floating point division. Try ``` gc_content = gc_total / float(total) ```
Beginner Python script for calculating GC content in DNA sequence
[ "", "python", "function", "rosalind", "" ]
I'm on linux, and I have one python script that I want to call from another python script. I don't want to import it as a module (for a layer of security, and now for an academic exercise because I want to figure this out), I want to actually have one script call the other with os.system() or another function like that...
Importing a module is different from executing it as a script. If you don't trust the child Python script; you shouldn't run any code from it. A regular way to use some code from another Python module: ``` import another_module result = another_module.some_function(args) ``` If you want to execute it instead of imp...
You can use [`subprocess`](http://docs.python.org/2/library/subprocess.html): ``` subprocess.call(["python", "myscript.py"]) ``` This will also return the process return value (such as 0 or 1).
Getting return information from another python script
[ "", "python", "linux", "" ]
I would like to do a huge find and replace using python. `tot11.txt` is a string (has 600000 items), I want to replace items here from the file `1.txt`. So for example `tot11.txt` has : `'alba'`, `'raim'`, and `1.txt` looks like this : `'alba':'barba', 'raim':'uva'`. and as a result i would get `'barba'`, `'uva'`...
`open('1.txt', 'r').read()` returns a string not dict. ``` >>> print file.read.__doc__ read([size]) -> read at most size bytes, returned as a string. ``` If `1.txt` contains: ``` 'alba':'barba', 'raim':'uva' ``` then you can use `ast.literal_eval` to get a dict: ``` >>> from ast import literal_eval >>> with open("...
The second argument of the replace\_all function is a string, as it came from reps = open('1.txt', 'r').read().... so the calling iteritems() over a string object fails because that function doesn't exist for string objects.
python: 'str' object has no attribute 'iteritems'
[ "", "python", "string", "" ]
I have created some code: ``` import numpy as np Length=(2.7)*10**-3 Nx=4 x = np.linspace(0, Length, Nx+1) # mesh points in space t1=110 t2=100 m=((t2-t1)/Length) T=5 N=5 t = np.linspace(0, T, N+1) Coeff=0.5 b=0.2 tamb = 20 u = np.zeros(Nx+1) u_1 = np.zeros(Nx+1) for i in range(0, Nx+1): u...
Change your function signature: ``` def function(data,time,n): ``` and call it like this: ``` for n in xrange(len(data)): r = function(data,time,n) ```
You're using the global `n` here ``` Values=data[n] ``` You're using `n` as a local variable here ``` for n in range(0, N+1): ``` Python won't let you use `n` as both a global and local in the same scope. Is it *supposed* to be the same `n` or is it just a bad reuse of a variable name? There are several ways to f...
Python local variable referenced before assignment
[ "", "python", "function", "" ]
I'm using the python [`requests` module](https://requests.readthedocs.io/) to send a RESTful GET to a server, for which I get a response in JSON. The JSON response is basically just a list of lists. What's the best way to coerce the response to a native Python object so I can either iterate or print it out using `ppri...
You can use [`json.loads`](http://docs.python.org/2/library/json.html#json.loads): ``` import json import requests response = requests.get(...) json_data = json.loads(response.text) ``` This converts a given string into a dictionary which allows you to access your JSON data easily within your code. Or you can use @...
Since you're using `requests`, you should use the response's [`json`](https://requests.readthedocs.io/en/latest/user/quickstart/#json-response-content) method. ``` import requests response = requests.get(...) data = response.json() ``` It [autodetects which decoder to use](https://github.com/requests/requests/blob/4...
What's the best way to parse a JSON response from the requests library?
[ "", "python", "json", "rest", "python-requests", "" ]
Is there any clean way to supress the unicode character prefix when printing an object using the pprint module? ``` >>> import pprint >>> pprint.pprint({u'foo': u'bar', u'baz': [u'apple', u'orange', u'pear', u'guava', u'banana'], u'hello': u'world'}) {u'baz': [u'apple', u'orange', u'pear', u'guava', u'banana'], u'foo...
It could be done by overriding the format method of the PrettyPrinter object, and casting any unicode object to string: ``` import pprint def my_safe_repr(object, context, maxlevels, level): typ = pprint._type(object) if typ is unicode: object = str(object) return pprint._safe_repr(object, context...
This may be too much, but one possible way is to implement a wrapper over the output stream: ``` import pprint,sys,re class writer : def write(self, text): text=re.sub(r'u\'([^\']*)\'', r'\1',text) sys.stdout.write(text) wrt=writer() d = { u'foo': u'bar', u'baz': [u'apple', u'orange', u'p...
Suppress unicode prefix on strings when using pprint
[ "", "python", "pprint", "" ]
I have this query: ``` SELECT `gift_donations`.*, `scholarships`.`name` AS scholarship_name FROM (`gift_donations`) LEFT OUTER JOIN `scholarships` scholarships ON `scholarships`.`id` = `gift_donations`.`scholarship_id` WHERE `gift_donations`.`contact_id` = '13' AND `gift_donations`.`in_memory` REGEXP '[a-...
`AND` takes precedence over `OR`. You should surround your second `AND` clause with parentheses like such ``` (`gift_donations`.`in_memory` REGEXP '[a-zA-Z]+' OR in_honor REGEXP '[a-zA-Z]+') ``` As it is, you have essentially written following where clause ``` A and B or C ``` wich due to operator precedence is equ...
Use bracket. ``` WHERE `gift_donations`.`contact_id` = '13' AND ( `gift_donations`.`in_memory` REGEXP '[a-zA-Z]+' OR in_honor REGEXP '[a-zA-Z]+') ORDER BY `gift_donations`.`id` desc ```
SQL Query not filtering right data
[ "", "mysql", "sql", "database", "" ]
Is there a function in Google App Engine to test if a string is valid 'string key' prior to calling `memcache.get(key)` without using `db.get()` or `db.get_by_key_name()` first? In my case the key is being passed from the user's get request: `obj = memcache.get(self.request.get("obj"))` Somehow I'd like to know if th...
That is probably the most efficient (and practical) way to determine if the key string is valid. The code is obviously performing that test for you before it attempts to retrieve the entity from memcache/datastore. Even better, Google will update that code if necessary. ``` try: obj = memcache.get(self.request.get...
A db module key sent to a client should pass through str(the\_key) which gives you an URL safe encoded key. Your templating environment etc.. will do this for you just by rendering the key into a template. On passing the key back from a client, you should recreate the key with `key = db.Key(encoded=self.request.get("o...
Test if string is valid key prior to memcache.get()
[ "", "python", "google-app-engine", "python-memcached", "" ]