Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
``` import pylab as pl data = """AP 10 AA 20 AB 30 BB 40 BC 40 CC 30 CD 20 DD 10""" grades = [] number = [] for line in data.split("/n"): x, y = line.split() grades.append(x) number.append(int(y)) fig = pl.figure() ax=fig.add_subplot(1,1,1) ax.bar(grades,number) p.show() ``` This is my code, i...
The problem is that your `for-loop` is splitting at the wrong token (`/n`) instead of `\n`. But when you only want to split the newlines there actually is a `splitlines()`-method on strings that does just that: you should actually use this method, because it will handle different newline delimiters between \*nix and W...
You have a line that does *not* have two items on it: ``` x, y = line.split() ``` did not split to two elements and that throws the error. Most likely because you are not splitting your `data` variable properly and have the whole text as *one* long text. `/n` does not occur in your `data` data. Use `.splitlines()` ...
A 'too many values to unpack' error in python
[ "", "python", "python-3.x", "syntax-error", "" ]
I have two lists: one contains the products and the other one contains their associated prices. The lists can contain an undefined number of products. An example of the lists would be something like: * Products : ['Apple', 'Apple', 'Apple', 'Orange', 'Banana', 'Banana', 'Peach', 'Pineapple', 'Pineapple'] * Prices: ['1...
``` from collections import OrderedDict products = ['Apple', 'Apple', 'Apple', 'Orange', 'Banana', 'Banana', 'Peach', 'Pineapple', 'Pineapple'] prices = ['1.00', '2.00', '1.50', '3.00', '0.50', '1.50', '2.00', '1.00', '1.00'] min_prices = OrderedDict() for prod, price in zip(products, prices): min_prices[prod] = m...
Probably the simplest way is to take advantage of dictionaries' enforcement of unique keys: ``` from operator import itemgetter Products = ['Apple', 'Apple', 'Apple', 'Orange', 'Banana', 'Banana', 'Peach', 'Pineapple', 'Pineapple'] Prices = ['1.00', '2.00', '1.50', '3.00', '0.50', '1.50', '2.00', '1.00', '1.00'] fina...
Data processing in lists with duplicates in Python
[ "", "python", "list", "duplicates", "" ]
This is my simple code. ``` def reverseString(aStr): newStr = '' if len(aStr) == 0: return newStr else: newStr = newStr + aStr[len(aStr)-1] return reverseString(aStr[:len(aStr)-1]) ``` For `'alina'` (if I insert `print newStr` before `return reverseString...`), the output is: `newS...
Something like this: ``` def reverseString(aStr, newStr = ''): if len(aStr) == 0: return newStr else: newStr = newStr + aStr[-1] #-1 returns the last element from the string return reverseString(aStr[:-1], newStr) #slice the string up to second last char print reverseString("foobar") ...
The reason your function has not worked is because you forgot to return `newStr` at the end. And every time you call your function, `newStr` will just get reset back to `''`. There's an easier way to do what you are doing. Use [slicing](http://docs.python.org/2/tutorial/introduction.html#strings): ``` def reverseStri...
Writing a string backwards
[ "", "python", "string", "recursion", "" ]
I want to define a class containing `read` and `write` methods, which can be called as follows: ``` instance.read instance.write instance.device.read instance.device.write ``` To not use interlaced classes, my idea was to overwrite the `__getattr__` and `__setattr__` methods and to check, if the given name is `device...
You must call the parent class `__setattr__` method: ``` class MyTest(object): def __init__(self, x): self.x = x def __setattr__(self, name, value): if name=="device": print "device test" else: super(MyTest, self).__setattr__(name, value) # in pytho...
Or you can modify `self.__dict__` from inside `__setattr__()`: ``` class SomeClass(object): def __setattr__(self, name, value): print(name, value) self.__dict__[name] = value def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 sc = SomeClass(attr1=1, attr...
How to use __setattr__ correctly, avoiding infinite recursion
[ "", "python", "python-2.7", "getattr", "setattr", "" ]
I have a query in which I want to select data from a column where the data is a date. The problem is that the data is a mix of text and dates. This bit of SQL only returns the longest text field: ``` SELECT MAX(field_value) ``` Where the date does occur, it is always in the format xx/xx/xxxx I'm trying to select th...
Try this using [`ISDATE`](http://msdn.microsoft.com/en-us/library/ms187347.aspx) and [`CONVERT`](http://msdn.microsoft.com/en-us/library/ms187928.aspx): ``` SELECT MAX(CONVERT(DateTime, MaybeDate)) FROM ( SELECT MaybeDate FROM MyTable WHERE ISDATE(MaybeDate) = 1) T ``` You could also use `MAX(CAST(MaybeDate AS ...
To do this without a conversion error: ``` select max(case when isdate(col) = 1 then cast(col as date) end) -- or use convert() from . . . ``` The SQL statement does *not* specify the order of operations. So, even including a `where` clause in a subquery will *not* guarantee that only dates get converted. In fact, t...
Select data in date format
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a scenario similar to the following and all I'm want to do is find the max of three columns - this seems like a very long-winded method that I'm using to find the column `mx`. What is a shorter more elegant solution? ``` CREATE TABLE #Pig ( PigName CHAR(1), PigEarlyAge INT, PigMiddleAge INT, PigOld...
SQL Server has no equivalent of the `GREATEST` function in other RDBMSs that accepts a list of values and returns the largest. However you can simulate something similar by using a [table valued constructor](http://msdn.microsoft.com/en-us/library/dd776382.aspx) consisting of the desired columns then applying `MAX` to...
If you want the max of the three fields: ``` select (case when max(PigEarlyAge) >= max(PigMiddleAge) and max(PigEarlyAge) >= max(PigOldAge) then max(PigEarlyAge) when max(PigMiddleAge) >= max(PigOldAge) then max(PigMiddleAge) else max(PigOldAge) end) ...
Max of several columns
[ "", "sql", "sql-server-2012", "" ]
I am trying to join two tables. Unfortunately there is no single column to join them. Only the combination of 2 columns (in each of the tables) creates a unique identifier that enables me to make an inner join. How do I do that? edit: someone suggested making a join using AND. Unfortunately this does not seem to work....
I think this will do the job ``` select t1.orderNo, t1.operationNo, t2.description from Table1 t1 inner join Table2 t2 on t1.orderNo = t2.orderNo and t1.operationNo = t2.OperationNo ```
Try the following ``` SELECT * FROM t1, t2 WHERE t1.f1 + t1.f2 = t2.f3 ``` On the other hand if you have 2 columns on which you want to join then [DanFromGermany's answer](https://stackoverflow.com/a/17039661/7028) is appropriate.
Join 2 tables using the combination of 2 columns
[ "", "sql", "join", "" ]
I have this query: ``` SELECT e.*, u.name AS event_creator_name FROM `edu_events` e LEFT JOIN `edu_users` u ON u.user_id = e.event_creator INNER JOIN `edu_event_participants` ON participant_event = e.event_id && participant_user = 1 WHERE MONTH(e.event_date_start) = 6 AND Y...
If I understand correctly you only want the results where there is an entry on edu\_event\_participants with the same event\_id and participant\_user = 1 but only if event\_type = 1, but you don't really want to get any information from the edu\_event\_participants table. If that is the case: ``` SELECT e.*, u.na...
I have edited the below following further feedback from @Matthias ``` -- This will get all events for a given user plus all globals SELECT e.*, u.name AS event_creator_name FROM `edu_users` u -- in the events INNER JOIN `edu_events` e  ON ( -- Get all the ones that the user is participant ...
MySQL do INNER JOIN if specific value is 1
[ "", "mysql", "sql", "" ]
As per subject - I am trying to replace slow SQL IN statement with an INNER or LEFT JOIN. What I am trying to get rid of: ``` SELECT sum(VR.Weight) FROM verticalresponses VR WHERE RespondentID IN ( SELECT RespondentID FROM verticalstackedresponses VSR WHERE VSR.Question = 'Brand Aware' ) ``` The ab...
The subquery ``` SELECT RespondentID FROM verticalstackedresponses VSR WHERE VSR.Question = 'Brand Aware' ``` could maybe be returning multiple rows for any RespondentID, then you would get different results between join and in versions Something along the lines of this may give the same results ``` SELECT ...
* A JOIN will multiply rows because it's an "Equi join" * IN (and EXISTS) will not multiply rows because these are "Semi joins" Either way, you need suitable indexes, probably * verticalresponses, (RespondentID) * verticalstackedresponses, (Question, RespondentID) See [Using 'IN' with a sub-query in SQL Statements](...
SQL - Replacing slow "IN" statement with a JOIN
[ "", "sql", "performance", "" ]
I'm accessing a Firebird database through Microsoft Query in Excel. I have a parameter field in Excel that contains a 4 digit number. One of my DB tables has a column (`TP.PHASE_CODE`) containing a 9 digit phase code, and I need to return any of those 9 digit codes that start with the 4 digit code specified as a param...
If you use `LIKE '?%', then the question mark is literal text, not a parameter placeholder. You can use `LIKE ? || '%'`, or alternatively if your parameter itself never contains a LIKE-pattern: `STARTING WITH ?` which might be more efficient if the field you're querying is indexed.
You can do ``` and TP.PHASE_CODE like ? ``` but when you pass your parameter `8000` to the SQL, you have to add the `%` behind it, so in this case, you would pass `"8000%"` to the SQL.
Using the '?' Parameter in SQL LIKE Statement
[ "", "sql", "excel", "parameters", "firebird", "sql-like", "" ]
I want to join two tables even if there is no match on the second one. table user: ``` uid | name 1 dude1 2 dude2 ``` table account: ``` uid | accountid | name 1 1 account1 ``` table i want: ``` uid | username | accountname 1 dude1 account1 2 dude2 NULL ``` the query i'...
use `Left Join` instead ``` SELECT user.uid as uid, user.name as username, account.name as accountname FROM user LEFT JOIN account ON user.uid=account.uid ```
Try with a `LEFT JOIN` query ``` SELECT user.uid as uid, user.name as username, account.name as accountname FROM user LEFT JOIN account ON user.uid=accout.uid ``` I'd like you have a look at this visual representation of [**`JOIN`** query](http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins...
right join even if row on second table does not exist
[ "", "mysql", "sql", "" ]
I am working on unicode values in python for sometime now. Firstly, all the questions and answers help alot. Thanks :) Next, I am stuck in my project where I want to isolate the unicode values for each language. Like, a certain function only accepts hindi codes which are from unicode values 0900 to 097F. Now I want i...
The best solution is most likely using regex to filter out the unwanted characters. You basically need a regex to match your Hindi characters, but as far as I know Hindi characters are bugged in "re" module, so I recommend downloading "regex" module with the command: > $ pip install regex After that you can just simp...
``` def filter(text, range): return ''.join([char for char in text if ord(char) in range]) ```
How to filter out unicode characters in Python?
[ "", "python", "unicode", "" ]
Is there a way to include the following line as a map? ``` alist = [] for name in range(4): for sname in range(15): final = Do_Class(name, sname) #Is a class not to be bothered with alist.append(final) ``` Instead as alist.append(map(.....multiple map within maybe?)) ...
I would use `itertools.product` : ``` from itertools import product alist = [Do_Class(x[0], x[1]) for x in product(range(4), range(15))] ``` if you absolutely need map : ``` alist = map(lambda x: Do_Class(x[0], x[1]), product(range(4), range(15))) ``` if you want a shorter version, but less readable: ``` alist = m...
You do not want/need `map` for this: ``` alist = [Do_Class(name, sname) for sname in range(15) for name in range(4)] ``` Using `map` would only be appropriate if you could do something like `map(somefunc, somelist)`. If that's not the case you'd need a lambda which just adds unnecessary overhead compared to a list co...
python: map() two iterations with variables in map iterator
[ "", "python", "python-2.7", "dictionary", "" ]
I am trying to find the unique differences between 5 different lists. I have seen multiple examples of how to find differences between two lists but have not been able to apply this to multiple lists. It has been easy to find the similarities between 5 lists. Example: ``` list(set(hr1) & set(hr2) & set(hr4) & set(h...
How's this? Say we have input lists `[1, 2, 3, 4]`, `[3, 4, 5, 6]`, and `[3, 4, 7, 8]`. We would want to pull out `[1, 2]` from the first list, `[5, 6]` from the second list, and `[7, 8]` from the third list. ``` from itertools import chain A_1 = [1, 2, 3, 4] A_2 = [3, 4, 5, 6] A_3 = [3, 4, 7, 8] # Collect the input...
Could this help? I m assuming a list of lists to illustrate this example. But you can modify the datastructure to cater to your needs ``` from collections import Counter from itertools import chain list_of_lists = [ [0,1,2,3,4,5], [4,5,6,7,8,8], [8,9,2,1,3] ] counts = Counter(chain.from_iterable(map(set, ...
Unique features between multiple lists
[ "", "python", "list", "set", "unique", "" ]
So, I have lists of words and I need to know how often each word appears on each list. Using ".count(word)" works, but it's too slow (each list has thousands of words and I have thousands of lists). I've been trying to speed things up with numpy. I generated a unique numerical code for each word, so I could use numpy....
Don't use numpy for this. Use [`collections.Counter`](http://docs.python.org/2/library/collections#counter-objects) instead. It's designed for this use case.
Why not reduce your integers to the minimum set using `numpy.unique`: ``` original_keys, lookup_vals = numpy.unique(big_int_string_array, return_inverse=True) ``` You can then just use `numpy.bincount` on `lookup_vals`, and if you need to get back the original string unique integer, you can just use the the values of...
Can I trick numpy.histogram into behaving like numpy.bincount?
[ "", "python", "numpy", "histogram", "" ]
I want to merge strings (words) that are similar (string is within other string). ``` word wor words wormhole hole ``` Would make: ``` words wormhole ``` As `wor` overlaps with: `word`, `words`, `wormhole` -`wor` is discarded; `word` overlaps with: `words` - `word` is discarded; `hole` overlaps with: `wor...
It seems to me that sorting the words longest-to-shortest, we can then step through the sorted list only once, matching only against kept words. I'm poor at algorithmic analysis, but this makes sense to me and I *think* the performance would be good. It also seems to work, assuming the order of the kept words doesn't m...
In Ruby: ``` list = %w[word wor words wormhole] list.uniq .tap{|a| a.reverse_each{|e| a.delete(e) if (a - [e]).any?{|x| x.include?(e)}}} ```
Merge/Discard overlapping words
[ "", "python", "ruby", "perl", "bash", "" ]
I have a question related to python code. I need to aggregate if the key = kv1, how can I do that? ``` input='num=123-456-7890&kv=1&kv2=12&kv3=0' result={} for pair in input.split('&'): (key,value) = pair.split('=') if key in 'kv1': print value result[key] += int(value) print result['kv1'] ``` Thanks a lot!!
I'm assuming you meant `key == 'kv1'` and also the `kv` within `input` was meant to be `kv1` and that `result` is an empty `dict` that doesn't need `result[key] += int(value)` just `result[key] = int(value)` ``` input = 'num=123-456-7890&kv1=1&kv2=12&kv3=0' keys = {k: v for k, v in [i.split('=') for i in input.split('...
``` import urlparse urlparse.parse_qs(input) ``` results in: {'num': ['123-456-7890'], 'kv2': ['12'], 'kv': ['1'], 'kv3': ['0']} The keys are aggregated for you.
Aggregating key value pair in python
[ "", "python", "key-value", "aggregation", "" ]
Using Python2.7, if I try to compare the identity of two numbers, I don't get the same results for `int` and `long`. **int** ``` >>> a = 5 >>> b = 5 >>> a is b True ``` **long** ``` >>> a = 885763521873651287635187653182763581276358172635812763 >>> b = 885763521873651287635187653182763581276358172635812763 >>> a is...
### Why is the behavior different between the two? When you create a new value in CPython, you essentially create an entire new object containing that value. For small integer values (from -5 to 256), CPython decides to reuse old objects you have created earlier. This is called *interning* and it happens for performan...
This isn't a difference between `int` and `long`. CPython interns small ints (from `-5` to `256`) ``` >>> a = 257 >>> b = 257 >>> a is b False ```
Why are CPython ints unique and long not?
[ "", "python", "identity", "python-2.x", "" ]
I have a MySQL table named 'events' that contains event data. The important columns are 'start' and 'end' which contain string (YYYY-MM-DD) to represent when the events starts and ends. I want to get the records for all the active events in a time period. Events: ``` ------------------------------ ID | START | ...
If I understood correctly you are trying to use a single query, i think you can just merge your date search toghter in `WHERE` clauses ``` SELECT id FROM events WHERE start BETWEEN '2013-06-13' AND '2013-07-22' AND end BETWEEN '2013-06-13' AND '2013-07-22' ``` or even more simply you can just use both column to se...
You need the events that start and end within the scope. But that's not all: you also want the events that start within the scope and the events that end within the scope. But then you're still not there because you also want the events that start before the scope and end after the scope. Simplified: 1. events with a...
MySQL query to select events between start/end date
[ "", "mysql", "sql", "date", "date-range", "" ]
I am taking a query from a database, using two tables and am getting the error described in the title of my question. In some cases, the field I need to query by is in table A, but others are in table B. I dynamically create columns to search for (which can either be in table A or table B) and my WHERE clause in my cod...
``` Employee ------------------ Emp_ID Emp_Name Emp_DOB Emp_Hire_Date Emp_Supervisor_ID Sales_Data ------------------ Check_ID Tender_Amt Closed_DateTime Emp_ID ``` Every column you reference should be proceeded by the table alias (but you already knew that.) For instance; ``` SELECT E.Emp_ID, B.Check_ID,...
You have to write your where clause in such a way that you can say A.field\_from\_A or B.field\_from\_B. You can always pass A.field\_from\_A. Although, you don't really want to say `SELECT * FROM A INNER JOIN B ON A.id=B.id where B.id = '1'`. You would want to say `SELECT * FROM B INNER JOIN A ON B.id=A.id where B...
How to fix an "ambigous column name error using inner join" error
[ "", "sql", "coldfusion", "" ]
I'm new in Python but basically I want to create sub-groups of element from the list with a double loop, therefore I gonna compare the first element with the next to figure out if I can create these sublist, otherwise I will break the loop inside and I want continue with the last element but in the main loop: Example:...
No loop! Well at least, no *explicit* looping... ``` import itertools def process(lst): # Guard clause against empty lists if len(lst) < 1: return lst # use a dictionary here to work around closure limitations state = { 'prev': lst[0], 'n': 0 } def grouper(x): if x < state['prev'...
I used a double loop as well, but put the inner loop in a function: ``` #!/usr/bin/env python def process(lst): def prefix(lst): pre = [] while lst and (not pre or pre[-1] <= lst[0]): pre.append(lst[0]) lst = lst[1:] return pre, lst res=[] while lst: ...
Find monotonic sequences in a list?
[ "", "python", "for-loop", "iteration", "" ]
I have a Python application which outputs an SQL file: ``` sql_string = "('" + name + "', " + age + "')," output_files['sql'].write(os.linesep + sql_string) output_files['sql'].flush() ``` This is not done in a `for` loop, it is written as data becomes available. Is there any way to 'backspace' over the last comma ch...
Use seek to move your cursor one byte (character) backwards, then write the new character: ``` f.seek(-1, os.SEEK_CUR) f.write(";") ``` This is the easiest change, maintaining your current code ("working code" beats "ideal code") but it would be better to avoid the situation.
How about adding the commas before adding the new line? ``` first_line = True ... sql_string = "('" + name + "', " + age + "')" if not first_line: output_files['sql'].write(",") first_line = False output_files['sql'].write(os.linesep + sql_string) output_files['sql'].flush() ... output_files['sql'].write(";"...
"Backspace" over last character written to file
[ "", "python", "" ]
This question is related with [Occasionally Getting SqlException: Timeout expired](https://stackoverflow.com/questions/16917107/occasionally-getting-sqlexception-timeout-expired/16917533?noredirect=1#comment24632507_16917533). Actually, I am using `IF EXISTS... UPDATE .. ELSE .. INSERT` heavily in my app. But user Remu...
Use [MERGE](http://technet.microsoft.com/en-us/library/bb510625.aspx) Your SQL fails because 2 concurrent overlapping and very close calls will both get "false" from the EXISTS before the INSERT happens. So they both try to INSERT, and of course one fails. This is explained more here: [Select / Insert version of an U...
The problem with `IF EXISTS ... UPDATE ...` (and `IF NOT EXISTS ... INSERT ...`) is that under concurrency multiple threads (transactions) will execute the `IF EXISTS` part and *all reach the same conclusion* (eg. it does not exists) and try to act accordingly. Result is that all threads attempt to INSERT resulting in ...
Danger of using 'IF EXISTS... UPDATE .. ELSE .. INSERT' and what is the alternative?
[ "", "sql", "sql-server-2008", "" ]
With Back-end validations I mean, during the- Triggers,CHECK, Procedure(Insert, Update, Delete), etc. **How practical or necessary** are they now, where nowadays most of these validations are handled in front-end strictly. **How much of back-end validations are good for a program?** Should small things be left out of b...
This is a conceptual question. In general modern programs are built in 3 layers: 1. Presentation 2. Business Logic 3. Database As a rule, layer 1 **may** elect to validate all input in a modern application, providing the user with quick feedback on possible issues (for example a JS popup saying *"this is not a valid ...
This might help: 1. Front end (interface) validation is for data entry help and contexual messages. This ensures that the user has a hassle free data entry experience; and minimizes the roundtrip required for validate *correctness*. 2. Application level validation is for business logic validation. The values are corre...
Is it practical to have back-end (database side) validation for everything?
[ "", "sql", "database", "" ]
I am using a `virtualenv`. I have `fabric` installed, with `pip`. But a `pip freeze` does not give any hint about that. The package is there, in my `virtualenv`, but pip is silent about it. Why could that be? Any way to debug this?
I just tried this myself: create a virtualenv in to the "env" directory: ``` $virtualenv2.7 --distribute env New python executable in env/bin/python Installing distribute....done. Installing pip................done. ``` next, activate the virtual environment: ``` $source env/bin/activate ``` the prompt changed. no...
You can try using the `--all` flag, like this: ``` pip freeze --all > requirements.txt ```
pip freeze does not show all installed packages
[ "", "python", "virtualenv", "pip", "fabric", "" ]
I have a table with lakhs of rows. Now, suddenly I need to create a varchar column index. Also, I need to perform some operations using that column. But its giving innodb\_lock\_wait\_timeout exceeded error. I googled it and changed the value of innodb\_lock\_wait\_timeout to 500 in my.ini file in my mysql folder. But ...
I found the answer. I need to run a query: `show variables like 'innodb_lock_wait_timeout';`.
There can be a difference between your command and the server settings: For Example: ``` SHOW GLOBAL VARIABLES LIKE '%INNODB_LOCK_WAIT_TIMEOUT%'; -- Default 50 seconds SET @@SESSION.innodb_lock_wait_timeout = 30; -- innodb_lock_wait_timeout changed in your session -- These queries will produce identical results, ...
effective innodb_lock_wait_timeout value check
[ "", "mysql", "sql", "innodb", "" ]
I'm working on a python temperature converter. It will convert Fahrenheit to Celsius and vice versa. I haven't added the if statements yet, or the Celsius to Fahrenheit function yet. But I'm having trouble with this Fahrenheit to Celsius function, ``` def F_C(x): x = raw_input("Please Enter A Value") x = int(x...
You are not returning a value. Also you are not storing all the computed values back into the variable `x` ``` def F_C(x): x = raw_input("Please Enter A Value") x = int(x) x = x - 32 x = x * 0.55 return x ``` You can simplify it to: ``` def F_C(): x = raw_input("Please Enter A Value") ret...
do this: ``` def F_C(): x = raw_input("Please Enter A Value") x = int(x) x = x - 32 x = x * 0.55 return x ``` becuase youre just assigning x the reassigning x or do this: ``` def F_C(): x = raw_input("Please Enter A Value") x = int(x) x = (x - 32)*0.55 return x print F_C() ``` ...
Python Temperature Converter
[ "", "python", "parameter-passing", "converters", "" ]
I am pretty new to Python so it might sound obvious but I haven't found this everywhere else Say I have a application (module) in the directoy A/ then I start developing an application/module in another directory B/ So right now I have ``` source/ |_A/ |_B/ ``` From B I want to use functions are classes...
Normally when you are developing a single application your directory structure will be similar to ``` src/ |-myapp/ |-pkg_a/ |-__init__.py |-foo.py |-pkg_b/ |-__init__.py |-bar.py |-myapp.py ``` This lets your whole project ...
I would recommend using the `imp` module ``` import imp imp.load_source('module','../B/module.py') ``` Else use absolute path starting from root ``` def setup_paths(): import sys sys.path.append('/path/to/B') ```
Developing Python modules - adding them to the Path
[ "", "python", "" ]
I would like students to solve a quadratic program in an assignment without them having to install extra software like cvxopt etc. Is there a python implementation available that only depends on NumPy/SciPy?
I ran across a good solution and wanted to get it out there. There is a python implementation of LOQO in the ELEFANT machine learning toolkit out of NICTA (<http://elefant.forge.nicta.com.au> as of this posting). Have a look at optimization.intpointsolver. This was coded by Alex Smola, and I've used a C-version of the ...
I'm not very familiar with quadratic programming, but I think you can solve this sort of problem just using `scipy.optimize`'s constrained minimization algorithms. Here's an example: ``` import numpy as np from scipy import optimize from matplotlib import pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D #...
Quadratic Program (QP) Solver that only depends on NumPy/SciPy?
[ "", "python", "numpy", "scipy", "mathematical-optimization", "" ]
``` my_list = ['a', 'b', 'c', 'd', 'e'] for i in my_list: my_need = my_list (i) print (my_need) ``` What's wrong? I want to obtain every elements of my\_list using for loop.
A for loop over a list or sequence in python automatically fetches one item at a time from the sequence: ``` my_list = ['a', 'b', 'c', 'd', 'e'] for my_need in my_list: print my_need ``` or may be you wanted to do something like this: ``` >>> my_list = ['a', 'b', 'c', 'd', 'e'] >>> my_need = [] >>> for item in my...
I think what you are looking for is an array slice: ``` my_need = my_list[:] ``` This will copy each element from my\_list into my\_need, so then print (my\_need) should return ``` ['a', 'b', 'c', 'd', 'e'] ``` If you want to concatenate these into a string, you could also do this: ``` my_need = "" for i in my_lis...
What is wrong when I want to get every elements of my list using for loop?
[ "", "python", "python-3.x", "" ]
hey I'm trying to change elements in my Python list, and I just can't get it to work. ``` content2 = [-0.112272999846, -0.0172778364044, 0, 0.0987861891257, 0.143225416783, 0.0616318333661, 0.99985834, 0.362754457762, 0.103690909138, 0.0767353098528, 0.0605534405723, 0.0, ...
You should avoid modifying by index in Python ``` >>> content2 = [-0.112272999846, -0.0172778364044, 0, 0.0987861891257, 0.143225416783, 0.0616318333661, 0.99985834, 0.362754457762, 0.103690909138, 0.0767353098528, 0.0605534405723, 0.0, -0.105599793882, -0.0193182826135, 0.040838960163] >>> [float(x) if x else ...
You should use list comprehension here: ``` >>> content2[:] = [x if x!= 0.0 else None for x in content2] >>> import pprint >>> pprint.pprint(content2) [-0.112272999846, -0.0172778364044, None, 0.0987861891257, 0.143225416783, 0.0616318333661, 0.99985834, 0.362754457762, 0.103690909138, 0.0767353098528, 0.060...
python changing integers/ floats to None in list
[ "", "python", "list", "python-2.7", "" ]
I am working on a network traffic monitor project in Python. Not that familiar with Python, so I am seeking help here. In short, I am checking both in and out traffic, I wrote it this way: ``` for iter in ('in','out'): netdata = myhttp() print data ``` netdata is a list consisting of nested lists, it...
Apart from minor fixes on your code (the issues raised by @Zero Piraeus), your question was probably answered [here](https://stackoverflow.com/questions/6340351/python-iterating-through-list-of-list). A possible code to traverse a list of lists in N degree (a tree) is the following: ``` def traverse(item): try: ...
The code you've shown doesn't make a great deal of sense. Here's what it does: * Iterate through the sequence `'in', 'out'`, assigning each of those two strings in turn to the variable `iter` (masking the built-in function [`iter()`](http://docs.python.org/2/library/functions.html#iter) in the process) on its two pass...
iterate python nested lists efficiently
[ "", "python", "nested-lists", "" ]
I'm trying to figure out how to count the number of items in a nest list. I'm stuck at how to even begin this. For example if I were to do NestLst([]) it would print 0 but if I do ``` NestLst([[2, [[9]], [1]], [[[[5]]], ['hat', 'bat'], [3.44], ['hat', ['bat']]]] ``` it would return 9. Any help on how to begin this or...
Your question contains the keyword: *recursively*. Create a function that iterates over the list and if it finds a non-list item, adds one to the count, and if it finds a list, calls itself recusively. The issue with **your** code its that you are using length instead of a recursive call. Here is a pythonic pseudocod...
``` import collections def NestLst(seq): if isinstance(seq, str) or not isinstance(seq, collections.Iterable): return 1 return sum(NestLst(x) for x in seq) >>> NestLst([[2, [[9]], [1]], [[[[5]]], ['hat', 'bat'], [3.44], ['hat', ['bat']]]]) 9 ```
How to count items in nest list?
[ "", "python", "" ]
In our running project,Using ASP.net 3.5 with C# and MS SQL, Currently its database size become 4 TB. It will increase gradullay , so we are looking for a solution. Some 1 told me to about BigData (use Hive + Hadoop). And he was giving the following refernce <https://cwiki.apache.org/confluence/display/Hive/GettingStar...
I'll share some of my experience. First of all I would analyze whether Hadoop fits into my requirements or not. Hadoop is not a replacement for traditional RDBMSs. It is meant for totally different purpose which is `offline batch processing` unlike RDBMSs which are used for real time queries. So, if you have real time ...
As many others pointed out, a 4TB database is not a reason to move to to Hadoop + Hive. There has to be a pain point that you can't solve with Ms SQL to look for options. Just as a thought, have you considered moving to Azure so that your infrastructure can grow with you?
SQL to BigData Migration?
[ "", "sql", "c#-4.0", "hadoop", "hive", "" ]
Difference between create instance of an objects by () and without parentheses? Assume this is my simple class: ``` class ilist(list): t1 = "Test1" t2 = "Test2" ``` And making the instances to this two variables: ``` list1 = ilist() list2 = ilist ``` When print the two instances ``` >>> list1 [] >>> list2...
`list1 = ilist()` creates an object of the class. `list2 = ilist` makes a reference to the class itself. Classes are first-class objects in Python, which means they can be assigned just like any other object. Because the attributes are part of the class, they're also part of the objects that are created with that clas...
When you are not calling the class (omitting the `()`), you are not making instances. You are creating another reference to the *class*. `()` calls a class to produce an instance. Your `list2` variable is merely a reference to your `ilist` class object. That class object has both `t1` and `t1` attributes, so you can r...
Create object using parentheses python
[ "", "python", "python-3.x", "" ]
I need to verify if the version number of application bigger than 1.18.10. How regular expression should look like in this case?
Don't use regular expressions for this. Use `split` and `tuple` comparison: ``` def is_recent(version): version_as_ints = (int(x) for x in version.split('.')) return tuple(version_as_ints) > (1, 18, 10) ``` And then check `is_recent("1.10.11")` or `is_recent("1.18.12")`
Seems like this battery has already been included in Python in [`distutils.version`](http://docs.python.org/2/distutils/apiref.html#module-distutils.version) : ``` from distutils.version import LooseVersion LooseVersion("1.18.11") > LooseVersion("1.18.10") #True LooseVersion("1.2.11") > LooseVersion("1.18.10") #False...
Regular expression for version number bigger than 1.18.10
[ "", "python", "regex", "" ]
I have the following values in my columns and I need to order them on the basis of their name.Datatype of the column is VARCHAR2 (25 BYTE).My data is ``` Oracle 10g, Oracle 9i, Oracle 11g ``` When I user ORDER BY Name, I got result in the order ``` Oracle 10g Oracle 11g Oracle 9i ``` What can I do to g...
``` /* order based on a number in string */ SELECT str FROM ( SELECT 'Oracle 10g' str FROM DUAL UNION ALL SELECT 'Oracle 11g' FROM DUAL UNION ALL SELECT 'Oracle 9i' FROM DUAL ) ORDER BY TO_NUMBER(REGEXP_REPLACE(str, '\D')) /* result */ Oracle 9i Oracle 10g Oracle 11g ```
Edited: Works as expected Here we have alpha numeric characters. please use `substring` function. > select column\_name from table\_name order by **SUBSTRING**(name,0,8) Use ascending or descending as per your requirement. Note: 8 is the length, because Oracle and Space is the common characters between them.
ORDER BY with characters and numeric
[ "", "sql", "sql-order-by", "varchar", "" ]
I have a dataframe in pandas which I would like to write to a CSV file. I am doing this using: ``` df.to_csv('out.csv') ``` And getting the following error: ``` UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128) ``` * Is there any way to get around this eas...
To delimit by a tab you can use the `sep` argument of [`to_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html): ``` df.to_csv(file_name, sep='\t') ``` To use a specific encoding (e.g. 'utf-8') use the `encoding` argument: ``` df.to_csv(file_name, sep='\t', encoding='utf-8') ```
When you are storing a `DataFrame` object into a **csv file** using the `to_csv` method, you probably wont be needing to store the **preceding indices** of each **row** of the `DataFrame` object. You can **avoid** that by passing a `False` boolean value to `index` parameter. Somewhat like: ``` df.to_csv(file_name, e...
Writing a pandas DataFrame to CSV file
[ "", "python", "csv", "pandas", "dataframe", "" ]
I'm writting a Cython wrapper to a C function. I have a pxd file with the following signature: ``` double contr_hrr(int lena, double xa, double ya, double za, double *anorms) ``` When I try to call this from a pyx file ``` ... return contr_hrr(len(acoefs),a.origin[0],a.origin[1],a.origin[2],anorms2) ``` where **ano...
1. cimport `array`: ``` from cpython cimport array ``` 2. Create an array object from your list. array class constructor will do all the heavy lifting allocating memory and iterating over your list (could be any iterable actually). ``` cdef array.array anorms2_arr = array.array('d', anorms2) ``` 3. ...
I think that you cannot do otherwise, but convert it by yourself : ``` cimport cython from libc.stdlib cimport malloc, free ... cdef double *anorms cdef unsigned int i; anorms = <double *>malloc(len(anorms2)*cython.sizeof(double)) if anorms is NULL: raise MemoryError() for i in xrange(len(anorms2)): anorms[...
Cython: can't convert Python object to 'double *'
[ "", "python", "arrays", "list", "cython", "" ]
I'm trying to use the delete command in Access using the shown specifications, but Access keeps saying "Data type mismatch in criteria expression." Does anyone know what to do? ``` DELETE ORDERS.OrderDate, ORDERS.CustomerID FROM ORDERS WHERE (((ORDERS.OrderDate)='2008-01-24') AND ((ORDERS.CustomerID)="C0003")); ```
``` DELETE ORDERS.OrderDate, ORDERS.CustomerID, * FROM ORDERS WHERE (((ORDERS.OrderDate)=#1/24/2008#) AND ((ORDERS.CustomerID)=3)); ```
Try this ``` DELETE ORDERS.OrderDate, ORDERS.CustomerID FROM ORDERS WHERE ORDERS.OrderDate = #01/24/2008# AND ORDERS.CustomerID = "C0003" ```
DELETE in Access?
[ "", "sql", "ms-access", "sql-delete", "mismatch", "" ]
So I need to record a set of 4 integers whose values are different for every second of the day. i.e.: ``` #Here the values are initialized to the same value, however they will change as samples are taken data = [[.25 for numData in range(4)] for numSecs in range(86400)] ``` Now obviously a two dimensional array(gah i...
You may need to modify this a bit and it assume that all lines are of the same length. For this, I had to pad the first column to a fixed width. But if you don't want padding you should be able to calculate the number of 1,2,3,4,.. digit numbers before a particular row. ``` data = [[.25 for numData in range(4)] for nu...
If the lines are of different lengths, then everything after the modified line will be in the wrong position and you have to rewrite all those lines. If the lines all have the same length, then you can `seek()` and `write()` the new data by calculating the line's offset in the file. See [Python File Objects](http://doc...
Editing a single line in a large text file
[ "", "python", "text-files", "" ]
I need to join something like this: ``` ["Círculo", 23] ["Triángulo, 25, 19, "dos"] ``` I have seen this post -> [Joining a list that has Integer values with Python](https://stackoverflow.com/questions/3590165/joining-list-has-integer-values-with-python) But solutions like: ``` ', '.join(map(str, myList)) or ', '.j...
Checking about encodings I found a solution that works for me: ``` u', '.join([unicode(x.decode('utf-8')) if type(x) == type(str()) else unicode(x) for x in a]) ``` The trick is to use `decode('utf-8')` for getting a valid 8-bit representation of the character. Hope this will help.
If you can specify the strings in your list as unicode, like: ``` [u"Círculo", 23] [u"Triángulo", 25, 19, u"dos"] ``` then this should work: ``` u', '.join(unicode(x) for x in list_of_ints) ``` Assuming you are running Python 2.
Python encoding: list to string having special characters and numbers in the list
[ "", "python", "unicode", "encoding", "" ]
I have a tuple that looks like this: ``` ('1 2130 0 279 90 92 193 1\n', '1 186 0 299 14 36 44 1\n') ``` And i want to split it so that each column will be seperate so i can access it in an easier way. So for an example: ``` tuple[0][2] ``` would return `0` ``` tuple[1][3] ``` would return `299` The second part ...
You could use a list comprehension: ``` rows = [row.split() for row in your_tuple] ``` As for `.rstrip()`, you don't need it. `.split()` (with no argument!) takes care of that for you: ``` >>> ' a b c \t\n\n '.split() ['a', 'b', 'c'] ```
Apply `str.split` to each item of the tuple: ``` >>> tup = ('1 2130 0 279 90 92 193 1\n', '1 186 0 299 14 36 44 1\n') >>> t = map(str.split, tup) >>> t [['1', '2130', '0', '279', '90', '92', '193', '1'], ['1', '186', '0', '299', '14', '36', '44', '1']] >>> t[0][2] '0' >>> t[1][3] '299' ```
What are the equivalents of .split() and .rstrip() for a tuple?
[ "", "python", "" ]
When I use requests to access an URL **cookies are automatically sent back to the server** (in the following example the requested URL set some cookie values and then redirect to another URL that display the stored cookie) ``` >>> import requests >>> response = requests.get("http://httpbin.org/cookies/set?k1=v1&k2=v2"...
You can do this by defining a cookie policy to reject all cookies: ``` from http import cookiejar # Python 2: import cookielib as cookiejar class BlockAll(cookiejar.CookiePolicy): return_ok = set_ok = domain_return_ok = path_return_ok = lambda self, *args, **kwargs: False netscape = True rfc2965 = hide_co...
A simpler alternative to creating a new class is to use `http.cookiejar.DefaultCookiePolicy` with an empty list of allowed domains: ``` from requests import Session from http.cookiejar import DefaultCookiePolicy s = Session() s.cookies.set_policy(DefaultCookiePolicy(allowed_domains=[])) ``` From the [documentation](...
How to disable cookie handling with the Python requests library?
[ "", "python", "cookies", "python-requests", "" ]
I have following function that takes a dictionary, sort it and return the list of dictionary values. ``` def sort_dict_values(dic): keys = dic.keys() keys.sort() return map(dic.get, keys) dict1 = {"b":"1", "a":"2", "d":"", "c":"3"} sorted_list = sort_dict_values(dict1) ``` This function returns a list including item...
``` >>> dict1 = {"b":"1", "a":"2", "d":"", "c":"3"} >>> [v for k, v in sorted(dict1.items()) if v] ['2', '1', '3'] ``` As @AlexChamberlain said in the comments, it would reduce the load on the O(N log N) sorting algorithm, by performing the O(N) filter first ``` >>> [v for k, v in sorted(x for x in dict1.items() if x...
You can use `filter` here: ``` from itertools import imap def sort_dict_values(dic): keys = dic.keys() keys.sort() return filter(None,imap(dic.get, keys)) dict1 = {"b":"1", "a":"2", "d":"", "c":"3"} print sort_dict_values(dict1) #['2', '1', '3'] ``` or as suggested by @Alex Chamberlain it would be bet...
Sort dictionary values and discard those which do not have a value
[ "", "python", "dictionary", "" ]
I'm trying to build a query that takes some input parameters. Few things to note... 1. Not all parameters are required to be passed to the query. 2. If a parameter is not going to be passed to the query, must it still be passed anyway but as `NULL`? 3. If a parameter is not passed, how would I build it to not include ...
As a previous poster state, pass NULL for the unused parameters. Then structure your query similar to... ``` SELECT * FROM Table WHERE ( ((nameParameter IS NULL) OR (NameColumn LIKE '%' + NameParameter + '%')) AND ((ageParameter IS NULL) OR (AgeColumn = ageParameter)) AND ((addressParameter IS NULL) OR (A...
The issue is optinal parameters Cannot be used in MYSQL. The workaround is to pass null value for parameter and inside the stored procedure use IF statement to handle the different situations. Take a look here: [Writing optional parameters within stored procedures in MySQL?](https://stackoverflow.com/questions/12652...
MySQL Search Query Using LIKE
[ "", "mysql", "sql", "search", "keyword", "" ]
I have a tuple with some names I want to match against one or more dictionaries. ``` t = ('A', 'B') d1 = {'A': 'foo', 'C': 'bar'} d2 = {'A': 'foo', 'B': 'foobar', 'C': 'bar'} def f(dict): """ Given t a tuple of names, find which name exist in the input dictionary dict, and return the name found and its va...
``` for k in t: try: return k, dic[k] except KeyError: pass ``` If you (like me) don't like exceptions, and assuming `None` is not a legitimate value: ``` for k in t: res = dic.get(k) if res is not None: return k, res ```
``` def f(d): try: return next((x, d[x]) for x in t if x in d) except StopIteration: return () ```
Return the key name and value found in a dictionary given a tuple of names
[ "", "python", "" ]
I have a huge list like ``` ['a', '2'] ['a', '1'] ['b', '3'] ['c', '2'] ['b', '1'] ['a', '1']['b', '1'] ['c', '2']['b', '3'] ['b', '1'] ``` I want to walk through this and get an output of number of each second item for a distinct first item: ``` {a:[2,1,1] b:[3,1,3,1] c:[2,2]} ```
``` data = [['a','2'],['a','1'],['b','3'],['c','2'],['b','1'],['a','1'],['b','1'],['c','2'],['b','3'],['b','1']] result = {} for key, value in data: result.setdefault(key, []).append(value) ``` Outcome: ``` >>> result {'a': ['2', '1', '1'], 'c': ['2', '2'], 'b': ['3', '1', '1', '3', '1']} ``` I prefer [dict.setd...
``` from collections import defaultdict dd = defaultdict(list) for k, v in your_list: dd[k].append(v) ``` Alternatively your data is already sorted (remove the sorted step - or is otherwise okay to sort...) ``` from itertools import groupby from operator import itemgetter print {k: [v[1] for v in g] for k, g in ...
Python list to dict
[ "", "python", "list", "dictionary", "" ]
I've a project at which I've to plot graphs using jQuery AJAX requests, by reading a constantly updated .txt file with python. However, what I really want to do is to keep the content of the file, until the next data is overwritten to file. However, when i try to read this data stack file, -since the python script cons...
This turned out to be simpler than I think. Problem is solved when I change the "a" to "w+r" Here is the working final code: ``` mydatatosend = str(distance0)+","+str(time0)+","+str(distance1).....) print mydatatosend text_file = open("sensor_file.inc","w+r") text_file.write(mydatatosend) text_file.close() ```
Have you tried this? ``` new_text = str(distance0)+","+str(time0)+","+str(distance1).....) print new_text text_file = open("sensor_file.inc","rw") previous_text = text_file.read() total_text = previous_text + new_text text_file.write(total_text) text_file.close() ``` This reads the data previously on the file...
Writing information on an always readable text file with Python
[ "", "jquery", "python", "python-2.7", "fopen", "" ]
I have a need for functions with default arguments that have to be set at function runtime (such as empty lists, values derived from other arguments or data taken from the database) and I am currently using the following pattern to deal with this: ``` def foo(bar, baz=None): baz = baz if baz else blar() # Stuf...
No, that's pretty much it. Usually you test for `is None` so you can safely pass in falsey values like `0` or `""` etc. ``` def foo(bar, baz=None): baz = baz if baz is not None else blar() ``` The old fashioned way is the two liner. Some people may prefer this ``` def foo(bar, baz=None): if baz is None: ...
You can replace ``` baz = baz if baz else blar() ``` with ``` baz = baz or blar() ``` if you're still happy with just testing for falsy values instead of `None`.
Dynamic default arguments in python functions
[ "", "python", "" ]
I am looking for a general and simple way to synchronize the methods of a python class that does not use asynchronous calls by itself. Some possibilities come to my mind: First, the use of decorators on all methods of the class itself: <http://code.activestate.com/recipes/577105-synchronization-decorator-for-class-meth...
I went with the SynchronizeProxy, and it seems to work so far. Since this solution comes closest to what I need, I will select my answer as a solution. If I experience any problems, I will update this answer. ``` #!/usr/bin/env python import types from pprint import pformat from threading import RLock class Synchroni...
If you really need to, you can use the black magic of python metaclasses to dynamically add a decorator to each method of the class at class creation time. The following is a quick example of how you might do this. It creates a generic synchronizer metaclass, which you then subclass to create synchronizers for each spe...
synchronize access to python object
[ "", "python", "synchronization", "" ]
``` out_file = open('result.txt', 'w') A = [1,2,3,4,5,6,7,8,9,10] B = [11,12,13,14,15] for a in A: for b in B: result = a + b print (result, file = out_file) out_file.close() ``` The above program writes one out file (result.txt) consisting of all the results (50 elements) together. I want to writ...
``` A = [1,2,3,4,5,6,7,8,9,10] B = [11,12,13,14,15] for a in A: results = [] # define new list for each item in A #loop over B and collect the result in a list(results) for b in B: result = a + b results.append(result) #append the result to results #print results ...
``` A = [1,2,3,4,5,6,7,8,9,10] B = [11,12,13,14,15] for a in A: with open(str(a) + '.txt', 'w') as fout: fout.write('\n'.join(str(a + b) for b in B) ```
writing multiple out files from for loop
[ "", "python", "python-3.x", "" ]
I am creating Log file for the code but I am getting the following error : ``` [Tue Jun 11 17:22:59 2013] [error] [client 127.0.0.1] import mainLCF [Tue Jun 11 17:22:59 2013] [error] [client 127.0.0.1] File "/home/ai/Desktop/home/ubuntu/LCF/GA-LCF/mainLCF.py", line 10, in [Tue Jun 11 17:22:59 2013] [error] [cli...
You need to change the Logfile path by using logging.handlers python module . In my case I did the following stuff : ``` import logging from logging.handlers import RotatingFileHandler import blackboard WEBAPP_CONSTANTS = { 'LOGFILE': '/home/ai/Desktop/home/ubuntu/LCF/GA-LCF/ga.log', } def getWebAppConstants(consta...
Looks like logging tried to open the logfile as `/genetic.log`. If you pass filename as a keyword argument to `logging.basicConfig` it creates a `FileHandler` which passes it to `os.path.abspath` which expands the filename to an absolute path based on your current working dir. So you're either in your root dir or your ...
Why am I getting IOError: [Errno 13] Permission denied?
[ "", "python", "python-2.7", "permissions", "permission-denied", "ioerror", "" ]
What is the easiest way to create a delay (or parking) queue with Python, Pika and RabbitMQ? I have seen an similar [questions](https://stackoverflow.com/questions/4444208/delayed-message-in-rabbitmq), but none for Python. I find this an useful idea when designing applications, as it allows us to throttle messages tha...
I found this extremely useful when developing my applications. As it gives you an alternative to simply re-queuing your messages. This can easily reduce the complexity of your code, and is one of many powerful hidden features in RabbitMQ. **Steps** First we need to set up two basic channels, one for the main queue, a...
You can use RabbitMQ official plugin: **x-delayed-message** . Firstly, download and copy the [ez file](http://www.rabbitmq.com/community-plugins/v3.5.x/rabbitmq_delayed_message_exchange-0.0.1-rmq3.5.x-9bf265e4.ez) into *Your\_rabbitmq\_root\_path/plugins* Secondly, enable the plugin (do not need to restart the server...
How to create a delayed queue in RabbitMQ?
[ "", "python", "queue", "rabbitmq", "delay", "pika", "" ]
I'm pretty confused about how to convert this program to a list comprehension. Any tips? Here's the original code I wrote (also, I'm new to python, so you can tell me if this sucks, I don't mind) The code is supposed to use the built in chr() function to return a string that when printed, is an ascii chart, four entri...
Here's an equivalent solution using a list comprehension and the [`enumerate()`](http://docs.python.org/2/library/functions.html#enumerate) built-in function: ``` def GiveAsciiChart5(): vals = [(value, chr(value)) for value in range(32, 127)] for i, (v, c) in enumerate(vals): print " |ASCII Value|: ", ...
So as to not give the answer entirely away, I annotated the code. ``` for count in a: #the type of count would be a tuple containing (i, chr(i)) if count % 4 == 0: #so then what should this statement be? print "\n" print " |ASCII Value|: ", "|",(i),"|", " |Character|: ", "|",chr(i),"|", # ^ ...
converting program to list comprehension
[ "", "python", "list-comprehension", "" ]
I am trying to convert codons within my string into aminoacids. This is what I currently have: ``` def converteRNAmParaAminoacidos(rna): dicionario = {'uuu':'F', 'uuc':'F','uua':'L', 'uug':'L', 'cuu':'L', 'cuc':'L', 'cua':'L', 'cug':'L', 'auu':'I', 'auc':'I', 'aua':'I', 'aug':'M', 'guu':'V', 'guc':'V', 'gua':'V',...
In your loop, you don't modify `aminoacidos`. You just keep re-setting it each iteration. While replacement may *seem* like it will work, the order of the replacements will make a difference. Take `ucuuuc` as an example. If you first replace `ucu`, you'll end up with `Suuc`. However, if you find `cuu` first, you'll ge...
In Python, the `replace` function returns a new string. What you're doing is taking the original string, doing a replacement and storing the result as `aminoacidos`. When you call `replace` again, you're not keeping the result from the previous iterations since you're calling `replace` on the original, un-altered strin...
Replace string based on a dictionary
[ "", "python", "replace", "" ]
Suppose a well-structured OOP Python application, where every call to a method is wrapped in a try block. Now suppose that I'm debugging this application and I want the exceptions to actually be thrown! It would be neigh impossible to replace every `try:` line with `if True:` and to comment out `"""` the `except:` port...
> "Suppose a well-structured OOP Python application, where every call to a method is wrapped in a try block ... " this doesn't sound well-structured to me at all. One of the basic principles of exception handling is **ONLY HANDLE EXCEPTIONS THAT YOU KNOW HOW TO DEAL WITH**. This is the driving principle behind the com...
This sound like a job for a debugger. I'm only familiar with the debugger for [PyCharm](http://www.jetbrains.com/pycharm/), with which you can set an exception breakpoint for any exception.
Don't catch exceptions, even from within a try block
[ "", "python", "exception", "" ]
I have to run jobs on a regular basis on compute servers that I share with others in the department and when I start 10 jobs, I really would like it to just take 10 cores and not more; I don't care if it takes a bit longer with a single core per run: I just don't want it to encroach on the others' territory, which woul...
Set the `MKL_NUM_THREADS` environment variable to 1. As you might have guessed, this environment variable controls the behavior of the Math Kernel Library which is included as part of Enthought's `numpy` build. I just do this in my startup file, .bash\_profile, with `export MKL_NUM_THREADS=1`. You should also be able ...
Only hopefully this fixes all scenarios and system you may be on. 1. Use `numpy.__config__.show()` to see if you are using OpenBLAS or MKL From this point on there are a few ways you can do this. 2.1. The terminal route `export OPENBLAS_NUM_THREADS=1` or `export MKL_NUM_THREADS=1` 2.2 (This is my preferred way) In ...
How do you stop numpy from multithreading?
[ "", "python", "multithreading", "numpy", "" ]
There is the "+=" operator for, namely, int. ``` a = 5 a += 1 b = a == 6 # b is True ``` Is there a "and=" operator for bool? ``` a = True a and= 5 > 6 # a is False a and= 5 > 4 # a is still False ``` I know, this 'and=' operator would correspond to: ``` a = True a = a and 5 > 6 # a is False a = a and 5 > 4 # a is...
Yes - you can use `&=`. ``` a = True a &= False # a is now False a &= True # a is still False ``` You can similarly use `|=` for "or=". It should be noted (as in the comments below) that this is actually a bitwise operation; it will have the expected behavior **only** if `a` starts out as a Boolean, and the opera...
nrpeterson showed you how to use `&=` with boolean. I show only what can happend if you mix boolean and integer ``` a = True a &= 0 # a is 0 if a == False : print "hello" # "hello" a = True a &= 1 # a is 1 if a == False : print "hello" # nothing a = True a &= 2 # a is 0 (again) if a == False : print "hello" # "hell...
Is there a "and=" operator for boolean?
[ "", "python", "boolean", "operators", "" ]
I want to run a Sql query with special characters in it. However, I don't want to use sql parameters. There is a way to run following query? ``` SqlString := 'Select * from Table1 where Name LIKE '`1234567890-=\]['';/.,<>?:"{}|+_)(*&^%$#@!~%' FSQLQuery.SQL.Clear; FSQLQuery.SQL.Add( SqlString ); FSQLQuery.Open; ``` De...
You should put something like this: ``` sqlString := 'SELECT * FROM Table1 WHERE Name LIKE ''`1234567890-=\]['''';/.,<>?:"{}|+_)(*&^%$#@!~%'' '; FSQLQuery.ParamCheck := False; //<<It MUST be prior than SetSql. FSQLQuery.SQL.Clear; FSQLQuery.SQL.Add( sqlString ); FSQLQuery.Open; ```
If `FSQLQuery` is `TADOQuery` then the easiest way to avoid this problem (colon char inside `SQL.Tex`) is to use `FSQLQuery.Connection.Execute(FSQLQuery.SQL.Text)` instead of `FSQLQuery.Open`. In this case you call ADO method directly without having Delphi parse your `Sql.Text`.
How do I avoid Delphi interpreting special characters as parameters in SQL?
[ "", "sql", "delphi", "" ]
How can i get (salary of Mr.Smith in the fist row +salary of Mr.Wong in the second row) of my Firebird sql like the following table? I tried ``` Select sum(column a +column b) ``` it didn't work . I get Null. ``` Name Salary Smith 4000 Wong 3000 John 3300 ... .... ```
try to use the `coalesce` operator. ``` select sum(coalesce(columna, 0) + coalesce(columnb, 0)) ``` cause if any part is null, result will be null. if you're talking of row instead of columns : ``` SELECT SUM(Salary) FROM yourTable WHERE Name IN ('Smith', 'Wong') GROUP BY Name ```
Try below: ``` SELECT name,salary FROM table WHERE name 'smith' UNION SELECT name,salary FROM table WHERE name 'wong' ```
sum of two different rows(salary) in a table
[ "", "sql", "firebird", "" ]
The user needs to input a set of coordinates like so (0,0), (0,1), (1,1), (1,0) The code I wrote for that looks like this: ``` def get_coords(): #user_input = raw_input("Enter a list of points. For example (0,0) (0,1) (1,1) (1,0)\n") print "Enter a list of points. For example (0,0) (0,1) (1,1) (1,0)\n" ui...
Replace the spaces with `','` and then apply `ast.literal_eval` ``` >>> strs = '(0,0) (0,1) (1,1) (1,0)' >>> from ast import literal_eval >>> literal_eval(strs.replace(' ',',')) ((0, 0), (0, 1), (1, 1), (1, 0)) ``` Using regex, this would work on any amount of spaces: ``` >>> import re >>> strs = '(0, 0) (0, 1) ( 1...
``` >>> from ast import literal_eval >>> uin = raw_input("coords: ").split() coords: (0,0) (0,1) (1,1) (1,0) >>> uin ['(0,0)', '(0,1)', '(1,1)', '(1,0)'] >>> coords = [literal_eval(coord) for coord in uin] >>> coords [(0, 0), (0, 1), (1, 1), (1, 0)] ``` In your file, you can just write this. Replace the prompt with wh...
input a list of 2D coordinates in python from user
[ "", "python", "input", "coordinates", "" ]
I am developing a program, in which I want a window that will display the output thrown by the terminal (like a package manager does ). For example, if I give the install command, the installation process should be outptutted to my window and not the terminal. Is there a way to do this in python Gtk? I am using an Ubu...
If you are on Linux (as you state), something like this should work: ``` import gtk import gobject import pango import os from subprocess import Popen, PIPE import fcntl wnd = gtk.Window() wnd.set_default_size(400, 400) wnd.connect("destroy", gtk.main_quit) textview = gtk.TextView() fontdesc = pango.FontDescription(...
I've been trying to do this and really struggling. I couldn't get the first example working and moved quickly onto the 2nd. Using the 2nd example above (Using Label to display text) and found that this works fine with Python 2.7 but I'm trying to use Python3 and some things just don't work. I struggled for ages tryin...
Show terminal output in a gui window using python Gtk
[ "", "python", "gtk", "" ]
I have a list of `datetime.dates` and I need to check if each date is from the next consecutive month. Hope it's clear what do I mean from the code: ``` import datetime from unittest import TestCase def is_consecutive(dates): # TODO return class DatesTestCase(TestCase): def test_consecutive(self): ...
Loop through each item of the list except the last, and compare it to the next item. Two items are consecutive if the month of the second is exactly one greater than the month of the first, or if the month of the second is 1 and the year of the second is exactly one greater than the year of the first. Return `False` at...
This works on your examples and should work generally: ``` def is_consecutive(data): dates=data[:] while len(dates)>1: d2=dates.pop().replace(day=1) d1=dates[-1].replace(day=1) d3=d1+datetime.timedelta(days=32) if d3.month!=d2.month or d3.year!=d2.year: return False ...
Determine consecutive dates
[ "", "python", "datetime", "python-2.x", "" ]
I have a `stored procedure` inside which I am creating a temporary table. My `vb` code will execute this stored procedure. Is it possible to access the data in the temp table in `vb6` after sp execution?
Use a global scope temporary table (they start with `##` rather than `#`). These are shared between sessions. They go out of scope when the session that created them ends AND no other session is referring to them. * [Temporary Tables in SQL Server](https://www.simple-talk.com/sql/t-sql-programming/temporary-tables-in-...
From [Books Online](http://msdn.microsoft.com/en-us/library/ms174979.aspx): > A local temporary table created in a stored procedure is dropped > automatically when the stored procedure is finished. The table can be > referenced by any nested stored procedures executed by the stored > procedure that created the table. ...
how to access the temporary table created inside stored procedure [vb6]
[ "", "sql", "stored-procedures", "vb6", "" ]
I apologize for being a newbie, but why does this loop run forever? ``` for i in range (1,3): while i < 5: print ('ha') ```
your code is basically doing the following: > For each value in 1, 2 and 3 do the following: while the current value is less than 5, print 'ha' As you can read it, the value will start in 1 and, while 1 is lesser than 5, 'ha' will be printed. As the value is not updated, 1 will always be lesser than 5 so you will get...
`for i in range(1, 3)` means it starts with the number `1`. You're saying, with the number 1: ``` while 1 < 5: print('ha') ``` Which will go on forever, because one is less than five, and it will always be. Thus the for-loop will never reach `2` and `3`, as it hasn't finished with `1` yet.
While inside for loop produces infinite loop?
[ "", "python", "for-loop", "while-loop", "infinite-loop", "" ]
I'm doing ``` item['desc'] = site.select('a/text()').extract() ``` but this will be printed like this ``` [u'\n A mano libera\n '] ``` What must I do to tim and remove strange chars like [u'\n , the traling space and '] ? I cannot trim (strip) ``` exceptions.AttributeError: 'li...
The html page may very well contains these whitespaces characters. What you retrieve a **list** of unicode strings, which is why you can't simply call `strip` on it. If you want to strip these whitespaces characters from *each* string in this list, you can run the following: ``` >>> [s.strip() for s in [u'\n ...
There's a nice solution to this using [Item Loaders](http://doc.scrapy.org/en/0.16/topics/loaders.html). Item Loaders are objects that get data from responses, process the data and build Items for you. Here's an example of an Item Loader that will strip the strings and return the first value that matches the XPath, if ...
Scrapy: Why extracted strings are in this format?
[ "", "python", "scrapy", "" ]
Suppose, I have a list of > 1,1 and it can take either + or - sign. So the possible combination would be 2 to the power 2. ``` 1 1 1 -1 -1 1 -1 -1 ``` Similarly, I have a list of > 1,1,1 and it can take either + or - sign. So the possible combination would be 2 to the power 3. ``` -1 1 -1 -1 1 1 1 ...
``` >>> import itertools >>> lst = [1,1,1] >>> for xs in itertools.product([1,-1], repeat=len(lst)): ... print([a*b for a,b in zip(lst, xs)]) ... [1, 1, 1] [1, 1, -1] [1, -1, 1] [1, -1, -1] [-1, 1, 1] [-1, 1, -1] [-1, -1, 1] [-1, -1, -1] ```
You can do: ``` from itertools import combinations size = 3 ans = list(set(combinations([-1,1]*size,size))) #[(1, 1, -1), # (-1, 1, 1), # (-1, -1, 1), # (1, -1, -1), # (1, -1, 1), # (-1, 1, -1), # (1, 1, 1), # (-1, -1, -1)] ``` This approach also gives the same result with `permutations`.
all possible phase combination
[ "", "python", "" ]
I have a table ("lms\_attendance") of users' check-in and out times that looks like this: ``` id user time io (enum) 1 9 1370931202 out 2 9 1370931664 out 3 6 1370932128 out 4 12 1370932128 out 5 12 1370933037 in ``` I'm trying to create a view of this table that would output only the mo...
Query: **[SQLFIDDLEExample](http://sqlfiddle.com/#!2/e353d/1)** ``` SELECT t1.* FROM lms_attendance t1 WHERE t1.time = (SELECT MAX(t2.time) FROM lms_attendance t2 WHERE t2.user = t1.user) ``` Result: ``` | ID | USER | TIME | IO | -------------------------------- | 2 | 9 ...
No need to trying reinvent the wheel, as this is common [greatest-n-per-group problem](https://stackoverflow.com/questions/tagged/greatest-n-per-group). Very nice [solution is presented](https://stackoverflow.com/q/8748986/684229). I prefer the most simplistic solution ([see SQLFiddle, updated Justin's](http://sqlfidd...
Select row with most recent date per user
[ "", "mysql", "sql", "greatest-n-per-group", "" ]
I'm following the tutorial "Think Python" and I'm supposed to install the package called swampy. I'm running python 2.7.3 although I also have python 3 installed. I extracted the package and placed it in site-packages: C:\Python27\Lib\site-packages\swampy-2.1.1 C:\Python31\Lib\site-packages\swampy-2.1.1 But when ...
> I extracted the package and placed it in site-packages: No, that's the wrong way of "installing" a package. Python packages come with a `setup.py` script that should be used to install them. Simply do: ``` python setup.py install ``` And the module will be installed correctly in the site-packages of the python int...
If anyone else is having trouble with this on Windows, I just added my sites-package directory to my PATH variable and it worked like any normal module import. ``` C:\Python34\Lib\site-packages ``` Hope it helps.
Python: I can't import a module even though it's in site-packages
[ "", "python", "module", "installation", "package", "" ]
Is it possible to create a list of functions where you can access them individually? For example: ``` e=0 def a(): global e e=1 def b(): global e e=2 def c(): global e e=3 l=[a(),b(),c()] l[2] print e l[0] print e ``` Output: ``` >>>3 >>>1 ```
The problem is that you are calling your functions at the beginning and storing only their values in the list. ``` e=0 def a(): global e e=1 def b(): global e e=2 def c(): global e e=3 l=[a,b,c] l[2]() print e l[0]() print e ``` Output ``` >>> 3 1 ```
`l=[a(),b(),c()]` is not a list of function, rather a collections of values returned from calling those functions. In a list the items are evaluated from left to right, so `e` is going to be 3 after this step. As functions are objects in python so you can do: ``` >>> l = [a, b, c] # creates new references to the func...
Python List of Functions
[ "", "python", "list", "" ]
I need to make function, which will return for a given folder, a Dictionary, which describes its content. Keys let be the names of the subfolders and files, key value representing the file should be their size and key values ​​that represent folders, whether they are dictionaries that describe the content of these subf...
``` def f(path): if os.path.isdir(path): d = {} for name in os.listdir(path): d[name] = f(os.path.join(path, name)) else: d = os.path.getsize(path) return d ```
``` def dumps(d, level=0, indent=4): if isinstance(d, dict): if not d: return '{}' return '{\n' + ',\n'.join( (' ' * (level+indent) + "'{}' : {}".format(name, dumps(d[name], level+indent, indent)) for name in d), ) + '\n' + ' ' * level + '}' else: return str(d) print...
dictionary of folders and subfolders
[ "", "python", "dictionary", "" ]
I have a table called books with following data: ``` id | description | section 1 | textbook 1 | 1 2 | textbook 2 | 1 3 | textbook 3 | 1 ``` I use the following query to select id 2 and the next and previous rows in section 1: ``` SELECT id FROM books where id IN (2, (SELECT id FROM books WHERE id < 2 LIMIT...
``` (SELECT id FROM books WHERE id < 2 and section = 1 ORDER BY id DESC LIMIT 1) UNION (SELECT id FROM books WHERE id >= 2 and section = 1 ORDER BY id ASC LIMIT 2) ``` The problem with your query is that you're picking random ids less than 2 and greater than 2, without taking the section into account. If those IDs ...
``` SELECT id FROM books where id IN (2, (SELECT id FROM books WHERE id < 2 ORDER BY id DESC LIMIT 1), (SELECT id FROM books WHERE id > 2 ORDER BY id ASC LIMIT 1) ) AND section = 1 ``` The `ORDER BY` should do the trick.
MYSQL returning incomplete results
[ "", "mysql", "sql", "database", "" ]
Given this table, I need to generate a year-to-date summary by month. The result should have one row for each month of the year, and a running total for the year up to that month. I am by no means a novice when it comes to SQL, yet I still have no idea how to achieve this in pure SQL. Does anyone know how to do this? P...
I found the answer by using a sub-query, and using aliases for the table name. ``` SELECT FORMAT(t1.completionDate,"mmm-yy") AS [month], ( SELECT SUM(t2.amount) FROM projects AS t2 WHERE MONTH(t2.completionDate) <= MONTH(t1.completionDate) ) AS [amount] FROM projects AS t1; ```
I think, trying to group it by Month could help. Look [here](https://stackoverflow.com/questions/5107562/sql-group-dates-by-month) to see how to Group it by Month. Then you should be able to sum the amount an give it out by the Month. Hope this Idea helps you. Sarajog
Year-To-Date Summary by Month in Access SQL
[ "", "sql", "ms-access", "ms-access-2010", "" ]
I want to write a SQL query where if the datetime is not been assigned I want to replace a string which can select all date and time. How Actually it works: ``` SELECT * FROM `entry` WHERE `user` like 'TOM' or `user` like 'PHP' and `entry_datetime` between '2013-03-13 22:20:18' and '2013-03-13 22:20:26' ``` My ...
You can use MIN and MAX values for datetime data type. ``` ... AND `entry_datetime` BETWEEN '1000-01-01 00:00:00' AND '9999-12-31 23:59:59' ``` > The DATETIME type is used for values that contain both date and time > parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD > HH:MM:SS' format. The supported ...
You could use the `IFNULL` function ``` IFNULL(mindate, '1000-01-01'); ``` Problem with this is you would need to know your date range so you could add the minimum and maximum values correctly. This assumes you are passing in or creating a variable called mindate.
MySQL IN BETWEEN with no condition
[ "", "mysql", "sql", "database", "logic", "" ]
Say I have an array of lists ``` B = [[1,2,3],[1,2,3,4],[1,2]] ``` and I want to calculate the mean of the elements in the lists across the coloumns. How do I do this? i.e How do I get a final array of mean values equal to the longest list: ``` [(1+1+1)/3,(2+2+2)/3,(3+3)/2,4/1] = [1,2,3,4] ``` I tried: ``` final...
One more way, using `cmp` and `izip_longest` ``` from itertools import izip_longest [float(sum(col)) / sum(cmp(x,0) for x in col) for col in izip_longest(*B, fillvalue=0)] ``` This assumes your values are positive.
You can it by using DataFrame of pandas. ``` from pandas import DataFrame B = [[1,2,3],[1,2,3,4],[1,2]] df = DataFrame(B) df.mean(axis=0) """" df 0 1 2 3 0 1 2 3 NaN 1 1 2 3 4 2 1 2 NaN NaN df.mean(axis=0) 0 1 1 2 2 3 3 4 """ ```
How do I calculate the mean of elements in a list across columns?
[ "", "python", "list", "numpy", "mean", "" ]
When I try to resize (thumbnail) an image using PIL, the exif data is lost. What do I have to do preserve exif data in the thumbnail image? When I searched for the same, got some links but none seem to be working. ``` from PIL import Image import StringIO file_path = '/home/me/img/a.JPG' im = Image.open( file_path)...
``` import pyexiv2 from PIL import Image file_path = '/home/../img/a.JPG' metadata = pyexiv2.ImageMetadata(file_path) metadata.read() thumb = metadata.exif_thumbnail thumb.set_from_file(file_path) thumb.write_to_file('512_' + "a") thumb.erase() metadata.write() ``` Now I open the image using (Patch Image Inspector) ...
I read throught some of the source code and found a way to make sure that the exif data is saved with the thumbnail. When you open a jpg file in PIL, the `Image` object has an `info` attribute which is a dictionary. One of the keys is called `exif` and it has a value which is a byte string - the raw exif data from the...
Preserve exif data of image with PIL when resize(create thumbnail)
[ "", "python", "python-imaging-library", "exif", "" ]
I want to log every method call in some classes. I could have done ``` class Class1(object): @log def method1(self, *args): ... @log def method2(self, *args): ... ``` But I have a lot of methods in every class, and I don't want to decorate every one separately. Currently, I tried using...
If the goal is to make your code easier to debug by simply logging call and response, check out the Autologging module. A single annotation is all it takes =) <https://pythonhosted.org/Autologging/examples-traced.html> ``` pip install Autologging ``` . ``` # my_module.py from autologging import traced @traced cl...
Why don't you alter the class object? You can go through the methods in a class with `dir(MyClass)` and replace them with a wrapped version... something like: ``` def logify(klass): for member in dir(klass): if not callable(getattr(klass, method)) continue # skip attributes setattr(kla...
Python: Logging all of a class' methods without decorating each one
[ "", "python", "class", "logging", "" ]
I wonder, is there a function in python -let's call it now `apply`- that does the following: ``` apply(f_1, 1) = f_1(1) apply(f_2, (1, 2)) = f_1(1, 2) ... apply(f_n, (1, 2,..., n)) = f_n(1, 2,..., n) # works with a tuple of proper length ``` Since it does exist in eg. *A+* and *Mathematica* and it used to be really u...
Python has language-level features for this, known as "argument unpacking", or just "splat". ``` # With positional arguments args = (1, 2, 3) f_1(*args) # With keyword arguments kwargs = {'first': 1, 'second': 2} f_2(**kwargs) ```
You can use the `*` operator for the same effect: ``` f_1(*(1, 2)) = f_1(1, 2) ... ``` The expression following the `*` needn't be a tuple, it can be any expression that evaluates to a sequence. Python also has a built-in `apply` function that [does what you'd expect](http://docs.python.org/2/library/functions.html#...
Is there such thing as "apply" in python?
[ "", "python", "wolfram-mathematica", "" ]
I installed [vim-flake8](https://github.com/nvie/vim-flake8) by git cloning it on my Pathogen bundle folder as usual, but when I tried to run the plugin pressing `F7` or using `:call Flake8()` in one Python file I receive the following message: > Error detected while processing function Flake8: > > line 8: > > File fl...
The error message is telling you that you didn't install the program [flake8](https://pypi.python.org/pypi/flake8). Install it. Assuming pip is installed ``` pip install flake8 ``` should work.
If installing flake8 via pip is not working try this: ``` apt-get install flake8 ``` Worked for me.
vim-flake8 is not working
[ "", "python", "vim", "pyflakes", "flake8", "" ]
I have an `if` block statement that is checking if a string that I have assigned to variable `movieTitle` contains the value of a key-value pair in a predefined dictionary. The code I have is: ``` import mechanize from bs4 import BeautifulSoup leaveOut = { 'a':'cat', 'b':'dog', 'c...
Could you confirm exactly what you're trying to achieve here? You're trying to execute a set of instructions if ANY of the values in the `leaveOut` dictionary is NOT present in the movieTitle? If so: ``` if [x for x in leaveOut.values() if x not in movieTitle]: ``` would be more concise. Also, if you're going to use ...
You can do as Captain Skyhawk suggests, or you can replace your entire `if` condition with: ``` if any(movieTitle.find(leaveOut[c]) < 1 for c in 'abcdefghijklm'): ``` As for your second question, are you sure you don't mean ``` if not any(movieTitle.find(leaveOut[c]) < 1 for c in 'abcdefghijklm'): ...
Python dictionary - value
[ "", "python", "dictionary", "" ]
I'm trying to write a condition based on whether a value in a column of a csv is a certain string. This is my code, where I will execute some stuff based on whether the content of the cell in the column 'type' is a 'Question': ``` f = open('/Users/samuelfinegold/Documents/harvard/edXresearch/snaCreationFiles/time_ser...
I put the data you provided in a comma delimited CSV file, I then ran your code on the data you provided and got a `KeyError` for `type`, so I changed `if line['type']` to `if line['types']` and it worked. My code: ``` import csv f = open('test.csv','rU') reader = csv.DictReader(f,delimiter=',') for line in reader:...
python has a module to handle csv files in the standard library <https://www.google.com/search?q=python+csv> 1st hit: <http://docs.python.org/library/csv.html>
How to check value of column in spreadsheet in Python
[ "", "python", "csv", "indexing", "" ]
I came across [this example](http://scikit-learn.org/stable/auto_examples/ensemble/plot_forest_multioutput.html#example-ensemble-plot-forest-multioutput-py) which involves completion of face for the test data set. Here, a value of `32` for `max_features` is passed to the `ExtraTreesRegressor()` function. I learnt that ...
Random forests do not do feature extraction. They use the features in the dataset given to them, which in this example are just pixel intensities from the Olivetti faces dataset. The `max_features` parameter to an [`ExtraTreesRegressor`](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesRegre...
The features used here are the raw pixel values. As the images in the dataset are aligned and quite similar, that seems to be enough for the task.
Features considered by ExtraTreeRegressor of Scikit Learn to construct Random Forest
[ "", "python", "machine-learning", "scikit-learn", "random-forest", "" ]
I have file that contains values separated by tab ("\t"). I am trying to create a list and store all values of file in the list. But I get some problem. Here is my code. ``` line = "abc def ghi" values = line.split("\t") ``` It works fine as long as there is only one tab between each value. But if there is one than o...
You can use `regex` here: ``` >>> import re >>> strs = "foo\tbar\t\tspam" >>> re.split(r'\t+', strs) ['foo', 'bar', 'spam'] ``` **update:** You can use `str.rstrip` to get rid of trailing `'\t'` and then apply regex. ``` >>> yas = "yas\t\tbs\tcda\t\t" >>> re.split(r'\t+', yas.rstrip('\t')) ['yas', 'bs', 'cda'] ```
Split on tab, but then remove all blank matches. ``` text = "hi\tthere\t\t\tmy main man" print([splits for splits in text.split("\t") if splits]) ``` Outputs: ``` ['hi', 'there', 'my main man'] ```
splitting a string based on tab in the file
[ "", "python", "string", "split", "" ]
I am using Oracle 11g. I am trying to realize scenario of concurrent loading into a table with index rebuild. I have few flows which are trying to realize this scenario: 1. load data from source, 2. transform the data, 3. turn off the index on DWH table, 4. load data into DWH, 5. rebuild index on DWH table. I turn off...
Problem solved. What I wanted to do can be easily achieved using DBMS\_LOCK package. ``` 1. DBMS_LOCK.REQUEST(...) 2. ALTER INDEX ... UNUSABLE 3. Load data 4. ALTER INDEX ... REBUILD 5. DBMS_LOCK.RELEASE(...) ```
You can use DBMS\_SCHEDULER: 1. run jobs that load and transform the data 2. turn off indexes 3. run jobs that load data into DWH 4. rebuild indexes ![enter image description here](https://i.stack.imgur.com/vQ5nP.gif) Using Chains: * <http://docs.oracle.com/cd/B28359_01/server.111/b28310/scheduse009.htm#CHDCFBHG>
Locking table for more transactions
[ "", "sql", "oracle", "data-warehouse", "locks", "" ]
I can't seem to find out how to do this after much searching. Dict: ``` mdr = {'main': {'sm': {'testm': {'test1': 'test', 'test2': 'test'}}, 'lm': {}, 'l': {}}} ``` I would like it to look like this: ``` -Main --SM ---Testm ----Test1:Test ----Test2:Test --LM --L ``` I **won't** know the exact amount of sub-directo...
I think recursion is a better bet than a loop. This is pretty close. ``` def print_dict(d, current_depth=1): for k, v in d.items(): if isinstance(v, dict): print '-' * current_depth + str(k) print_dict(v, current_depth + 1) else: print '-' * current_depth + str(k...
``` def tree(data, indent=0): if isinstance(data, basestring): print '{i}{d}'.format(i='-'*indent, d=data) return for key, val in data.iteritems(): if isinstance(val, dict): print '{i}{k}'.format(i='-'*indent, k=key) tree(val, indent + 1) else: ...
Python Looping Entire Dictionary
[ "", "python", "dictionary", "" ]
I'm developing a new project. I need a help for the mysql query, I think it is very slow. ``` SELECT post_id, user_id, content, title, TIME, ( SELECT username FROM users WHERE id = posts.user_id ) AS username FROM posts WHERE user_id =1 OR user_id IN ( SELECT DISTINCT user_to FROM friends WHERE user_from =1 OR user_...
Try: ``` SELECT p.post_id, p.user_id, p.content, p.title, p.TIME, u.username FROM (select distinct us.* from friends f join users us on f.user_to = us.id WHERE f.user_from =1 OR f.user_to =1) u JOIN posts p on u.id = p.user_id ORDER BY p.post_id DESC LIMIT 0 , 10 ```
You can use an `INNER JOIN` query ``` SELECT a.post_id, a.user_id, a.content, a,title, a.TIME, b.username FROM posts a INNER JOIN users b ON a.user_id = b.id WHERE a.user_id =1 OR a.user_id IN ( SELECT DISTINCT user_to FROM friends WHERE user_from =1 OR user_to =1 ) ORDER BY a.post_id DESC LIMIT 0 , ...
How to optimize this my mysql query?
[ "", "mysql", "sql", "" ]
I have a problem with attaching the database with information about users. I'm trying to move the asp.net mvc4 project to the IIS. MS SQL Server 2008 Express. ``` <add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-comvc4-20130423110032;Integrated Security=true;AttachDBFilename=|DataDi...
I've tried harder. This one worked for me: ``` <add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-comvc4-20130423110032.mdf;Integrated Security=false;AttachDBFilename=|DataDirectory|\aspnet-comvc4-20130423110032.mdf;User Id=sa2; Password=123456;" providerName="System.Data.SqlClient"/>...
I notice that with my connection string there is this `User Instance=True` so you could try adding that to the connection string if you were looking to continue to use integrated security. would look something like ``` <add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-comvc4-2013042...
CREATE DATABASE permission denied in database 'master'. Cannot attach the file 'C:\co\App_Data\xxx.mdf' as database 'xxx'
[ "", "asp.net", "sql", "connection-string", "" ]
I have two tables in Oracle, job and reference. I want to insert a new record into both tables, with a key generated from a sequence. Something like: ``` insert into ( select j.jobid, j.fileid, j.jobname, r.reffileid from job j inner join reference r on j.jobid=r.jobid) values (jobidsequence.nextval, 4660, 'name', 4...
You can use a side-effect of the [`insert all` multi-table insert](http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9014.htm#i2095116) syntax for this: ``` insert all into job (jobid, fileid, jobname) values (jobidsequence.nextval, fileid, jobname) into reference (jobid, reffileid) values (jobidsequenc...
You can use `jobidsequence.currval` to get the current value of the sequence (within one session transaction, i.e. until `COMMIT` when you called `nextval` before, and until you call `nextval` again). See: [Oracle Admin Manual: Managing Sequences](http://docs.oracle.com/cd/B28359_01/server.111/b28310/views002.htm)
Inserting into two oracle tables with a sequence
[ "", "sql", "oracle", "" ]
How would I remove the space after the equals sign? I searched all over google and could not find anything on how to do it. Anyhelp would be greatly appreciated. ``` Code customer = input('Customer Name:') mpid = input('MPID=<XXXX>:') print ('description' ,customer,'<MPID=',mpid+'>') Output Customer N...
Here are some ways of combining strings... ``` name = "Joel" print('hello ' + name) print('hello {0}'.format(name)) ``` So you could use any of these in your case... ``` print('description', customer, '<MPID={0}>'.format(mpid)) print('description {0} <MPID={1}>'.format(customer, mpid)) ```
`print(a, b, c)` puts `a` into the output stream, then a space, then `b`, then a space, then `c`. To avoid the space, create a new string and print it. You could: concatenate strings: `a + b + c` better: join strings: `''.join(a, b, c)` even better: format a string: `'description {0} <MPID={1}>'.format(customer, mp...
Python Newbie Combine Text
[ "", "python", "" ]
i have a python list whose items are objects of a class with various attributes such as birthday\_score, anniversary\_score , baby\_score..... I want to to sort the list on the basis of one of these attributes ,say anniversary\_score. How do i do it ?
``` your_list.sort(key = lambda x : x.anniversary_score) ``` or if the attribute name is a string then you can use : ``` import operator your_list.sort(key=operator.attrgetter('anniversary_score')) ```
`attrgetter` is handy if you don't know the name of the attribute in advance (eg. maybe it is from a file or a function parameter) ``` from operator import attrgetter sorted(my_list, key=attrgetter('anniversary_score')) ```
sorting a list with objects of a class as its items
[ "", "python", "list", "class", "sorting", "" ]
I've followed the [official tutoral of Scrapy](http://doc.scrapy.org/en/latest/intro/tutorial.html), it's wonderful! I'd like to remove all of DEBUG messages from console output. Is there a way? ``` 2013-06-08 14:51:48+0000 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:6029 2013-06-08 14:51:48+0000 [scrapy] DEB...
You need to add the following to your `settings.py` document: ``` LOG_LEVEL = 'INFO' ``` See [the documentation](http://doc.scrapy.org/en/latest/topics/settings.html#log-level).
You can also disable it completely with `LOG_ENABLED=False`. And you can pass settings when invoking the command: `scrapy crawl myspider -s LOG_ENABLED=False`
Scrapy: how to disable or change log?
[ "", "python", "scrapy", "" ]
`the_map = { 1:'a',0:'b'}` Now to generate, 8 patterns of `a` and `b` , we create 8 bit patterns: ``` >>> range(8) [0, 1, 2, 3, 4, 5, 6, 7] # 001,010,011....111 ``` How to map the bits to characters 'a' and 'b' , to receive output like : ``` ['aaa','aab','aba'.......'bbb'] ``` I am looking for an efficient one lin...
I think you are looking for [`product`](http://docs.python.org/2/library/itertools.html#itertools.product): ``` >>> from itertools import product >>> [''.join(i) for i in product('ABC',repeat=3)] ['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB', 'B AC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'B...
Not a huge improvement besides readability, but I think new style formatting could be a better fit here: ``` >>> '{:0<3b}'.format(1).translate(string.maketrans('01', 'ab')) 'baa' ```
A good pythonic way to map bits to characters in python?
[ "", "python", "" ]
I have a file that an application updates every few seconds, and I want to extract a single number field in that file, and record it into a list for use later. So, I'd like to make an infinite loop where the script reads a source file, and any time it notices a change in a particular figure, it writes that figure to an...
Thanks for all the answers, unfortunately my error was in the shell, and not in the script with Python. The cause of the problem turned out to be the way I was putting the script in the background. I was doing: `Ctrl+Z` which I thought would put the task in the background. But it does not, `Ctrl+Z` only suspends the t...
Unless you are implementing some synchronization mechanism or could guarantee somehow atomic read and write, I think you are calling for race condition and subtle bugs here. Imagine the "reader" accessing the file whereas the "writer" hasn't completed its write cycle. There is a risk of reading incomplete/inconsistent...
Python: Reread contents of a file
[ "", "python", "file", "io", "refresh", "" ]
I was trying a simple regex code to match the following: ``` line = 'blah black blacksheep blah' if re.match(r'(\bblack\b)', line): print 'found it! ``` What am I doing wrong, I can't find "black" by itself?
From [the docs](http://docs.python.org/2/library/re.html#re.match): > ### `re.match(pattern, string, flags=0)` > > If zero or more characters at the beginning of *string* match the regular expression *pattern*, return a corresponding `MatchObject` instance. You probably want to use `re.search` or `re.findall` instead...
You should use `re.search` or `re.findall` here: ``` >>> strs = 'blah black blacksheep blah' >>> re.search(r'\bblack\b', strs).group(0) 'black' >>> re.findall(r'\bblack\b', strs) ['black'] ```
How to use regex for words
[ "", "python", "regex", "" ]
I'm writing my own container, which needs to give access to a dictionary inside by attribute calls. The typical use of the container would be like this: ``` dict_container = DictContainer() dict_container['foo'] = bar ... print dict_container.foo ``` I know that it might be stupid to write something like this, but th...
Your first example is perfectly fine. Even the official Python documentation recommends this style known as [EAFP](https://docs.python.org/3/glossary.html#term-EAFP). Personally, I prefer to avoid nesting when it's not necessary: ``` def __getattribute__(self, item): try: return object.__getattribute__(se...
While in Java it's indeed a bad practice to use exceptions for flow control (mainly because exceptions force the JVM to gather resources ([more here](https://stackoverflow.com/questions/6092992/why-is-it-easier-to-ask-forgiveness-than-permission-in-python-but-not-in-java))), in Python you have two important principles:...
Are nested try/except blocks in Python a good programming practice?
[ "", "python", "" ]
I am using csv package now, and every time when I write to a new csv file and open it with excel I will find a empty row in between every two rows. ``` filereader = csv.reader(open("tests.csv", "r"), delimiter=",") filewriter = csv.writer(open("test_step1.csv", "w"), delimiter=",") #Delete header for row in filereader...
You need to open the file in wb mode try: ``` import csv filereader = csv.reader(open("tests.csv", "r"), delimiter=",") filewriter = csv.writer(open("test_step1.csv", "wb"), delimiter=",", newline="") #Delete header for row in filereader: if row[0].isdigit(): filewriter.writerow(row) ``` The csv.writer w...
I am using `Python 3.6` and it seems that `csv.writer(open("test_step1.csv", "wb"), delimiter=",", newline="")` is not correct. Rather, *`newline=""`* should added in the `open()` clause.
Empty space in between rows after using writer in python
[ "", "python", "csv", "python-3.3", "writer", "" ]
I have the following SQL (SQL Server) and it works for the most part. The problem is I am really creating a square and not a true circle. My goal is to pass in a city and state which has a lat and long, then find all cities within a 100 mile radius of that lat long. The latitude and longitude are stored in the DB so al...
I've used the great circle distance to do this in the past. The implementation below tells you the distance between two different points, which could be used to do what you are talking about: ``` create function dbo.GreatCircleDistance ( @Latitude1 float, @Longitude1 float, @Latitude2 float, @Lon...
Not sure if this helps, but I think there is an error here: ``` SELECT @LatRange = @Radius / ((6076 / 5280) * 60) ``` The (6076 / 5280) part will always evaluate to 1.
How to Return Resultset with a Given Radius
[ "", "sql", "sql-server", "" ]
I have to make a function to transform example 1 into example 2. I have already made a function for example 1. How do I make a function for example 2, with nested readout and with their sizes in brackets and with newlines? example 1. ``` { 'delo' : { 'navodila.docx' : 83273, 'poročilo.pdf' ...
This is what i really wanted, an easier way , just to refill it ``` def f(map,n=0): dictionary=beforeF(map) #function before i made for key in dictionary.keys(): fullName = map + '\\' + key if path.isdir(fullName): print(n*'\t'+key+':') f(fullN...
``` def dump(d, level=0, indent=4): for name in d: if isinstance(d[name], dict): print('{0}{1}'.format(' ' * level, name)) dump(d[name], level+indent) else: print('{0}{1} ({2})'.format(' ' * level, name, d[name])) ```
How to dict folders?
[ "", "python", "dictionary", "nested", "" ]
how to convert text to date in sql as listed below? > Y12-W01 to 20120102 > > Y12-W02 to 20120109 > > Y12-W03 to 20120116 and so on... i use ms-access. thank you in advance regards.
You don't need a separate function, try this SQL example: ``` SELECT FieldName, DateAdd("ww",CDbl(Mid([FieldName],6,2))-1,DateSerial(Mid([FieldName],2,2),1,1)) AS ConvDate FROM TableName ```
Parse your Week and Year out of your field. I'll let you figure out that one. ;o) Once you have the Week and Year, pass them into this function: ``` Function GetWeekStart(weekNum As Integer, yr As Integer) As Date GetWeekStart = DateSerial(yr, 1, 1 + (weekNum * 7) - 6 - Weekday(DateValue("1/1/" & yr))) End Func...
convert years and weeks to date in sql msaccess
[ "", "sql", "ms-access", "ms-access-2010", "" ]