Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
A user gave me a table that looks like the following. ``` Name HH08 HH09 HH10 HH11 HH12 HH13 Bob 2 3 4 2 7 1 Steve 2 9 3 2 2 5 Mike 2 2 2 2 3 2 Pat 1 0 2 0 0 0 ``` I need some sql that will...
Try: ``` select case to_char(sysdate,'hh24') when '08' then hh08 when '09' then hh09 when '10' then hh10 when '11' then hh11 when '12' then hh12 when '13' then hh13 end OutputValue from TableName WHERE Name = 'Steve' ```
``` with t as ( select 'Bob' name, 2 hh08, 3 hh09, 4 hh10, 2 hh11, 7 hh12, 1 hh13 from dual union all select 'Steve', 2, 9, 3, 2, 2, 5 from dual union all select 'Mike', 2, 2, 2, 2, 3, 2 from dual union all select 'Pat', 1, 0, 2, 0, ...
Oracle SQL dynamically select column name
[ "", "sql", "oracle", "select", "" ]
I am trying to write a txt file but I am getting a `TypeError`. How do I go about this? Here is my code below: ``` yesterdays_added = f1_set - f2_set yesterdays_removed = f2_set -f1_set with open('me{}{}{}.txt'.format(dt.year, '%02d' % dt.month, '%02d' % dt.day), 'w') as out: for line in todays: if line in...
You need to concatenate those together. ``` out.write("Added "+line.strip()) # Or out.write("Added {}".format(line.strip())) ``` For example, ``` >>> "Added "+"abc\n".strip() 'Added abc' ``` From [The Python Docs](http://docs.python.org/2/tutorial/inputoutput.html) > f.write(string) writes the contents of string t...
As the error message suggests, `write` takes only one argument. If you want to write two things, make two calls to `write`, or concatenate them with `+`.
How to Print this statment in to a txt file
[ "", "python", "file-io", "" ]
I have a table with records from many dates. I would like to perform a query that only returns records that fall on the last day of the date's month. Something like: ``` SELECT * FROM mytable WHERE DATEPART(d, mytable.rdate) = DATEPART(d,DATEADD(m,1,DATEADD(d, -1, mytable.rdate))) ``` Except this doesn't work as the ...
Use the [DateSerial Function](http://office.microsoft.com/en-us/access-help/dateserial-function-HA001228813.aspx) to compute the last day of the month for a given date. Passing zero as the third argument, *day*, actually returns the last date of the *previous* month. ``` rdate = #2013-7-24# ? DateSerial(Year(rdate), ...
Try This. ``` SELECT * FROM mytable WHERE DATEPART(d, mytable.rdate) = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, GETDATE()) + 1, 0)) ```
SQL Query for retreiving records that fall on the last day of the month
[ "", "sql", "date", "ms-access", "dateadd", "datepart", "" ]
I'm aware that there are 1001 ways of solving this solution, I'm asking the community to get an understanding of what the most Pythonic approach seems to be. Lets say I have a list of dictionaries taking the format: ``` colours = [{"color": "green", "owner": "Mark"}, {"color": "blue", "owner": "Luke"}, ...
Not the best, but nice and readable: ``` def get_with_default(colour, L, default=''): temp = None for d in L: if d['color'] == colour: return d elif d['color'] == default: temp = d return temp ``` When testing: ``` >>> get_with_default('blue', colours, 'green') {'c...
[`next()`](http://docs.python.org/2/library/functions.html#next) is the most pythonic function to achieve just that: ``` def get_with_default(colour, colours, default): search = (d for d in colours if d['color'] in (colour, default)) match_or_default = next(search) if match_or_default['color'] != default o...
Filter a list of dictionaries to always return a single dictionary, given a default key value to lookup
[ "", "python", "list", "dictionary", "" ]
This is one of those things where I'm sure I'm missing something simple, but... In the sample program below, I'm trying to use Python's RE library to parse the string "line" to get the floating-point number just before the percent sign, i.e. "90.31". But the code always prints "no match". I've tried a couple other reg...
`match` only matches from the *beginning* of the string. Your code works fine if you do `pct_re.search(line)` instead.
You should use `re.findall` instead: ``` >>> line = ' 0 repaired, 90.31% done' >>> >>> pattern = re.compile("\d+[.]\d+(?=%)") >>> re.findall(pattern, line) ['90.31'] ``` `re.match` will match at the start of the string. So you would need to build the regex for complete string.
Python regular expression not matching
[ "", "python", "regex", "" ]
I'm pretty new to Django and keep getting this error and can't for the life of me, figure out the solution. I think I've included all the relevant possible code sections and any help would really be appreciated! The error occurs when I'm trying to print out all the students in a schoolclass. I think the error is caused...
This part of the traceback: ``` File "C:\Python27\lib\site-packages\django\template\loaders\filesystem.py" in load_template_source 38. return (fp.read().decode(settings.FILE_CHARSET), filepath) ``` indicates that the error occurred while loading the template from the disk, not while rendering th...
I think you have a problem with template file encoding. Try to open it without any data (empty student\_list, some dummy schoolclass). If it will be still throwing an error, the problem is a template file itself so you just need to save it with you editor forcing utf-8. Otherwise, if it will work fine with an empty co...
Django UnicodeDecodeError
[ "", "python", "django", "" ]
I have a long string which contains various combinations of \n, \r, \t and spaces in-between words and other characters. * I'd like to reduce all multiple spaces to a single space. * I want to reduce all \n, \r, \t combos to a single new-line character. * I want to reduce all \n, \r, \t and space combinations to a sin...
Use a combination `str.splitlines()` and splitting on all whitespace with `str.split()`: ``` '\n'.join([' '.join(line.split()) for line in ex_str.splitlines() if line.strip()]) ``` This treats each line separately, removes empty lines, and then collapses all whitespace *per line* into single spaces. Provided the inp...
Use simple regexps: ``` import re new_str = re.sub(r'[^\S\n]+', ' ', re.sub(r'\s*[\n\t\r]\s*', '\n', ex_str)) ```
Removing odd \n, \t, \r and space combinations from a given string in Python
[ "", "python", "string", "python-2.7", "replace", "split", "" ]
Im stuck on a SQL query. Im using SQL Server. Given a table that contains Jobs with a start and end date. These jobs can span days or months. I need to get the total combined number of days worked each month for all jobs that intersected those months. Jobs ``` ----------------------------------- JobId | Start | End...
You can use recursive CTE to extract all days from start to end for each JobID and then just group by month (and year I guess). ``` ;WITH CTE_TotalDays AS ( SELECT [Start] AS DT, JobID FROM dbo.Jobs UNION ALL SELECT DATEADD(DD,1,c.DT), c.JobID FROM CTE_TotalDays c WHERE c.DT < (SELECT [End] FROM Jobs...
You can do it using following approach: ``` /* Your table with periods */ declare @table table(JobId int, Start date, [End] date, DayRate money) INSERT INTO @table (JobId , Start, [End], DayRate) VALUES (1, '20130101','20130202', 2500), (2,'20130105','20130205', 2000), (3,'20130303','20130402' , 3000 ) /* create tab...
SQL query to calculate days worked per Month
[ "", "sql", "sql-server", "t-sql", "" ]
I'm trying to write a comprehension that will compose two dictionaries in the following way: ``` d1 = {1:'a',2:'b',3:'c'} d2 = {'a':'A','b':'B','c':'C'} result = {1:'A',2:'B',3:'C'} ``` That is, the resulting dictionary is formed from the keys of the first one and the values of the second one for each pair where the ...
One way to do it is: ``` result = {k: d2.get(v) for k, v in d1.items()} ``` What behavior did you want for keys that have a value that is not in d2?
Just loop through the items of `d1` and then for each element you want to put in the result don’t use the value from `d1` but instead look up the new value within `d2` using `d1`’s value as the key: ``` >>> d1 = {1: 'a', 2: 'b', 3: 'c'} >>> d2 = {'a': 'A', 'b': 'B', 'c': 'C'} >>> d = {k: d2[v] for (k, v) in d1.items()...
Python: comprehension to compose two dictionaries
[ "", "python", "" ]
Let's say I read from a file, called 'info.dat', containing this: ``` [{'name': 'Bob', 'occupation': 'architect', 'car': 'volvo'}, {'name': 'Steve', 'occupation': 'builder', 'car': 'Ford'}] ``` How could I read this and turn it into a list of dictionaries? If I do this: ``` with open('info.dat') as f: data = f.r...
Using `ast.literal_eval` which can read simple Python literals such as dicts/tuples/lists - while not as "powerful" as `eval` it is safer due to its more restrictive nature. ``` from ast import literal_eval with open('yourfile') as fin: your_list = literal_eval(fin.read()) ```
Use [`ast.literal_eval`](http://docs.python.org/3.4/library/ast.html#ast.literal_eval): ``` import ast with open('info.dat') as f: data = ast.literal_eval(f.read()) ``` As said in the docs, this is much more safer than the docs as it "safely evaluate[s] an expression node or a string containing a Python expressio...
Reading a list from a file, and converting it into a list of Python dictionaries
[ "", "python", "file-io", "dictionary", "" ]
I am creating an EU quiz. I have gotten up to: ``` import random as r import timeit as tr import time as t print "How many questions would you like?" q = int(raw_input()) count = 0 while q > count: aus_country = r.randrange(1,29) from random import choice if aus_country == 28: country = ...
Use a dictionary to store Country->Capital, and look it up using that: ``` capital = { 'UK': 'London', 'Austria': 'Vienna' } if ans == capital[country]: # it's correct ``` --- I would also re-work it to be based on something to pick a random number of countries (without duplicates) and use that as the m...
store country name and capital as a dictionary of key:value pair and see if the answer value matches the key pair - the answer is correct if not answer is wrong
How can I create an EU quiz without 28 "if" statements
[ "", "python", "python-2.7", "" ]
Let's consider the following script: ``` def a(): def b(): smth = 3 print smth ``` **Is there any way to make the object smth defined not in the global scope, but in the scope of the a() function although we create it inside the b() function ?** Something like: ``` def a(): def b(): smth = 3 ...
As Josh said: Deplace the functions inside the class and store smth\_2 as self.smth\_2
You could just use a return statement e.g. ``` def a(): def b(): smth = 3 return smth smth = b() print smth ```
Python, making a variable defined in a "slightly more global" scope
[ "", "python", "function", "python-2.7", "global", "" ]
I'm working on some computer vision algorithm and I'd like to show how a numpy array changes in each step. What works now is that if I have a simple `imshow( array )` at the end of my code, the window displays and shows the final image. However what I'd like to do is to update and display the imshow window as the ima...
You don't need to call `imshow` all the time. It is much faster to use the object's `set_data` method: ``` myobj = imshow(first_image) for pixel in pixels: addpixel(pixel) myobj.set_data(segmentedimg) draw() ``` The `draw()` should make sure that the backend updates the image. **UPDATE:** your question w...
I struggled to make it work because many post talk about this problem, but no one seems to care about providing a working example. In this case however, the reasons were different : * I couldn't use Tiago's or Bily's answers because they are not in the same paradigm as the question. In the question, the refresh is ...
How to update matplotlib's imshow() window interactively?
[ "", "python", "numpy", "matplotlib", "spyder", "" ]
I have a select statement that gets 4 column values in a row for one iteration from a query that has lot of joins. One of the column value has to be given to another select statement as input to check a where condition. This select statement returns three rows for a input from each iteration of the first select stateme...
You can do something like this ``` WITH first AS ( SELECT val1, val2, val3, val4 FROM Table1 WHERE 1 = 1 ), second AS ( SELECT val1, MIN(CASE WHEN rnum = 1 THEN val5 END) val51, MIN(CASE WHEN rnum = 1 THEN val6 END) val61, MIN(CASE WHEN rnum = 2 THEN val5 END) val52, MIN...
Example for SQLServer2005+ First part of the script combines result of the query into a single variable. Thus we have a names of columns in a PIVOT statement. ``` DECLARE @cols varchar(100), @dml nvarchar(max) SET @cols = N'' SELECT @cols += ',[val5' + CAST(ROW_NUMBER() OVER(ORDER BY 1/0) AS va...
Two SELECT statements in one stored procedure, one supplying input for another and the other returning more than one row
[ "", "sql", "sql-server", "t-sql", "" ]
Why MySQL query always returns all column data from the table?: ``` SELECT column FROM table WHERE column = "+" ``` The column type is VARCHAR.
Ok, after clarifying your query, it's a little clearer what has happened. In MySQL, `+` is a numeric operator only, not a concatenation operator. Non-numeric strings will always cast to zero, so if you attempt to "add" together two empty strings (pairs of single quotes), you are effectively selecting `0 + 0`. ``` MySQ...
Because you compare with `0` (an integer), the column value is converted to integer before the comparison. All those values will therefor be `0`, unless they contain a string that can be typecasted to a different integer value (like `'1'`). To solve it, try: ``` WHERE column = '0' ```
Query always return all the data
[ "", "mysql", "sql", "" ]
I just learn python today, and so am thinking about writing a code about recursion, naively. So how can we achieve the following in python? ``` class mine: def inclass(self): self = mine(); def recur(num): print(num, end="") if num > 1: print(" * ",end="") return...
Each method of a class has to have `self` as a first parameter, i.e. do this: ``` def recur(self, num): ``` and it should work now. Basically what happens behind the scene is when you do ``` instance.method(arg1, arg2, arg3, ...) ``` Python does ``` Class.method(instance, arg1, arg2, arg3, ....) ```
This is a code example that actually works ``` class Card(): def __init__(self,cardsPlayedList,cardPosition): self.cardsPlayedList = cardsPlayedList self.cardPosition = cardPosition # self.cardPosition def getNewCard(self,cardPosition): cardNum = 0 cardInList = False ...
Python Recursion within Class
[ "", "python", "" ]
I have a dataframe like this: ``` A B C 0 1 0.749065 This 1 2 0.301084 is 2 3 0.463468 a 3 4 0.643961 random 4 1 0.866521 string 5 2 0.120737 ! ``` Calling ``` In [10]: print df.groupby("A")["B"].sum() ``` will return ``` A 1 1.615586 2 0.421821 3 0.46346...
``` In [4]: df = read_csv(StringIO(data),sep='\s+') In [5]: df Out[5]: A B C 0 1 0.749065 This 1 2 0.301084 is 2 3 0.463468 a 3 4 0.643961 random 4 1 0.866521 string 5 2 0.120737 ! In [6]: df.dtypes Out[6]: A int64 B float64 C object dtype: object ``` ...
You can use the `apply` method to apply an arbitrary function to the grouped data. So if you want a set, apply `set`. If you want a list, apply `list`. ``` >>> d A B 0 1 This 1 2 is 2 3 a 3 4 random 4 1 string 5 2 ! >>> d.groupby('A')['B'].apply(list) A 1 [This, string] 2 ...
Pandas groupby: How to get a union of strings
[ "", "python", "pandas", "" ]
Can anyone tell me how i can SELECT DISTINCT from my database without it being case-sensitive? My query is ``` SELECT DISTINCT email FROM `jm_order` ``` The results brings out all the emails in the table but repeats the ones with different cases. This is expected because the values are different case wise. e.g ``` ...
Try to use `upper` function ``` SELECT DISTINCT UPPER(email) FROM `jm_order` ``` you can also use `lower` instead ``` SELECT DISTINCT LOWER(email) FROM `jm_order` ``` [**More information**](http://www.sqlinfo.net/mysql/mysql_function_upper_lower.php).
If you want to preserve the case of the email (so it actually matches one of the rows), you can do: ``` select email from jm_order group by lower(email); ```
MySQL case-insensitive DISTINCT
[ "", "mysql", "sql", "database", "distinct", "case-insensitive", "" ]
I am currently facing the problem of visualizing three dimensional data. Concretely, I have two parameters that are varying and the third dimension is the resulting output which in this case is a value between zero and one (percentage). I have several distinct datasets that I want to illustrate. It is working well wit...
There are a few options to present 2 datasets together: **Options 1** - draw a heatmap of the difference of 2 datasets (or ratio, whatever is more appropriate in your case) ``` pcolor(D2-D1) ``` and then present several of these comparison figures. **Option 2** - present 1 dataset as pcolor, and another as countour...
Although it 's an old question, i recently did something related: plotting two heatmaps in the same figure. I did that by converting the squares into scatterplots where i converted the squares to two triangles. I made the two triangles by using custom markers: ``` import matplotlib import matplotlib.pyplot as plt ...
Combine multiple heatmaps
[ "", "python", "matplotlib", "heatmap", "matplotlib-3d", "" ]
I have a XML file and I have a XML schema. I want to validate the file against that schema and check if it adheres to that. I am using python but am open to any language for that matter if there is no such useful library in python. What would be my best options here? I would worry about the how fast I can get this up ...
Definitely [`lxml`](http://lxml.de/). Define an [`XMLParser`](http://lxml.de/api/index.html) with a predefined schema, load the the file `fromstring()` and catch any XML Schema errors: ``` from lxml import etree def validate(xmlparser, xmlfilename): try: with open(xmlfilename, 'r') as f: etre...
The python snippet is good, but an alternative is to use xmllint: ``` xmllint -schema sample.xsd --noout sample.xml ```
XML (.xsd) feed validation against a schema
[ "", "python", "xml", "python-2.7", "xsd", "xml-validation", "" ]
I have two SQL tables, Projects and Milestones: Projects PK -> ProID Milestones combined PK -> ProID and MstNo For some reason I cannot use ProID as a foreign key to link those two tables together (FOREIGN KEY constraint). However, I need to write a query which would show me details of all of the Projects table reco...
Try this one - ``` SELECT P.* , cnt = ISNULL(M.cnt, 0) FROM dbo.Projects P LEFT JOIN ( SELECT ProID, cnt = COUNT(1) FROM dbo.Milestones GROUP BY ProID ) M ON M.ProID = P.ProID ```
Yes, you can. `inner join` match data from one table with another on declared condition. `select * from Projects inner join Milestones on Projects.ProId = Milestones.ProID`. This query will read all data from `Projects` table and match to it data from `Milestones`. In the result you will have the entities that have ...
SQL query count elements in other table
[ "", "sql", "sql-server", "relational-database", "" ]
Trying to find whether id2 is used in table X. Easiest way to use 'count': `SELECT COUNT(*) FROM X WHERE id1 = :1 AND id2 = :2 ;` If **X is a large table containing over 90,00,000 data**, above query has severe performance impact. Is there any alternative with better performance? > Note: both column have indexing in...
If you use: ``` SELECT COUNT(*) FROM X WHERE id1 = :1 AND id2 = :2 AND ROWNUM = 1; ``` Then you will get a 0 if no rows are not found, and a 1 if a single row is found. The query will stop executing when it finds the first row, and you will not have to deal with NO\_DATA\_FOUND exceptions if no row ...
You need only one row exists with this condition so try: ``` select 1 from dual where EXISTS(SELECT id1 FROM X WHERE id1 = :1 AND id2 = :2) ```
Oracle checking for existence of rows in a large table
[ "", "sql", "oracle", "count", "indexing", "query-performance", "" ]
I'm using different Django framework version(1.3, 1.4, 1.5) for different projects. On my laptop, I have to reinstall Django with pip, every time I want to switch to another project. Is there an easier(less stupid! :D) way, that i can automatically switch to the version I need? Something like NVM for node?
In my opinion the easiest way is to use a `requirements.txt` file for `virtualenv`. With a `requirements.txt` file you can specify the version and every other person that uses your project can just use `pip install -r requirements.txt`. This is the way how almost all big projects do it (the "pythonic" way). Here you ...
The standard method is to use [virtualenv](http://www.virtualenv.org/en/latest/). With this you can make standalone python interpreters running there own set of libraries (django versions) and/or python versions. Switching between them is as easy as typing `virtualenv my_env_with_django_1.4`.
Switch Django's version
[ "", "python", "django", "virtualenv", "" ]
How to create trigger to insert a value in a column same as value of another column of same table of a newly inserted row in the table. Suppose I have table like below ``` ColumnA | ColumnB ``` I want columnB value to be inserted into ColumnA as soon as row gets inserted into table or columnB value gets updated . Bu...
Try this trigger (it will copy the values from ColumnB to ColumnA when are inserted values into ColumnB or when are updated the values from ColumbB): ``` CREATE TRIGGER trgIU_triggertestTable_UpdateColumnAWhenColumnB ON dbo.triggertestTable AFTER INSERT,UPDATE AS BEGIN -- SET NOCOUNT ON added to prevent ex...
`inserted` is a pseudo-table and may contain *multiple* rows. You should write something set-based. Something like: ``` update triggertestTable set columnA=COALESCE(columnA,columnB) where id in (select id from inserted) ``` (If `triggertestTable` has a primary key column called `id`) The above sets `columnA` to...
Create trigger to insert a column value into other column of same table SQL Server 2005
[ "", "sql", "sql-server", "sql-server-2005", "triggers", "" ]
I'm weighing the potential performance impact of using one of three different methods of returning a single, scalar value from a stored procedure to my C# routine. Can anyone tell me which of these is "faster" and, most importantly, why? Method 1: ``` CREATE PROCEDURE GetClientId @DealerCode varchar(10) AS BEGIN...
Returning a scalar value is more efficient than a result set, the reason is result set carries lot more helper methods along with it, which makes it heavy thus increasing latency in transmission of the object from sql to C# code/routine. In your method 3: You have used a variable to return the value this is more bette...
In terms of performance penalty, method 3 (RETURN) is penalty-free. The reason being that SQL Server will *always* return an integer result code from a Stored Procedure. If you do not explicitly specify one, then it it will implicitly return 0 (SUCCESS).
SQL Server Performance ResultSet vs Output Parameter vs Return Value
[ "", "sql", "performance", "return", "output", "resultset", "" ]
Users can sign up for a premium listing for a specified number of days, e.g. 30 days. ``` tblPremiumListings user_id days created_date --------------------------------- 1 30 2013-05-21 2 60 2013-06-21 3 120 2012-06-21 ``` How would I select records where th...
``` SELECT * FROM tblPremiumListings WHERE created_date + INTERVAL `days` DAY >= CURDATE() ```
It's easiest to read with INTERVAL ``` select * from tblPremiumListings where created_date + interval days day >= now(); ``` But I would also change the table to instead of `created_date` and `days` instead store `end_date`. That way the query is ``` select * from tblPremiumListings where end_date >= now(); `...
MySql - get days remaining
[ "", "mysql", "sql", "" ]
I have a table where I have multiple integer columns: year, month and day. Unfortunately, while the three should have been grouped into one DATE column from the beginning, I am now stuck and now need to view it as such. Is there a function that can do something along the lines of: ``` SELECT makedate(year, month, day)...
You can ``` SELECT format('%s-%s-%s', "year", "month", "day")::date FROM ... ``` or use date maths: ``` SELECT DATE '0001-01-01' + ("year"-1) * INTERVAL '1' YEAR + ("month"-1) * INTERVAL '1' MONTH + ("day"-1) * INTERVAL '1' DAY FROM ... ``` Frankly, it's surprising that PostgreSQL doesn't offer a date-c...
# PostgreSQL 9.4+ In [PostgreSQL 9.4](https://www.postgresql.org/docs/9.4/static/functions-datetime.html), a function was added to do just this * [`make_date(year int, month int, day int)`](https://www.postgresql.org/docs/9.4/static/functions-datetime.html)
PostgreSQL: SELECT integers as DATE or TIMESTAMP
[ "", "sql", "postgresql", "date", "" ]
I'm trying to parse a sentence (or line of text) where you have a sentence and optionally followed some key/val pairs on the same line. Not only are the key/value pairs optional, they are dynamic. I'm looking for a result to be something like: Input: ``` "There was a cow at home. home=mary cowname=betsy date=10-jan-2...
I'd use `re.sub`: ``` import re s = "There was a cow at home. home=mary cowname=betsy date=10-jan-2013" d = {} def add(m): d[m.group(1)] = m.group(2) s = re.sub(r'(\w+)=(\S+)', add, s) d['theSentence'] = s.strip() print d ``` Here's more compact version if you prefer: ``` d = {} d['theSentence'] = re.sub(r'...
The first step is to do ``` inputStr = "There was a cow at home. home=mary cowname=betsy date=10-jan-2013" theSentence, others = str.split('.') ``` You're going to then want to break up "others". Play around with split() (the argument you pass in tells Python what to split the string on), and see what you can do. :)
Python tokenize sentence with optional key/val pairs
[ "", "python", "regex", "tokenize", "text-parsing", "" ]
Suppose my update query looks like the following: ``` UPDATE a SET a.colSomething= 1 FROM tableA a WITH (NOLOCK) INNER JOIN tableB b WITH (NOLOCK) ON a.colA= b.colB INNER JOIN tableC c WITH (NOLOCK) ON c.colC= a.colA ``` Let's say the above joins to tableB and tableC takes several minutes to co...
**Blocking vs. dead locking** I think you may be confusing locking and blocking with DEADLOCKS. On any update query SQL server will lock the involved data. While this lock is active, other processes will be blocked ( delayed ) from editing the data. If the original update takes a long time ( from a users perspective'...
I would put indexes on your foreign keys, it can speed up update and delete operations as well as relieve your deadlock situation.
sql server- When does table get locked when updating with join
[ "", "sql", "sql-server", "" ]
I am looking for an sql script which can select all fields in a database which are of a particualr datatype. I have looked all over stack overflow and various pages i have found in google but yet no avail! Maybe I am looking in the wrong places. Any ideas?
This will give you list of all the fields to of perticular data type in a data base with table name may be you can work around this. SELECT \* FROM .INFORMATION\_SCHEMA.COLUMNS where DATA\_TYPE='' Regards Ashutosh Arya
Try this ``` USE DatabaseName; SELECT TABLE_CATALOG ,TABLE_SCHEMA ,TABLE_NAME ,COLUMN_NAME ,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE DATA_TYPE LIKE 'varchar' --Or other Data Type ```
Select all fields within database of certain datatype
[ "", "sql", "" ]
I have got a table that got a column with duplicate values. I would like to update one of a 2 duplicate values so for example `row1 = tom` and `row2 = tom`.. I want to add a 1 or an a to one of them and that will be for many other duplicates in the same column. Basically just add one number or letter to every 1 of the ...
Try This with `CTE` and `PARTITION BY` ``` ;WITH cte AS ( SELECT ROW_NUMBER() OVER(PARTITION BY Column1 ORDER BY Column1 ) AS rno, Column1 FROM Clients ) UPDATE cte SET Column1 =Column1 +' 1 ' WHERE rno=2 ```
I think this simple update is what you're looking for; ``` UPDATE Table1 SET Column1=Column1+CAST(id AS VARCHAR) WHERE id NOT IN ( SELECT MIN(id) FROM Table1 GROUP BY Column1 ); ``` Input: ``` (1,'A'), (2,'B'), (3,'A'), (4,'C'), (5,'C'), (6,'A'); ``` Output: ``` (1,'A'), (2,'B'), (3,'A3'), (4,'C'), (5,'C5')...
Update one of 2 duplicates in an sql server database table
[ "", "sql", "sql-server", "" ]
I have data in below mentioned format, when I am trying to insert into table I am getting errors ``` ORA-01858: a non-numeric character was found where a numeric was expected ``` How can I successfully insert record into table? ``` create table mytab (dt timestamp(0)); Insert into mytab (dt) Values (TO_TIMES...
You need to specify zero fractional seconds. Here's your error: ``` SQL> create table mytab (dt timestamp(0)); Table created. SQL> Insert into mytab (dt) Values (TO_TIMESTAMP('16/JUL/13 2:53:08. PM','DD/MON/YY fmHH12fm:MI:SS.FF AM')); 2 3 4 (TO_TIMESTAMP('16/JUL/13 2:53:08. PM','DD/MON/YY fmHH12f...
You need the second fraction: ``` Insert into mytab(dt) Values (TO_TIMESTAMP('16/JUL/13 2:53:08.00 PM','DD/MON/YY fmHH12fm:MI:SS.FF AM')); ```
ORA-01858: Error when trying to insert into timestamp(0) column
[ "", "sql", "oracle", "oracle10g", "" ]
I am working with tkinter in python2.7. All I want to do is draw a canvas in one class, then class another class which will move a square around the canvas. But for some reason I get ``` Exception in Tkinter callback Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/li...
You're passing in an Animation instance to after, which then tries to call it. I suspect you meant to create an instance and then pass in its animate method, right? EDIT: So to elaborate a bit now that I'm back on the Internet; the problem is with this line: ``` self.root.after(0, animation.Animation(self.root, self....
You give an `Animation` instance as callback to `self.root.after()`. Callback objects are *called* after the given time. *Calling* them means that their `__call__()` method gets called. Your `Animation` class does not have such a method. I propose to add one which then does whatever you want it to do. For instance: ``...
Python, instance has no __call__ method
[ "", "python", "tkinter", "attributeerror", "" ]
I am trying to submit a form in AJAX in JSON format. But whenever the form is submitted I get redirect to the form action page. **HTML** ``` <form id="acc" action="#" method="post" autocomplete="off">{% csrf_token %} <p>Username: {{accform.username}}</p> <p>Password: {{accform.password}} </p>...
If using [this](https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js) Jquery cookies library, which is the one I was using and @Archer suggested me as well then you do need to get the cookies as `$.cookie("cookie_name")` If you do it like that whole function is working and I get no errors when postin...
First, I think adding this line will prevent form from submitting while the function is computing: ``` $("#acc").submit(function(e){ e.preventDefault(); // LINE ADDED /* treatment here */ return false; }); ``` Furthermore, just to avoid mixing the CSRF token with your data, you can call the following func...
Submit form in JSON with AJAX
[ "", "jquery", "python", "django", "json", "forms", "" ]
What does the "s" do at the end of line 8 of this query: <http://www.sqlfiddle.com/#!3/f8816/20/0> I can't find it anywhere and the statement won't work without it. Thanks!
The `s` is a table alias. It gives a name to a table or subquery used in the `from` clause. SQL Server requires that all subqueries use aliases. Not all databases do. I strongly encourage you to use them. They often make queries much more readable.
The `s` is an alias for the result set which allows it to be referenced within the query. > The readability of a `SELECT` statement can be improved by giving a table an alias, also known as a correlation name or range variable. A table alias can be assigned either with or without the `AS` keyword: > > ``` > table_name...
SQL Server 2008 - DECLARE function
[ "", "sql", "sql-server-2008", "" ]
If you run `os.stat(path)` on a file and then take its `st_mode` parameter, how do you get from there to a string like this: `rw-r--r--` as known from the Unix world?
Since Python 3.3 you could use [`stat.filemode`](http://docs.python.org/3/library/stat.html#stat.filemode): ``` In [7]: import os, stat In [8]: print(stat.filemode(os.stat('/home/soon/foo').st_mode)) -rw-r--r-- In [9]: ls -l ~/foo -rw-r--r-- 1 soon users 0 Jul 23 18:15 /home/soon/foo ```
Something like this: ``` import stat, os def permissions_to_unix_name(st): is_dir = 'd' if stat.S_ISDIR(st.st_mode) else '-' dic = {'7':'rwx', '6' :'rw-', '5' : 'r-x', '4':'r--', '0': '---'} perm = str(oct(st.st_mode)[-3:]) return is_dir + ''.join(dic.get(x,x) for x in perm) ... >>> permissions_to_un...
How to convert a stat output to a unix permissions string
[ "", "python", "" ]
Both methods return a list of the returned items of the query, did I miss something here, or they have identical usages indeed? Any differences performance-wise?
If you are using the default cursor, a `MySQLdb.cursors.Cursor`, *the entire result set will be stored on the client side* (i.e. in a Python list) by the time the `cursor.execute()` is completed. Therefore, even if you use ``` for row in cursor: ``` you will not be getting any reduction in memory footprint. The enti...
`cursor.fetchall()` and `list(cursor)` are essentially the same. The different option is to not retrieve a list, and instead just loop over the bare cursor object: ``` for result in cursor: ``` This can be more efficient if the result set is large, as it doesn't have to fetch the entire result set and keep it all in ...
cursor.fetchall() vs list(cursor) in Python
[ "", "python", "mysql-python", "database-cursor", "" ]
I want to enumerate all possible products of some integer factors, only up to some maximum value: * `P((2, 3, 11), 10)` would return `(2, 3, 4, 6, 8, 9)`. * `P((5, 7, 13), 30)` would return `(5, 7, 13, 25)`. This seems like a tree traversal where the branches stop growing once reaching the maximum, but I don't know w...
I like this method, which involves multiplying 1 by all the elements in the input list, then multiplying all the results by the elements in the input list, etc. until the limit is reached. ``` def signature_seq(signature, limit): products = set((1,)) for factor in signature: new_products = set() for prod i...
Here's a solution using a generator (and [`itertools.count`](http://docs.python.org/2/library/itertools.html#itertools.count)): ``` from itertools import count def products(numbers, limit): numbers = set(numbers) # needs a set to pop from, not a tuple while numbers: n = numbers.pop() for r in...
Enumeration of all factor products less than a maximum
[ "", "python", "algorithm", "permutation", "primes", "factors", "" ]
``` vec = [[1,2,3], [4,5,6], [7,8,9]] print [num for elem in vec for num in elem] <----- this >>> [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` This is tricking me out. I understand elem is the lists inside of the list from `for elem in vic` I don't quite understand the usage of `num` and `for num in elem` in the beginnin...
Lets break it down. A simple list-comprehension: ``` [x for x in collection] ``` This is easy to understand if we break it into parts: `[A for B in C]` * `A` is the item that will be in the resulting list * `B` is each item in the collection `C` * `C` is the collection itself. In this way, one could write: ``` [x...
From the [list comprehension documentation](http://docs.python.org/2/reference/expressions.html#list-displays): > When a list comprehension is supplied, it consists of a single expression followed by at least one `for` clause and zero or more `for` or `if` clauses. In this case, the elements of the new list are those ...
python list comprehension double for
[ "", "python", "list-comprehension", "" ]
I am attempting to do Project Euler problem #2. Which is: > Each new term in the Fibonacci sequence is generated by adding the previous two > terms. By starting with 1 and 2, the first 10 terms will be: > > 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... > > By considering the terms in the Fibonacci sequence whose values do no...
You have a bug. You're generating the first 4,000,000 Fibonacci numbers, but the problem statement only asks for those Fibonacci numbers whose *values* are not more than 4,000,000. Since the Fibonacci numbers grow exponentially (Fn ~ 1.618n), you're generating some numbers with a very large number of digits (log10 Fn ...
You just need to add logic to stop when the next fibonacci number exceeds 4000000. Also, I spy a potential problem with this line: ``` def start(): fib = fib_generator() even_sum = even_sum(fib) #<--- right here print even_sum ``` It isn't good to have a variable name the same as the function name.
Solving Project Euler #2 in Python
[ "", "python", "" ]
I have a Table(Send) with columns(Id, UserId,SendDate) and another table(Receive) with columns(Id,SendId,UserName). I want show all records in SendTable with all RecieveUserName. for example. ``` (Send) 1 1 2013 2 2 2013 (Recieve) 1 1 Jack 2 1 Ema 3 2 Alex 4 2 Sara Result 1 1 2013 Ja...
It doesn't seem to me that you need to use Distinct in this Linq query. Assuming you have the relationships between tables set up on your linq datacontext, you can do something like this: ``` var result = from s in context.Send select new { id = s.Id, userId = s.UserId, ...
`Distinct` is also available in `LINQ`. For example ``` public class Product { public string Name { get; set; } public int Code { get; set; } } Product[] products = { new Product { Name = "apple", Code = 9 }, new Product { Name = "orange", Code = 4 }, new Product { Nam...
What is the equivalent DISTINCT(sql server) in the Linq
[ "", "sql", "linq", "" ]
I need to join 2 tables ``` tableA ---------- colA colB A 1 B 2 C 3 D 4 tableB ---------- colC ColD ColE... A A X A B X A C X B A Y B B Y B C Y ``` Previously I would have joined the table as such: ``` SELECT * FROM tableA a JOIN tableB b ON b.ColC = ...
You can use `GROUP BY` in subquery or `ROW_NUMBER()` (You haven't specified RDBMS, but guessing SQL Server based on TOP 1) *`Group By` version:* ``` ;WITH CTE_Group AS ( SELECT colC, MIN(ColE) ColE FROM TableB GROUP BY colC ) SELECT a.ColA, a.ColB, b.ColE FROM TableA a LEFT JOIN CTE_Group b on a.ColA = b.ColC; `...
SQL doesn't do "doesn't matter"1. Assuming you're using a database system that supports the windowing functions, then this should work: ``` SELECT * FROM tableA a JOIN (select *,ROW_NUMBER() OVER (PARTITION BY ColC ORDER BY ColD) as rn from tableB) b ON b.ColC = a.ColC and b.rn = 1 ``` In this instance, I've...
SQL JOIN limit to top 1 when have multiple column join
[ "", "sql", "" ]
I want to read two lines from a file, skip the next two lines and read the next two lines and so on ``` line 1 (read) line 2 (read) line 3 (skip) line 4 (skip) line 5 (read) line 6 (read) ... <eof> ``` Any ideas how to do this? Thanks! My solution: ``` j = 2 for i, line in enumerate(f.readl...
You can advance the iteration of the file with [the `itertools` `consume()` recipe](http://docs.python.org/3/library/itertools.html#itertools-recipes) - as it is fast (it uses `itertools` functions to ensure the iteration happens in low-level code, making the process of consuming the values very fast, and avoids using ...
Group them into pairs, and then skip every other pair, eg: ``` from itertools import izip_longest, islice with open('somefile') as fin: paired = izip_longest(*[iter(fin)] * 2, fillvalue='') every_other = islice(paired, None, None, 2) for lines in every_other: line1, line2 = lines print lin...
Read from file: read two lines, skip two lines
[ "", "python", "" ]
I have a .txt file with the following lines: ``` pablo 9.50 sergio 2 Rose 10 oto 11.4 maria 7.9 ``` and I have the following program: ``` scores = {} read = open("C:/Users/renato/Desktop/HTML Files/myfile.txt") for cont in read: (name,score)=cont.split() scores[score] = name read.close() print("The top...
Are you looking for them to be ordered on the basis of their float value? Then, you're forgetting a call to `float()`. Without it, the following is the result : ``` >>> scores {'11.4': 'oto', '10': 'Rose', '9.50': 'pablo', '2': 'sergio', '7.9': 'maria'} >>> sorted(scores.keys(), reverse = True) ['9.50', '7.9', '2', '1...
you must not add scores as `dict key` the problem is : ``` >>> x={'9':'suhail','9':'ta'} >>> x {'9': 'ta'} ``` the key overwrites the old so the best way is use name as `dict key` ``` import operator scores = {} read = open("C:/Users/renato/Desktop/HTML Files/myfile.txt") for cont in read: (name,score)=cont.s...
Sorted() function Python
[ "", "python", "" ]
I'm cleaning up some code, and have run into a handful of situations where there are repetitive cleanup actions in a try/except : ``` try: ... except KeyError , e : cleanup_a() cleanup_b() cleanup_c() handle_keyerror() except ValuesError , e : cleanup_a() cleanup_b() cleanup_c() han...
You can differenciate the Error by catching all of them in the same except, and testing the type like this: ``` try: ... except (KeyError, ValuesError) as e : cleanup_a() cleanup_b() cleanup_c() if type(e) is KeyError: handle_keyerror() else: handle_valueerror() ```
If the cleanup can always run, you can use the `finally` clause, which runs whether an exception is thrown or not: ``` try: do_something() except: handle_exception() finally: do_cleanup() ``` If the cleanup should *only* be run in the event of an exception, something like this might work: ``` should_cleanup = ...
cleaner way to handle python exceptions?
[ "", "python", "exception", "" ]
How do I use string formatting to call information from a dictionary? Here's what I attempted so far (probably quite bad...) ``` value = raw_input("Indicate a number: ") print number_stats["chm%"] % (value,) ``` The dictionary number\_stats holds information about values "chm1", "chm2", etc. I get a key error, whic...
``` print number_stats["chm%s" % (value)] ``` should work. But you should do this instead: ``` print number_stats.get("chm%s" % (value), "some_default_value") ``` To avoid crashing if the user enters an invalid key. See [this](http://docs.python.org/2/library/stdtypes.html#dict.get) for more info on the `get` metho...
When you do `number_stats["chm%"] % (value,)`, you are doing `number_stats["chm%"]` first and then applying `% (value,)` to the result. What you want is to apply the `%` directly to the string: ``` number_stats["chm%s" % (value,)] ``` Note that you need `%s`; `%` by itself is not a valid string substitution. However...
Using String Formatting to pull data from a dictionary
[ "", "python", "dictionary", "string-formatting", "" ]
I have 64-bit Python (2.7.5) installed at `C:\Python27` and 32-bit Python at `C:\Python27_32`. I would like to use virtualenv to set up a 32-bit virtual environment that I can switch into when I need to use 32-bit Python. Once that environment is set up, I plan to edit the `bin\activate` file to change all the necessa...
For your virtual env to run after you have changed your paths you will need to install virtualenv into the 32 bit python - there is nothing stopping you having a copy of virtualenv in each python. Assuming you have python 2.7.c 64-bit as your default python and you have also installed python 2.7.x 32-bit *you would ne...
If you installed the 32Bit version first, and install the 64Bit version second (And you added python to path), Then you can use the updated python launcher (`py`) to create the 64Bit version of your virtualenv `py -m venv my-env-name`
How can I use virtualenv to use 32-bit and 64-bit Python in Windows?
[ "", "python", "virtualenv", "" ]
I am using mysql-connector with python and have a query like this: ``` SELECT avg(downloadtime) FROM tb_npp where date(date) between %s and %s and host like %s",(s_date,e_date,"%" + dc + "%") ``` NOw, if my variable 'dc' is a list like this: ``` dc = ['sjc','iad','las'] ``` Then I have a mysql query like below: `...
I'm not familiar with mysql-connector, but its behavior appears to be [similar to MySQLdb](https://stackoverflow.com/q/4574609/190597) in this regard. If that's true, you need to use a bit of string formatting: ``` sql = """SELECT avg(downloadtime) FROM tb_npp where date(date) = %s and substring(host,6,3) in...
As an alternative to @unutbu's answer which is specific to using mysql-connector: ``` cursor.execute( "SELECT thing " " FROM table " " WHERE some_col > %(example_param)s " " AND id IN ({li})".format(li=", ".join(list_of_values)), params={ "example_param": 33 }) ``` If you try...
mysql-connector python 'IN' operator stored as list
[ "", "python", "mysql", "mysql-connector", "" ]
I am trying to combine two tables that have no dates in common only a caseid. Here is my SQL code. I am also trying to combine the EcoDate and ProductionMonth columns as they both contain date information. ``` SELECT cmp.ProductionMonth, cmp.ProductionAmount, rce.EcoDate, rcl.CaseCaseId, cmp.CaseCaseId AS CaseId...
I think what you're trying to do is something like this: ``` select * from ( select rc1.CaseId, rce.EcoDat as Date, rce.GrossOil, 0 as ProductionAmount from phdrpt.reportcaselist_465 as rcl inner join phdrpt.rptcaseeco_465 as rce on rcl.ReportRunCaseId = rce.ReportRunCaseId union rc1.CaseId, cmp.ProductionMon...
Try this: ``` select CaseCaseId AS CaseCaseId, EcoDate AS Date, GrossOil AS GrossOil, NULL AS ProductionAmount FROM table1 union all select CaseId AS CaseCaseId, ProductionMonth AS Date, NULL AS GrossOil, ProductionAmount AS ProductionAmount FROM table2 ``` [Union operation](http://msdn.microsoft.com/en-us/library/ms...
Combining 2 tables with no dates in common
[ "", "sql", "sql-server-2008", "" ]
i have exception when i execute query that i think is well created, the error is : Msg 102, Niveau 15, État 1, Ligne 6 Syntaxe incorrecte vers ')'. here the request : ``` SELECT DISTINCT designation FROM (select top 100 percent designation , code_piececomptable from cpt_lignepiececomptable WHERE code_piececom...
You need to give it an alias: ``` SELECT DISTINCT designation FROM (select top 100 percent designation , code_piececomptable from cpt_lignepiececomptable WHERE code_piececomptable IN (SELECT code_piececomptable FROM cpt_piececomptable WHERE terminer is null or terminer <>1) ORDER BY code_piececom...
select top 100 percent designation from cpt\_lignepiececomptable WHERE code\_piececomptable IN (SELECT code\_piececomptable FROM cpt\_piececomptable WHERE terminer is null or terminer <>1) ORDER BY code\_piececomptable I think Order by gives error in Subqueries. Try using this Regards Ashutosh Arya
Order Sql Request with top Percent
[ "", "sql", "t-sql", "sql-server-2008-r2", "" ]
For example: ``` >>> s = 'string' >>> hasattr(s, 'join') True >>> 'join' in dir(s) True ``` [Python documentation](http://docs.python.org/3/library/functions.html#hasattr) says that `hasattr` is implemented calling `getattr` and seeing whether it raises an exception or not. However, that leads to a great overhead, si...
It is not quite the same thing. `dir()` is a diagnostic tool that *omits* attributes that `getattr()` and `hasattr()` would find. From the [`dir()` documentation](http://docs.python.org/3/library/functions.html#dir): > The default `dir()` mechanism behaves differently with different types of objects, as it attempts t...
the hasattr is more than 100 times faster :) ``` In [137]: s ='string' In [138]: %timeit hasattr(s, 'join') 10000000 loops, best of 3: 157 ns per loop In [139]: %timeit 'join' in dir(s) 100000 loops, best of 3: 19.3 us per loop ```
What's the difference between hasattr() and 'attribute' in dir()?
[ "", "python", "" ]
I'm using Oracle Database 11g. I have a query that selects, among other things, an ID and a date from a table. Basically, what I want to do is keep the rows that have the same ID together, and then sort those "groups" of rows by the most recent date in the "group". So if my original result was this: ``` ID Date 3 ...
One way to get this is by using analytic functions; I don't have an example of that handy. This is another way to get the specified result, without using an analytic function (this is ordering first by the most\_recent\_date for each ID, then by ID, then by Date): ``` SELECT t.ID , t.Date FROM mytable t JOIN...
You can use the `MAX ... KEEP` function with your aggregate to create your sort key: ``` with sample_data as (select 3 id, to_date('11/26/11','MM/DD/RR') date_col from dual union all select 1, to_date('1/5/12','MM/DD/RR') date_col from dual union all select 2, to_date('6/3/13','MM/DD/RR') date_col from ...
"Group" some rows together before sorting (Oracle)
[ "", "sql", "oracle", "plsql", "oracle11g", "" ]
[Disclaimer: there may be more pythonic ways of doing what I want to do, but I want to know how python's scoping works here] I'm trying to find a way to make a decorator that does something like injecting a name into the scope of another function (such that the name does not leak outside the decorator's scope). For ex...
You can't. Scoped names (closures) are determined at compile time, you cannot add more at runtime. The best you can hope to achieve is to add *global* names, using the function's *own* global namespace: ``` def decorator_factory(value): def msg_decorator(f): def inner_dec(*args, **kwargs): g =...
Here's a way of injecting *multiple* variables into a function's scope in a manner somewhat similar to what @Martijn Pieters does in [his answer](https://stackoverflow.com/a/17862336/355230). I'm posting it primarily because it's a more general solution and would *not* need to be applied multiple times to do it — as wo...
How to inject variable into scope with a decorator?
[ "", "python", "scope", "closures", "decorator", "python-decorators", "" ]
[How to check a string for specific characters?](https://stackoverflow.com/questions/5188792/how-to-check-a-string-for-specific-characters) I find the link is very useful. But what's wrong with my codes? ``` string = "A17_B_C_S.txt" if ("M.txt" and "17") in string: print True else: print False ``` and the an...
This is because your `and` evaluates to `17` which is in `stringList`. The `and` evaluates to 17 because of short circuiting. ``` >>> "M.txt" and "17" '17' ``` Python evaluates non empty strings to the value `True`. Hence, `M.txt` evaluates to `True`, thus the value of the expression depends on the second value which...
``` stringList = "A17_B_C_S.txt" if "M.txt" in stringList and "17" in stringList: print True else: print False >>> True ``` `('M.txt' and '17')` returns `'17'`. So you are just testing `'17' in stringList`. ``` >>> ('M.txt' and '17') '17' >>> ```
What's wrong with the IF some words IN a string
[ "", "python", "" ]
I am trying to assign ID numbers to records that are being inserted into an SQL Server 2005 database table. Since these records can be deleted, I would like these records to be assigned the first available ID in the table. For example, if I have the table below, I would like the next record to be entered at ID 4 as it ...
First build a table of all N IDs. ``` declare @allPossibleIds table (id integer) declare @currentId integer select @currentId = 1 while @currentId < 1000000 begin insert into @allPossibleIds select @currentId select @currentId = @currentId+1 end ``` Then, left join that table to your real table. You can...
Don't go for identity, Let me give you an easy option while i work on a proper one. Store int from 1-999999 in a table say Insert\_sequence. try to write an Sp for insertion, You can easly identify the min value that is present in your Insert\_sequence and not in your main table, store this value in a variable and...
Get all missing values between two limits in SQL table column
[ "", "sql", "identity", "" ]
Basically, I want to iterate through a file and put the contents of each line into a deeply nested dict, the structure of which is defined by the amount of whitespace at the start of each line. Essentially the aim is to take something like this: ``` a b c d e ``` And turn it into something li...
Here is a recursive solution. First, transform the input in the following way. Input: ``` person: address: street1: 123 Bar St street2: city: Madison state: WI zip: 55555 web: email: boo@baz.com ``` First-step output: ``` [{'name':'person','value':'','level':...
Here is an object oriented approach based on a composite structure of nested `Node` objects. Input: ``` indented_text = \ """ apple colours red yellow green type granny smith price 0.10 """ ``` a Node class ``` class Node: def __init__(self, indented_line): ...
Creating a tree/deeply nested dict from an indented text file in python
[ "", "python", "parsing", "data-structures", "dictionary", "nested", "" ]
I have the following table in sql server 2008 ,with hospital id's and their departments: ``` HID DEPT 5 neuro 2 derma 3 cardio 2 ent 1 neuro 5 optha 3 ent 3 optha 4 derma 1 optha 5 derma ``` Need to get the list of id's and department names that it doesn't have, using sql. eg: ``` HID DEPT...
Try this: ``` ;WITH CTE AS ( SELECT * FROM ( SELECT DISTINCT HID FROM YourTable) A CROSS JOIN (SELECT DISTINCT DEPT FROM YourTable) B ) SELECT * FROM CTE A WHERE NOT EXISTS(SELECT 1 FROM YourTable WHERE HID = A.HID AND DEPT = A.DEPT) ``` [**Here is**](http://s...
To make the list of options more complete, here's also an EXCEPT solution: ``` SELECT h.HID, d.DEPT FROM (SELECT HID FROM atable) h CROSS JOIN (SELECT DEPT FROM atable) d EXCEPT SELECT HID, DEPT FROM atable; ``` Depending on how many times values are repeated in either of the columns, you could also try cross ...
get list of unavailable values from table using sql
[ "", "sql", "sql-server-2008", "" ]
I am somewhat new to Python, having made several scripts, but not too many serious programs. I am trying to understand where to put the functions/scripts (as well as any modules I create in the future) I have written so that they can be accessed by other programs. I've found two different Python help pages on the topic...
You seem to have opened interactive mode of python. I am not 100% sure, but I would actually bet my finger that `cwd` on Windows and \*NIXes is by default set to the directory the interpreter was invoked from. So the question is how did you open your python shell ? Probably from `C:\Program Files\Python33` or used som...
You doing nothing wrong. Current working directory `C:/Program Files/Python33` and your set `PYTHONPATH=D:/Google Drive/Python` are two different things. With your current configuration you can easyly put modules (`*.py` files) and packages (folders with `__init__.py` files) inside `D:/Google Drive/Python` and then im...
File Management in Python
[ "", "python", "windows", "file-management", "" ]
I have a numpy array of 2D vectors, which I am trying to normalize as below. The array can have vectors with magnitude zero. ``` x = np.array([[0.0, 0.0], [1.0, 0.0]]) norms = np.array([np.linalg.norm(a) for a in x]) >>> x/norms array([[ nan, 0.], [ inf, 0.]]) >>> nonzero = norms > 0.0 >>> nonzero array([...
If you can do the normalization in place, you can use your boolean indexing array like this: ``` nonzero = norms > 0 x[nonzero] /= norms[nonzero] ```
Here's one possible way of doing this ``` norms = np.sqrt((x**2).sum(axis=1,keepdims=True)) x[:] = np.where(norms!=0,x/norms,0.) ``` This uses np.where to do the substitution you need. Note: in this case x is modified in place.
Dealing with zeros in numpy array normalization
[ "", "python", "numpy", "" ]
Say I have a list `l = ['h','e','l','l','o']` I want to be able to take the last two items and use them, but I don't know how long the list is(It's user input). So can't do `l[3:]` because what if the list is seven(or any number) items long instead of five? How can I count from the back of the list?
``` print l[-2:] ``` Negative numbers count from the end. ``` >>> l = ['h','e','l','l','o'] >>> print l[-2:] ['l', 'o'] >>> print l[-5:] ['h', 'e', 'l', 'l', 'o'] >>> print l[-6:] ['h', 'e', 'l', 'l', 'o'] >>> ```
There you go , this should give you a good idea ``` l = ['h','e','l','l','o'] print l[2:] #['l', 'l', 'o'] print l[:2] #['h', 'e'] print l[:-2] #['h', 'e', 'l'] print l[-2:] #['l', 'o'] ``` In your case, as someone has already suggested you can use, the bellow to print last two items...
How can I "count from the back" in python lists?
[ "", "python", "string", "list", "python-2.5", "" ]
Is there a way in Python to detect, within a process, where that process is being executed? I have some code that includes the `getpass.getpass()` function, which [is broken in Spyder](https://code.google.com/p/spyderlib/issues/detail?id=693), and it's annoying to go back and forth between the command line and the IDE ...
Here is the solution I ended up using. After reading [Markus's answer](https://stackoverflow.com/a/17729264/2359271), I noticed that Spyder adds half a dozen or so environment variables to `os.environ` with names like `SPYDER_ENCODING`, `SPYDER_SHELL_ID`, etc. Detecting the presence of any of these seems relatively una...
By default, Spyder uses a startup scrip, see Preferences -> Console -> Adanced setting. This option is usually set to the `scientific_startup.py` file that loads pylab et al. The easiest solution is to just add a global variable to the file and then use that in your if statement, e.g. add this line at the end of `scie...
Detect where Python code is running (e.g., in Spyder interpreter vs. IDLE vs. cmd)
[ "", "python", "interpreter", "spyder", "" ]
``` date_base_start = datetime(2013, 07, 17, 20, 0) #July 17,2013 08:00PM date_base_end = datetime(2013, 07, 17, 22, 0) #July 17,2013 10:00PM date_1_start = datetime(2013, 07, 17, 21, 0) #July 17,2013 09:00PM date_1_end = datetime(2013, 07, 17, 21, 30) #July 17,2013 09:30PM date_2_start = datetime(2013, 07, ...
``` delta = min(date_1_end,date_base_end)-max(date_1_start,date_base_start) # # Check if delta is negative, # if delta.seconds < 0: print 0 else: print delta.seconds/60.0 ```
``` def overlap(range1,range2): start_datetime = max(range1[0],range2[0]) end_datetime = min(range1[1],range2[1]) return end_datetime-start_datetime print overlap([date_base_start,date_base_end],[date_3_start, date_3_end]) ```
Python: Get minutes overlap between time range
[ "", "python", "python-datetime", "" ]
I know there are a bunch of other regex questions, but I was hoping someone could point out what is wrong with my regex. I have done some research into it and it looks like it should work. I used [rubular](http://rubular.com/) to test it, yes I know that is regex for ruby, but the same rules I used should apply to pyth...
The error in: ``` c = [re.sub(r'$?_[^A-Z_]+', "", x) for x in a] ``` Is caused by the `?`, it is not preceded by any characters so it doesn't know what to match 0 or 1 times. If you change it to: ``` >>> [re.sub(r'_?[^A-Z_]+$', "", x) for x in a] ['SDFSD_SFSDF', 'SDFSDF_SDFSDF', 'TSFSD_SDF'] ``` It works as you exp...
``` import re a = ["SDFSD_SFSDF234234","SDFSDF_SDFSDF_234324","TSFSD_SDF_213123"] c = [re.match(r'[A-Z_]+[A-Z]', x).group() for x in a] print c ``` Results: ``` ['SDFSD_SFSDF', 'SDFSDF_SDFSDF', 'TSFSD_SDF'] ``` Please note, that "re.sub" which you use in your example is a regex replace command, not a search. Your ...
Python Removing last character _ from string using regex
[ "", "python", "regex", "" ]
I am using `urllib2` in `Python` to scrape a webpage. However, the `read()` method does not return. Here is the code I am using: ``` import urllib2 url = 'http://edmonton.en.craigslist.ca/kid/' headers = {'User-Agent': 'Mozilla/5.0'} request = urllib2.Request(url, headers=headers) f_webpage = urllib2.urlopen(reques...
As requested in comments :) Install `requests` by `$ pip install requests` Use `requests` as the following: ``` >>> import requests >>> url = 'http://edmonton.en.craigslist.ca/kid/' >>> headers = {'User-Agent': 'Mozilla/5.0'} >>> request = requests.get(url, headers=headers) >>> request.ok True >>> request.text # co...
It returns (or more specifically, errors out) fine for me: ``` >>> import urllib2 >>> url = 'http://edmonton.en.craigslist.ca/kid/' >>> headers = {'User-Agent': 'Mozilla/5.0'} >>> request = urllib2.Request(url, headers=headers) >>> f_webpage = urllib2.urlopen(request) >>> html = f_webpage.read() Traceback (most recent...
Python urllib2 - cannot read a page
[ "", "python", "urllib", "" ]
I'm using Fabric to automate, including the task of creating a directory. Here is my fabfile.py: ``` #!/usr/bin/env python from fabric.api import * def init(): try: local('mkdir ./www') except ##what exception?##: #print exception name to put in above ``` Run fab `fabfile.py` and f I already ...
The issue is that fabric uses subprocess for doing these sorts of things. If you look at the source code for `local` you can see it doesn't actually raise an exception. It calls suprocess.Popen and uses `communicate()` to read stdout and stderr. If there is a non-zero return code then it returns a call to either `warn`...
It is nothing to handle with exception, it is from the fabric api try to set the entire script's warn\_only setting to be true with ``` env.warn_only = True ```
Print Python Exception Type (Raised in Fabric)
[ "", "python", "python-2.7", "exception", "" ]
I have a list of lists in the form: ``` list = [[3, 1], [3, 2], [3, 3]] ``` And I want to split it into two lists, one with the x values of each sublist and one with the y values of each sublist. I currently have this: ``` x = y = [] for sublist in list: x.append(sublist[0]) y.append(sublist[1]) ``` But th...
By doing `x = y = []` you are creating `x` and `y` and referencing them to the same list, hence the erroneous output. (The Object IDs are same below) ``` >>> x = y = [] >>> id(x) 43842656 >>> id(y) 43842656 ``` If you fix that, you get the correct result. ``` >>> x = [] >>> y = [] >>> for sublist in lst: x.a...
When you say `x = y = []`, you're causing `x` and `y` to be a reference to the *same* list. So when you edit one, you edit the other. There is a good explanation [here](https://stackoverflow.com/a/17702997/2452770) about how references work. Therefore you can use your code if you say instead ``` x = []; y = [] ``` Y...
How to append an element of a sublist in python
[ "", "python", "list", "" ]
I have a list of dictionaries. Each Dictionary has an integer key and tuple value. I would like to sum all the elements located at a certain position of the tuple. Example: ``` myList = [{1000:("a",10)},{1001:("b",20)},{1003:("c",30)},{1000:("d",40)}] ``` I know i could do something like : ``` sum = 0 for i in myLi...
Use a generator expression, looping over all the dictionaries then their values: ``` sum(v[1] for d in myList for v in d.itervalues()) ``` For Python 3, substitute `d.itervalues()` with `d.values()`. Demo: ``` >>> sum(v[1] for d in myList for v in d.itervalues()) 100 ```
``` import itertools sum((v[1][1] for v in itertools.chain(*[d.items() for d in myList]))) ``` itertools can "chain" together several lists to there are logically one.
Python List of Dictionaries[int : tuple] Sum
[ "", "python", "" ]
Sorry to ask a dumb question, but this one's got me stumped. ``` SELECT 81234 / 160000 * 100 AS Try1, CAST((81234 / 160000 * 100) AS float) AS Try2 ``` The answer is 50.77125 but both values return zero. What's the problem? Thanks,
Try using a decimal point. Something like ``` SELECT 81234 / 160000 * 100 AS Try1, CAST((81234 / 160000 * 100) AS float) AS Try2, 81234. / 160000. * 100. AS Try3 ``` ## [SQL Fiddle DEMO](http://sqlfiddle.com/#!3/d41d8/17633) From [/ (Divide) (Transact-SQL)](http://msdn.micro...
you're implementing a division by int Try this: ``` SELECT cast(81234 as float) / cast(160000 as float) * 100 ``` or ``` SELECT 81234.00 / 160000.00 * 100 ```
math expression returns zero
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a huge file where there lines like this one: "**En g茅n茅ral un tr猫s bon hotel La terrasse du bar pr猫s du lobby**" How to remove these Sinographic characters from the lines of the file so I get a new file where these lines are with Roman alphabet characters only? I was thinking of using regular expressions. Is t...
You can use the [`string`](http://docs.python.org/3/library/string.html) module. ``` >>> string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.digits '0123456789' >>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' >>> ``` And it seems the code you want to replace is Chinese. ...
I find this [regex cheet sheet](http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/) to come in very handy for situations like these. ``` # -*- coding: utf-8 import re import string u = u"En.!?+ 123 g茅n茅ral un tr猫s bon hotel La terrasse du bar pr猫s du lobby" p = re.compile(r"[^\w\s\d{}]".format(re...
Cleaning text files with regex of python
[ "", "python", "regex", "string", "text", "" ]
I have a dictionary with a bunch of integer keys. for keys I don't have, I'd like to be able to retrieve the smallest and largest keys right before and after they key I want to retrieve but that does not exist. The Treemap class in java has two methods doing exactly this: `ceilingkey()` and `floorkey()`. > How can I...
``` def floor_key(d, key): if key in d: return key return max(k for k in d if k < key) def ceil_key(d, key): if key in d: return key return min(k for k in d if k > key) ``` I'm not sure how you want to handle border conditions. Note that this will raise an exception (`ValueError`) if y...
You can use the [bisect](http://docs.python.org/2/library/bisect.html) module here, in case the key the not found then it can find the ceil and floor values in `O(log N)` time.: ``` >>> import bisect >>> from random import randint def get_value(dic, key): if key in dic: return dic[key] else: in...
python: retrieving ceiling key and floor key in a dictionary or a set
[ "", "python", "dictionary", "tree", "" ]
I am using Sikuli the OCR testing library. In my Python script I am looking for one of two possible images to appear. When one of them does appear, if chooses that object. However, I would like for the script to end. It doesn't. I've tried `quit()` and `exit()` but that isn't doing it. It is working fine, beside the s...
You can exit any loop with `break`: ``` while True: if exists ("lose.png"): click ("lose.png") print ("***** YOU LOSE! *****") break if exists ("win.png"): click ("win.png") print ("***** YOU WIN! *****") break ``` If neither of the `if` statements evaluate to ...
You can always do this: ``` status = TRUE while status: if exists ("lose.png"): click ("lose.png") print ("***** YOU LOSE! *****") status = FALSE if exists ("win.png"): click ("win.png") print ("***** YOU WIN! *****") status = FALS...
Stopping a While loop and quitting script in Python
[ "", "python", "while-loop", "sikuli", "" ]
My stored procedure is defined as ``` create procedure p1 ( @id INT, @name varchar(20) OUTPUT, @company varchar(20) OUTPUT ) AS BEGIN select @name = name, @company = company from table1 where id = @id; END GO ``` I call it using ``` DECLARE @name varchar(20), @company varchar(20), @id I...
Brother, I am not sure what you're trying to select but maybe you can try the query below: ``` CREATE PROCEDURE p1 ( @id INT, @name varchar(20) OUTPUT, @company varchar(20) OUTPUT ) AS BEGIN Set @name = 'name' Set @company = 'company' select @name , @company from table1 where id = @id; END GO ```
Follow the instructions in the error message: ``` DECLARE @name varchar(20), @company varchar(20), @id INT; exec dbo.p1 @id=2, @name = @name OUTPUT, @company = @company OUTPUT; select @name AS 'NAME', @company AS 'COMPANY' ``` --- Alternative - don't name parameter 1: ``` DECLARE @name varchar(20), @company varchar...
T-SQL Stored procedure with OUTPUT parameter giving an error
[ "", "sql", "t-sql", "stored-procedures", "" ]
Yesterday I have been implementing a small Python scripts that checks difference between two files (using difflib), printing the result if there is any, exiting with code 0 otherwise. The precise method, `difflib.unified_diff()` is returning a generator on the diffs found. How can I test this generator to see if it ne...
You're already converting your generator to a list, so you don't need to rebuild it. ``` diff = list(difflib.unified_diff(fromlines, tolines, n=0)) if diff: ... sys.stdout.writelines(diff) else: ... ``` You don't even need to convert the generator to a list if you don't want by using a simple flag: ``` d...
You could convert the generator into a list. ``` diff = list(difflib.unified_diff(fromlines, tolines, n=0)) ```
What is Pythonic way to test size of a generator, then display it?
[ "", "python", "python-3.x", "" ]
This is my directory tree ``` Game/ a/ 1.py ... b/ 2.py ``` In 2.py I want import function display from 1.py. First I keep both file in same folder there is no problem.But how to import from other location?
Use [imp](http://docs.python.org/2/library/imp.html). ``` import imp foo = imp.load_source('filename', 'File\Directory\filename.py') ``` This is just like importing normally. You can then use the file. For example, if that file contains `method()`, you can call it with `foo.method()`. You can also try this. ``` imp...
You have two options: Add another folder to `sys.path` and import it by name ``` import sys sys.path.append('../a') import mod1 # you need to add `__init__.py` to `../a` folder # and rename `1.py` to `mod1.py` or anything starts with letter ``` Or create distutils package and than you will be able to make relative ...
how to import module from other directory in python?
[ "", "python", "python-2.7", "python-import", "" ]
I installed [scikit-learn](https://github.com/scikit-learn/scikit-learn) from GitHub a couple of weeks ago: ``` pip install git+git://github.com/scikit-learn/scikit-learn@master ``` I went to GitHub and there have been several changes to the master branch since then. How can I update my local installation of `scikit...
`pip` searches for the library in the Python package index. Your version is newer than the newest one in there, so pip won't update it. You'll have to reinstall from Git: ``` $ pip install git+git://github.com/scikit-learn/scikit-learn@main ```
You need to install the version from github, or locally. The way I usually do is that I git clone the repository locally and I run `python setup.py install` or `python setup.py develop` on it so I'm sure about the version being used. Re-issuing the command you've done the first time with the upgrade flag would do the...
pip: pulling updates from remote git repository
[ "", "python", "git", "github", "pip", "scikit-learn", "" ]
I have declared two variables in RAW sql ``` DECLARE @str nvarchar(max), @str1 nvarchar (max); SET @str = " AND (c.BondSales_Confirmed <> -1)"; SET @str1 = " AND (c.BondSales_IssueType = 'REGULAR')"; ``` My SQL query is: ``` SELECT * From t_BondSales Where (BondSales_cType <> 'Institute') " + str1 + str " ``` ...
Try this one - ``` DECLARE @str NVARCHAR(MAX) , @str1 NVARCHAR (MAX); SELECT @str = ' AND c.BondSales_Confirmed != -1' , @str1 = ' AND c.BondSales_IssueType = ''REGULAR'''; DECLARE @SQL NVARCHAR(MAX) SELECT @SQL = ' SELECT * FROM t_BondSales WHERE BondSales_cType != ''Institute''' +...
very easy!! in mysql use CONCAT() function: ``` SELECT * FROM tbl_person WHERE CONCAT(first_name,' ',last_name) = 'Walter White'; ``` but this does **not** work in mysql: ``` SELECT * FROM tbl_person WHERE first_name+' '+last_name = 'Walter White'; ```
How to Concat String in SQL WHERE clause
[ "", "sql", "sql-server", "where-clause", "string-concatenation", "" ]
I have a python application in which a function runs in a recursive loop and prints updated info to the terminal with each cycle around the loop, all is good until I try to stop this recursion. It does not stop until the terminal window is closed or the application is killed (control-c is pressed) however I am not sat...
You can intercept the `ctrl+c` signal and call your own function at that time rather than exiting. ``` import signal import sys def exit_func(signal, frame): '''Exit function to be called when the user presses ctrl+c. Replace this with whatever you want to do to break out of the loop. ''' print("Exiti...
``` import keyboard import sys from time import sleep def kb(): while True: if keyboard.is_pressed("a"): print("A key was pressed") sys.exit(0) def main(): kb() if __name__ == "__main__": main() ```
Simplest method to call a function from keypress in python(3)
[ "", "python", "python-3.x", "keypress", "" ]
Here is a piece of SQL code that does not work: ``` SELECT bl.regn_id, RTRIM(LTRIM(dv.dv_id)) + '_' + RTRIM(LTRIM(bl.regn_id)) AS bu_regn, (SELECT COUNT (em.em_id) FROM em LEFT OUTER JOIN bl bl_s ON em.bl_id = bl_s.bl_id LEFT OUTER JOIN irs_self_cert_em ON em.em_id = irs_self_cert_em....
You can not use an aliased (calculated) column in a WHERE clause. I would create another subquery to add criteria to that field. ``` SELECT * FROM ( SELECT bl.regn_id, RTRIM(LTRIM(dv.dv_id)) + '_' + RTRIM(LTRIM(bl.regn_id)) AS bu_regn, ( SELECT COUNT(em.em_id) A...
Without having tables structure (ex: to know which id is unique) some data related to them and the way you want the output, it's hard to say and test but I went with something that look like this : ``` SELECT bl.regn_id, RTRIM(LTRIM(dv.dv_id)) + '_' + RTRIM(LTRIM(bl.regn_id)) AS bu_regn, result.certified FROM ...
How do I use a SELECT ... AS in a WHERE clause
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to make a dictionary from a csv file in python, but I have multiple categories. I want the keys to be the ID numbers, and the values to be the name of the items. Here is the text file: ``` "ID#","name","quantity","price" "1","hello kitty","4","9999" "2","rilakkuma","3","999" "3","keroppi","5","1000" "4","k...
You can use a dictionary directly: ``` dictionary = {} file_data.readline() # skip the first line for key in file_data: key = key.replace('"', '').strip() k = key.split(",") dictionary[k[0]] = k[1] ```
Use the [`csv` module](http://docs.python.org/3/library/csv.html) to handle your data; it'll remove the quoting and handle the splitting: ``` results = {} with open('hk.txt', 'r', newline='') as txt: reader = csv.reader(txt) next(reader, None) # skip the header line for row in reader: results[row...
Python - make a dictionary from a csv file with multiple categories
[ "", "python", "csv", "dictionary", "python-3.x", "" ]
I am maintaining logs in a list currently of the last 1000000 entries by just using log.append(line). To make sure it doesn't get too long when the size gets to 2000000 I copy do log = log[1000000:] . However this is rather slow. In C I could use a linked list to just move the pointer to the position of the middle of ...
You can use [`collections.deque`](http://docs.python.org/2/library/collections.html#collections.deque): > Deques support thread-safe, memory efficient appends and pops from > either side of the deque with approximately the same **O(1)** performance > in either direction For python versions before py2.6: When appendi...
You could use a `deque`, from the standard library: <http://docs.python.org/2/library/collections.html#collections.deque> It supports a fixed maximum length, which might do automatically what you are looking for, from the documentation: > If `maxlen` is not specified or is None, deques may grow to an arbitrary > len...
Python fast data structure for truncatable circular buffer
[ "", "python", "performance", "" ]
In C# language we use `continue` statement in a loop to move to next iteration. But in using Cursor in TSQL how can I perform the same. Let say I have, ``` DECLARE db_cursor CURSOR FOR SELECT age, name, color FROM table; DECLARE @myName VARCHAR(256); DECLARE @myAge INT; DECLARE @myFavoriteColor VARCHAR(40); OPEN db_c...
`CONTINUE` does go back to the start of the `WHILE` loop, but it's not exactly like in C#, since the cursor looping idiom in T-SQL is broken into two separate statements, and the `WHILE` is the second of them - the cleanest, requiring the least repetition, may be our old friend [`GOTO`](http://msdn.microsoft.com/en-us/...
you can use CONTINUE in this manner ``` DECLARE db_cursor CURSOR FOR SELECT age, name, color FROM table; DECLARE @myName VARCHAR(256); DECLARE @myAge INT; DECLARE @myFavoriteColor VARCHAR(40); OPEN db_cursor; FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor; WHILE @@FETCH_STATUS = 0 BEGIN -...
Continue from top in SQL SERVER Cursor?
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I'm trying to use the [python-docx module](https://github.com/mikemaccana/python-docx) to replace a word in a file and save the new file with the caveat that the new file must have exactly the same formatting as the old file, but with the word replaced. How am I supposed to do this? The docx module has a savedocx that...
As it seems to be, Docx for Python is not meant to store a full Docx with images, headers, ... , but only contains the inner content of the document. So there's no simple way to do this. Howewer, here is how you could do it: First, have a look at the [docx tag wiki](https://stackoverflow.com/tags/docx/info): It expl...
this worked for me: ``` rep = {'a': 'b'} # lookup dictionary, replace `a` with `b` def docx_replace(old_file,new_file,rep): zin = zipfile.ZipFile (old_file, 'r') zout = zipfile.ZipFile (new_file, 'w') for item in zin.infolist(): buffer = zin.read(item.filename) if (item.filename == 'word/d...
Text-Replace in docx and save the changed file with python-docx
[ "", "python", "ms-word", "docx", "python-docx", "" ]
### The Problem: I have an a input button in a form that when its submitted should redirect two parameters , `search_val` and `i`, to a `more_results()` function, (listed below), but I get a type error when wsgi builds. The error is: `TypeError: more_results() takes exactly 2 arguments (1 given)` html: ``` <form a...
Your route doesn't specify how to fill in more than just the one `past_val` arg. Flask can't magically create a URL that will pass two arguments if you don't give it a two-argument pattern.
It's also possible to create routes that support variable number of arguments, by specifying default values to some of the arguments: ``` @app.route('/foo/<int:a>') @app.route('/foo/<int:a>/<int:b>') @app.route('/foo/<int:a>/<int:b>/<int:c>') def test(a, b=None, c=None): pass ```
Flask url_for() with multiple parameters
[ "", "python", "html", "flask", "" ]
I have a Product Table which has following structure. ``` ProductID ProductName ProductType 1 Irrigation 1 2 Landscape 2 3 Sleeving 3 4 Planting 4 ``` Now i need to returns rows in order of product type 3,2,4,1 For t...
This will satisfy the specification: ``` ORDER BY NULLIF(ProductName,'') IS NULL, FIELD(producttype,3,2,4,1) ``` The first expression will return a 1 if the ProductName is "empty" (NULL or zero length string'), otherwise it will return 0. So, this will sort all the non-empty ProductName first, followed by the empty ...
``` Select * from product order by ISNULL(PRODUCTNAME),FIELD(producttype,3,2,4,1); ``` [fiddle](http://www.sqlfiddle.com/#!2/d3701/1)
MYSQL Order by with case
[ "", "mysql", "sql", "sql-order-by", "" ]
I'm trying to write some code that if a certain occurence happens, a specific number has to change to -that number. I have the following code so far: ``` x=6 for words in foo: if "bar" in words: crazy_function(x) else: pass ``` if the word "bar" is in words, x will need to come out as -6, if it is ...
Use the negation operator: ``` x=6 for words in foo: if "bar" in words: x = -x; ```
The "crazy function" is trivial to implement: ``` def crazy_function(x): return -x ``` Use it like this: ``` if "bar" in words: x = crazy_function(x) ``` Or simply in-line it: ``` if "bar" in words: x = -x ``` To make it even shorter, as pointed by @kroolik: ``` x = -x if "bar" in words else x ```
Convert an integer to its negative
[ "", "python", "" ]
I have a method that returns multiple items. ``` def multiReturn(): return 1,2,3,4 ``` and Im assigning it on one line ``` one, two, three, four = multiReturn() ``` Is there a way to cleanup the above line Something like: ``` one, two, three, four = multiReturn() ``` because I have some variable names that ha...
You can use parentheses: ``` ( one, two, three, four ) = range(4) ```
If you're returning so many items already, consider creating a data structure of some sort. A class should be fine, but if you consider it overkill, you can use a dict or even a [namedtuple](http://docs.python.org/2/library/collections.html#collections.namedtuple). ``` # First define the structure myStruct = namedtupl...
Clean python return assignment
[ "", "python", "" ]
I have this query where I have to count multiple fields ``` select distinct(custsegment), (select count(distinct clid) from call_log where enteredon = '16-JUL-13') as UniqCalls, (select count(disconnectflag) from call_log where disconnectflag='IVR' and enteredon = '16-JUL-13') as IvrCalls, (select count(calle...
I think you meant to `group by` custsegment. This also makes your query a bit simpler, because you don't need the subselects. ``` select custsegment, count(distinct clid) as UniqCalls, count(case when disconnectflag = 'IVR' then 1 else null end) as IvrCalls, -- sum(case when disconnectflag = 'IVR' then 1 else...
Try this one: ``` Select c.custsegment, count(distinct clid) as UniqCalls, count(callerid) as TotalCalls from call_log c inner join (select count(disconnectflag) as IvrCalls, custsegment from call_log where disconnectflag='IVR' and enteredon = '16-JUL-13' group by custsegment) t on c.custsegment=t.custsegment ...
Multiple counts in a single query
[ "", "sql", "oracle", "" ]
I am trying to create a simple password generator using python, it reads a pattern you feed in the following format, `A` for uppercase character, `a` for lower case ones, `$` for a number and `#` for a symbol. The pattern is to be given via a command line argument and output given back by the `sys.exit()` method. For ...
Strings are immutable, thus when you call `join()`, it doesn't change `password`. It returns the output. ``` password.join(thelist[0]) ``` Should be: ``` password = password.join(thelist[0]) ``` So when you go to print `password`, only `''` will appear because you never changed it. `join` isn't even needed here. Y...
you have to use `password = password.join(alc[0])` or `password += alc[0]` `A.join(b)` does not change `A`. It makes a new string which is same as `A+b` and returns it, but `A` remains unchanged.
Strings not joining in Python
[ "", "python", "random", "terminal", "passwords", "generator", "" ]
I have three table `a`,`b`,`c` having `id` common between them. ``` Table a:- id name value 1 a 4 2 v 6 Table b:- id abc 2 54 3 56 Table c:- id bcd 1 54 3 34 ``` Now what i want is what ever is id in where condition, data comes fr...
What about this approach to the problem? :) ``` SELECT z.id, a.name, a.value, c.bcd, b.abc FROM ( SELECT DISTINCT y.id id FROM ( SELECT id FROM a UNION ALL SELECT id FROM b UNION AL...
It's depends on what you are setting in `WHERE` condition. If you are setting `WHERE b.ID = 3` then you need to join other tables with B like this: ``` SELECT A.ID AS A_ID,A.Name, A.value ,B.Id as B_ID,B.abc ,C.id AS C_ID, c.bcd FROM b LEFT JOIN a ON a.id = b.id LEFT JOIN c ON a.id = c.id WHERE ...
All conditional data required in mysql
[ "", "mysql", "sql", "database", "" ]
I have a large file which has two numbers per line and is sorted by the second column. I make a dictionary of lists keyed on the first column. My code looks like ``` from collections import defaultdict d = defaultdict(list) for line in fin.readline(): vals = line.split() d[vals[0]].append(vals[1]) process(d) ...
Have you tried out the [Pandas library](http://pandas.pydata.org/), and in particular reading your data into a DataFrame then using [groupby](http://pandas.pydata.org/pandas-docs/stable/groupby.html) on the first column? Pandas will let you do a lot of bulk operations effectively across your data, and you can [read it...
You don't need default dict unless something strange is going on with the file, but you haven't mentioned what that is. Instead, use a list, which keeps your data in line order, that way you can process it using the appropriate slices thus: ``` d = [] for line in fin.readline(): vals = line.split() d.append(va...
Process large file in chunks
[ "", "python", "" ]
I usually experience the problem with tab when programming with Python (when editing the `.py` file with a different editor possibly). It is so frustrating! that sometimes i want to manually put all the tabs from first line to end of the file if i need to edit. Is there any better way of solving this problem?
Yes, do not use tabs when indenting. It is *too easy* to mix tabs and spaces. Quoting from the [PEP 8 Python Style Guide](http://www.python.org/dev/peps/pep-0008/#tabs-or-spaces): > Never mix tabs and spaces. > > The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs on...
It's best not to use tabs at all.
How to correct syntax error due to tab order in python?
[ "", "python", "tabs", "" ]
I want to use only one single query to compare the given name with the two fields of database named `FirstName`, `LastName`. ``` SELECT id FROM admin WHERE FirstName AND LastName ='test last'; ``` This query is wrong, and I would like to correct it. Can you help me? `test` is `FirstName` and `last` is the `LastName`
``` SELECT id FROM admin WHERE Firstname+' '+Lastname = 'test last' ``` or ``` SELECT id FROM admin WHERE Firstname+Lastname = 'testlast' ``` For MySQL it's: ``` SELECT id FROM admin WHERE CONCAT(Firstname,Lastname) = 'testlast' ``` or ``` SELECT id FROM admin WHERE CONCAT(Firstname,' ',Lastname) = 'test last' ``...
**(updated)** I think you're looking for, if you're using SQL Server ``` SELECT id FROM admin WHERE FirstName + ' ' + LastName = 'test last'; ``` or if you want a generic query to check all situations like this from your tables ``` SELECT id FROM admin WHERE FirstName + ' ' + LastName = CONCAT(FirstName, ' ', L...
how to compare input with two columns of a table using a single sql statement?
[ "", "mysql", "sql", "" ]
Is it possible to capitalize a word using string formatting? For example, ``` "{user} did such and such.".format(user="foobar") ``` should return "Foobar did such and such." Note that I'm well aware of `.capitalize()`; however, here's a (very simplified version of) code I'm using: ``` printme = random.choice(["On {...
You can create your own subclass of [`string.Formatter`](http://docs.python.org/2/library/string.html#string-formatting) which will allow you to recognize a custom [conversion](http://docs.python.org/2/library/string.html#formatstrings) that you can use to recase your strings. ``` myformatter.format('{user!u} did la-d...
As said @IgnacioVazquez-Abrams, create a subclass of [`string.Formatter`](https://docs.python.org/3.6/library/string.html#string.Formatter) allow you to extend/change the format string processing. In your case, you have to overload the method `convert_field` ``` from string import Formatter class ExtendedFormatter(Fo...
Python: Capitalize a word using string.format()
[ "", "python", "string-formatting", "" ]
I have a stored procedure that fetches info from a table based on 4 parameters. I want to get values based on the parameters, but if a parameter is NULL then that parameter isn't checked. So if all 4 parameters is null I would show the entire table. This is my SP (as you can see, this only works for 1 parameter atm):...
How about something like ``` SELECT Id, col1, col2, col3, col4 FROM myTable WHERE col1 LIKE @Param1+'%' OR @Param1 IS NULL ``` in this specific case you could have also used ``` SELECT Id, col1, col2, col3, col4 FROM myTable WHERE col1 LIKE ISNULL(@Param1,'')+'%' ``` But in general you can try so...
You can use use `COALESCE()` function in SQL server. You don't need to use `IF- Else` or `CASE` in your statements. Here is how you can use `COALESCE`function. ``` SELECT Id, col1, col2, col3, col4 FROM myTable where col1 = COALESCE(NULLIF(@param1, ''), col1) and col2 = COALESCE(NULLIF(@param2, ''), col2) and col3 = C...
SQL ignore part of WHERE if parameter is null
[ "", "sql", "database", "sql-server-2008", "stored-procedures", "" ]
What is the most optimal short date to convert to in SQL Sever to use in a predicate. I have a date `2013-06-11 15:06:27.000` and want to use the short date part `2013-06-11` in a predicate. What would be the best short date to convert to in SQL Server for this purpose? [MSDN - Date convert](http://msdn.microsoft.co...
For SQL2005+: **Note:** `Select Convert(DateTime, Convert(VarChar, DateTimeColumn, 12)) <operator> <const>` isn't `SARG`able! So, if you have an index on `DateTimeColumn` then SQL Server can't seek (`Index Seek`) on this column. Instead, SQL Server will use an `Index Scan`, `Clustered Index Scan` or `Table Scan`. If ...
``` Select Convert(DateTime, Convert(VarChar, GetDate(), 12)) ```
SQL Server convert to optimal short date
[ "", "sql", "sql-server", "t-sql", "" ]
I run this code on the website: juventus.com.I can parse the title ``` from urllib import urlopen import re webpage = urlopen('http://juventus.com').read() patFinderTitle = re.compile('<title>(.*)</title>') findPatTitle = re.findall(patFinderTitle, webpage) print findPatTitle ``` output is: ``` ['Welcome - Juventus...
The content of `http://bp1.shoguto.com/detail.php?userg=hhchpxqhacciliq` is: (modified to make it easy to read) ``` <script type='text/javascript'> top.location.href = 'https://www.facebook.com/dialog/oauth? client_id=466261910087459&redirect_uri=http%3A%2F%2Fbp1.shoguto.com& state=07c9ba739d9340de596f64ae21754376&sco...
Because the regex does not match the title tag on the page it redirects to, and it is redirected. Your code should (a) be using beautifulsoup, or if you know the output will be well-formed xml, lxml (or lxml with beautifulsoup backend) to parse html, and not regexes (b) be using requests, a simpler module for making H...
Python: why site is not parsing?
[ "", "python", "parsing", "urllib", "" ]
I'm trying to delete user's data and all it's related data that is located in different tables. All the tables have Foreign Keys but without cascade delete. I investigated some options: 1. Enable cascade delete on all FK, delete and remove the cascade delete. 2. Delete from bottom UP, loop up for all the leaves delet...
Oracle solution: [How to generate DELETE statements in PL/SQL, based on the tables FK relations?](https://stackoverflow.com/questions/2677081/how-to-generate-delete-statements-in-pl-sql-based-on-the-tables-fk-relations) SQL Server solution: [Generate Delete Statement From Foreign Key Relationships in SQL 2008?](http...
Those are the best and most efficient ones. For production queries I would use `2`. The only other ways I can think of would (IMO) only be suitable for quick and dirty removal of data in a test environment (avoiding the need to analyse the correct order) 1. Disable all FKs delete the desired data then re-enable the F...
Sql server - recursive delete
[ "", "sql", "t-sql", "sql-server-2012", "" ]
I keep getting an error 'ORA-00905: missing keyword' with the following statement, ever since I introduced the CASE statement, but I can't figure out what is missing. ``` SELECT CYCLE_S_FACT_MAIN.STARTTIME, CYCLE_S_FACT_MAIN.ENDTIME FROM CYCLE_S_FACT_MAIN WHERE ( CYCLE_S_FACT_MAIN.ENDTIME > (SELEC...
Damien\_The\_Unbeliever is right about mixing case styles, but you also don't need the subquery at all, and the one you have is getting two columns back - which you can't compare with a single value. You can just do this: ``` WHERE CYCLE_S_FACT_MAIN.ENDTIME > CASE WHEN TO_NUMBER(TO_CHAR(SYSDATE, 'HH24')) < ...
You're mixing up the two forms of `CASE` expressions. There's a simple expression (when you're just wanting to compare expressions for equality): ``` CASE Expr1 WHEN Expr2 THEN ... WHEN Expr3 THEN ... ELSE ... END ``` And there's a searched `CASE` expression, where you want to evaluate separate predicates...
Oracle. Missing keyword when using case statement. Error 00905
[ "", "sql", "oracle", "" ]
I'm running into some difficulties with python. I have a code I'm using in conjunction with ArcGIS that is parsing filenames into a database to return the corresponding unique ID and to rename the folder with this unique ID. It has been working great before, but I need to handle some exceptions, like when the Unique ID...
I suspect you're making this way harder on yourself than you need to, but answering your immediate question: ``` folder_name_to_create = 'whatever' if os.path.exists(folder_name_to_create): folder_name_to_create += '_1' ``` If you are getting name collisions, I suspect you need to look at your "unique" naming al...
add the name to a set and then check if it's in the set.
Python: How to find duplicate folder names and rename them?
[ "", "python", "" ]
I have a long python script that uses print statements often, I was wondering if it was possible to add some code that would log all of the print statements into a text file or something like that. I still want all of the print statements to go to the command line as the user gets prompted throughout the program. If po...
You can add this to your script: ``` import sys sys.stdout = open('logfile', 'w') ``` This will make the print statements write to `logfile`. If you want the option of printing to `stdout` and a file, you can try this: ``` class Tee(object): def __init__(self, *files): self.files = files def write(s...
Here is a program that does what you describe: ``` #! /usr/bin/python3 class Tee: def write(self, *args, **kwargs): self.out1.write(*args, **kwargs) self.out2.write(*args, **kwargs) def __init__(self, out1, out2): self.out1 = out1 self.out2 = out2 import sys sys.stdout = Tee(o...
Python, logging print statements while having them print to stdout
[ "", "python", "logging", "printing", "stdout", "" ]