Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am using some code I found here on SO to google search a set of strings and return the "expected" amount of results. Here is that code: ``` for a in months: for b in range(1, daysInMonth[a] + 1): #Code if not myString: googleStats.append(None) else: try: ...
The answer is what I was fearing for a while, but thanks to everyone who tried to help, I upvoted you if anythign was useful. So, Google seems to randomly freak out that I'm searching so must stuff. Here's the error they give to me : ``` Suspected Terms of Service Abuse ...... responseStatus:403 ``` So, I guess they...
First, I'd say remove your `try..except` clause and see where exactly the problem is. Then as a general good practice, when you try to access layers of dictionary elements, use `.get()` method instead for better control. As a demonstration of your possible `TypeError`, here is my educated guess: ``` >>> a = {} >>> a[...
Google search with python is sporadically non-accurate and has Type Errors
[ "", "python", "json", "google-api", "google-search", "" ]
I'm plotting some data with matplotlib. I want the plot to focus on a specific range of x-values, so I'm using set\_xlim(). Roughly, my code looks like this: ``` fig=plt.figure() ax=fig.add_subplot(111) for ydata in ydatalist: ax.plot(x_data,y_data[0],label=ydata[1]) ax.set_xlim(left=0.0,right=1000) plt.savefig(f...
Out of curiosity, what about switching in the old `xmin` and `xmax`? ``` fig=plt.figure() ax=fig.add_subplot(111) ax.plot(x_data,y_data) ax.set_xlim(xmin=0.0, xmax=1000) plt.savefig(filename) ```
**The text of this answer was taken from an answer that was deleted almost immediately after it was posted.** `set_xlim()` limits the data that is displayed on the plot. In order to change the bounds of the axis, use [`set_xbound()`](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_xbound). ``` fig=p...
Why is set_xlim() not setting the x-limits in my figure?
[ "", "python", "matplotlib", "" ]
The Python "for c in string" idiom is good but sometimes you might do a check and find that you need to pass a section of string say to a function. So for example ``` str = "I am a <token>" for ch in str: if ch == '<': # I need to know where in string we are now ``` Is there way way? Or for this sort of t...
``` >>> for i, ch in enumerate(str): print i, ch Would print 0 I 1 2 a ... ``` You should also be careful while using `str` as a variable name as that's the name of the built-in type.
Unless you need to do something in the loop besides finding the index just use `find`: ``` >>> "I am a <token>".find('<') 7 >>> s = "I am a <token>" >>> s[s.find('<'):s.find('>')+1] '<token>' >>> s[s.find('<')+1:s.find('>')] 'token' ```
for c in string is there a way to find position of c
[ "", "python", "" ]
I have some conditions/comparisons stored as strings. How can I check these conditions? A very simple example is given below. I want the conditions as strings because I want to print them in case they fail. I think I'll need to make a parser for this but that would be a really stupid idea to make a complete Python par...
You *can* do that using `eval(cond_string)`: ``` for i in conditions: if eval(i): print(i) ``` **Edit**: yes, as several have pointed out, `eval` can be dangerous if you can't be absolutely certain about the content of the strings you're evaluating. For that reason, using `eval` is often seen as bad g...
You could use [`eval`](http://docs.python.org/3.1/library/functions.html#eval), but I wouldn't suggest to do so. If you already know that you want to perform several calls to `rev_num(x) != y`, just create an auxiliary function and use a list of tuples to store the arguments: ``` def check_condition(x, y): return ...
How to check conditions stored as strings? Do I need a parser?
[ "", "python", "unit-testing", "python-3.x", "" ]
In Python, is there a way to detect whether a given **network interface** is **up**? In my script, the user specifies a network interface, but I would like to make sure that the interface is up and has been assigned an IP address, before doing anything else. I'm on **Linux** and I am **root**.
As suggested by @Gabriel Samfira, I used `netifaces`. The following function returns True when an IP address is associated to a given interface. ``` def is_interface_up(interface): addr = netifaces.ifaddresses(interface) return netifaces.AF_INET in addr ``` The documentation is [here](https://github.com/raphd...
The interface can be configured with an IP address and not be up so the accepted answer is wrong. You actually need to check `/sys/class/net/<interface>/flags`. If the content is in the variable flags, `flags & 0x1` is whether the interface is up or not. Depending on the application, the `/sys/class/net/<interface>/op...
Python: check whether a network interface is up
[ "", "python", "networking", "ip", "dhcp", "network-interface", "" ]
I'm new to http and in need of help. I'm trying to fill out a search form in [craigslist](http://auburn.craigslist.org/ "this") so that I can get the link to the page I would have normally gotten if I had filled out the form manually. By viewing the source, I've found this form: ``` <form id="search" action="/search/"...
You send HTTP GET params in the URL (and not as an encoded part of the request body like `POST`), change your Python to look like this and you should get what you are after: ``` import urllib,httplib conn = httplib.HTTPConnection("auburn.craigslist.org") params = urllib.urlencode({'query': 'english tutor', 'catAbb': ...
why don't you use requests (<http://docs.python-requests.org/en/latest/>): ``` import requests response = requests.get("http://auburn.craigslist.org/search/", params={"query": "english tutor", "catAbb": "sss"}) response.content ```
html get request "you didn't select a category"
[ "", "python", "html", "python-2.7", "get", "httplib", "" ]
Have a 2-dimensional array, like - ``` a[0] = [ 0 , 4 , 9 ] a[1] = [ 2 , 6 , 11 ] a[2] = [ 3 , 8 , 13 ] a[3] = [ 7 , 12 ] ``` Need to select one element from each of the sub-array in a way that the resultant set of numbers are closest, that is the difference between the highest number and lowest number in the set is ...
collect all the values to create a single ordered sequence, with each element tagged with the array it came from: 0(0), 2(1), 3(2), 4(0), 6(1), ... 12(3), 13(2) then create a window across them, starting with the first (0(0)) and ending it at the first position that makes the window span all the arrays (0(0) -> 7(3)) ...
A wordy Haskell version of the nice algorithm by whiterook6: ``` import Data.List (minimumBy,sortBy) import qualified Data.Map as M (fromList,toList,adjust,lookup) f arrays = g (zip arrays [1..]) [] h [(100,0),(0,0)] where n = length arrays h = (M.fromList $ zip [1..n] (repeat 0)) g arrays sequence indexes best...
Finding N closest numbers
[ "", "python", "algorithm", "" ]
So i have this line of code: ``` fc = round((1+5*100)/100, 3) if fc_no_rocks == None else round(fc_no_rocks/100, 3) ``` that takes in a variable, whose type should be float. When I test the variable type using type(), it returns: ``` >>>type(fc_no_rocks) <type 'float'> ``` but i keep getting an error that says "uns...
There was a for loop that had changed the variables so the fc\_no\_rocks was set to None. This made the logic when setting the fc variable switch to the left, where one of the variables i had replaces was also a string. sorry for the mixup
Obviously, `fc_no_rocks` is a string in your case. That bug is on you. Better to check for several cases: 1. `fc_no_rocks` is a number 2. `fc_no_rocks` is a string indicating a number 3. `fc_no_rocks` is neither of the above You check to make sure that `fc_no_rocks` isn't `None`, but it could be *anything*. So it's b...
Type Error while using variables
[ "", "python", "" ]
I was reading the python documentation where I came across `elem [,n]` this notation for arguments. I have seen such notations in past. Don't just know what they mean. Also, google doesn't support searching brackets.
The Python documentation has a [section about the used notation](http://docs.python.org/3/reference/introduction.html#notation), which says: > […] a phrase enclosed in square brackets (`[ ]`) means zero or one occurrences (in other words, the enclosed phrase is optional). This notation originates from the [Backus–Nau...
It means that the argument so bracketed is optional.
What does [, element] mean?
[ "", "python", "" ]
lets say that you have the following two lists: ``` l1 = [0,30,45,55,80,90] l2 = [35,65,70,75,100,120] ``` **rules for the lists:** 1. `l1` always starts at 0 and `l2` must start at greater than 0 both 2. lists must be in order from smallest to biggest **the goal:** essentially each number is an index for opening ...
You can use the `bisect` module: ``` import bisect def f(l1,l2): for x in l2: ind = bisect.bisect(l1,x) # if the index where the item from l2 can fit in l1 is 1, # then it's time to return if ind - 1 == 0: return x del l1[ind-1] #otherwise remove th...
This problem is a variation of a standard parenthesis matching problem. The primary difference is that instead of a single sequence of openers and closers, the openers and closers are numbered, and their order is defined by their numbers. We can lazily merge them into a single sequence, then go through the sequence and...
list manipulation with minimal iteration
[ "", "python", "list", "iteration", "" ]
Complete novice programmer here. I've been going through Zed's *Learn Python the Hard Way* book for the past few weeks to cover the basics of programming, and I've found myself at a standstill. I've more or less been following everything he's been throwing at me, but once I found myself at exercise 43, Zed seems to hav...
In the code on pastebin you have `return` used inside methods of classes, not inside classes directly. In a method (just a function associated with an object, really) `return` works just like it does in a regular function - it passes back some piece of data (or nothing) to whatever called it and returns control to the ...
The `return` statement isn't necessarily being used in a class, but more specifically, in a function which happens to be in a class. So when you call the function in the class, that will be returned. There's nothing different to it than a normal function. You create an instance of the `Map()` class to use in the `Engi...
understanding classes in python 2 [learn python the hard way exercise 43]
[ "", "python", "class", "python-2.7", "return", "" ]
My table: ``` PageOrderID PageName 3 Citation Number 3 Citation Number 3 Citation Number 1 Account Info 1 Account Info 1 Account Info ``` I wanted to order it Pagename according to PageOrderID, but distinct PageNames. I have tried the followi...
``` select DISTINCT PageOrderID,PageName from ScreenMaster order by PageOrderID ```
Maybe you want to group by: ``` SELECT PageOrderID,PageName FROM dbo.ScreenMaster GROUP BY PageOrderID,PageName ORDER BY PageOrderID ``` [**Demo**](http://sqlfiddle.com/#!3/c87d3/3/0) ``` PAGEORDERID PAGENAME 1 Account Info 3 Citation Number ```
order by with distinct name
[ "", "sql", "database", "sql-server-2008-r2", "" ]
I've got a list of dictionaries like this: ``` users = [{'id':1, 'name': 'shreyans'}, {'id':2, 'name':'alex'}, {'id':3, 'name':'david'}] ``` and a list of ids with the desired order: ``` order = [3,1,2] ``` What's the best way to order the list `users` by the list `order`?
Use sort with a custom key: ``` users.sort(key=lambda x: order.index(x['id'])) ```
``` users = [{'id':1, 'name': 'shreyans'}, {'id':2, 'name':'alex'}, {'id':3, 'name':'david'}] order = [3,1,2] users.sort(key=lambda x: order.index(x['id'])) ```
how do I sort a python list of dictionaries given a list of ids with the desired order?
[ "", "python", "sorting", "" ]
So far all I have configured is a table for users where each user has a unique `user_id`. However, I need to store a list of contacts for each user. This would only need to contain the user\_id of each contact. However, I'm faced with a design challenge. Should I create a table for each user in which to store that use...
The single normalised table is absolutely the correct approach. You're worried about its performance, due to a concern about "lack of indexing". Lack of indexing? Why lack of indexing? Make your primary key `(user_id,contact_id)` — which makes sense semantically an' all — and that's all you need. Never, *ever* have...
The second way with the "pivot" table is the best way and best practice for normalization. You would also want to make foreign key relations with indexes to the proper tables and columns.
How to design a database in which there are many users and each has a list of multiple contacts?
[ "", "mysql", "sql", "database", "database-design", "" ]
First off, I'm a novice... I'm a newbie to Python, pandas, and Linux. I'm getting some errors when trying to populate a DataFrame (sql.read\_frame() gives an exception when trying to read from my MySQL DB, but I am able to execute and fetch a query / stored proc). I noticed that pandas is at version 0.7.0, and running...
As nitin points out, you can simply upgrade pandas using pip: ``` pip install --upgrade pandas ``` Since this version of pandas will be installed in `site-packages` you will, in fact, be at the mercy of any automatic updates to packages within that directory. It's wise to install the versions of packages you want int...
"pip install --upgrade pandas" did not work for me on a fresh Ubuntu: 12.04.2 LTS Desktop instance. Within Python, pandas was still showing version 0.7.0. Instead, I was able to get the update through by using easy install: ``` sudo easy_install -U pandas ```
Python pandas stuck at version 0.7.0
[ "", "python", "pandas", "" ]
I am trying to get an output such as this: ``` 169.764569892, 572870.0, 19.6976 ``` However I have a problem because the files that I am inputing have a format similar to the output I just showed, but some line in the data have 'nan' as a variable which I need to remove. I am trying to use this to do so: ``` TData...
``` TData_Pre_Out = map(itemgetter(0, 7, 8), HDU_DATA) ``` This statement gives you **a list of tuples**. And then you compare the tuple with a string. All the `!=` comparisions success.
Without showing how you read in your data, the solution can only be guessed. However, if `HDU_DATA` stores real `NaN` values, try following: Comparing variable to `NaN`s does not work with the equality operator `==`: ``` foo == nan ``` where `nan` and foo are both `NaN`s gives always false. Use `math.isnan()` inst...
Removing Indices from a list in Python
[ "", "python", "list", "list-comprehension", "" ]
I have got two tables as following Table `Person` ``` Id Name 1 A 2 B 3 C 4 D 5 E ``` Table `RelationHierarchy` ``` ParentId ChildId 2 1 3 2 4 3 ``` This will form a tree like structure ``` D | C | ...
You can use [recursive CTE](http://msdn.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx) to achieve that: ``` DECLARE @childID INT SET @childID = 1 --chield to search ;WITH RCTE AS ( SELECT *, 1 AS Lvl FROM RelationHierarchy WHERE ChildID = @childID UNION ALL SELECT rh.*, Lvl+1 AS Lvl FR...
I've used this pattern to associate items in a hierarchy with the item's root node. Essentially recursing the hierarchies maintaining the values of the root node as additional columns appended to each row. Hope this helps. ``` with allRows as ( select ItemId, ItemName, ItemId [RootId],ItemName [RootName] fro...
Finding a Top Level Parent in SQL
[ "", "sql", "sql-server", "" ]
I'm using MS SQL Server Management Studio 2008. I'm having an issue with writing a subquery. This is the entire query as follows: ``` SELECT DISTINCT FH.ShipDate, AVG(FH.[Dist Freight]) AS [Atlantic Freight Charge], (SELECT DISTINCT [Non-Atlantic Freight Charge] FROM (SELECT DISTINCT ...
I think what you want is something like this: ``` SELECT FH.ShipDate, AVG(CASE WHEN VendorName = 'Atlantic Trucking' THEN FH.[Dist Freight] ELSE NULL END) AS [Atlantic Freight Charge], AVG(CASE WHEN VendorName != 'Atlantic Trucking' ...
The problem is you have a subquery returning multiple rows and you're trying to store it as a value in a single row/column combination. To understand why this is the case, let's look at what the result would look like for the outer query, the 'Atlantic Freight Charge': ## Table 1 - Atlantic Freight Charges ``` ShipD...
"Subquery returned more than 1 value" for SELECT subquery
[ "", "sql", "sql-server", "sql-server-2008", "subquery", "" ]
I am using mysql.connector in python to get a list of values from a database. can you please help extract each value from the list separately my code is as below ``` cnx = mysql.connector.connect(host=mysql_localhost, user=user, password=password, database=database) cursor = cnx.cursor() cursor.execute("select * fr...
Use a `for` loop: ``` for each in results[0]: ... ``` Or if you do want assign them to variables: ``` a, b, c, d, e, f, g = results[0] ```
``` for Value in results: # do what you need ```
Filter out values from python mysql query
[ "", "python", "mysql", "list", "filter", "" ]
curious about this behavior from SQL Server. This query produces results very quickly, just as I'd expect: ``` SELECT * FROM dbo.v_View1 View1 FULL OUTER JOIN dbo.v_View2 View2 ON View1.Portfolio = View2.Portfolio AND View1.AsOfDate = View2.AsOfDate where (View1.AsOfDate IN (NULL, '20130717')) ``` However, ...
I suspect the query optimizer is doing something very strange because the naive implementation involves two scans on `v_View1` perhaps the optimizer is failing to realize that the subquery `SELECT MAX(AsOfDate) ...` is going to be the same for each row. I suspect it might be failing to realize that the subquery is not ...
I believe it is recalculating MAX(AsOfDate) for every record it comapres to. A simple solution would be to use a WITH clause (also known as common table expression) which would only be calculated at the beginning.
SELECT subquery within IN statement hanging SQL Server
[ "", "sql", "sql-server", "" ]
To test if lst1 is a shallow copy of lst2, I did this: ``` def check_shallow_copy(lst1, lst2): ''' Return True if lst1 is a shallow copy of lst2. Return False if not. ''' for idx in range(len(lst1)): if lst1 == lst2 and id(lst1[idx]) == id(lst2[idx]) and lst1 is not lst2: return True else: re...
Let me explain a little bit what gnibbler has done. ``` def check_shallow_copy(lst1, lst2): return lst1 is not lst2 and all([x is y for x, y in zip(lst1, lst2)]) ``` The zip function takes two lists and return a list of tuples (ele1, ele2), where ele1 is from lst1 and ele2 is from lst2, preserving ord...
``` def check_shallow_copy(lst1, lst2): if lst1 is lst2 or len(lst1) != len(lst2): return False return all(x is y for x, y in zip(lst1, lst2)) ``` It's difficult to define exactly what `check_deep_copy` should do. For example, if all the objects are immutable, a deep copy *may* look exactly like a shal...
Python: writing a function that tests if list1 is a shallow copy of list2
[ "", "python", "list", "deep-copy", "shallow-copy", "" ]
I've got three tables: Resource, Timesheet, TimePeriod. A Resource has many Timesheets and a Timesheet has one TimePeriod. This used for us to keep track of employee timesheets. I'm trying to figure out how to find out the status of each person's timesheet for this week. The problem is, if a person hasn't filled out a ...
Another one: ``` SELECT r.id, r.Name, s.Status FROM Resource r INNER JOIN TimePeriod p ON p.week = '2013week2' LEFT JOIN Timesheet s ON s.Resource_id = r.id AND s.TimePeriod_id = p.id ; ``` Alternatively you could replace the `INNER JOIN ... ON` with a `CROSS JOIN ... WHERE`: ``` SELECT r.id, r.Name, s.Status FROM R...
You need to a LEFT JOIN the combination of Timesheet and the inner join to TimePeriod The syntax for that is ``` SELECT res.id, res.name, ts.status FROM Resource res LEFT JOIN (Timesheet ts INNER JOIN TimePeriod tp ON ts.timeperiod_id = tp.id AND tp.week = '2013Week2') ON ts.resource_id = r...
SQL Query Across Multiple Joined Tables
[ "", "mysql", "sql", "sql-server", "" ]
I have seen it both ways, but which way is more Pythonic? ``` a = [1, 2, 3] # version 1 if not 4 in a: print 'is the not more pythonic?' # version 2 if 4 not in a: print 'this haz more engrish' ``` Which way would be considered better Python?
The second option is more Pythonic for two reasons: * It is **one** operator, translating to one bytecode operand. The other line is really `not (4 in a)`; two operators. As it happens, [Python *optimizes* the latter case](http://hg.python.org/cpython/file/ed8b0ee1c531/Python/peephole.c#l407) and translates `not (x...
Most would agree that `4 not in a` is more Pythonic. Python was designed with the purpose of being easy to understand and intelligible, and `4 not in a` sounds more like how you would say it in English - chances are you don't need to know Python to understand what that means! Note that in terms of bytecode, the two w...
What is more 'pythonic' for 'not'
[ "", "python", "python-2.x", "" ]
I have to modify some SQL code that does not seem to be working as it is supposed to. The SQL code looks awful to me, but it works for the most part. Say we had multiple vendors with similar names: Microsoft, Microsoft Corp, and Microsoft, Inc, etc. All the query returns is Microsoft, even though the existing code i...
Try something like this: ``` ALTER PROCEDURE GetSignalMasterByFilter2( @planner varchar(50), @reorder int, @release int, @CMTTED varchar(50), @partid varchar(50), @global_short_dt int, @PRI_VENDOR_NAME varchar(50) ) as begin SELECT DISTINCT PRIMARY_VENDOR, case when PRI_VENDOR_NAME is null t...
I have been in a similar situation many times. With me.... it's usually my own code that I am trying to clean up. When doing things like this, please do not ONLY consider code readability. You must also consider the impact on the server. Often times, there are various ways to write a query that produces identical resu...
Converting Dirty SQL Code to Something Clean and Efficient
[ "", "sql", "sql-server-2008", "t-sql", "" ]
We have a large Django application made up of a large number of different views (some of which contain forms). As with most large applications, we use a base layout template that contains the common layout elements across the applications (mainly a header and a footer), which the templates for all of our views extend. ...
This seems like such an obvious question that maybe I'm overlooking something. But as others have said your universal search form should not make a POST request to the view that rendered the current page. Each html form has an `action` attribute. The attribute of your search form should point towards an URL. Probably ...
Instead of handling the form submission on every view of the application, you can implement a separate `view` (endpoint), which handles all the `search queries`. (an endpoint which returns JSON result) since you dont want to add overhead of rendering the whole page with that view. So the search query (which client side...
Implementing Universal Search in a Django Application
[ "", "python", "django", "search", "inheritance", "django-forms", "" ]
I have written a rather large module which is automatically compiled into a .pyc file when I import it. When I want to test features of the module in the interpreter, e.g., class methods, I use the `reload()` function from the `imp` package. The problem is that it reloads the `.pyc` file, not the `.py` file. For exa...
yes. here are things you can use [the `-B` command line option](http://docs.python.org/2/using/cmdline.html#cmdoption-B): ``` python -B ``` or use the [`PYTHONDONTWRITEBYTECODE` environment option](http://docs.python.org/2/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE): ``` export PYTHONDONTWRITEBYTECODE=1 ``` ...
if you're using ipython, you can can do a shell command by prefixing it with `!` So you could do ``` >>> !rm some_file.pyc >>> reload(some_file) ``` Alternatively, you could define a quick function in your current shell: ``` >>> import os >>> def reload(module_name): ... os.system('rm ' + module_name + '.pyc') ...
Make python reload() function read from .py instead of .pyc
[ "", "python", "reload", "imp", "" ]
I am trying to learn python with codeacademy, and the assignment was to take two given dictionaries (one is a list of food and the price to buy + the second is a list of the same foods, but the quantities in stock) and calculate how much revenue i will have if all the foods sell. At first, i got this error message `"c...
One method is to loop over only the keys: ``` for key in prices: if key in stock: print(prices[key] * stock[key]) ``` Though in your case both dictionaries have the same keys, I added a conditional to check that each key in `prices` is also in `stock`. Then, assuming it is, multiply the dictionary values ...
The `cost` and `quan` are both lists, they can not be passed to `float`. I doubt why you make the solution complex. You can just use: ``` for fruit in prices: print prices[fruit] * stock.get(fruit, 0) ``` Or if you want, you can use a dict comprehension to make the result more clear: ``` {fruit: prices[fruit]*st...
how do i use float to convert a value string inside a dictionary and do math with the new values?
[ "", "python", "dictionary", "" ]
I'm using: ``` CPython 2.7.3, Flask==0.10.1 Flask-SQLAlchemy==0.16 psycopg2==2.5.1 and postgresql-9.2 ``` Trying to get PK from insert call with alchemy. Getting engine like so: ``` app = Flask(__name__) app.config.from_envvar('SOME_VAR') app.wsgi_app = ProxyFix(app.wsgi_app) # Fix for old proxyes db = SQLAlchemy...
You can use the `RETURNING` clause and handle this yourself: ``` INSERT INTO test (...) VALUES (...) RETURNING id ``` Then you can retrieve the id as you normally retrieve values from queries. Note that this works on Postgres, but does not work on other db engines like MySQL or sqlite. I don't think there is a db a...
Is there any reason you do text query instead of normal sqlalchemy insert()? If you're using sqlalchemy it will probably be much easier for you to rephrase your query into: ``` from sqlalchemy import text, exc, insert # in values you can put dictionary of keyvalue pairs # key is the name of the column, value the valu...
How to get inserted_primary_key from db.engine.connect().execute call
[ "", "python", "sqlalchemy", "flask", "" ]
basically... i'm trying to get my "count" method to count how many nodes there are in the tree... but the recursion isnt working.. how do i do it? ``` ''' Created on Jul 11, 2013 To practice building native recursion things @author: bailey ''' class AllWords : def __init__(self): self.my_tree = Tree() def add(...
`Tree` has that method, but `AllWords` doesn't. You are passing in an `AllWords` object as `blob` in `Tree.count()` on the line that says `tout.my_tree.count(tout)`, because you have declared `tout = Searching.AllWords()`. You probably meant to make it a `Tree`.
Try: > tout.my\_tree.count(tout.my\_tree.root) because `tout` is not an instance of `Blob`
Node counter in Binary Search Tree
[ "", "python", "" ]
I need a MySQL Function that will allow me to pass a number of working days (Monday - Friday) and a start DATE or DATETIME (doesn't matter for my implementation), and have it return a new DATE or DATETIME that many work days in the future. Example: `SELECT AddWorkDays(10, "2013-09-01")` returns "2013-09-16" assuming "...
This is new function with mysql syntax: ``` DROP FUNCTION IF EXISTS AddWorkDays; DELIMITER $$ CREATE FUNCTION AddWorkDays ( WorkingDays INT, StartDate DATETIME ) RETURNS DATETIME BEGIN DECLARE Count INT; DECLARE i INT; DECLARE NewDate DATETIME; SET Count = 0; SET i = 0; WHILE (i < Wor...
This implementation is a bit more efficient then the accepted answer (probably not important), but also works for negative business days (was important for me). The basic idea was every 5 days converts to 7 days, then you might need to adjust by adding or subtracting 2 days if the (days % 5) + the start day of the wee...
MySQL Function to add a number of working days to a DATETIME
[ "", "mysql", "sql", "sql-function", "" ]
## Is it possible to fetch data synchronously from cordova-sqlite? I have a table `caseTable` with fields (ID, caseName, date). Each row in that table corresponds to another table named after the caseName field. I need to loop through the `caseTable` table and get a count of the number of rows in the table referred to...
You could loop through them asynchronously by doing something like this (not tested, but hopefully you get the idea): ``` var count = 0; var caseTableResult = []; var getallTableData = function (tx) { tx.executeSql('SELECT * FROM CaseTable', [], querySuccess, errorCB); } var querySuccess = function (tx, result) ...
I don't believe it is possible to do this synchronously, and it's probably not a good idea to try. In this case, you can probably get the value you are after using a subquery, something like: ``` SELECT *, (SELECT COUNT(*) FROM CaseTableDetail WHERE CaseTableDetail.CaseID = CaseTable.id) AS CaseCount FRO...
How can I fetch data synchronously from cordova-sqlite?
[ "", "jquery", "sql", "sqlite", "cordova", "" ]
I have table like this: ``` q A B 1 0 1 1 2 0 2 3 0 2 0 4 ``` and I want to get something like this: ``` q A B 1 2 1 1 2 1 2 3 4 2 3 4 ``` and then remove duplicated values. Any idea how to do this? I have duplicated value of q saved in another table if that helps :)
You need to *group* your table with a suitable aggregate function (I use `SUM()` below, but you may want to use `MAX()` or something else, depending on your requirements): ``` SELECT q, SUM(A) A, SUM(B) B FROM my_table GROUP BY q ``` See it on [sqlfiddle](http://sqlfiddle.com/#!2/182e1f/1/0).
``` ALTER IGNORE TABLE yourtable ADD UNIQUE INDEX idx_name (q, a, b); ```
Update duplicated records MySQL
[ "", "mysql", "sql", "database", "sql-update", "duplicates", "" ]
In C there's a clever trick that lets you avoid pyramid-style code by turning: ``` if (check1()) if (check2()) if (check3()) do_something(); ``` into: ``` do { if (!check1()) break; if (!check2()) break; if (!check3()) break; do_something(); } while (0); ``` What's the cleanest wa...
In C, the use of the `do ... while(0)` construct that you have shown is usually used when the C programmer wants something that behaves like a `goto`, but using an actual `goto` is out of the question (for various reasons). So, the `break` out of the `do ... while(0)` is really a kind of hack. Using the same idiom in P...
The Pythonic way of writing this would be ``` if check1() and check2() and check3(): do_something() ``` In Python we emphasize clarity and simplicity of the code, not using clever programming tricks. --- **[Edit]** If you need to *"create a variable and use it in the first check"*, then you would use the pyrami...
How can I write C's do-while(0) in Python?
[ "", "python", "loops", "do-while", "" ]
I am trying to create a script to create/setup a group of stored procedures that will all be fairly similar. So I am trying to loop through this code, changing the `@DATABASE_NAME` and `@TableName` when needed. ``` /* Start loop */ DECLARE @create_stored_procedure nvarchar(max) SET @create_stored_procedure =...
I wouldn't call the solution intuitive, but apparently [this](https://stackoverflow.com/a/483868/2400222) works. I prefer the look of [this one](https://stackoverflow.com/a/793362/2400222) though.
Try with spiting USe DB and create procedure. Like this ``` DECLARE @create_store_procedure nvarchar(max) SET @create_store_procedure = N' USE [' + @DATABASE_NAME + '] ' EXEC sp_executesql @statement = @create_store_procedure SET @create_store_procedure = N' CREATE PROCEDURE [dbo].[sproc_imp_' + @TableName +...
SQL dynamically create stored procedures?
[ "", "sql", "sql-server-2005", "stored-procedures", "dynamic-sql", "" ]
What is the difference between `CROSS JOIN` and `INNER JOIN`? **CROSS JOIN:** ``` SELECT Movies.CustomerID, Movies.Movie, Customers.Age, Customers.Gender, Customers.[Education Level], Customers.[Internet Connection], Customers.[Marital Status], FROM Customers CROSS JOIN Movies ``` **INNE...
Cross join does not combine the rows, if you have 100 rows in each table with 1 to 1 match, you get 10.000 results, Innerjoin will only return 100 rows in the same situation. These 2 examples will return the same result: Cross join ``` select * from table1 cross join table2 where table1.id = table2.fk_id ``` Inner ...
Here is the best example of Cross Join and Inner Join. Consider the following tables **TABLE : `Teacher`** ``` x------------------------x | TchrId | TeacherName | x----------|-------------x | T1 | Mary | | T2 | Jim | x------------------------x ``` **TABLE : `Student`** ``` x----------...
CROSS JOIN vs INNER JOIN in SQL
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "cross-join", "" ]
I am quite new to Python and recently I wanted to send some files using Python. I quickly found out about sockets. But I searched for ready-made solution, because I thought client-server communication is such a common use, there must exist some kind of library (or maybe it's just because of my Java background and I got...
twisted is a very common one: <http://twistedmatrix.com/trac/> <http://twistedmatrix.com/documents/13.0.0/core/examples/>
If you use sockets, you can use ssh and then do scp (secured copies). If you are moving files back and forth, that would probably be the easiest way.
Sending files in Python
[ "", "python", "python-2.7", "io", "client-server", "communication", "" ]
I wrote a program to play hangman---it's not finished but it gives me an error for some reason... ``` import turtle n=False y=True list=() print ("welcome to the hangman! you word is?") word=raw_input() len=len(word) for x in range(70): print print "_ "*len while n==False: while y==True: print "insert ...
You assigned to a local name `len`: ``` len=len(word) ``` Now `len` is an integer and shadows the built-in function. You want to use a *different* name there instead: ``` length = len(word) # other code print "_ " * length ``` Other tips: * Use `not` instead of testing for equality to `False`: ``` while not n...
Just use `del len` and initialize with a new (non-keyword) variable, it should work fine.
TypeError: 'int' object is not callable,,, len()
[ "", "python", "python-2.7", "int", "" ]
If I have a large list that I want to create a dictionary out of, what would be the most efficient way of doing this supposing I just want to assign the value as so: ``` {'item1':'0','item2':'1','item3':'2','itemn':'n-1'} ``` I've seen a lot on here about just assigning same value to all the keys, but nothing about h...
Try this command: ``` d = dict(zip(your_list, range(len(your_list))) ```
``` dict(x[i:i+2] for i in range(0, len(x), 2)) ```
Create a dictionary from a list
[ "", "python", "dictionary", "" ]
Is there a way to reduce a duplicated characters to specific number, for example if we have this string. `"I liiiiked it, thaaaaaaank you"` Expected output: `"I liiiiked it thaaaank you"` so if the duplicated character over 4, for example, it should be reduced to only four characters and if it less than or equal 4 t...
``` >>> import re >>> s="I liiiiked it, thaaaaaaank you" >>> re.sub(r"(.)(\1{3})(\1+)", r"\1\2", s) 'I liiiiked it, thaaaank you' ``` This regular expression looks for 3 groups. The first is any character. The second is 3 more of that same character, and the third is one or more of the first character. Those 3 group...
You can do this with a single scan through the input string, just keep a count of the current character and don't add it to the output if you've got too many repeats: ``` input_string = "I liiiiked it, thaaaaaaank you" max_reps = 4 prev_char = None rep_count = 0 output = "" for char in input_string: if not char ...
How to reduce the duplicated characters in a string using Python
[ "", "python", "string", "duplicates", "" ]
Like [this question](https://stackoverflow.com/questions/7439555/noun-adjective-etc-word-lists-or-dictionaries-common-words), I am interested in getting a large list of words by part of speech (a long list of nouns; a list of adjectives) to be used programmatically elsewhere. [This answer](https://stackoverflow.com/que...
It's worth noting that Wordnet is actually one of the corpora included in the NLTK downloader by default. So you could conceivably just use the solution you already found without having to reinvent any wheels. For instance, you could just do something like this to get all noun synsets: ``` from nltk.corpus import wor...
You should use the [Moby Parts of Speech Project](http://archive.org/details/mobypartofspeech03203gut) data. Don't be fixated on using only what is directly in NLTK by default. It would be little work to download the files for this and pretty easy to parse them with NLTK once loaded.
Getting a Large List of Nouns (or Adjectives) in Python with NLTK; or Python Mad Libs
[ "", "python", "machine-learning", "nltk", "" ]
I have very simple table: ``` CREATE TABLE `navigation` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `parent_id` int(11) unsigned DEFAULT NULL, `title` varchar(255) NOT NULL COMMENT 'Название ссылки', `priority` tinyint(3) NOT NULL COMMENT 'Параметр сортировки' PRIMARY KEY (`id`) ) ENGINE=InnoDB; ``` wi...
> How can I to avoid using filesort? Or is it impossible? I have read a lot of topics on SO, but couldn't understand right answer. You would need an index over the `priority` column: ``` ALTER TABLE navigation ADD INDEX (priority); ``` However, the chances are that MySQL will calculate that using such an index to so...
To avoid a filesort, most of the times you should be adding an index. In your case that would mean an index on the `priority` column. You can do this as follows: ``` ALTER TABLE `navigation` ADD INDEX (`priority`); ``` Note that even with this index it is still possible that a filesort is used as that might actually ...
Using filesort in simple query
[ "", "mysql", "sql", "explain", "" ]
I have found several questions regarding finding the frequency of a value in a list. Though I haven't found anything regarding finding the frequency of a list in a list. (or ndarray in ndarray) In essence I want to find the unique rows in : ndarray: [[ 3.95428571 5.67428571] ``` [ 3.795 4.67166667] [ 5.05 ...
You should have a look at `numpy.histogram2d`
Or convert the items to tuples and hash them like so :- ``` l = [[ 3.95428571, 5.67428571], [ 3.795 ,4.67166667], [ 5.05 ,6.79 ], [ 4.54333333 ,6.16666667], [ 5.1 ,6.78 ], [ 4.03 ,6.655 ], [ 3.71 ,6.22 ]] hashtable = dict() for i in l: hashtabl...
Frequency of list in list in python
[ "", "python", "list", "" ]
Let's say I have the following code: ``` import logging import logging.handlers a = logging.getLogger('myapp') h = logging.handlers.RotatingFileHandler('foo.log') h.setLevel(logging.DEBUG) a.addHandler(h) # The effective log level is still logging.WARN print a.getEffectiveLevel() a.debug('foo message') a.warn('warn...
It allows finer control. By default the root logger has `WARNING` level set; this means that it won't print messages with a lower level (no matter how the handlers' levels are set!). But, if you set the root logger's level to `DEBUG`, indeed the message gets sent to the log file: ``` import logging import logging.hand...
In Python logging there are two different concepts: the level that the logger logs at and the level that the handler actually activates. When a call to log is made, what is basically happening is: ``` if self.level <= loglevel: for handler in self.handlers: handler(loglevel, message) ``` While each of th...
What is the point of setLevel in a python logging handler?
[ "", "python", "logging", "python-logging", "" ]
For an assignment, I'm creating a program that retrieves from a file information regarding Olympic countries and their medal count. One of my functions goes through a list in this format: ``` Country,Games,Gold,Silver,Bronze AFG,13,0,0,2 ALG,15,5,2,8 ARG,40,18,24,28 ARM,10,1,2,9 ANZ,2,3,4,5 ``` The function needs to...
You are storing the whole string '13,0,0,2' as value, so ``` medalDict[code] = medal_count ``` should be replaced by: ``` medalDict[code] = tuple(medal_count.split(',')) ``` Your original thought is correct, with this line being the sole exception. What is changed is now it splits the '13,0,0,2' into a list ['13', ...
This line: ``` code, medal_count = eachline.strip().split(',',1) ``` ... is `split`ting the whitespace-`strip`ped `eachline`, `1` time, on `','`, then storing the resulting two strings into `code` and `medal_count` ... so yes, `medal_count` contains a string. You could handle this one of two ways: 1. Add a line alo...
How to read from a file into a dict with string key and tuple value?
[ "", "python", "python-3.x", "dictionary", "tuples", "iterable-unpacking", "" ]
I need to present the occurrences of letters in a text. If one of the letters doesn't occur, it should show zero and also output should be sorted alphabetically. I have prepared the following Python code, my questions are how can I show zero for non-occurring letters and how can I sort the list values based on the list...
Something like this (ignoring the sorting part for now) ? ``` import string result = [fdist.get(l, 0) for l in string.letters] ``` or ``` result = [fdist.get(l, 0) for l in string.ascii_lowercase] ``` since you're only dealing with lowercase characters
Note @astrognocci answer is simpler and more elegant, but this will also work. Create the counter with the keys of the alphabet (but set to zero initially) ``` import string fdist = Counter([f for f in string.ascii_lowercase]) for c in string.ascii_lowercase: fdist[c] = 0 ``` The `sorted(fdist.items())` returns ...
Sorting letter occurrences in a text alphabetically
[ "", "python", "sorting", "" ]
I am using py.test and wonder if/how it is possible to retrieve the name of the currently executed test within the `setup` method that is invoked before running each test. Consider this code: ``` class TestSomething(object): def setup(self): test_name = ... def teardown(self): pass def t...
You can also do this using the [Request Fixture](https://docs.pytest.org/en/6.2.x/reference.html#request) like this: ``` def test_name1(request): testname = request.node.name assert testname == 'test_name1' ```
You can also use the `PYTEST_CURRENT_TEST` environment variable set by pytest for each test case. [PYTEST\_CURRENT\_TEST environment variable](https://docs.pytest.org/en/latest/example/simple.html?highlight=PYTEST_CURRENT_TEST#pytest-current-test-environment-variable) To get just the test name: ``` os.environ.get('P...
py.test: how to get the current test's name from the setup method?
[ "", "python", "pytest", "" ]
I've been making heavy use of the answer in "[Really Cheap Command-Line Option Parsing in Ruby](https://stackoverflow.com/questions/897630/really-cheap-command-line-option-parsing-in-ruby)". It's great and for my purposes, always what I need. Now I find myself back in Python land for a bit because of internal library ...
You might want to use `sys.argv`: ``` from sys import argv quiet = '-d' in argv # True if '-d' in argv else False ``` If you want to remove `'-d'` from the `argv`, change the second line to this: ``` quiet = '-d' in argv and (argv.remove('-d') or True) ``` If this reduces its cheapness, let's make a function of it:...
Python has a few nice libraries for argument parsing: 1. [argparse](http://docs.python.org/2/library/argparse.html) 2. [optparse (depreciated since 2.7)](http://docs.python.org/2/library/optparse.html) Example: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", action='store_true') ```
How can I do really cheap command line parsing in Python?
[ "", "python", "ruby", "parsing", "command-line-arguments", "" ]
First: I'm using Access 2010. What I need to do is pull everything in a field out that is NOT a certain string. Say for example you have this: 00123457\**A8V*\* Those last 3 characters that are bolded are just an example; that portion can be any combination of numbers/letters and from 2-4 characters long. The 001234...
Why not use a replace function? ``` REPLACE(Facility.ID, "00123457", "") ```
You are missing a closing square bracket in here `Len([ID)` You also need to reverse this "00123457" in `InStrRev()`, but you don't need `InStrRev()`, just `InStr()`.
How to select everything that is NOT part of this string in database field?
[ "", "sql", "database", "ms-access", "ms-access-2010", "" ]
I have a MySQL problem I can not get to solve. I have a mysql to manage a virtual user dovecot installation, that uses two tables (one for the aliases, another for the domains). The table aliases has these fields: domain\_id(INT), source(VARCHAR), destination(VARCHAR), whereas table domains has only two fields: id (IN...
My experience is mainly in MS SQL Server, but I reckon it should go the same way in MySQL: ``` INSERT INTO valias(domain_id, source, destination) SELECT id, 'canto', 'george' FROM vdomains WHERE name = 'domain_name'; ```
Either I'm missing something here or your query seems a bit to overingeenered. How about this: ``` INSERT INTO aliases(domain_id, source, destination) VALUES (id, 'canto', 'george') JOIN domains ON domains.id = aliases.domain_id WHERE domains.name = 'domain name' ```
mysql insert with value, with selected data from another table
[ "", "mysql", "sql", "insert", "where-clause", "" ]
I'm currently having issues using the TinyMCE editor within the Django admin interface. When entering text into two particular TinyMCE fields and pressing save, the form is returned with both fields empty, flagged red and tagged with a "This field is required" label: ![enter image description here](https://i.stack.img...
I guess that your custom form and custom widget give you trouble. First two things. Just to be sure... Did you add tinymce in settings.py? ``` INSTALLED_APPS = ( ... 'tinymce', ) ``` And in urlpatterns? ``` urlpatterns = patterns('', ... (r'^tinymce/', include('tinymce.urls')), ) ``` According to th...
You should add a `blank=True` parameter in companycms/news/models.py: ``` content = tinymce_models.HTMLField(blank=True) ```
TinyMCE with Django: "This field is required"
[ "", "python", "django", "django-admin", "tinymce", "django-tinymce", "" ]
I want to check both whether a file exists and, if it does, if it is empty. If the file doesn't exist, I want to exit the program with an error message. If the file is empty I want to exit with a different error message. Otherwise I want to continue. I've been reading about using Try: Except: but I'm not sure how t...
I'd use [`os.stat`](http://docs.python.org/2/library/os.html#os.stat) here: ``` try: if os.stat(filename).st_size > 0: print "All good" else: print "empty file" except OSError: print "No file" ```
How about this: ``` try: myfile = open(filename) except IOError: # FileNotFoundError in Python 3 print "File not found: {}".format(filename) sys.exit() contents = myfile.read() myfile.close() if not contents: print "File is empty!" sys.exit() ```
Correct way to check for empty or missing file in Python
[ "", "python", "python-2.7", "" ]
I have a string: ``` s = '&nbsp;<span>Mil<\/span><\/th><td align=\"right\" headers=\"Y0 i7\">112<\/td><td align=\"right\" headers=\"Y1 i7\">113<\/td><td align=\"right\" headers=\"Y2 i7\">110<\/td><td align=\"right\" headers=\"Y3 i7\">107<\/td><td align=\"right\" headers=\"Y4 i7\">105<\/td><td align=\"right\" headers=\...
``` >>> r = re.compile(r'headers="Y\d+ i\d+">(\d+)<\\/td>') >>> r.findall(s) ['112', '113', '110', '107', '105', '95', '95', '87', '77', '74', '74'] >>> ```
All of the numbers you want are in between ">" and "<". So, you can just do this: ``` re.findall(">(\d+)<", s) ``` output: ``` ['112', '113', '110', '107', '105', '95', '95', '87', '77', '74', '74'] ``` Basically, it's saying get every stream of digits that is between ">" and "<". Then, with `set`, you can get only...
python re, multiple matching groups
[ "", "python", "regex", "python-3.x", "" ]
I have a small problem with a math in python. So I have a few variables, `x`, `y` and `answer`: ``` >>>x = 20 >>>y = 21 >>>answer = x / y * 100 >>>answer 0 ``` So it's prints out null. OK i know that it's prints out null because i had to print `x = 20.0` instead of print `x = 20`. But anyway I need it to print out: ...
Use `from __future__ import division` to make *all* division float division. Alternatively, use `float()` instead of `int()` to interpret a string as a floating point number instead: ``` answer = float(x) / y * 100 ```
Just use ``` >>> answer = float(x) / y * 100 ```
Python 2: ValueError: invalid literal for int() with base 10: '20.0'
[ "", "python", "math", "" ]
It's all in the title. Here is the following example: ``` class A(object): my_var = 5 def my_method(self, drink='beer'): return 'I like %s' % drink @property def my_property(self): return 'I do not drink coffee' ``` I instantiate an A object and I want to know the type of each attrib...
You need to look at the class (this is the case for descriptors in general), which for objects you can find via the `__class__` attribute or by using the type function: ``` >>> obj.__class__.my_property <property object at 0xb74bd16c> ``` or by ``` >>> type(obj).my_property <property object at 0xb720b93c> ``` These...
I once asked a similar question. The trouble you'll run into, of course, is that you can't access the property through the instance to determine its type without calling the getter, which gets you the type of whatever the getter returns. So you have to access the property through its class rather than through the insta...
Determine if given class attribute is a property or not, Python object
[ "", "python", "" ]
I have two lists like thw following: ``` a=['not','not','not','not'] b=['not','not'] ``` and I have to find the `len` of the list containing the intesection of the two above list, so that the result is: ``` intersection=['not','not'] len(intersection) 2 ``` Now the problem is that I have tried `filter(lambda x: x i...
If you don't mind using [collections.Counter](http://docs.python.org/2/library/collections.html#collections.Counter), then you could have a solution like ``` >>> import collections >>> a=['not','not','not','not'] >>> b=['not','not'] >>> c1 = collections.Counter(a) >>> c2 = collections.Counter(b) ``` and then index b...
I don't see any particularly compact way to compute this. Let's just go for *a* solution first. The `intersection` is some sublist of the shorter list (e.g. `b`). Now, for better performance when the shorter list is not extremely short, make the longer list a set (e.g. `set(a)`). The intersection can then be expressed...
common elements in two lists where elements are the same
[ "", "python", "list", "intersection", "" ]
here is an example text file ``` the bird flew the dog barked the cat meowed ``` here is my code to find the line number of the phrase i want to delete ``` phrase = 'the dog barked' with open(filename) as myFile: for num, line in enumerate(myFile, 1): if phrase in line: print 'found at line:...
You could use the `fileinput` module to update the file - note this will remove *all* lines containing the phrase: ``` import fileinput for line in fileinput.input(filename, inplace=True): if phrase in line: continue print(line, end='') ```
A user by the name of gnibbler posted something similar to this on another thread. Modify the file **in place**, offending line is replaced with spaces so the remainder of the file does not need to be shuffled around on disk. You can also "fix" the line in place if the fix is not longer than the line you are replacing...
How to delete a line from a text file using the line number in python
[ "", "python", "python-3.x", "" ]
I have a table that contains all purchased items. I need to check which users purchased items in a specific period of time (say between 2013-03-21 to 2013-04-21) and never purchased anything after that. I can select users that purchased items in that period of time, but I don't know how to filter those users that nev...
Give this a try ``` SELECT user_id FROM my_table WHERE purchase_date >= '2012-05-01' --your_start_date GROUP BY user_id HAVING max(purchase_date) <= '2012-06-01'; --your_end_date ``` It works by getting all the records `>= start date`, groups the resultset by `user_id` and then finds the `max`...
This is probably a standard way to accomplish that: ``` SELECT `userId`, `email` FROM my_table mt WHERE `date` BETWEEN '2013-03-21' AND '2013-04-21' AND NOT EXISTS ( SELECT * FROM my_table mt2 WHERE mt2.`userId` = mt.`userId` and mt2.`date` > '2013-04-21' ) GROUP BY `userId` ```
How to get users that purchased items ONLY in a specific time period (MySQL Database)
[ "", "mysql", "sql", "" ]
I have written a module in Python and want it to run continuously once started and need to stop it when I need to update other modules. I will likely be using monit to restart it, if module has crashed or is otherwise not running. I was going through different techniques like [Daemon](https://pypi.python.org/pypi/pyth...
From your mention of Upstart I will assume that this question is for a service being run on an Ubuntu server. On an Ubuntu server an upstart job is really the simplest and most convenient option for creating an always on service that starts up at the right time and can be stopped or reloaded with familiar commands. T...
You could check out [supervisor](http://supervisord.org/). What it is capable of is starting a process at system startup, and then keeping it alive until shutdown. The simplest configuration file would be: ``` [program:my_script] command = /home/foo/bar/venv/bin/python /home/foo/bar/scripts/my_script.py environment =...
Daemon vs Upstart for python script
[ "", "python", "daemon", "upstart", "monit", "python-daemon", "" ]
Here is problem in detail: ![Database diagram](https://i.stack.imgur.com/0mStq.png) I want to populate the data from source table t1 into destination table t2,t3 and t4. Now, what i'm doing , first i'm inserting into t2 as : ``` insert into t2(t2.t2Data0, t2.t2Data1) select t1.t2Data0,t1.t2.Data1 from t1 ``` Now, fo...
If I'm understanding your question correctly, after you insert your rows into t2, you want to use it's identity field to help populate t3 and t4? If so, you can just use a `JOIN`: ``` INSERT INTO t3 SELECT t2.id, t1.t3Data0 FROM t1 INNER JOIN t2 ON t1.t2Data0 = t2.tdData0 AND t1.t2Data1 = t2.tdData1 INSERT INT...
I have not tested but I see something like...an after insert trigger on t1 that a) inserts into t2 (insert into t2(t2.t2Data0, t2.t2Data1) select t1.t2Data0,t2.Data1 from t1 join inserted on t1.id=inserted.id) b) selects scope identity (select @T2ID=SCOPE\_IDENTITY() c) inserts into t3 (insert into t3(id, t3data0) s...
Need help in insert statement
[ "", "sql", "sql-server", "t-sql", "" ]
Is there a way for configparser in python to **set** a value without having sections in the config file? If not please tell me of any alternatives. Thank you. **more info:** So basically I have a config file with format: `Name: value` It's a system file that I want to change the value for a given name. I was wonderi...
You could use the `csv` module to do most of work of parsing the file and writing it back out after you made changes -- so it should be relatively easy to use. I got the idea from one of the [answer](https://stackoverflow.com/questions/2885190/using-configparser-to-read-a-file-without-section-name/13019292#13019292)s t...
I know of no way to do that with configparser, which is very section-oriented. An alternative would be to use the [Voidspace](http://www.voidspace.org.uk/) Python module named [ConfigObj](http://www.voidspace.org.uk/python/modules.shtml#configobj) by Michael Foord. In the [**The Advantages of ConfigObj**](http://www.v...
Configparser set with no section
[ "", "python", "python-2.7", "configparser", "" ]
`SELECT test_column FROM test_table ORDER BY test_column` gives me this: ``` 1 12 123 2 3 ``` Why not: ``` 1 2 3 12 123 ``` How can I sort strings like numbers?
Try ``` SELECT test_column FROM test_table ORDER BY cast(test_column as int) ``` But you should look into changing the column types to the correct ones.
This worked for me: ``` ORDER BY cast(test_column as SIGNED) ``` here, `cast` function convert value from string to integer(SIGNED) then it applied ORDER BY. <https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html>
This SQL 'ORDER BY' is not working properly
[ "", "sql", "" ]
I'm looking for an elegant way to extract some values from a Python dict into local values. Something equivalent to this, but cleaner for a longer list of values, and for longer key/variable names: ``` d = { 'foo': 1, 'bar': 2, 'extra': 3 } foo, bar = d['foo'], d['bar'] ``` I was originally hoping for something like...
You can do something like ``` foo, bar = map(d.get, ('foo', 'bar')) ``` or ``` foo, bar = itemgetter('foo', 'bar')(d) ``` This may save some typing, but essentially is the same as what you are doing (which is a good thing).
Somewhat horrible, but: ``` globals().update((k, v) for k, v in d.iteritems() if k in ['foo', 'bar']) ``` Note, that while this is possible - it's something you don't really want to be doing as you'll be polluting a namespace that should just be left inside the `dict` itself...
Elegant way to unpack limited dict values into local variables in Python
[ "", "python", "" ]
I have a bit of a problem with an advanced query that I am struggling to get my head around. Essentally there are votes in a votes table that correspond to a given soundtrack. My query needs to get a rank for a soundtrack based on the votes that it has been awarded. My approach below works just fine when there are vo...
THAT ONE IS GOOD: ``` SELECT soundtrack.*, (SELECT WrappedQuery.rank FROM (SELECT @rownum := @rownum + 1 AS rank, prequery.soundtrack_id FROM (SELECT @rownum := 0) sqlvars, ( SELECT COALESCE(COUNT(vote.soundtrack_id),0) AS no_rows, s...
I've had some luck ranking in my own work using the row\_number function. But otherwise, the coalesce function might help you out. ``` SELECT soundtrack.*, rankquery.rank FROM ( SELECT row_number() over(partition by prequery.soundtrack_id order by prequery.num_votes) as rank, prequery.soundtrack_id FRO...
COUNT() with nulls, inside subquery
[ "", "mysql", "sql", "t-sql", "" ]
I don't get the concept of loops yet. I got the following code: ``` x=0 while x < n: x = x+1 print x ``` which prints 1,2,3,4,5. That's fine, but how do I access the computation, that was done in the loop? e.g., how do I return the product of the loop( 5\*4\*3\*2\*1)? Thanks. Edit: **That was my final code...
You want to introduce one more variable (`total`) which contains accumulated value of a bunch of actions: ``` total = 1 x = 1 while x <= 5: total *= x x += 1 print x, total print 'total:', total ``` Actually, more pythonic way: ``` total = 1 n = 5 for x in xrange(1, n + 1): total *= x print total ``` N...
By storing that product and returning *that* result: ``` def calculate_product(n): product = 1 for x in range(n): product *= x + 1 return product ``` Now we have a function that produces your calculation, and it returns the result: ``` print calculate_product(5) ```
How do I return the product of a while loop
[ "", "python", "python-2.7", "while-loop", "" ]
I am trying to write an SQL query that returns all student email addresses for clients who have had a new invoice since April 1 and have not yet scheduled a delivery for this fall. This is returning an empty set even though I know there are entries that meet these conditions. I've tried a few different things with no l...
You have to relate your `not exists` subquery to the outer query. For example: ``` select clients.studentemail from clients c join invoices i on c.clientid = i.clientid where invoices.dateposted > "2013-04-01" and not exists ( select * from appointments a ...
I'm not sure what resultset you are trying to return. But including the clients table in the subquery doesn't look right. What we usually want is a correlated subquery. For example: ``` SELECT c.studentEmail FROM `clients` c JOIN `invoices` i ON i.clientId = c.clientId WHERE i.datePosted > '2013-04-01' ...
SQL using NOT EXISTS
[ "", "sql", "not-exists", "" ]
How would I count the number of occurrences of some value in a multidimensional array made with nested lists? as in, when looking for 'foobar' in the following list: ``` list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']] ``` it should return `2`. (yes I am aware that I could write a loo...
``` >>> list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']] >>> sum(x.count('foobar') for x in list) 2 ```
First [join the lists together using `itertools`](https://stackoverflow.com/questions/716477/join-list-of-lists-in-python), then just count each occurrence using the [`Collections` module](http://docs.python.org/3/library/collections.html#collections.Counter): ``` import itertools from collections import Counter some...
python .count for multidimensional arrays (list of lists)
[ "", "python", "" ]
I'm new at using sqlalchemy. How do I get rid of a circular dependency error for the tables shown below. Basically my goal is to create A question table with a one to one relationship "best answer" to answer and a one to many relationship "possible\_answers" as well. ``` class Answer(Base): __tablename__ = 'answer...
Apparently SQLAlchemy does not play well with circular dependencies. You might consider using an association table instead to represent the best answer... ``` from sqlalchemy import Column, Integer, String, ForeignKey, create_engine from sqlalchemy import Table from sqlalchemy.ext.declarative import declarative_base f...
Mark's solution works, but I wanted to find a way to do it without creating an additional table. After extensive searching, I finally found this example in the docs: <http://docs.sqlalchemy.org/en/latest/orm/relationship_persistence.html> (the 2nd example) The approach is to use `primaryjoin` [1] on both relationship...
How do I get rid of a circular dependency error while creating a database in sqlalchemy?
[ "", "python", "sqlalchemy", "" ]
One of my model's field looks like this: ``` total_amount = models.DecimalField(max_digits=20,decimal_places=4,default=Decimal('0.0000')) ``` but when I run this command `python manage.py syncdb`, it shows this error: ``` NameError: name 'Decimal' is not defined ``` I have imported `from django.db import models`, d...
You need to import Decimal. ``` from decimal import Decimal ```
``` total_amount = models.DecimalField(max_digits=20, decimal_places=4, default=0.0) ```
django - How to set default value for DecimalField in django 1.3?
[ "", "python", "django", "django-models", "" ]
I have tried with below query, ``` SELECT registration_line1 FROM table WHERE REGEXP_LIKE(column, '[$]+'); ``` here I have used the above query to pull the records which stars with $, but its giving records irrespective of starts position? for example, its giving below result ``` $shankar shank$ ar but i need only $...
Prepend `^` to denote `at the beginning of the input`. `+` is not needed. ``` SELECT registration_line1 FROM table WHERE REGEXP_LIKE(column, '^[$]'); ```
You can use [LIKE](http://psoug.org/definition/LIKE.htm) instead of regex: ``` SELECT registration_line1 FROM table WHERE column LIKE '$%'; ``` `%` means match any character(s).
how to use reg-exp to fetch the string which starts with $ symbol?
[ "", "sql", "regex", "oracle", "" ]
I'm trying to figure out why is one of my query slow and how I can fix it but I'm a bit puzzled on my results. I have an `orders` table with around 80 columns and 775179 rows and I'm doing the following request : `SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL ORDER BY creation_date DESC LIMIT 200` wh...
Indexes do not necessarily improve performance. To better understand what is happening, it would help if you included the `explain` for the different queries. My best guess would be that you have an index in `id_state` or even `id_state, id_mp` that can be used to satisfy the `where` clause. If so, the first query wit...
Same problem happened in my project, I did some test, and found out that LIMIT is slow because of row lookups See: [MySQL ORDER BY / LIMIT performance: late row lookups](https://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/) So, the solution is: (A)when using LIMIT, select not all...
Why is MySQL slow when using LIMIT in my query?
[ "", "mysql", "sql", "performance", "" ]
In Sqllite table, I have a column values in a table like * Mario * Fly machine * Evil Dead * 4 cross Sudoku * 20 cross Sudoku * 15 cross Sudoku * SimCity how do i sort to have text first, and then sorting of text that prefix with numbers. Output required: * Evil Dead * Fly machine * Mario * SimCity * 4 cross Sudoku...
You can try this ``` SELECT * FROM Table1 ORDER BY CAST(column1 AS INTEGER), column1 ``` Output: ``` | column1 | ------------------- | Evil Dead | | Fly machine | | Mario | | SimCity | | 4 cross Sudoku | | 15 cross Sudoku | | 20 cross Sudoku | ``` Here is **[SQLFiddle](http:...
``` SELECT * FROM [table] ORDER BY [column] GLOB '[0-9]*', [column]; ``` will make the job. ``` SELECT * FROM [table] ORDER BY CAST([column] AS INTEGER), [column]; ``` may be faster, but `0` started strings will appear before text. EDIT: Better option: ``` SELECT * FROM [table] ORDER BY TYPEOF([column])='text' D...
How to sort by text first and then text containing numbers
[ "", "android", "sql", "database", "sqlite", "sorting", "" ]
If I run `echo a; echo b` in bash the result will be that both commands are run. However if I use subprocess then the first command is run, printing out the whole of the rest of the line. The code below echos `a; echo b` instead of `a b`, how do I get it to run both commands? ``` import subprocess, shlex def subproces...
You have to use shell=True in subprocess and no shlex.split: ``` import subprocess command = "echo a; echo b" ret = subprocess.run(command, capture_output=True, shell=True) # before Python 3.7: # ret = subprocess.run(command, stdout=subprocess.PIPE, shell=True) print(ret.stdout.decode()) ``` returns: ``` a b ```
I just stumbled on a situation where I needed to run a bunch of lines of bash code (not separated with semicolons) from within python. In this scenario the proposed solutions do not help. One approach would be to save a file and then run it with `Popen`, but it wasn't possible in my situation. What I ended up doing is...
running multiple bash commands with subprocess
[ "", "python", "bash", "subprocess", "" ]
I have the following code: ``` g = lambda a, b, c: sum(a, b, c) print g([4,6,7]) ``` How do I get the lambda function to expand the list into 3 values?
Expand the list t0 3 values can be done by this: ``` g(*[4,6,7]) ``` But the `sum` won't work in your way. Or you can write this way: ``` >>> g = lambda *arg: sum(arg) >>> print g(4, 5, 6) 15 >>> ``` Or just make your lambda accept a list: ``` g = lambda alist: sum(alist) print g([4,6,7]) ```
``` g = lambda L: sum(L) print g([4,6,7]) ``` would work for any arbitrarily sized list. If you want to use `g = lambda a, b, c: someFunc(a, b, c)`, then call `print g(4,6,7)`
Python lambda parameters
[ "", "python", "lambda", "" ]
I would like my python script to use all the free RAM available but no more (for efficiency reasons). I can control this by reading in only a limited amount of data but I need to know how much RAM is free at run-time to get this right. It will be run on a variety of Linux systems. Is it possible to determine the free R...
You could just read out `/proc/meminfo`. Be aware that the "free memory" is usually quite low, as the OS heavily uses free, unused memory for caching. Also, it's best if you don't try to outsmart your OS's memory management. That usually just ends in tears (or slower programs). Better just take the RAM you need. If yo...
On Linux systems I use this from time to time: ``` def memory(): """ Get node total memory and memory usage """ with open('/proc/meminfo', 'r') as mem: ret = {} tmp = 0 for i in mem: sline = i.split() if str(sline[0]) == 'MemTotal:': ret['...
Determine free RAM in Python
[ "", "python", "memory-management", "" ]
I am doing this ``` declare @num float = 7708369000 select @num as [float], convert(varchar, @num) as [varchar] ``` it gives me this ``` float varchar ---------------------- ------------------------------ 7708369000 7.70837e+009 ``` But I want this ``` float var...
convert it to decimal first, ``` CAST(CAST(@num AS DECIMAL(20)) AS VARCHAR(20)) ``` * [SQLFiddle Demo](http://www.sqlfiddle.com/#!3/2f0e3/8)
Try using the Str function rather than using convert ``` DECLARE @num float = 7708369000; SELECT Str(@num); ```
How to convert Float to Varchar in SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I can understand simple recursion, such as: ``` def count(n): if n <= 0: return else: print n count(n-1) count(3) ``` However, when faced with more complicated code, such as, an implementation of Koch snowflake: ``` def koch(order, size): if order == 0: t.forward(size...
I don't think it's especially easy for anyone to visualize the execution path in detail in their head. Drawing a tree, with the nodes representing the individual recursive calls, is a good way to visualize it on paper. If each node is a bubble, you can put information about variable states, etc., in them. In the situat...
Your Koch snowflake example is a good one. What does the snowflake consist of? In the first iteration (`order == 0`), it starts out as a simple line. This is the base case. ``` ________ ``` Now, for the next level of recursion (`order == 1`), that base case is split into four sub-lines that form an inverted `V`. To a...
I don't understand recursion
[ "", "python", "recursion", "" ]
I come from a sql background and I use the following data processing step frequently: 1. Partition the table of data by one or more fields 2. For each partition, add a rownumber to each of its rows that ranks the row by one or more other fields, where the analyst specifies ascending or descending EX: ``` df = pd.Dat...
You can do this by using `groupby` twice along with the `rank` method: ``` In [11]: g = df.groupby('key1') ``` Use the min method argument to give values which share the same data1 the same RN: ``` In [12]: g['data1'].rank(method='min') Out[12]: 0 1 1 2 2 2 3 1 4 4 dtype: float64 In [13]: df['RN'] = ...
you can also use `sort_values()`, `groupby()` and finally `cumcount() + 1`: ``` df['RN'] = df.sort_values(['data1','data2'], ascending=[True,False]) \ .groupby(['key1']) \ .cumcount() + 1 print(df) ``` yields: ``` data1 data2 key1 RN 0 1 1 a 1 1 2 10 a 2 2 ...
SQL-like window functions in PANDAS: Row Numbering in Python Pandas Dataframe
[ "", "python", "pandas", "numpy", "dataframe", "" ]
I'm using SQL Server 2008 R2, I have this simple table ![enter image description here](https://i.stack.imgur.com/8dCSA.png) What I was trying to do is make a selection from this table and get this following result ``` x | 1 | 2 | 3 --+------------+-------------+------------ 1 | first 1 | ...
When you are using the PIVOT function the values inside the IN clause need to match a value that you are selecting. Your current data does not include 1, 2, or 3. You can use `row_number()` to assign a value for each `x`: ``` select x, [1], [2], [3] from ( select x, value, row_number() over(partition by x order ...
Key is to use the Max function for text fields. Query: ``` SELECT X, [51] [1], [52] [2], [53] [3] FROM (select * from test) t PIVOT(max(Value) FOR Y IN ([51], [52], [53]) )as total ``` [Working demo](http://sqlfiddle.com/#!3/59e55/16)
SQL Server 2008 R2 using PIVOT with varchar columns not working
[ "", "sql", "sql-server", "sql-server-2008-r2", "pivot", "" ]
I have function foo() in main.py. In main.py, I import create.py. but there is a function in create.py that needs foo() from main. I can't import main.py into create.py because main.py errors out...I assume this is some kind of race condition. How can I make foo() available in create.py namespace? It seems kind of ine...
The easy answer is move foo() to foo.py and import from there or move it to create.py and import it from there into main.py - if there are things in main.py that it needs the move the too. Your other option is to pass foo from main into create as a function parameter where it is needed.
Just a simple hack, but this would not help in general situation. import create.py in main.py when it is **NOT** called by importing. ``` # in main.py if __name__ == '__main__': from create import * ``` So this will import create when you excute main.py by `python main.py` and that will import create and it will...
Python Import Statement and Recursion- need function available in module namespace
[ "", "python", "import", "module", "namespaces", "" ]
i have following two case-tables. tbl\_emp is master table, say:- ``` ---------------------------------------------------------- tbl_emp ---------------------------------------------------------- emp_id emp_name 1 Peter 2 Matt 3 Jaco...
First point: ``` --wihout wife select tbl_emp.* from tbl_emp left join tbl_family on tbl_emp.emp_id = tbl_family.emp_id and tbl_family.relation = 'WIFE' where tbl_family.emp_id IS NULL; ``` Second point: ``` --having any relation at least twice select tbl_emp.id, tbl_emp.name, tbl_family.relation fr...
Third point: ``` SELECT tbl_emp.* FROM tbl_emp INNER JOIN tbl_family tf1 ON tbl_emp.emp_id = tf1.emp_id AND tf1.relation = 'WIFE' INNER JOIN tbl_family tf2 ON tbl_emp.emp_id = tf2.emp_id AND tf2.relation = 'MOTHER'; ```
Return records from master table having particular records in detail table
[ "", "sql", "oracle", "join", "multi-table", "" ]
I want to write a file containing some arithmetic problems for my little child. I want to have some coloring, so that he can easily make the difference between plus and minus. This worked for me very well. Unfortunately, only in a terminal. ``` import random as rd from termcolor import colored N = 10 MAX = 100 f = op...
You could check out [Pygments](http://pygments.org/docs/quickstart/) with any suitable [lexer](http://pygments.org/docs/lexers/) and a [TerminalFormatter](http://pygments.org/docs/formatters/). E.g. the following code: ``` import sys from pygments import highlight from pygments.formatters.terminal import TerminalForm...
This requires the program that you are using to view the files to support ANSI escape sequences. This is possible, for example, in GNU/Linux with `less -R`.
Python: Write colored text in file
[ "", "python", "" ]
Ok, here's the code where I setup everything: ``` if __name__ == '__main__': app.debug = False applogger = app.logger file_handler = FileHandler("error.log") file_handler.setLevel(logging.DEBUG) applogger.setLevel(logging.DEBUG) applogger.addHandler(file_handler) app.run(host='0.0.0.0')...
Why not do it like this: ``` if __name__ == '__main__': init_db() # or whatever you need to do import logging logging.basicConfig(filename='error.log',level=logging.DEBUG) app.run(host="0.0.0.0") ``` If you now start you application, you'll see that error.log contains: ``` INFO:werkzeug: * Running...
Ok, my failure stemmed from two misconceptions: 1) Flask will apparently ignore all your custom logging unless it is running in production mode 2) debug=False is not enough to let it run in production mode. You have to wrap the app in any sort of WSGI server to do so After i started the app from gevent's WSGI server...
Flask logging - Cannot get it to write to a file
[ "", "python", "python-2.7", "flask", "logging", "python-logging", "" ]
I have a table in database and a column named `timedate` the time is stored like this in this column: `2013-05-25 12:15:25` I need to `SELECT` the row with the time within last 15 minutes only; so in the case above > *SELECT if timedate is after `2013-05-25 12:00:25`* I tried: `TO_DAYS(NOW()) - TO_DAYS('timedate') ...
``` SELECT * FROM `column` WHERE `name` = {$name} AND `family` = {$family} AND (`test1` = {$test1} || `test2` = {$test2} || `test3` = {$test3}) AND `timedate` > NOW() - INTERVAL 15 MINUTE ``` **Important**: Note that I replaced your `'` around timedate with backticks. With `'` MySQL thinks it's a string, not a co...
If type of field `test1`, `test2` and `test3` is number, then your query should be : ``` SELECT * FROM `column` WHERE `name` = '{$name}' AND `family` = '{$family}' AND ( `test1` = {$test1} || `test2` = {$test2} || `test3` = {$test3} ) AND ADDTIME(`timedate`, '00:15:00.000000') > NOW() ``` And if ...
How to limit time when SELECTing (MYSQL)
[ "", "mysql", "sql", "datetime", "" ]
Basic question. If I have a form that asks a user for their name, email, and comments, and I store the entries in the database... What happens if someone types in a SQL query such as: ``` DROP tablename ``` in the comments section. ``` @Name, @Email, @Comments INSERT INTO mytable (Name, Email, Comments) VALUES (@Na...
Yes, you are safe. SQL injection works by changing the *syntax* of an SQL query by interpolating malicious input. But one query parameter always substitutes for *one* scalar value. There's no way any malicious input can change the syntax of the query if you use parameters.
Short answer to your question is – you are safe if you use parameters. (comments below are a bit outside of the scope of your original question but I strongly recommend you take some time to learn more on this topic) However this doesn’t mean you shouldn’t validate user input in any way. Even though you are safe from...
Danger of SQL query being sent as a parameter?
[ "", "sql", "sql-server", "sql-injection", "database-security", "" ]
In Django, how can I return the time **it took to load a page** (not the date) in **every** page of the site, **without** having to **write in every views.py** a code similar to the following one? ``` start = time.time() #model operations loadingpagetime = time.time() - start ``` If using a `TEMPLATE_CONTEXT_PROCESSO...
You can create a custom [middleware](https://docs.djangoproject.com/en/dev/topics/http/middleware/) to log this. Here is how I create a middleware to achieve this purpose base on <http://djangosnippets.org/snippets/358/> (I modified the code a bit). Firstly, assuming your project has a name: `test_project`, create a f...
[Geordi](https://bitbucket.org/brodie/geordi) gives you an awesome breakdown of everything that happens in the request cycle. It's a middleware that generates a full call-tree to show you exactly what's going on and how long is spent in each function. It looks like this: ![enter image description here](https://i.stac...
Django: display time it took to load a page on every page
[ "", "python", "django", "" ]
I have a table with timestamp column (`RowId`) in my SQL Server database. I want to query new rows according to this timestamp. The SQL query is following ``` SELECT * FROM [MyTable] where RowId>=0x0000000000A99B06 ``` `0x0000000000A99B06` is a max timestamp value from the previous query. How can I make such a qu...
You can't do this with Entity Framework because it does not allow the `>=` operator in timestamp comparisons. It only allows `=`. You can do e.g. ``` var b = BitConverter.GetBytes(1000000L); var query = from x in MyTable where x.RowId = b; // not >= ``` But that would not be very useful. So you've got to ...
Actually you can do small hack. It works for me 100% ``` internal static class EntityFrameworkHelper { public static int Compare(this byte[] b1, byte[] b2) { throw new NotImplementedException(); } } ``` And after that you can use it like this: ``` public void SomeMethod() { var messages = Set<Mes...
Select new records by timestamp column with Entity Framework
[ "", ".net", "sql", "sql-server", "entity-framework", "timestamp", "" ]
Code 1 ``` nums = [1, 2, 3] tri = nums nums.append(4) print(tri) //this prints [1, 2, 3, 4] ``` Code 2 ``` num = 9 num2 = num num = 12 print num2 // this prints 9 **BUT I expected 12 like abouve code** ``` My Ques is Why there is a Difference between these two outputs when the the Procedure and Assignme...
In your first example, `nums` and `tri` refer the same object. The `append` method modifies the reference object in place, so both `nums` and `tri` continue to refer to the same (modified) object. In your second example, `num` is set to a completely new object (12); `num2` continues to refer to the object (9) that `nu...
nums is a list, so it is copied by reference and the num is copied by value. you can use `tri = nums[:]` to copy the nums by value
Please Explain the Difference between these two Codes
[ "", "python", "" ]
How do i grab the last payment using SQL example: ``` SELECT DATEOFPAYMENT FROM PAYMENTS WHERE DATEOFPAYMENT = (SELECT MAX(DATEOFPAYMENT) FROM PAYMENTS) ``` but this doesnt work as it complains asking for group by?
I would normally use `TOP` and `ORDER BY`. ``` SELECT TOP 1 DATEOFPAYMENT FROM PAYMENTS ORDER BY DATEOFPAYMENT DESC ``` Or to get the whole record: ``` SELECT TOP 1 * FROM PAYMENTS ORDER BY DATEOFPAYMENT DESC ```
``` SELECT DATEOFPAYMENT FROM PAYMENTS WHERE DATEOFPAYMENT = (SELECT MAX(DATEOFPAYMENT) FROM PAYMENTS GROUP BY DATEOFPAYMENT); ```
selecting the last payment date using SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table of `STUDENTS` which contains student information. Each student might or might not be a `CANDIDATE` in a college voting event, depending on the value of `CANDIDATE BIT`. I'd like to have a table `VOTE` which keeps the votes of students, but I'd like to check if the student which is being inserted as `VOT...
Declare a UNIQUE constraint on the pair of columns "ID" and "CANDIDATE", and reference that pair from the table "VOTES". Use a CHECK constraint in "VOTES" to guarantee that votes are recorded only for a candidate. ``` CREATE TABLE STUDENTS( ID INTEGER PRIMARY KEY, FIRST_NAME VARCHAR2(20) NOT NULL, LAST_NAM...
Right on for seeking a DDL solution for this type of problem. I'd push towards incorporating a Candidate table. My reasoning is this will allow you to declare unique traits such as start and end candidacy times that would enable a student to try to become a candidate the following year or later. Also this gives you a...
Referential integrity checking in table definition
[ "", "sql", "database", "oracle", "ddl", "" ]
I have a `dict` like this: ``` >>> my_dict = {u'2008': 6.57, u'2009': 4.89, u'2011': 7.74, ... u'2010': 7.44, u'2012': 7.44} ``` Output with `has_key`: ``` >>> my_dict.has_key(unicode(2012)) True ``` Output with `hasattr`: ``` >>> hasattr(my_dict, unicode(2012)) False ``` I couldn't understand why this...
`dict` instances are objects too. But their keys are just not exposed as as attributes. Exposing the keys as attributes (too or instead of item access) would lead to namespace pollution; you'd never be able to use a `has_key` key, for example. `has_key` is *already* an attribute on dictionaries: ``` >>> hasattr({}, '...
`has_key` checks for the existence of a key in the dictionary. (One your code defines while creating a dictionary) [`hasattr`](http://docs.python.org/2/library/functions.html#hasattr) checks if the object has an attribute. Dictionaries are objects, and they have certain attributes. `hasattr` checks for those. ``` >>>...
Is Python dict an Object?
[ "", "python", "dictionary", "" ]
May be this question is redundant but I am posting it as I could not get an exact solution (Please read Actual Scenario). I have the following script which returns all the tables and corresponding no. of rows. ``` SELECT sysobjects.Name, sysindexes.Rows FROM sysobjects INNER JOIN sysind...
put .dbo between "My\_Database1. and sysobjects.Name" as in ``` My_Database1.dbo.sysobjects ```
you should be ble to query sys tables on different database than the one you are connected (as long as they are on the same instance, of course). Check your sysntax, I believe you are missing the schema name sys so it would be: ``` SELECT * FROM My_Database1.sys.sysobjects ```
Join two result sets on different databases in SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have the following code that works great. It get my IP address out of a file and counts how many times they appear in the logfile. ``` def count_ips(): fp=open('logfile','r') store=[] while 1: line=fp.readline() if not line: break if line[-1:] == '\...
Assuming that `count` is your dict of IP->Count, then: ``` from operator import itemgetter sorted_counts = sorted(count.iteritems(), key=itemgetter(1)) for ip, cnt in sorted_counts: print ip, 'had', cnt, 'results' ```
so assume that you have a dictionary d which contain keys that are IPs and values are the counts. ``` >>> d = {'1.1.1.1':5, '2.2.2.2':4} ``` Here is what I would do in a one liner: ``` >>> sorted((d[ip], ip) for ip in d) [(4, '2.2.2.2'), (5, '1.1.1.1')] ``` You can also use parameter reverse=True to sorted the list...
Sort dictionary based on count
[ "", "python", "list", "sorting", "" ]
I'm creating a report with iReport over an Oracle DB. I have to select some values depending on a condition like this: ``` AND EXISTS (SELECT 1 FROM TABLE_1 WHERE x = y) OR EXISTS (SELECT 1 FROM TABLE_2 WHERE z = y) ``` is it possible to execute the second EXISTS only if the first is false?
Try to use your conditions in brackets: ``` AND ( EXISTS (SELECT 1 FROM TABLE_1 WHERE x = y) OR EXISTS (SELECT 1 FROM TABLE_2 WHERE z = y) ) ```
use CASE ``` where ... AND 1 = case when EXISTS (SELECT 1 FROM TABLE_1 WHERE x = y) then 1 when EXISTS (SELECT 1 FROM TABLE_2 WHERE z = y) then 1 else 0 end ```
Execute only one exists in SQL
[ "", "sql", "oracle", "" ]
I have the following query: ``` select * from cars where make in ('BMW', 'Toyota', 'Nissan') ``` What I want to do is store the where parameters in a SQL variable. Something like: ``` declare @caroptions varchar(max); select @caroptions = select distinct(make) from carsforsale; print @caroptions; select * from c...
You can use a table variable: ``` declare @caroptions table ( car varchar(1000) ) insert into @caroptions values ('BMW') insert into @caroptions values ('Toyota') insert into @caroptions values ('Nissan') select * from cars where make in (select car from @caroptions) ```
I wrote about this [here](http://sqlstudies.com/2013/04/08/how-do-i-use-a-variable-in-an-in-clause/) if you want to see it in detail. In the mean time, you can't do it exactly how you are thinking. Your choices are: Using the LIKE command: ``` DECLARE @CarOptions varchar(100) SET @CarOptions = 'Ford, Nisan, Toyota' ...
SQL Server store multiple values in sql variable
[ "", "sql", "sql-server", "arrays", "variables", "stored-procedures", "" ]
I have a small problem with list. So i have a list called `l`: ``` l = ['Facebook;Google+;MySpace', 'Apple;Android'] ``` And as you can see I have only 2 strings in my list. I want to separate my list `l` by **';'** and put my new 5 strings into a new list called `l1`. How can I do that? And also I have tried to do...
[`strip()`](http://docs.python.org/2/library/string.html#string.strip) is a method for strings, you are calling it on a `list`, hence the error. ``` >>> 'strip' in dir(str) True >>> 'strip' in dir(list) False ``` To do what you want, just do ``` >>> l = ['Facebook;Google+;MySpace', 'Apple;Android'] >>> l1 = [elem.st...
What you want to do is - ``` strtemp = ";".join(l) ``` The first line adds a `;` to the end of `MySpace` so that while splitting, it does not give out `MySpaceApple` This will join l into one string and then you can just- ``` l1 = strtemp.split(";") ``` This works because strtemp is a string which has .split()
Python 2: AttributeError: 'list' object has no attribute 'strip'
[ "", "python", "list", "split", "" ]
When I take the square root of -1 it gives me an error: > invalid value encountered in sqrt How do I fix that? ``` from numpy import sqrt arr = sqrt(-1) print(arr) ```
You need to use the sqrt from the [cmath](https://docs.python.org/2/library/cmath.html) module (part of the standard library) ``` >>> import cmath >>> cmath.sqrt(-1) 1j ```
To avoid the `invalid value` warning/error, the argument to numpy's `sqrt` function must be complex: ``` In [8]: import numpy as np In [9]: np.sqrt(-1+0j) Out[9]: 1j ``` As @AshwiniChaudhary pointed out in a comment, you could also use the `cmath` standard library: ``` In [10]: cmath.sqrt(-1) Out[10]: 1j ```
How can I take the square root of -1 using python?
[ "", "python", "numpy", "" ]
I have the following database structure in MS SQL Server: ID, Col\_A, Col\_B, Col\_C, etc... All the other columns except for ID are of type Boolean. Lets say for example that Col\_A = 1, Col\_B = 0, Col\_C = 1 I am looking for a way to return the names of the columns where the column is 1. In this example the return...
This is pretty straight-forward (SQLFiddle: <http://sqlfiddle.com/#!3/c44bc/1/0>): ``` DECLARE @cmd NVARCHAR(MAX); DECLARE @cmd_partial NVARCHAR(MAX); SET @cmd_partial = ''; SELECT @cmd_partial = @cmd_partial + ' CASE ' + COLUMN_NAME + ' WHEN 1 THEN ''' + COLUMN_NAME + ', '' E...
try this: ``` create table jtr (id varchar(36), col_a tinyint, col_b tinyint, col_c tinyint) insert into jtr values (1, 1, 0, 1), (2, 0, 0, 1), (3, 1, 0 ,0), (4, 0, 1, 0) CREATE TABLE #app (res tinyint) CREATE TABLE #outmess (message varchar(1000)) DECLARE @dynsql varchar(1000) DECLARE @colname sysname DECLARE @mess...
Select column names that match a criteria (MS SQL Server)
[ "", "sql", "sql-server", "" ]
I am trying to figure out times of logins into my systems (basically systems boot). I am making use of `last` Unix command. However, it does not let me pull more than a certain number of entries. I assume that the log file from which it pulls, which is `/var/log/wtmp`, gets overwritten after a certain size. I see tha...
you don't say what type of unix / linux you are running but on my Ubuntu hosts this works good for last boot times ``` for f in /var/log/wtmp*; do last -f $f reboot;done ``` All it does is find all the wtmp files in /var/log and then filter out the reboot user
last searches back through the file /var/log/wtmp. So regarding 2) it can only list those entries contained in wtmp. (use parameter f to specify any other file) E.g. if you rotate that file with a log rotator, it won't see those entries per default. 1) depends ;-) You can only list those logins for which the log (resp...
Finding login times in Linux
[ "", "python", "linux", "unix", "boot", "" ]
I have 2 tables and am trying to do one query to save myself some work. ``` Table 1: id, category id, colour Table 2: category id, category name ``` I want to join them so that I get `id, category id, category name, colour` Then I want to limit it so that no "red" items are selected (`WHERE colour != "red"`) Then I ...
You have to use `GROUP BY` so you will have multiple records returned, ``` SELECT COUNT(*) TotalCount, b.category_id, b.category_name FROM table1 a INNER JOIN table2 b ON a.category_id = b.category_id WHERE a.colour <> 'red' GROUP BY b.category_id, b.category_name ```
``` SELECT COUNT(*), table1.category_id, table2.category_name FROM table1 INNER JOIN table2 ON table1.category_id=table2.category_id WHERE table1.colour <> 'red' GROUP BY table1.category_id, table2.category_name ```
SQL Query with Join, Count and Where
[ "", "sql", "join", "count", "where-clause", "" ]
I have four arrays, say, A, B, C and D, of the same size NumElements, and I want to remove all the 0s in them. If A has a zero, B, C and D have one too, in the same position. So I was thinking to loop over the elements of A: ``` for n in range(NumElements): if A[n]==0: A.pop(n) B.pop(n) C.pop(...
If they all have zeros in the same place, then loop over the index *in reverse* and remove that index from each list: ``` for i in reversed(range(NumElements)): if not A[i]: del A[i], B[i], C[i], D[i] ``` By looping over the list in reverse, you keep the indices stable (only elements *past* the current in...
``` a,b,c,d = [filter(lambda i: i != 0, l) for l in [a,b,c,d]] ``` Filter each list removing elements that are not 0. Edit, Just to explain whats happening Filter takes an expression and "filters" the list, by applying the function to everything in the list, everything that does not return True. Lambda is a short ...
Remove all occurences of a given value in multiple arrays at once
[ "", "python", "arrays", "" ]