Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have 3 classes like this: ``` class Person (models.Model) name = models.CharField(max_length=200) class Device (models.Model) mobile = models.CharField(max_length=200) class Uses (models.Model) .... person_name = models.ForeignKey(Person) person_device = models.ForeignKey(Device) ``` My question is: H...
Life will be easier if you use ManyToManyField, i.e. add this field to the Person model: ``` devices = models.ManyToManyField('Device', through='Uses') ``` Then, to get the list, you just need to get the devices attribute of the model object: ``` Person.objects.get(name="TheNameYouWant").devices ``` If you do not w...
> How can I make a query to get the devices used by the person "name"? ``` devices = Uses.objects.filter(person_name__name='name').values_list('person_device') ```
A query with 3 tables in django
[ "", "sql", "django", "" ]
I have the following data set. ``` create table t1 ( dept number, date1 date ); Table created. insert into t1 values (100, '01-jan-2013'); insert into t1 values (100, '02-jan-2013'); insert into t1 values (200, '03-jan-2013'); insert into t1 values (100, '04-jan-2013'); commit; ``` MY goal is to create a rank c...
This is a little complicated. Instead of using `rank()` or the like, use `lag()` to see when something changes. Then do a cumulative sum of the flag. ``` select dept, date1, CASE WHEN StartFlag = 0 THEN 1 ELSE 1+StartFlag+NVL(lag(StartFlag) over (order by date1),0) END as rnk from (select t1....
This could have been a case for `model` clause, but unfortunately it dramatically underperforms on significant amount of rows compared to Gordon's query. ``` select dept, date1, rank from t1 model dimension by ( row_number() over(order by date1) as rn ) measures( 1 as rank, dept, date1 ) rules ( rank[1] =...
Oracle Analytic functions - resetting a windowing clause
[ "", "sql", "oracle", "analytic-functions", "" ]
I'm trying to customize the recaptcha inside my form, but I only get a javascript error. Can it be made, or do I have to modify the Flask-WTF code myself?
The example from bbenne10 almost does it except for one little detail: besides putting `theme: 'custom'` into your config you also must specify the `custom_theme_widget: 'recaptcha_widget'`. Or whatever will be the id of container where the actual image will be injected and of course the container must be present in yo...
You can now do this quite easily, actually. First, set (or extend) `RECAPTCHA_OPTIONS` to a dictionary containing `{'theme': 'custom'}` (and ensure you're doing `app.config.from_object(__name__)` or similar), and then ensure that your template contains all of the required DOM elements specified under the Custom Themein...
How to use a recaptcha custom theme with Flask-WTF
[ "", "python", "flask", "recaptcha", "flask-wtforms", "" ]
When I type ``` import matplotlib.pyplot as plt ``` in my IPython notebook I get ``` ImportError: No module named matplotlib.pyplot ``` Shouldn't be this module installed by default? Do I need to extra install it. If it is the case, how can I do it. I use virtual environment on Linux to install stuff (including IPy...
In my Python setup (2.7.3, Linux), I installed `matplotlib` as well as `IPython` via `pip`. `matplotlib` is available from the normal Python interpreter as well as from IPython (as expected). The order of installation does not matter. And no, `IPython` should not have `matplotlib` installed by default, this does not m...
Matplotlib is not installed by default, there are instructions on the [IPython install page](http://ipython.org/install.html) to install on linux: > Optionally install additional tools for scientific computing: On > Ubuntu or other Debian-based distributions, type at the shell: > > ``` > sudo apt-get install python-ma...
How to get matplotlib working under IPython?
[ "", "python", "matplotlib", "ipython", "" ]
I am conversting a float to integer in the below code. But , the resultant output is not correct for nickels. **Code:** ``` actual = 25 paid = 26.65 cents = (paid-actual)*100 quarters = int(cents/25) cents = cents %25 dimes = int(cents/10) cents = cents %10 nickels = int(cents/5) print quarters, dimes, nickels,cents ...
Floating point numbers are not guaranteed to be spot on the number you expect, they could just be barely off, say `5.0` might actually be `4.999...` and since `int()` truncates/rounds down, you get your error. Many banks just completely give up on the floating point issue and just work with $1.00 = 100 I would advise ...
[Floating point numbers cannot represent all real numbers](http://docs.python.org/2/tutorial/floatingpoint.html). Every time you do anything with floating-point numbers, you are approximating the exact result by the closest thing your floating-point representation can represent. When you write ``` 26.65 ``` Python a...
int() conversion of float in python
[ "", "python", "python-2.6", "" ]
How would I take the contents of the file and change it into a dictionary? The contents would include menu items in this form: ``` 1 Chocolate ice cream 2 Green tea 8 Shrimp roll ``` And I want the key to be the number and the value to be the food item. So far, I got: ``` d = {} for line in menu.read().strip().spl...
Loop over the file object, line by line, then split the lines: ``` with open('inputfilename.txt') as menu: d = {} for line in menu: key, value = line.split(None, 1) d[key] = value.strip() return d ``` The `.split(None, 1)` call applies the default split algorithm (split on arbitrary-width ...
You can try this: ``` d = {} for line in menu.read().strip().split(): d[line[0]] = line[1:] # you want to use just line[1:], than d[line[1:]] return d ``` The issue here is that `d[line[1:]]` gives you the value mapped by the key `line[1:]`.
Converting file to dict
[ "", "python", "string", "file", "dictionary", "" ]
I have a list: ``` ab = [1, 2, a, b, c] ``` I did: ``` strab = str(ab). ``` So `strab` is now a string. I want to cast that string back into a list. How can I do that?
The easiest and safest way would be to use [`ast.literal_eval()`](http://docs.python.org/2/library/ast.html#ast.literal_eval): ``` import ast ab = [1, 2, 'a', 'b', 'c'] # a list strab = str(ab) # the string representation of a list strab => "[1, 2, 'a', 'b', 'c']" lst = ast.literal_eval(strab) # con...
Use the ast package: ``` import ast lst = ast.literal_eval(strab) ```
How to cast string back into a list
[ "", "python", "string", "list", "casting", "" ]
i want a good way to improve my sql code, i have to use inner join when condition is met. I am currently replicates the code: ``` @SystemMerge bit if (@SystemMerge=1) BEGIN SELECT ....... FROM myTable INNER JOIN table ON table.param1=myTable.param1 INNER JOIN systemTable on systemTable...
This should (approxmately) do the same thing: ``` SELECT ....... FROM myTable INNER JOIN table ON table.param1=myTable.param1 LEFT JOIN systemTable on systemTable.param2=myTable.param2 and @SystemMerge = 1 WHERE (@SystemMerge = 0 OR systemTable.NonNullableColumn IS NOT NULL) ``` Of course, this also mean...
How about dynamic sql? ``` declare @sel varchar(max) set @sel = ' SELECT ....... FROM myTable INNER JOIN table ON table.param1=myTable.param1 ' if (@SystemMerge=1) begin set @sel = @sel+'INNER JOIN systemTable on systemTable.param2=myTable.param2' end exec(@sel) ```
SQL do inner join if condition met
[ "", "sql", "sql-server", "" ]
If I have variables `x` and `y`, such that: * `x` is always a string * `y` can either be a string or a list of strings How can I create a list `z == [x, <all elements of y>]`? For instance: ``` x = 'x' y = 'y' # create z assert z == ['x', 'y'] ``` ``` x = 'x' y = ['y', 'y2'] # create z assert z == ['x', 'y', 'y2']...
``` z = [x] + (y if isinstance(y, list) else [y]) ``` Generally I'd avoid having a `y` that could be either a string or a list, though: it seems unnecessary.
``` z = [x] if isinstance(y, list): z.extend(y) else: z.append(y) ```
Create a list of 2 variables
[ "", "python", "string", "list", "" ]
Is there a canonical location where to put self-written packages? My own search only yielded a blog post about [where to put version-independent pure Python packages](http://pythonsimple.noucleus.net/python-install/python-site-packages-what-they-are-and-where-to-put-them) and a [SO question for the canonical location u...
Thanks to the [two](http://docs.python.org/2/install/#how-installation-works) [additional](http://docs.python.org/2/install/#alternate-installation-the-home-scheme) links, I found not only the intended answer to my question, but also a solution that I like even more and that - ironically - was also explained in my firs...
Place the source of your package wherever you'd like, but at least give your package a minimal `setup.py` file, immediately outside the package: ``` import setuptools setuptools.setup(name='mypackage') ``` Then fake-install your package into your python install's `site-packages` by running: ``` python setup.py deve...
Where shall I put my self-written Python packages?
[ "", "python", "" ]
I've got these tables in my database: Tourist - this is the first table ``` Tourist_ID - primary key Extra_Charge_ID - foreign key name...etc... ``` **EXTRA\_CHARGES** ``` Extra_Charge_ID - primmary key Excursion_ID - foreign key Extra_Charge_Description ``` **Tourist\_Extra\_Charges** ``` Touri...
Your database schema is not completely clear to me, but it seems you can link tourists from the **Tourist** table to their extra charges in the **EXTRA\_CHARGES** table via the **Tourist\_Extra\_Charges** table like this: ``` SELECT T.Tourist_ID ,T.Tourist_Name ,EC.Extra_Charge_ID ,EC.Extra_Ch...
You can have it in delimited list with `GROUP_CONCAT` like: ``` SELECT Tourist_ID, Name, GROUP_CONCAT(Extra_Charge_ID SEPARATOR ',') FROM Tourist GROUP BY Tourist_ID ```
Sql subquery with inner join
[ "", "sql", "" ]
This is a simple program I am working on to learn python because I am a beginner. How would I add an exception if the user types something other that y,Y,n,N. I have searched everywhere but can't seem to find what exception to use? Thanks for everyone's help. EDIT:I adjusted my code. The only thing that is not working...
In this case you do not really need an exception - an exception tends to be an *exceptional* case that prevents the program from continuing, if it can still continue but under certain circumstances due to user input or conditions it may use a Warning to signal that. Here you can easily check input using any number of ...
Invalid user input should not normally result in an exception being thrown. Exceptions are for exceptional conditions. This isn't a hard-and-fast rule and you could argue that some standard exceptions don't follow it, but the way to deal with this kind of user input validation is regular flow control. Use an `if` state...
Python adding an exception (edited)
[ "", "python", "" ]
suppose we have many text files as follows: file1: ``` abc def ghi ``` file2: ``` ABC DEF GHI ``` file3: ``` adfafa ``` file4: ``` ewrtwe rewrt wer wrwe ``` How can we make one text file like below: result: ``` abc def ghi ABC DEF GHI adfafa ewrtwe rewrt wer wrwe ``` Related code may be: ``` import csv imp...
You can read the content of each file directly into the write method of the output file handle like this: ``` import glob read_files = glob.glob("*.txt") with open("result.txt", "wb") as outfile: for f in read_files: with open(f, "rb") as infile: outfile.write(infile.read()) ```
The `fileinput` module is designed perfectly for this use case. ``` import fileinput import glob file_list = glob.glob("*.txt") with open('result.txt', 'w') as file: input_lines = fileinput.input(file_list) file.writelines(input_lines) ```
combine multiple text files into one text file using python
[ "", "python", "" ]
I'm trying to write a basic algorithm for encrypting a file. It takes the ASCII value of each character in a string and moves it up or down an amount depending on how long the password is, then you can layer more passwords on top. ``` def encrypt(s): lenStr=s.__len__() #used later for working how far the int is mo...
You're getting the`TypeError`exception because the value of`x`in the`s[x]=ord(s[x])` statement is one of the elements of the `s` list, so it's an individual character from the string argument passed to`encrypt()`. To fix that, just loop through all the possible indices of the `s` list which happens to be the same as th...
`x` is a character from the string, not an integer. Let me illustrate: ``` >>> s = list('abcd') >>> for x in s: ... print(x) ... a b c d >>> ``` You want x to be integer values from 0 to the length of the string, like this: ``` >>> for x in range(len(s)): ... print(x) ... 0 1 2 3 >>> ``` So, your function s...
python list indices must be integers not string
[ "", "python", "python-3.x", "" ]
If I have a list of strings, such as: ``` lst = ['aa bb', 'cc dd', 'cc aa'] ``` How can I get this into a list of unique words such as this: ``` ['aa', 'bb', 'cc', 'dd'] ``` using a comprehension? Here's as far as I've gotten, to no avail: ``` wordList = [x.split() for row in lst for x in row] ```
The simplest approach I think is probably this, although not the most efficient. ``` set(' '.join(lst).split()) ``` If you really want a list, then just wrap that in a call to `list()`
You want to loop over the split values: ``` wordList = [word for row in lst for word in row.split()] ``` then use a set to make the whole list unique: ``` wordList = list({word for row in lst for word in row.split()}) ``` or just use a set and be done with it: ``` wordList = {word for row in lst for word in row.sp...
How do I create a list of words from a list of sentences?
[ "", "python", "list-comprehension", "" ]
I have a log in table that have something like this: tablelog ``` date | time | event | program | ordendate 20130722 070000 executing program1 20130722 20130722 070040 end ok program1 20130722 20130722 070100 executing program1 20130722 20130722 070140 end o...
As far as I understand it, you want to list sequential start/stops by program(?) This uses `LEAD` to do the work in a `CTE`, then just filters and orders using an outer query; ``` WITH cte AS ( SELECT CASE WHEN "event"='executing' THEN "date" || "time" END "datetimeStart", LEAD(CASE WHEN "event"='end ok' TH...
The query that you are trying to do is best done using the analytic functions `lag()` or `lead()`: ``` select dateTimeStart, dateTimeStop, program, orderdate from (select tl.date || tl.time as datetimeStart, lead(tl.date || tl.time) over (partition by program order by date, time) as dateTimeStop, ...
SQL QUERY Oracle log analysis
[ "", "sql", "oracle", "plsql", "" ]
I am trying to parse an HTML file ([demo.html](http://pastebin.com/P54pNvLY) to make all relative links absolute. Here is how I try to do this in Python script - ``` from bs4 import BeautifulSoup f = open('demo.html', 'r') html_text = f.read() f.close() soup = BeautifulSoup(html_text) for a in soup.findAll('a'): f...
It seams beautiful soup 4 is giving problem just Downgrade Beautifult soup to version3 your problem will be solved ``` import BeautifulSoup #This is version 3 not version 4 f = open('demo.html', 'r') html_text = f.read() f.close() soup = BeautifulSoup.BeautifulSoup(html_text) print soup.contents for a in soup.fi...
Your HTML code is alittle messy. You have closed `script` tag and you are closing it again ``` <script type="text/javascript" src="/scripts/ddtabmenu.js" /></script> ``` It breaks DOM. Just remove `/` from the end of `<script type="text/javascript" src="/scripts/ddtabmenu.js" />`
Parse HTML to edit links
[ "", "python", "html", "hyperlink", "beautifulsoup", "web-crawler", "" ]
So, I've got a very basic deployment on an EC2 instance that largely works, except for a couple of large issues. Right now I'm just ssh'ing into the box and running ``` python -m SimpleHTTPServer 80 ``` and I have the box on a security group that allows http requests in on Port 80. This seems to work, but if I leave...
`SimpleHTTPServer` just serves static pages on port 80, mainly for use during development. For production usage (if you want to use EC2) I recommend you read up on `Apache` or `nginx`. Basically you want a web server that runs on Linux. If you think your site will remain static files (HTML, CSS, JS) I recommend you h...
Use `screen`! Here's a quick tutorial: <http://www.nixtutor.com/linux/introduction-to-gnu-screen/> Essentially just ssh in, open a new window via screen, start the server via `python -m SimpleHTTPServer 80`, then detach from the window. Additionally, you should be able to close your terminal and it should stay up.
AWS deployment goes down frequently
[ "", "python", "deployment", "amazon-web-services", "amazon-ec2", "" ]
Consider this sample python code. It reads from stdin and writes to a file. ``` import sys arg1 = sys.argv[1] f = open(arg1,'w') f.write('<html><head><title></title></head><body>') for line in sys.stdin: f.write("<p>") f.write(line) f.write("</p>") f.write("</body></html>") f.close() ``` Suppose I wan...
Just do ``` >>> import sys >>> f = sys.stdout >>> f.write('abc') abc ``` Now you just need to do `f = sys.stdout` instead of `f = open(fileName)`. (And remove `f.close()`) **Also**, Please consider using the following syntax for files. ``` with open(fileName, 'r') as f: # Do Something ``` The file automaticall...
Names in Python are just bindings. Therefore: ``` f = sys.stdout ``` Just binds the name `f` to *the object* that's *also bound* to `sys.stdout`... Note that since they're both the same object, any changes you make to `f` or `sys.stdout` at this point will affect *both*... So don't do `f.close()` as you normally wou...
Is it possible to have an alias for sys.stdout in python?
[ "", "python", "" ]
I would like process a file line by line. However I need to sort it first which I normally do by piping: ``` sort --key=1,2 data |./script.py. ``` What's the best to call sort from within python? Searching online I see `subprocess` or the `sh` module might be possibilities? I don't want to read the file into memory a...
Its easy. Use subprocess.Popen to run sort and read its stdout to get your data. ``` import subprocess myfile = 'data' sort = subprocess.Popen(['sort', '--key=1,2', myfile], stdout=subprocess.PIPE) for line in sort.stdout: your_code_here sort.wait() assert sort.returncode == 0, 'sort failed' ```
~~I believe sort will read all data in memory, so I'm not sure you will won anything~~ but you can use `shell=True` in [`subprocess`](http://docs.python.org/2/library/subprocess.html) and use pipeline ``` >>> subprocess.check_output("ls", shell = True) '1\na\na.cpp\nA.java\na.php\nerase_no_module.cpp\nerase_no_module....
Best way to pipe output of Linux sort
[ "", "python", "" ]
user table ``` ID | name 1 | ada 2 | bob 3 | tom ``` group Table ``` ID | name 1 | group A 2 | group B 3 | group C ``` user\_group Table ``` user_id | group_id 1 | 1 2 | 1 1 | 2 2 | 2 3 | 2 1 | 3 3 | 3 ``` Given group of user ids : [1, 2, 3] How to query th...
To get all groups that contain exactly the specified users (i.e. all specified users and no other users) ``` DECLARE @numUsers int = 3 SELECT ug.group_id --The Max doesn't really do anything here because all --groups with the same group id have the same name. The --max is just used so we can sel...
Try This: ``` Select t2.name FROM (Select group_id From user_group Group by group_id Having Count(user_id) = (Select Count(*) FROM User_Table)) AS T1 INNER JOIN Group_Table AS T2 ON T1.group_id = T2.ID ``` See Fiddle: <http:/...
(SQL) Match users belong to which group given user_id[]
[ "", "sql", "" ]
I am defining a class that represents a vector: ``` ''' An entity with size and direction ''' UNINITIALIZED = -1 class myVector(): def __init__(self,direction = UNINITIALIZED,size = UNINITIALIZED): self.direction = direction self.size = size ``` For using the class I imagine 2 scenarios : Eit...
Size and direction sound like a tuple to me: ``` class myVector(): def __init__(self, sd=(UNINITIALIZED, UNINITIALIZED)): try: self.size, self.direction = sd except (ValueError, TypeError) as e: raise ValueError('two values of size and direction must be specified') ``` It i...
You can also define the class like this: ``` class myVector(): def __init__(self,*direction_and_size): if not len(direction_and_size): direction_and_size = [UNINITIALIZED, UNINITIALIZED] assert len(direction_and_size) == 2, "Please provide both parameters" self.direction, self....
python function use multiple defaults or no defaults at all
[ "", "python", "function", "default", "" ]
I've been searching for hours now but can't find anything that actually works. I've got this in multiple records : ``` <p style="text-align: justify;"> SOME TEXT </p> <p style="text-align: justify;"> MORE TEXT </p> ``` I want to change it to this : ``` <p style="text-align: justify;"> SOME TEXT MORE TEXT </p> ``` ...
If possible, you'd probably be better off doing this sort of replacement in your language of choice, which will offer stronger string handling capabilities than MySQL. That said, MySQL recognizes several C-style [character escapes](http://dev.mysql.com/doc/refman/5.0/en/string-literals.html) in strings, including both ...
I suggest you not to use MySQL for the string operations. This is not what a Database is made for. Use PHP, Perl, ASP, whatever you are coding with. Problems you might run into: Instead of common line break `\r\n` between the tags, you might have to parse different cases: ``` <blankspace>\r\n \n\n \n \r\n<blankspace...
Detect line breaks in MySQL?
[ "", "html", "mysql", "sql", "replace", "line-breaks", "" ]
I tried display 1 monthly data but I want display e.g between 01.06.2013 and 01.07.2013 ? How to change this query for display between two date ? Thanks in advance ``` select b.ID ID, bt.type BULTEN_TYPE, b.ID TOPIC, b.Bul_Effect EFFECTT, b.Bul_Comment COMMENTS, concat(date_format(b.Bul_date,'%d.%m.%Y'), ' '...
This `WHERE` clause will get you exactly what you used as an example: ``` ... and Bul_date BETWEEN '1/6/2013' AND '1/7/2013' ... ``` Now, a more dynamic way of getting at what I *think* you want would be: ``` ... and Bul_date BETWEEN GETDATE() AND DATEADD(DAY, 1, GETDATE()) ... ``` that would get you everything bet...
``` select b.ID ID, bt.type BULTEN_TYPE, b.ID TOPIC, b.Bul_Effect EFFECTT, b.Bul_Comment COMMENTS, concat(date_format(b.Bul_date,'%d.%m.%Y'), ' ', b.Bul_hour, ':', b.Bul_min) as BEGIN, concat(date_format(b.bitdate,'%d.%m.%Y'), ' ', b.bithour , ':', b.bitmin) as FINISH fro...
How to list data between two dates in sql?
[ "", "sql", "sql-server", "" ]
I want to poll a folder continuously for any new files, lets say every 1 hours and whenever it finds a new file, it copies to a specific location. I found code to [find latest file](https://stackoverflow.com/questions/6714491/python-script-to-test-for-most-recently-modified-file-inconsistent-results) and to [copy to an...
For polling, the simplest solution is `time.sleep(n)` which sleeps for `n` seconds. Your code would look something like this, then: ``` import time.sleep as sleep import sys try: while True: # code to find the latest file # code to copy it to another location sleep(3600) except KeyboardI...
The periodic nature of it suggests that you can use a cron job for it. You can set a cron job to run your python script every hour. It's then the script that handles copying of the file. That is if you're on a Unix machine ``` crontab -e // this will open your crontab file, then add 0 * * * * /path/to/your/script.py `...
python script to poll a folder continuously after a certain time interval and copy the new files to another location
[ "", "python", "file", "copy", "polling", "" ]
In a Django application, I have some checks in a form which will return error = "something". The thing is that that error will not be defined unless there is any error. ``` mycharacters = Character.objects.filter(username_id=request.user.id) if(mycharacters.count() >= 5): error = True if not error: #save to...
You can do following: ``` error = mycharacters.count() >= 5 if not error: ... ``` **UPDATE** ``` error = mycharacters.count() >= 5 if error: to_json = {"incorrect":"Excedeed maximum"} else: # Save to DB ```
Either use an `else` branch: ``` if mycharacters.count() >= 5: error = True else: error = False ``` or initialize the variable to the least likely value, and reassign: ``` error = False if mycharacters.count() >= 5: error = True ``` The latter is often easier to read, but both approaches work (and so do...
variable 'error' referenced before assignmentRequest
[ "", "python", "django", "" ]
Clutter is not doing the full animation. This is my current code: ``` from gi.repository import Clutter, Gtk import sys def onClick(actor, event): actor.animatev(Clutter.AnimationMode.LINEAR, 1000, ["x"], [280]) # clutter does not seem to be running this line actor.animatev(Clutter.AnimationMode.LINEAR, 100...
like the documentation for ClutterActor.animate() says: > Calling this function on an actor that is already being animated will > cause the current animation to change with the new final values, the > new easing mode and the new duration > <https://developer.gnome.org/clutter/stable/clutter-Implicit-Animations.html#cl...
Try following code: ``` def onClick(actor, event): animation1 = actor.animatev(Clutter.AnimationMode.LINEAR, 1000, ["x"], [280]) animation1.connect_after( 'completed', lambda animation: actor.animatev(Clutter.AnimationMode.LINEAR, 1000, ["x"], [20]) ) ```
Clutter messing up animations
[ "", "python", "linux", "animation", "clutter", "" ]
I'm running queries in SQL Server 2008.. I have a `sales` table and a `payments` table.. sometimes a sale has multiple methods of payment (part giftcard + part cash or part credit + part cash etc..) so what I want to do is list the sales and the payments for each sale in a table. If I do a `LEFT JOIN ON sales.SaleID =...
I wouldn't mix data retrieval and data display, which is what I think you are asking about. Do you have some sort of column to indicate which payment should be displayed first? I'm thinking something like: ``` SELECT columnlist, rn = ROW_NUMBER() OVER (PARTITION BY sales.salesID ORDER BY payment.paymentID) FROM sales...
It is probably easier to do this in the interface. The basic query you want is: ``` select s.saleID, s.SaleDate, s.Amount, p.PaymentType, p.PaymentAmount, ROW_NUMBER() over (partition by p.SaleId order by p.PaymentAmount desc) as seqnum from sales s join payments p on p.saleID = s....
SQL query one to many relationship join without duplicates
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "join", "" ]
I have a search function on my site which uses GET. I have been trying to code something that would take words out of the GET post and then search in using SQL. This is what I been able to do: ``` $id = $_GET["search"]; $searchTerms = explode(' ', $id); $searchTermBits = array(); foreach ($searchTerms as $term) { ...
``` $lol = mysql_query("SELECT * FROM database WHERE .implode(' AND ', $searchTermBits).") ``` should be ``` $lol = mysql_query("SELECT * FROM database WHERE ". implode(' AND ', $searchTermBits). "") ```
`implode` is just a part of the string in your case, you need to take it out from quotes: ``` mysql_query("SELECT * FROM database WHERE ".implode(' AND ', $searchTermBits)) ```
Multiple keywords in SELECT LIKE
[ "", "mysql", "sql", "select", "implode", "" ]
The idea of this loop was to iterate through a list. If a certain property of an object was not a key of the OrderedDict, it would add it. It is a dictionary of lists of objects ``` for object in someList: if object.DATE not in myOrderedDict: myOrderedDict[object.DATE]=[] myOrderedDict[object.DATE].append(obj...
It would appear that you expect the items in an `OrderedDict` to be ordered by key, which is not the case. An OrderedDict is ordered by the order items are added to it. From the [PEP 372](http://www.python.org/dev/peps/pep-0372/) FAQ: > **Does OrderedDict support alternate sort orders such as alphabetical?** > > No. T...
The pure-Python [sortedcontainers module](http://www.grantjenks.com/docs/sortedcontainers/index.html) has a [SortedDict](http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html) type that can help you. It maintains the dict keys automatically in sorted order and is well documented and tested. You use it just as...
OrderedDict not staying in order
[ "", "python", "python-2.7", "ordereddictionary", "" ]
I noticed Pandas now has [support for Sparse Matrices and Arrays](http://pandas.pydata.org/pandas-docs/dev/sparse.html). Currently, I create `DataFrame()`s like this: ``` return DataFrame(matrix.toarray(), columns=features, index=observations) ``` Is there a way to create a `SparseDataFrame()` with a `scipy.sparse.cs...
A direct conversion is not supported ATM. Contributions are welcome! Try this, should be ok on memory as the SpareSeries is much like a csc\_matrix (for 1 column) and pretty space efficient ``` In [37]: col = np.array([0,0,1,2,2,2]) In [38]: data = np.array([1,2,3,4,5,6],dtype='float64') In [39]: m = csc_matrix( (d...
As of pandas v 0.20.0 you can use the `SparseDataFrame` constructor. An example from [the pandas docs](https://pandas.pydata.org/pandas-docs/stable/sparse.html#interaction-with-scipy-sparse): ``` import numpy as np import pandas as pd from scipy.sparse import csr_matrix arr = np.random.random(size=(1000, 5)) arr[arr...
Populate a Pandas SparseDataFrame from a SciPy Sparse Matrix
[ "", "python", "numpy", "scipy", "pandas", "sparse-matrix", "" ]
the difference between query() and rawQuery() in SQLite when making more complex SQL queries. for example i want to use the SQL keyword DISTINCT, so I don't get any duplicates returned from the database. i understand how to use rawQuery() method, that way you can put an actual SQL query statement in the method. in th...
Instead of the... ``` public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) ``` ...method you're using, just use the... ``` public Cursor query (boolean distinct, String table, String[] col...
you can use this, ``` Cursor cursor = db.query(true, YOUR_TABLE_NAME, new String[] { COLUMN1 ,COLUMN2, COLUMN_NAME_3 }, null, null, COLUMN2, null, null, null); ``` Here first parameter is used to set the DISTINCT value i.e if set to true it will return distinct column value. and sixth parameter denotes column name w...
adding DISTINCT keyword to query() with SQLite in Android
[ "", "android", "sql", "database", "sqlite", "" ]
I have a view that needs to join on a concatenated column. For example; ``` dbo.View1 INNER JOIN dbo.table2 ON dbo.View1.combinedcode = dbo.table2.code ``` Inside the 'View1' there is a column which is comprised like so; ``` dbo.tableA.details + dbo.tableB.code AS combinedcode ``` Performing a join on this column i...
Since there's no index on `combinedcode`, the `JOIN` will most likely result in a full "table scan" of the view to calculate the code for every row. If you want to speed things up, try making the view into an [indexed view](http://msdn.microsoft.com/en-us/library/aa933148%28SQL.80%29.aspx) with an index on `combinedco...
Try this way: ``` select * into #TemTap from View1 /*where conditions on view1*/ ``` after that You could create `index` on `#TemTap.combinedcode` and than ``` dbo.#TemTap as View1 INNER JOIN dbo.table2 ON dbo.View1.combinedcode = dbo.table2.code ``` It often works for me.
JOIN on concatenated column performance
[ "", "sql", "sql-server", "t-sql", "" ]
I have a large file with each line of the form `a b c` I would like to remove all such lines where there does not exist another line either like `b d e` or `d a e` with `abs(c - e) < 10`. `a`, `b`, `c`, `d`, `e` are all integers. For example if the input is: ``` 0 1 10 1 2 20 2 3 25 0 1 15 1 4 40 ``` then th...
I don't know if this can be done in linear time. It is straightforward to do it in O(n·log n) time if there are n triplets in the input. Here is a sketch of a method, in a not-necessarily-preferred form of implementation: 1. Make an array of markers M, initially all clear. 2. Create an array and make a copy of the inp...
Like others have said, linear time may not be possible. Here is an easy O(n^2) implementation. If you sort the lists inside the dictionaries, you should be able to improve the runtime. ``` lines = """0 1 10 1 2 20 2 3 25 0 1 15 1 4 40""" Adata = {} Bdata = {} for line in lines.split('\n'): a,b,c = line.split(' '...
How to remove lines from a large file
[ "", "python", "algorithm", "" ]
I have created AFTER INSERT TRIGGER Now if any case if an error occurs while executing Trigger. It should not effect Insert Operation on Triggered table. In One word if any ERROR occurs in trigger it should Ignore it. As I have used ``` BEGIN TRY END TRY BEGIN CATCH END CATCH ``` But it give following error mess...
Interesting problem. By default, triggers are designed that if they fail, they rollback the command that fired it. So whenever trigger is executing there is an active transaction, whatever there was an explicit BEGIN TRANSACTION or not on the outside. And also BEGIN/TRY inside trigger will not work. Your best practice ...
You cannot, and any attempt to solve it is snake oil. No amount of TRY/CATCH or @@ERROR check will work around the fundamental issue. If you want to use the tightly coupling of a trigger then you must buy into the lower availability induced by the coupling. If you want to preserve the availability (ie. have the INSER...
How to Ignoring errors in Trigger and Perform respective operation in MS SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "triggers", "" ]
I am trying to make a list containing all possible variations of 1 and 0. like for example if I have just two digits I want a list like this: ``` [[0,0], [0,1], [1,0], [1,1]] ``` But if I decide to have 3 digits I want to have a list like this: ``` [[0,0,0], [0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0], [1,1...
[`itertools.product()`](http://docs.python.org/2/library/itertools.html#itertools.product) can take a second argument: the length. It defaults to one, as you have seen. Simply, you can add `repeat=n` to your function call: ``` >>> list(itertools.product(range(2), repeat=3)) [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),...
itertools.product(.., repeat=n) ``` >>> import itertools >>> list(itertools.product((0,1), repeat=3)) [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] ``` [Python Module Index](http://docs.python.org/2/py-modindex.html) contains links for standard library modules documentation.
Python: How do i use itertools?
[ "", "python", "list", "python-itertools", "" ]
``` #def func(param): # if param < 0: # return "test" # i = 0 # while i < param: # yield i # i += 1 def func(param): if param < 0: return "test" def gen(n): i = 0 while i < param: yield i i += 1 return gen(param) print(func(-1)) ...
The reason is simply, if the `def` contains a `yield` statement, it creates a generator: <http://www.python.org/dev/peps/pep-0255/> > The yield statement may only be used inside functions. A function that > contains a yield statement is called a generator function. A generator > function is an ordinary function objec...
In python2.x, you can not return something in a generator: ``` >>> def func(): ... return 3 ... yield 3 ... File "<stdin>", line 3 SyntaxError: 'return' with argument inside generator >>> ``` In python3.x, use `return` in a generator means raise a `StopIteration(<something>)`: ``` >>> def func(): ... ...
Why doesn't the Python interpreter implicitly create the generator?
[ "", "python", "generator", "yield", "" ]
I currently have the following table: ``` ID | Name | EventTime | State 1001 | User 1 | 2013/07/22 00:00:05 | 15 1002 | User 2 | 2013/07/23 00:10:00 | 100 1003 | User 3 | 2013/07/23 06:15:31 | 35 1001 | User 1 | 2013/07/23 07:13:00 | 21 1001 | User 1 | 2013/07/23 08:15:00 | ...
In databases that support analytic functions, you could use `row_number()`: ``` select * from ( select row_number() over (partition by ID order by EventTime desc) as rn , * from YourTable ) as SubQueryAlias where rn = 1 ```
``` SELECT ID, Name, EventTime, State FROM MyTable mt WHERE EventTime = (SELECT MAX(EventTime) FROM MyTable sq WHERE mt.ID = sq.ID) ```
Select distinct rows whilst grouping by max value
[ "", "sql", "sql-server-2008", "greatest-n-per-group", "" ]
I have stored procedure to find customer, its working fine. If `Customer_City_Name` is null in the table then I am not able to retrieve the row. SP fails . how to do this I have to get result even if `Customer_City_Name` or `Customer_Country_Code` `IS NULL` ``` EXEC findCustomer null,'%',null,null, ``` SP code: ``` ...
I have fixed this issue by doing this AND ISnull(c.Customer\_City\_Name,'''') LIKE ' + CASE WHEN @customerCityNamePattern IS NOT NULL THEN '''' +@customerCityNamePattern + '''' ELSE 'isnull (c.Customer\_City\_Name,'''')' END + ' AND Isnull(c.Customer\_Country\_Code,'''') LIKE ' + CASE WHEN @customerCountryCode IS NOT ...
@user2218371 you should reconsider alternatives instead of dynamic SQL. anyway, this is an alternative code. ``` CREATE PROCEDURE findCustomer @customerNumber NVARCHAR(100), @customerNamePattern NVARCHAR(35), @customerCityNamePattern NVARCHAR(35), @customerCountryCode NVARCHAR(5) AS BEGIN DECLARE @SQL NVARCH...
not able to retrieve if the table column has null value
[ "", "sql", "sql-server-2008", "" ]
I am getting various data types from a config file and adding them to a dictionary. but I am having a problem with lists. I want to take a line with text: `alist = [1,2,3,4,5,6,7]` and convert into a list of integers. But I am getting ``` ['1', ',', '2', ',', '3', ',', '4', ',', '5', ',', '6', ',', '7']. ``` How can ...
You need to change the `return` statement to. ``` return [int(elem) for elem in s[1:-1].split(',')] # Or map(int, s[1:-1].split(',')) ```
maybe try `ast.literal_eval` here is an example: ``` import ast str1 = '[1,2,3,4,5]' ast.literal_eval(str1) ``` output will be a list like this: ``` [1,2,3,4,5] ``` it wont include the commas in the list
How to convert text format list into a python list
[ "", "python", "parsing", "" ]
I am trying to `UPDATE` all records of a table with the results of a function which uses the other rows of the table as arguments. However, the result of this operation for all records is repeated from the first record. Can anyone explain why this might be the case? ``` def fun(a,b,c,d): return a + b + c + d cur ...
First, you select all of the rows: ``` SELECT field1, field2, field3, field4 FROM TABLE1 ``` This yields this result set in `cur`: ``` 4, 3, 2, 1 7, 3, 1, 0 8, 5, 2, 0 ``` You begin to iterate through the rows. You start with the first row: ``` 4, 3, 2, 1 ``` You add all the columns together, correctly yielding t...
I know this is an old and solved issue but I can't help it: That is the worse way to update a table with values form its own columns. All you need to do is one single update statement executed in the database: ``` UPDATE table SET field1 = function(params1), field2=function(params2), field3=function(params3), ...
Updating SQLite table with Python function using table columns as arguments
[ "", "python", "sqlite", "" ]
In the data I am working with the index is compound - i.e. it has both item name and a timestamp, e.g. `name@domain.com|2013-05-07 05:52:51 +0200`. I want to do hierarchical indexing, so that the same e-mails are grouped together, so I need to convert a DataFrame Index into a MultiIndex (e.g. for the entry above - `(n...
Once we have a DataFrame ``` import pandas as pd df = pd.read_csv("input.csv", index_col=0) # or from another source ``` and a function mapping each index to a tuple (below, it is for the example from this question) ``` def process_index(k): return tuple(k.split("|")) ``` we can create a hierarchical index in ...
In `pandas>=0.16.0`, we can use the `.str` accessor on indices. This makes the following possible: ``` df.index = pd.MultiIndex.from_tuples(df.index.str.split('|').tolist()) ``` (Note: I tried the more intuitive: `pd.MultiIndex.from_arrays(df.index.str.split('|'))` but for some reason that gives me errors.)
Converting Index into MultiIndex (hierarchical index) in Pandas
[ "", "python", "pandas", "" ]
I searched a lot, but didn't find a proper solution to my problem. What do I want to do? I have 2 tables in MySQL: - Country - Currency (I join them together via CountryCurrency --> due to many to many relationship) See this for a working example: <http://sqlfiddle.com/#!2/317d3/8/0> I want to link both tables toge...
You can do this with `substring_index()`. The following query uses yours as a subquery and then applies this logic: ``` select Name, ISOCode_2, substring_index(currencies, ',', 1) as Currency1, (case when numc >= 2 then substring_index(substring_index(currencies, ',', 2), ',', -1) end) as Currency2, ...
Use this query to work out the number of currency columns you'll need: ``` SELECT MAX(c) FROM ((SELECT count(currency.name) AS c FROM country INNER JOIN countryCurrency ON country.country_id = countryCurrency.country_id INNER JOIN currency ON currency.currency_id = countryCurrency.currency_id GROUP BY country.name) a...
SQL GROUP_CONCAT split in different columns
[ "", "mysql", "sql", "group-concat", "" ]
I have this possible values in a column ``` 1 65 5 excellent 54 -1 - . ``` If I use isnumeric with the last example I get 1, but when I try to convert to number I got an error. I want to use a try-catch in a function but I can't, how can I deal with this?
By the way, an even worse example is `'-.'`, which `isnumeric()` considers to be valid. My advice is to look for at least one digit in the value as well. Yucky, but: ``` isnumeric(val) and val like '%[0-9]%' ``` Note that `isnumeric()` also considers something in exponential notation to be valid. So `'8e4'` will tes...
I think you are looking for something like this: > select case isnumeric('a') when 1 then convert(int,'a') else null end
Catch exception with isnumeric in sql server
[ "", "sql", "sql-server", "" ]
I have the following code: ``` CASE WHEN (1+sum(x)/sum(y)) >=0 and (1+sum(x)/sum(y)) < 0.5 Then 1 ELSE 0 ``` x and y are columns. my problem is, `sum(y)` can be 0 and i get the error dividing by 0 is not possible. How can i catch up this error in the else clause. So that if `y = 0 "ELSE 0"` gets activated.
Maybe one more condition ? ``` CASE WHEN sum(y)=0 then 0 WHEN (1+sum(x)/sum(y)) >=0 and (1+sum(x)/sum(y)) < 0.5 Then 1 ELSE 0 END ```
Try to use expression `NullIf(sum(y), 0)` in place of `sum(y)`: ``` select CASE WHEN (1+sum(x)/NullIf(sum(y), 0)) >=0 and (1+sum(x)/NullIf(sum(y), 0)) < 0.5 Then 1 ELSE 0 END ``` [SQLFiddle](http://sqlfiddle.com/#!3/7a1ec/3) sample
0 division in a 'when else' environment
[ "", "sql", "sql-server", "t-sql", "" ]
I am thinking a transaction would help me in the following example but I could be wrong. What I am attempting to avoid is making 3 different calls to the database if I dont have too in the following scenerio.. I want to do the following: 1. select name, address from employee 2. select state from states 3. select erro...
If there is no relation between the tables you could do a kind of ``` Select [Your selected columns] From (select * from table1 where [conditon for table1]) t1 Inner join (select * from table2 where [condition for table2]) t2 on 1=1 Inner join (select * from table3 where [condition for table3]) t3 on 1=1 ``` This ma...
I think you can use `reader.NextResult()` to iterate through result sets. An example borrowed from [codeproject](http://www.codeproject.com/Articles/306722/Executing-multiple-SQL-statements-as-one-against-S#pre5): ``` connection.Open(); dataReader = command.ExecuteReader(); // a multi-select query while (loopResult) {...
Best Approach To Handle Multiple Select Statements In A Single Trip To The Database
[ "", ".net", "sql", "sql-server", "t-sql", "" ]
I have two variables as follows. ``` a = 2 b = 3 ``` I want to construct a DataFrame from this: ``` df2 = pd.DataFrame({'A':a, 'B':b}) ``` This generates an error: ``` ValueError: If using all scalar values, you must pass an index ``` I tried this also: ``` df2 = (pd.DataFrame({'a':a, 'b':b})).reset_index() ``` ...
The error message says that if you're passing scalar values, you have to pass an index. So you can either not use scalar values for the columns -- e.g. use a list: ``` >>> df = pd.DataFrame({'A': [a], 'B': [b]}) >>> df A B 0 2 3 ``` or use scalar values and pass an index: ``` >>> df = pd.DataFrame({'A': a, 'B'...
You may try wrapping your dictionary into a list: ``` my_dict = {'A':1,'B':2} pd.DataFrame([my_dict]) ``` ``` A B 0 1 2 ```
Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"
[ "", "python", "pandas", "dataframe", "valueerror", "scalar", "" ]
Does including an extra column in group by change the number of rows in the results ? I was doing a select query on a table A(col1,col2....col9) and I first included ``` select col1,col2,col3 from A where col1 = (condition) group by col1, col2, col3 ``` which yielded me certain number of results. now I changed th...
If the combination of col1, col2 and col3 is not unique, you can have more than one row with the same combination of those three. If that happens, *and* those duplicates have different values for col8 and/or col9, then grouping by those extra columns will result in more rows. Note that you can use `select distinct` t...
By grouping on those columns you are, in essence, making the results distinct on the grouped columns. So if there were rows that had columns 1, 2, 3, 18, and 19 in common, they would be folded together.
How does group by statement in SQL affect the results ?
[ "", "sql", "performance", "sql-server-2008", "" ]
The only way i could do this was: ``` var1 = list[0] var2 = list[1] var3 = list[2] var4 = list[3] ... ``` Is there a simpler way?
``` var1, var2, var3, var4 = l ``` This assumes `l` is exactly 4 elements long. Most of the time, you want that, but if you don't, ``` var1, var2, var3, var4 = l[:4] ``` will ignore extra elements.
``` var1, var2, var3, var4 = alist ``` The number of names should be as many as the length of list, or there will be an error. If you have no need to have all the variables, you can use a for loop.
What's the simplest way to assign list members to different variables?
[ "", "python", "" ]
I have a strong background in numeric compuation using FORTRAN and parallelization with OpenMP, which I found easy enough to use it on many problems. I switched to PYTHON since it much more fun (at least for me) to develop with, but parallelization for nummeric tasks seem much more tedious than with OpenMP. I'm often i...
While there is no general answer to your question (in the title), I think it is valid to say that `multiprocessing` alone is not the key for great number-crunching performance in Python. In principle however, Python (+ 3rd party modules) are awesome for number crunching. Find the right tools, you will be amazed. Most ...
Number crunching with Python... You probably should learn about [Cython](http://cython.org/). It is and intermediate language between Python and C. It is tightly interfaced with numpy and has support for paralellization using openMP as backend.
Is the multiprocessing module of python the right way to speed up large numeric calculations?
[ "", "python", "parallel-processing", "multiprocessing", "" ]
my study question is: Define a procedure, total\_enrollment, that takes as an input a list of elements, where each element is a list containing three elements: a university name, the total number of students enrolled, and the annual tuition fees. The procedure should return two numbers, not a string, giving the total ...
First of all, you can't return twice, change your code to this in order to return a tuple. Also I fixed your math for calculating total cost. You were multiplying total students by total cost, you want to calculate each university separately. Students at CalTech are going to pay $37704, not the total cost of all unive...
You can't return twice from a function. You can rather return both the values as `tuple`: ``` return total_students, all_in_all ``` And then unpack the return value in two variables. *E.g.:* ``` >>> def func(): ... return 1, 2 ... >>> v1, v2 = func() >>> v1 1 >>> v2 2 ```
Why does the code return wrong multiplication?
[ "", "python", "" ]
I'm running a FlaskApp using `mod_wsgi` and `apache2` on Ubuntu server. I tried running the flask app on `localhost` successfully and then deployed it on ubuntu server. But when i try to update database, its giving error: ``` Failed to update model. (OperationalError) attempt to write a readonly database u'UPDATE mys...
Resolved the issue. It was due to database file permission conflict.
This issue is related to the files permissions management AND mostly to the user chosen in the Apache configuration file (`*.conf`) defined to holds the application processes. In a few words : the **write permissions** need to match this user. Most of the time, the sqlite database file has been created by a specific u...
OperationalError: attempt to write a readonly database in ubuntu server
[ "", "python", "apache", "ubuntu", "flask", "mod-wsgi", "" ]
I have upgraded from django 1.2.7 to django 1.5.1 I am using python 2.6.6 When i try to run `python manage.py collectstatic` i get > Unknown command: 'collectstatic' from my settings.py ``` STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finde...
I had a similar error message, but despite my suspicions, it had nothing to do with the Django update. If you have an error in settings (I had an empty SECRET\_KEY value), then "django" will be the only app that gets loaded. I found the root of the problem by running `python manage.py shell` and that quickly told me wh...
For those coming here from google, I resolved it through adding ``` 'django.contrib.staticfiles', ``` to `INSTALLED_APPS`
Django admin.py Unknown command: 'collectstatic'
[ "", "python", "django", "" ]
I have a list of 3D-points for which I calculate a plane by numpy.linalg.lstsq - method. But Now I want to do a orthogonal projection for each point into this plane, but I can't find my mistake: ``` from numpy.linalg import lstsq def VecProduct(vek1, vek2): return (vek1[0]*vek2[0] + vek1[1]*vek2[1] + vek1[2]*vek2...
You are doing a very poor use of `np.lstsq`, since you are feeding it a precomputed 3x3 matrix, instead of letting it do the job. I would do it like this: ``` import numpy as np def calc_plane(x, y, z): a = np.column_stack((x, y, np.ones_like(x))) return np.linalg.lstsq(a, z)[0] >>> x = np.random.rand(1000) ...
You can simply do everything in matrices is one option. If you add your points as row vectors to a matrix `X`, and `y` is a vector, then the parameters vector `beta` for the least squares solution are: ``` import numpy as np beta = np.linalg.inv(X.T.dot(X)).dot(X.T.dot(y)) ``` but there's an easier way, if we want ...
orthogonal projection with numpy
[ "", "python", "arrays", "numpy", "" ]
I have a class: ``` class DatabaseThing(): def __init__(self, dbName, user, password): self.connection = ibm_db_dbi.connect(dbName, user, password) ``` I want to test this class but with a test database. So in my test class I am doing something like this: ``` import sqlite3 as lite import unittest fro...
Instead of mocking, you could simply subclass the database class and test against that: ``` class TestingDatabaseThing(DatabaseThing): def __init__(self, connection): self.connection = connection ``` and instantiate **that** class instead of `DatabaseThing` for your tests. The methods are still the sam...
If you want to return a mock when you initialize a class, mock out the\_\_new\_\_ method, not **init**. **new** makes the new instance and **init** initializes it, but can only return None. If you mock **new**, it can return a mock you can assert on to simulate instance creation in the test. ``` @mock.patch('Car.__n...
Mocking __init__() for unittesting
[ "", "python", "sqlite", "unit-testing", "mocking", "" ]
i'm making a query in mysql but i have a problem: this is my column structure ``` |country| -------- Boston -------- Chicago -------- washington ``` The thing is i may have a search item like: ``` North Washington Boston Easht South Chicago ``` So i'm trying to match it using the %like% operador like that: ``` sel...
**`IN` method** Use comma separated list of your search query: ``` SELECT * FROM am_ciudad WHERE Ciu_Nombre IN('North', 'Washington', ...) ``` **`REGEXP` method** I can imagine the `REGEXP` will be slower, but I haven't benchmarked it. ``` SELECT * FROM am_ciudad WHERE Ciu_Nombre REGEXP(North|Washington|...) ```
Your other searches won't match because they do not exist. If you want to match Boston in the phrase I love Boston Red Sox then you would need to use `...LIKE '%Boston%';` the %s are wild cards so using them before and after the word you are tying to match tell the query that you don't care what come before and after....
MySQL search match at least one word on query string
[ "", "mysql", "sql", "" ]
I got 1000 rows in my data-table `dt` and I want to insert all this data to my sql table in one shot.I know how to do this with a for loop..but I wonder is there any other better way to do this all rows to datatbase in single shot. My current code to insert this data is like this ``` DataTable dt = result.Tables[0]; ...
You can do this by leveraging the `SqlBulkCopy` class. In short, get a `SqlConnection` created and opened and then use this code to copy that in bulk from the `DataTable` to the server. ``` using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn)) { bulkCopy.DestinationTableName = "tbl_Projects"; bulkCopy.WriteT...
You could also use a table type parameter and pass an entire dataset from C# to the SQL Server. See this question: [INSERT using LIST into Stored Procedure](https://stackoverflow.com/questions/17487299/insert-using-list-into-stored-procedure/17487572#comment25416816_17487572)
Insert multiple rows in SQL as sqlparameter
[ "", "sql", "sql-server-2008", "" ]
I have two pandas data frames, which look like this: ``` import pandas as pd df_one = pd.DataFrame( { 'A': [1,1,2,3,4,4,4], 'B1': [0.5,0.0,0.2,0.1,0.3,0.2,0.1], 'B2': [0.2,0.3,0.1,0.5,0.3,0.1,0.2], 'B3': [0.1,0.2,0.0,0.9,0.0,0.3,0.5]} ); df_two = pd.DataFrame( { 'A': [1,2,3,4], 'C1': [1.0,9.0,...
Not sure if you want unique values for column A (If you do, use groupby on the result below) ``` pd.merge(df_one, df_two, on='A') A B1 B2 B3 C1 C2 C3 0 1 0.5 0.2 0.1 1.0 2.0 5.0 1 1 0.0 0.3 0.2 1.0 2.0 5.0 2 2 0.2 0.1 0.0 9.0 3.0 4.0 3 3 0.1 0.5 0.9 2.1 0.7 2.3 4 4 0.3 0.3...
Another approach would be something similar to this: ``` import pandas as pd df_one = pd.DataFrame( { 'A': [1,1,2,3,4,4,4], 'B1': [0.5,0.0,0.2,0.1,0.3,0.2,0.1], 'B2': [0.2,0.3,0.1,0.5,0.3,0.1,0.2], 'B3': [0.1,0.2,0.0,0.9,0.0,0.3,0.5]} ); df_two = pd.DataFrame( { 'A': [1,2,3,4], 'C1': [1.0,9.0,...
numpy/pandas effective multiplication of arrays/dataframes
[ "", "python", "numpy", "pandas", "" ]
Say, for example, I want to know whether the pattern "\section" is in the text "abcd\sectiondefghi". Of course, I can do this: ``` import re motif = r"\\section" txt = r"abcd\sectiondefghi" pattern = re.compile(motif) print pattern.findall(txt) ``` That will give me what I want. However, each time I want to find a n...
Use [`re.escape()`](http://docs.python.org/2/library/re.html#re.escape) to make sure input text is treated as literal text in a regular expression: ``` pattern = re.compile(re.escape(motif)) ``` Demo: ``` >>> import re >>> motif = r"\section" >>> txt = r"abcd\sectiondefghi" >>> pattern = re.compile(re.escape(motif))...
One way to do this is using an argument parser, like [`optparse`](http://docs.python.org/2/library/optparse.html) or [`argparse`](http://docs.python.org/2/library/argparse.html#module-argparse). Your code would look something like this: ``` import re from optparse import OptionParser parser = OptionParser() parser.a...
Convert command line arguments to regular expression
[ "", "python", "regex", "shell", "" ]
I'm looking for a Python 3.x library that is able to allow interaction with other programs. For example, I already have some sort of command-line interface which I have developed in python, and I want to be able to enter, say "1", and have another program open. From here, I wish to hit another input like "2" and have i...
You could look into [sikuli](http://doc.sikuli.org/). It lets you automate clicks and other actions based on region or matched graphic. Fairly smart. Is there a reason you're dead set on using py3?
Py3-compatible pywinauto released! New home page: <http://pywinauto.github.io/> P.S. I'm maintainer of pywinauto.
Python 3.x Interaction with other Program GUIs
[ "", "python", "user-interface", "pywinauto", "" ]
I'm remaking my battleship game, and I have a constant variable called SEA which holds an empty board. However, the variable is being modified, and I don't know why (or where). I suspect it's being passed by reference to player\_board and when player\_board is modified, so is SEA. How do I stop that from happening? Her...
`SEA` and its members are lists, and lists in Python are mutable. When you say `player_radar = SEA`, etc., you're not making a copy of `SEA`; you're making a new reference to it. Any changes you then make to `player_radar` will be reflected in `SEA`. [`copy.deepcopy`](http://docs.python.org/2/library/copy.html) is oft...
SEA is a list, so make a copies of it: ``` player_radar = SEA[:] player_board = SEA[:] ai_radar = SEA[:] ai_board = SEA[:] ``` or deeper copies of it, if you need to. EDIT: By "deeper copies", I mean that if your list contains, for instance, other lists, then just making a top level copy will create a new list, but ...
Constant Variable is being changed
[ "", "python", "" ]
I want to import .sql file in Oracle by command prompt so please tell me that command to import .sql file in oracle in MYSQL I am using it like this ``` mysql -u root -p -h localhost softpoint < D:\Nisarg\NEult\softpoint.sql ``` but In Oracle I don't know how to use this utility so please help me Thanks
In Oracle, to run a script (*.sql) you use [SQL](http://docs.oracle.com/cd/E11882_01/server.112/e16604/ch_five.htm#sthref434)*PLUS command line utility. ``` c:\> sqlplus user_name/user_password@connect_string @path\your_sql.sql ```
Try to use `sqlplus`: ``` sqlplus user/password@connect @/Nisarg/NEult/softpoint.sql ``` [More information.](http://www.techonthenet.com/oracle/questions/script.php)
Oracle Database import .sql file by command prompt
[ "", "sql", "oracle", "oracle11g", "oracle10g", "oracle-sqldeveloper", "" ]
I have a string like `'$200,000,000'` or `'Yan300,000,000'` I want to split the currency and number, and output a tuple `('$', '200000000')`, without `','` in the number string. Currently I'm using the following script, which is working: ``` def splitCurrency(cur_str): cuttingIdx = 0 for char in cur_str: ...
``` >>> import re >>> string = 'YAN300,000,000' >>> match = re.search(r'([\D]+)([\d,]+)', string) >>> output = (match.group(1), match.group(2).replace(',','')) >>> output ('YAN', '300000000') ```
``` >>> filter(str.isdigit, s) '200000000' >>> filter(lambda x: not x.isdigit() and x != ',', s) '$' >>> >>> (filter(lambda x: not x.isdigit() and x != ',' ,s), filter(str.isdigit, s)) ('$', '200000000') >>> ```
How to efficiently split currency sign and number in one string without using a for loop or try statement
[ "", "python", "algorithm", "performance", "" ]
I'd like to know the simplest way to bind keys in python for example, the default python console window apears and waits, then in psuedo -> ``` if key "Y" is pressed: print ("Yes") if key "N" is pressed: print ("No") ``` I would like to achieve this **without** the use of any **modules** not included by python...
From <http://code.activestate.com/recipes/134892/> (although a bit simplified): ``` class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def...
Well, the way to do it with Tkinter which is a module included in the python install is here: ``` from tkinter import * window = Tk() window.geometry("600x400") window.title("Test") def test(event): print("Hi") window.bind("a", test) window.mainloop() ```
Python key binding/capture
[ "", "python", "python-2.7", "python-3.x", "keyboard", "" ]
I am solving few sql queries myself, in a question , which says > Find the largest country (by area) in each continent, show the continent, the name and the area: ``` SELECT continent, name, area FROM world x WHERE area >= ALL (SELECT area FROM world y WHERE y.continent=x.continent AND area...
x and y are aliases. it allows you to identify the table in "WHERE y.continent=x.continent"
x and y are used as aliases (a short alternative name for reference purposes) of the table. This allows the use of the world table in two different scopes.
Regarding use of a query
[ "", "sql", "" ]
I've got a numpy array with shape 1001, 2663. Array contains values of 12 and 127, now I would like to count the number of a specific value, in this case 12. So I try using bincount, but that's doing strange. See what I get: ``` >>> x.shape (1001, 2663) >>> np.bincount(x) Traceback (most recent call last): File "<in...
You want the number of occurrences of a simple `number` in your `data` array? Try ``` np.bincount(data)[number] ```
`bincount` returns an array where the frequency of `x` is `bincount[x]`, It requires a flat input so you can use `bincount(array.ravel())` to handle cases when `array` might not be flat. If your array only has a few unique values, ie 2 and 127, it might be worth reducing the array using unique before calling bincount ...
How to get the frequency of a specific value in a numpy array
[ "", "python", "numpy", "" ]
I have a table like so ``` ID Node ParentID 1 A 0 2 B 1 3 C 1 4 D 2 5 E 2 6 F...
``` Select Id, Node, ParentID, Dense_Rank() Over(Order by ParentID) as Level from Table_Name ``` [**SQL Fiddle Demo**](http://sqlfiddle.com/#!3/88877c/1)
Something like: ``` ;with tree (ID, ParentID, Level) as ( select ID, ParentID, 1 from TableName where ParentID = 0 union all select t.ID, t.ParentID, 1 + tree.Level from Tree join TableName t on t.ParentID = Tree.ID ) select ID, Level from Tree ```
Need a query to insert 'level' into an adjacent list
[ "", "sql", "sql-server", "" ]
I'm maintaining someone else's SQL at the moment, and I came across this in a Stored Procedure: ``` SELECT Location.ID, Location.Location, COUNT(Person.ID) As CountAdultMales FROM Transactions INNER JOIN Location ON Transactions.FKLocationID = Location.ID INNER JOIN Perso...
Performance is the same in your examples, however you can tune it this way: ``` SELECT Location.ID, Location.Location, COUNT(Person.ID) As CountAdultMales FROM Transactions INNER JOIN Location ON Transactions.FKLocationID = Location.ID INNER JOIN Person ON Transactions.FKPersonID = Person.ID WHERE...
With an `inner join` this wont really make much of a difference as SQL has a query optimiser which will do its best to excecute the query in the most efficiant way (not perfect). If this was an `outer join` it could make a difference though so its something to be aware of
Is there any performance or functional difference between these two SQL statements?
[ "", "sql", "sql-server", "" ]
I have a csv cell value, `row[13]` that contains the following text: `POINT (174.29635 -41.60557)` I need to strip out the text and brackets, and convert the two numbers to float, each assigned to a var:- ``` geo_pair = row[13].replace("POINT (", "") geo_pair = geo_pair.replace(")", "") self.longitude, self.latitude ...
Since the format is fixed and consists of prefix, data, and suffix, I would use slicing to remove prefix and suffix: `map(float, s[7:-1].split())`. This is clear and simple at the same time: ``` >>> s = "POINT (174.29635 -41.60557)" >>> longitude, latitude = map(float, s[7:-1].split()) ``` This also works upon sign ...
Use the regex? ``` >>> map(float, re.search(r'\((.*)\)', s).group(1).split()) [174.29635, -41.60557] >>> ```
most Pythonic way of achieveing these 4 lines?
[ "", "python", "text", "" ]
I have two tables - 'Users' and 'Supervision' For this example, my users table is very simple:- ``` Users ===== ID (PK) UserName ``` Some users manage other users, so I've built a second table 'Supervision' to manage this:- ``` Supervision =========== UserID SuperID - this is the ID of the staff member that the use...
You should use [recursive CTE](http://msdn.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx): ``` WITH RCTE AS ( SELECT * FROM dbo.Supervision WHERE UserID = 1 UNION ALL SELECT s.* FROM dbo.Supervision s INNER JOIN RCTE r ON s.userID = r.superID ) SELECT DISTINCT u.userID, u.userName FRO...
Sounds to me like you need a Recursive CTE. This article serves as a primer, and includes a fairly similar example to the one you have: <http://blog.sqlauthority.com/2012/04/24/sql-server-introduction-to-hierarchical-query-using-a-recursive-cte-a-primer/> Hope it helps.
SQL Query to display heirarchical data
[ "", "sql", "t-sql", "recursive-query", "" ]
`class` `Foo`: ``` class Foo(): def __init__(self): del self.foo def foo(self): pass ``` when instantiated `raise`s `AttributeError: Foo instance has no attribute 'foo'`. Deriving `Foo` from `object` (`class Foo(object)`) `raise`s `AttributeError: 'Foo' object attribute 'foo' is read-only`. U...
``` class Foo(object): def __init__(self): self.foo = None # This masks the foo method on the instance `self` def foo(self): pass foo = Foo() print(foo.foo) # None print(foo.foo()) # TypeError: 'NoneType' object is not callable ``` However, are you sure you want this design? Perhaps instead ...
The problem is that what you're trying to delete is a method, and methods aren't stored on the instance, they're stored on the class. So your instance `Foo()` doesn't really have an attribute `foo`. When you do `Foo().foo`, it finds the `foo` on `Foo`. So there's nothing to delete on `self`, because the attribute isn'...
How to delete class attributes defined outside the __init__ from within __init__?
[ "", "python", "attributes", "" ]
Let's say I have a string of the following form: ``` "000000111100011100001011000000001111" ``` and I want to create a list containing the lengths of the 1-streaks: ``` [4, 3, 1, 2, 4] ``` Is there a nice one-liner for this?
If you don't mind the `from itertools import groupby`... ``` >>> from itertools import groupby >>> [len(list(g)) for k, g in groupby(s) if k == '1'] [4, 3, 1, 2, 4] ```
Can be done with regex, though not quite as elegant as the itertools solutions ``` answer = [len(item) for item in filter(None, re.split(r"[^1]+", test_string))] ``` Or, more elegant: ``` answer = [len(item) for item in re.findall(r"1+", test_string)] ``` and more elegant still (credits to Jon): ``` answer = map(l...
Replacing a string with counts of streaks
[ "", "python", "string", "list", "" ]
I am working in access and utilizing VBA to make queries in wich I have variable names, so I can't use the query wizard in access I have the following 2 tables: ``` tblKabelInfo ``` And a table with a name that varies depending on something else in my program ``` tblName1 as String ``` the tables look like this: ...
It seems the basic challenge here is to identify the digits in `tblName1.Filename` which can then be used to join with `tblKabelInfo.Kabelnummer`. If those digits are always the first 4 of the last 8 characters of the string, you can use `Right` and `Left`, which are compatible with Access SQL, to get them easily. He...
Have a try with this ``` INSERT INTO tableNew SELECT B.Filename, A.Kabelnummer, B.bla, B.databla, A.data, A.[more data], A.[even more] FROM tblKabelInfo A INNER JOIN tblName1 B ON A.Kabelnummer=CAST(RIGHT(SUBSTRING( B.Filename,1,LEN(SUBSTRING( B.Filename, 0, PATINDEX('%.%', B...
Creating a table with data from 2 other tables
[ "", "sql", "ms-access", "vba", "" ]
I am using SQL Server 2008 and I need help in writing a query that compares two consecutive records. ``` select recordDate from SiteHistory where siteId = 556145 and isRecent = 0 and isRunning = 1 order by recordDate DESC ``` Gives me around 2000 rows that looks like this: ``` recordDate ---------------...
Logic of your query is correct, only thing its trying to get date difference in month change it to minutes in ``` datediff(minute, t1.RecordDate, t2.RecordDate) > 15 ``` Query: ``` ;with temp as( select row_number()over(order by recordDate DESC)as 'row', recordDate from SiteHistory where siteId = ...
"mm" gives you the date difference in *months* ``` where DATEDIFF(mm,t1.recordDate,t2.recordDate)>15 ``` Replace "mm" with "minute" ``` where DATEDIFF(minute,t1.recordDate,t2.recordDate)>15 ```
Trying to compare two consecutive records
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have written the following script to concatenate all the files in the directory into one single file. Can this be optimized, in terms of 1. idiomatic python 2. time Here is the snippet: ``` import time, glob outfilename = 'all_' + str((int(time.time()))) + ".txt" filenames = glob.glob('*.txt') with open(outfil...
Use [`shutil.copyfileobj`](http://docs.python.org/2/library/shutil.html#shutil.copyfileobj) to copy data: ``` import shutil with open(outfilename, 'wb') as outfile: for filename in glob.glob('*.txt'): if filename == outfilename: # don't want to copy the output into the output conti...
Using Python 2.7, I did some "benchmark" testing of ``` outfile.write(infile.read()) ``` vs ``` shutil.copyfileobj(readfile, outfile) ``` I iterated over 20 .txt files ranging in size from 63 MB to 313 MB with a joint file size of ~ 2.6 GB. In both methods, normal read mode performed better than binary read mode an...
python script to concatenate all the files in the directory into one file
[ "", "python", "file", "copy", "" ]
I have a list with 2,500 items. I want to print the first 50 items in a line and the next 50 items in the next line. So there will be a total of 50 lines with 50 items in each line. ``` myList = ['item1', item2,..., 'item2500'] line1 = item1, item2, ..., item50 line2 = item51, item52,...., item100 . . line 50 = item...
If you want to just print the list with next 50 items on the next line: ``` for i in range(0, len(myList), 50): print myList[i:i+50] ``` If you want to make a list of lists with 50-len chunks: ``` [myList[i:i+50] for i in range(0, len(myList), 50)] ```
Same thing really, but looks nicer and reusable chunks function as a generator, I think. ``` def chunks_of_n(l,n): for i in xrange(0, len(l), n): yield l[i:i+n] def show_my_list_in_chunks(l): for chunk in chunks_of_n(l,50): print ', '.join(l) ```
Print item from list in chunks of 50 in Python
[ "", "python", "list", "" ]
I had to write a script that generates some fixture file with increasing fake MAC addresses. To do that, I decided to have some fun and try to make it as compact as I could. I ended up with: ``` def mac_address(i): return ':'.join(['%02x'] * 6) % tuple([(i >> (8 * j)) & 0xFF for j in reversed(range(6))]) ``` Whi...
What about ``` ':'.join('%02x' % (i>>(8*j) & 0xFF) for j in reversed(range(6))) ``` That is more compact *and* easier to understand.
``` def mac_address(i): return ':'.join(a+b for a, b in zip(*[iter('{:012x}'.format(i))]*2)) ``` The first step is to get a hex string zero filled so that it is exactly 12 digits, which is what `'{:012x}'.format(i)` does. Then we break that string up in two-character chunks using the method of grouping items from ...
Is there any more compact way of writing that statement?
[ "", "python", "maintainability", "" ]
I have the following table in my sql server 2008 database: ``` MsgID TrackerId MsgContent 1 123 red //MsgContent corresponding to colour 2 123 E2120 //MsgContent corresponding to model 5 123 sam //MsgContent corresponding to password 1 111...
Here's a version using `PIVOT`. My only problem with this is the unnecessary aggregate function. I don't know your table definition, but if you have only the columns MsgID, TrackerID, MsgContent, then the CTE that selects the grouping, spreading, and aggregation columns to pivot is superfluous. If you do have more colu...
You can do this by joining the table to itself based on `TrackerID` and filter by `MsgID`. Example: ``` SELECT Colour.TrackerId, Colour.MsgContent AS Colour, Model.MsgContent AS Model, Password.MsgContent AS Password FROM MyTable Colour JOIN MyTable Model ON Colour.TrackerId = Model.TrackerId A...
How to fetch rows by applying multiple filtres to a single column in sql server 2008?
[ "", "sql", "sql-server", "" ]
``` ID GROUP NAME 1 1,2, Supreeth 2 1,2,5, Aishu 3 3, Arvi 4 4,5, Gani 5 4,3,2, Jyo 6 3,2,1, Upi 7 2,3,4,1,5, Savi ``` I have table like this, I'm trying to get the count of group ``` DECODE Count 1 A 4 2 B 5 3 C 4 4 D ...
This solution might not be good, or flexible as it depends on hard coded values but it achieves the desired output as described in the question: ``` SELECT 1 AS [Num], 'A' AS Decode, COUNT(*) AS [Count] FROM my_table WHERE [Group] LIKE '%1%' UNION SELECT 2 AS [Num], 'B' AS Decode, COUNT(*) AS [Count] FROM my_table WHE...
One simple minded (not necessarily efficient) approach is to obtain the separate counts for each of the group values. Note that the column name `Group` is using a reserved word, so you have to use an appropriate delimited identifier notation. When you use the portable (SQL standard) double quotes, you have to get the c...
how to get the count of GROUP
[ "", "sql", "" ]
A and B of table T3 are the same as A and B from T1. Basically what I need to do is select all the values that aren't on T3. If there is a line with A,B on T3 I don't wanna show it. ``` SELECT T1.A, T1.B, T1.C FROM T1, T2 WHERE T1.X=T2.X AND NOT EXISTS ( SELECT T3.A, T3.B FROM T3 ) ``` Any help? Thanks
``` SELECT T1.A, T1.B, T1.C FROM T1 INNER JOIN T2 ON T1.X=T2.X WHERE NOT EXISTS ( SELECT 1 FROM T3 WHERE T3.A = T1.A AND T3.B = T1.B ) ```
``` select T1.A,T1.B,T1.C from T1 inner join T2 on T1.X=T2.X left join T3 on T1.A=T3.A and T1.B=T3.B where T3.A is null ```
Select rows where some values are not in other table
[ "", "sql", "oracle", "" ]
In python I usually loop through ranges simply by ``` for i in range(100): #do something ``` but now I want to skip a few steps in the loop. More specifically, I want something like `continue(10)` so that it would skip the whole loop and increase the counter by 10. If I were using a for loop in C I'd just sum 10...
You cannot alter the target list (`i` in this case) of a `for` loop. Use a `while` loop instead: ``` while i < 10: i += 1 if i == 2: i += 3 ``` Alternatively, use an iterable and increment that: ``` from itertools import islice numbers = iter(range(10)) for i in numbers: if i == 2: next(...
The best way is to assign the iterator a name - it is common have an iterable as opposed to an iterator (the difference being an iterable - for example a list - starts from the beginning each time you iterate over it). In this case, just use [the `iter()` built-in function](http://docs.python.org/3.3/library/functions....
How do I skip a few iterations in a for loop
[ "", "python", "loops", "" ]
I have data in following format. ``` match_id team_id won_ind ---------------------------- 37 Team1 N 67 Team1 Y 98 Team1 N 109 Team1 N 158 Team1 Y 162 Team1 Y 177 Team1 Y 188 Team1 Y 198 Team1 N 207 Team1...
``` with original_data as ( select 37 match_id, 'Team1' team_id, 'N' won_id from dual union all select 67 match_id, 'Team1' team_id, 'Y' won_id from dual union all select 98 match_id, 'Team1' team_id, 'N' won_id from dual union all select 109 match_id, 'Team1' team_id, 'N' won_id from dual union all select...
This should work, Fiddle here: <http://sqlfiddle.com/#!4/31f95/27> ``` SELECT team_id, MAX(seq_length) AS longest_sequence FROM (SELECT team_id, COUNT(*) AS seq_length FROM (SELECT team_id, won_ind,match_id, SUM(new_group) OVER(ORDER BY match_id) AS group_no FROM (SE...
Finding the longest streak of wins
[ "", "sql", "oracle", "oracle11gr2", "" ]
Usually when one has to search in oracle for a single where condition where you don't know the exact condition we use : ``` Select * from Table where column like '%Val%' ``` If I have to run check for multiple condition we use `IN` ``` Select * from Table where column in ('Value1','ABC2') ``` How we combine the two...
``` Select * from Table where column like '%Val%' or column like '%AB%'; ```
``` Select * from Table where column like '%Val%' or column like '%AB%'..... ``` I know its little hard to write you can create a vertical list and change \n and \r by '% and %' respectively.
using % is IN condition
[ "", "sql", "oracle", "plsql", "sql-in", "" ]
``` import pandas as pd date_stngs = ('2008-12-20','2008-12-21','2008-12-22','2008-12-23') a = pd.Series(range(4),index = (range(4))) for idx, date in enumerate(date_stngs): a[idx]= pd.to_datetime(date) ``` This code bit produces error: > TypeError:" 'int' object is not iterable" Can anyone tell me how to get ...
``` >>> import pandas as pd >>> date_stngs = ('2008-12-20','2008-12-21','2008-12-22','2008-12-23') >>> a = pd.Series([pd.to_datetime(date) for date in date_stngs]) >>> a 0 2008-12-20 00:00:00 1 2008-12-21 00:00:00 2 2008-12-22 00:00:00 3 2008-12-23 00:00:00 ``` **UPDATE** Use pandas.to\_datetime(pd.Series...
``` In [46]: pd.to_datetime(pd.Series(date_stngs)) Out[46]: 0 2008-12-20 00:00:00 1 2008-12-21 00:00:00 2 2008-12-22 00:00:00 3 2008-12-23 00:00:00 dtype: datetime64[ns] ``` ## Update: benchmark ``` In [43]: dates = [(dt.datetime(1960, 1, 1)+dt.timedelta(days=i)).date().isoformat() for i in range(20000)] In...
In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame?
[ "", "python", "datetime", "pandas", "" ]
Is there a way for `TextInput`s to receive a bounded string value (i.e., string of maximum length, x)? I tried investigating how to mixin `AliasProperty` in order to mimic `BoundedNumericProperty`, but can't find any Property class methods.
By the time `on_text` is called text is already changed in the textinput. You want to override [insert\_text](http://kivy.org/docs/api-kivy.uix.textinput.html#kivy.uix.textinput.TextInput.insert_text) to catch the text before it is inserted into the TextInput and thus before the [text](http://kivy.org/docs/api-kivy.uix...
I think that the event `on_text` is triggered each time you modify the text. So you can override the method: ``` def on_text(self, instance, value): print('The widget', instance, 'have:', value) # validate here!!! # you might also want to call the parent. #super(ClassName, self).on_text(instance, val...
Kivy: Is there a "BoundedString" property available for TextInputs?
[ "", "python", "kivy", "" ]
I have a query inside a stored procedure that sums some values inside a table: ``` SELECT SUM(columnA) FROM my_table WHERE columnB = 1 INTO res; ``` After this select I subtract `res` value with an integer retrieved by another query and return the result. If `WHERE` clause is verified, all works fine. But if it's not...
You could: ``` SELECT COALESCE(SUM(columnA), 0) FROM my_table WHERE columnB = 1 INTO res; ``` This happens to work, because your query has an aggregate function and consequently *always* returns a row, even if nothing is found in the underlying table. Plain queries without aggregate would return ***no row*** in such...
I'm not familiar with postgresql, but in SQL Server or Oracle, using a subquery would work like below (in Oracle, the `SELECT 0` would be `SELECT 0 FROM DUAL`) ``` SELECT SUM(sub.value) FROM ( SELECT SUM(columnA) as value FROM my_table WHERE columnB = 1 UNION SELECT 0 as value ) sub ``` Maybe this would work...
Return zero if no record is found
[ "", "sql", "postgresql", "null", "plpgsql", "coalesce", "" ]
I am trying to insert a question in database with field in table as nvarchar(max) (sql server 2008 r2) Code is as follows: ``` Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click gc.ExecuteCommand("insert into QuestionMaster values('" & txtQuestion.Text & "','" &...
You could **escape single quote by replacing single quote (') with two single quotes ('')** in the txtQuestion.Text. ``` Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click gc.ExecuteCommand("insert into QuestionMaster values('" & txtQuestion.Text.Replace("'", "''...
You should be using parameterised queries if possible since simple string insertion directly into a query will, as you have seen, possibly corrupt the query. In other words, if the text box contains `Paddy O'Rourke`, your query becomes: ``` open close what the ? ...
string with 's not getting inserted with insert statement
[ "", "asp.net", ".net", "sql", "vb.net", "" ]
I am using the following code for creating the Comma Delimited List. I wanted the sequence of the list in particular order: ``` USE AdventureWorks GO DECLARE @listStr VARCHAR(MAX) SELECT @listStr = COALESCE(@listStr+',' ,'') + Name FROM Production.Product SELECT @listStr GO ``` When I tried like ``` USE AdventureWo...
Use [STUFF](http://msdn.microsoft.com/en-us/library/ms188043.aspx)() Which gives you the same comma seperated result ``` USE AdventureWorks GO DECLARE @listStr VARCHAR(MAX) SELECT @listStr = STUFF((SELECT ',' + Name FROM Production.Product ORDER BY sortOrder FOR XML PATH('')), 1, 1, ''...
I don't believe you can put an order by when getting a scalar value. And you should not need it since you are expecting only one value.
ORDER BY in Comma Delimited List Using SELECT Clause
[ "", "sql", "sql-server", "sql-order-by", "csv", "" ]
So I'm parsing a really big log file with some embedded json. So I'll see lines like this `foo="{my_object:foo, bar:baz}" a=b c=d` The problem is that since the internal json can have spaces, but outside of the JSON, spaces act as tuple delimiters (except where they have unquoted strings . Huzzah for whatever idiot ...
Found a really cool answer. Use json.JSONDecoder's scan\_once function ``` In [30]: import json In [31]: d = json.JSONDecoder() In [32]: my_string = 'key="{"foo":"bar"}"more_gibberish' In [33]: d.scan_once(my_string, 5) Out[33]: ({u'foo': u'bar'}, 18) In [37]: my_string[18:] Out[37]: '"more_gibberish' ``` Just be...
Match everything around it. ``` >>> re.search('^foo="(.*)" a=.+ c=.+$', 'foo="{my_object:foo, bar:baz}" a=b c=d').group(1) '{my_object:foo, bar:baz}' ```
In python, is there a way to extract a embedded json string?
[ "", "python", "json", "" ]
My function (name CovexHull(point)) accepts the argument as a two-dimensional array: ``` hull = ConvexHull(points) ``` ### Session ``` In [1]: points.ndim Out[1]: 2 In [2]: points.shape Out[2]: (10, 2) In [3]: points Out[3]: array([[ 0. , 0. ], [ 1. , 0.8], [ 0.9, 0.8], [ 0.9, 0.7], [...
If you wish to combine two 10 element one-dimensional arrays into a two-dimensional array, `np.vstack((tp, fp)).T` will do it. `np.vstack((tp, fp))` will return an array of shape (2, 10), and the `T` attribute returns the transposed array with shape (10, 2) (i.e., with the two one-dimensional arrays forming columns ra...
You can use NumPy's [column\_stack](https://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html): ``` np.column_stack((tp, fp)) ```
Create a two-dimensional array with two one-dimensional arrays
[ "", "python", "arrays", "numpy", "" ]
I am trying to translate a piece of code I wrote from Python to Lua. I am using this code inside of compositing package Blackmagic Fusion. Any help would be greatly appreciated! Python script (working): ``` try: comp.ActiveTool() # checks if a tool is selected except: print("nothin...
Lua's exception handling works a bit differently than in other languages. Instead of wrapping code in try/catch statements, you instead run a function in a 'protected environment' with `pcall`. The general syntax for pcall is: ``` local ok, err = pcall(myfunc, arg1, arg2, ...) if not ok then print("The error mess...
You aren't using pcall correctly. you need to pass it the function you actually want called, and it'll call it in a protected mode where it can trap errors. pcall returns 2 values, a bool indicating if the call succeeded or not, and an error code if the call did not succeed. your lua code should look more something l...
How to translate a Python script to Lua script?
[ "", "python", "error-handling", "lua", "try-catch", "blackmagic-fusion", "" ]
Currently, I have created a code that makes graphs from data in .csv files. However, I can only run the code if that code is present in the folder with the csv files. How can I make the the script file so that it doesn't have to be in the same directory as the .csv files. Also, I would like that same script to read eve...
just set `directory="/path/to/fldr/with/csv"` and `full_name = os.path.join(directory,files)`
Yes, it is wrong; you'll need to accept a argument that tells your script where to find the CSV files: ``` import argparse def import_function(sourcedir): for filename in os.listdir(sourcedir): csvfilename = os.path.join(sourcedir, filename) with open(csvfilename) as csvfile: reader = ...
A Script that can run in any directory
[ "", "python", "" ]
I'm trying to find the minimum array indices along one dimension of a very large 2D numpy array. I'm finding that this is very slow (already tried speeding it up with bottleneck, which was only a minimal improvement). However, taking the straight minimum appears to be an order of magnitude faster: ``` import numpy as ...
``` In [1]: import numpy as np In [2]: a = np.random.rand(3000, 16000) In [3]: %timeit a.min(axis=0) 1 loops, best of 3: 421 ms per loop In [4]: %timeit a.argmin(axis=0) 1 loops, best of 3: 1.95 s per loop In [5]: %timeit a.min(axis=1) 1 loops, best of 3: 302 ms per loop In [6]: %timeit a.argmin(axis=1) 1 loops, b...
I just took a look at [the source code](https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/calculation.c#L153), and while I don't fully understand why things are being done the way they are, this is what happens: 1. `np.min` is basically a call to `np.minimum.reduce`. 2. `np.argmin` first moves the a...
Is there a way to make numpy.argmin() as fast as min()?
[ "", "python", "arrays", "numpy", "min", "" ]
I've just started to use Django and I haven't found a lot of info on how to display an `imageField`, so I made this: models.py: ``` class Car(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=5, decimal_places=2) photo = models.ImageField(upload_to='site_media')...
An `ImageField` contains a `url` attribute, which you can use in your templates to render the proper HTML. ``` {% block content %} <img src="{{ carx.photo.url }}"> {% endblock %} ```
You can also make use of the Static URL in Settings.py. Make a directory for example "Uploads", in the Static directory of your app. Also change this in your model in `models.py`. Use the following code: ``` <img src="{% static carx.photo.url %}" /> ```
Django - Display ImageField
[ "", "python", "django", "imagefield", "" ]
OK, so I have a load of records in a table and they have many different dates. I want to retern only those records whose date falls on the last day of whatever quarter it's in. I.e. I basically need the equivalent of a `lastDayOfQuarter(date)` function that calculates the date that is the last day in the quarter for t...
I'm answering myself as, with the help of [HansUp](https://stackoverflow.com/users/77335/hansup) answering a [previous question of mine](https://stackoverflow.com/q/17830458/1606323) for finding month-end records, I found out quite an easy way to acheive this: ``` WHERE DateValue(m.rdate) = DateSerial(Year(m.rdate), M...
the "last day of the quarter" could be different for different users. You may be best to build a table of "lastdays" based on your business rules, then use that table in your query.
MS Access SQL query for testing dates for last day of the quarter
[ "", "sql", "ms-access", "" ]
I'm new to SQL (using postgreSQL) and I've written a java program that selects from a large table and performs a few functions. The problem is that when I run the program I get a java OutOfMemoryError because the table is simply too big. I know that I can select from the beginning of the table using the LIMIT operator,...
There is offset option in Postgres as in: ``` select from table offset 50 limit 50 ```
For mysql you can use the follwoing approaches: 1. SELECT \* FROM table LIMIT {offset}, row\_count 2. SELECT \* FROM table WHERE id > {max\_id\_from\_the previous\_selection} LIMIT row\_count. First max\_id\_from\_the previous\_selection = 0.
Select from a SQL table starting with a certain index?
[ "", "sql", "" ]
I Have a stored procedure that has a table with one column and I need to generate a NEWID() for each row in that column. Would I only be able to accomplish this with a loop? ``` +---+ +--------------------------------------+---+ | a | | FD16A8B5-DBE6-46AB-A59A-6B6674E9A78D | a | | b | => | 9E4A6EE6-1C95-4C7F-A66...
You should be able to select from your table and include the `newid()` to generate the value for each row: ``` select newid(), col from yourtable; ``` See [SQL Fiddle with Demo](http://sqlfiddle.com/#!3/d6aff/1)
You can create a column with the new guid ``` alter table yourtable add id varchar(40) not null default NEWID() ``` <http://sqlfiddle.com/#!3/b3c31/1>
generate guid for every row in a column
[ "", "sql", "sql-server", "t-sql", "" ]
This query is taking an average of 4 seconds. It will become a subquery in a stored procedure and I need it to take a sub second. Here is the query: ``` (select customercampaignname + ' $' + convert(varchar, cast(amount as numeric(36,2) ) ) As 'Check_Stub_Comment2' from ( select ROW_NUMBER() OVER (ORDER BY amount ...
If you don't need to actually use the row number for anything, then I would just go with getting the TOP 1 row. The query could be simplified a lot. I like to start by first selecting from the table that will be filtered out the most by your predicates. Hopefully, you have a good index on frs.fundraiserid and all of th...
I don't know if this will run faster, but by my reckoning, this can be simplified to: ``` Select top 1 customercampaignname + ' $' + convert(varchar(255), cast(sum(d.mastercurrencyamount) as numeric(36,2) ) ) As amount from bb02_donation d JOIN bb02_donationline dl on d.donationid = dl.donationid JOIN b...
SQL Server - how can this query be optimized?
[ "", "sql", "sql-server", "subquery", "query-optimization", "" ]
*(In 2013)* I don't know why Python is that weird, you can't find this by searching in google very easily, but it's quite simple. How can I detect 'SPACE' or actually any key? How can I do this: ``` print('You pressed %s' % key) ``` This should be included in python core, so please do not link modules not related fo...
You could make a little Tkinter app: ``` import Tkinter as tk def onKeyPress(event): text.insert('end', 'You pressed %s\n' % (event.char, )) root = tk.Tk() root.geometry('300x200') text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12)) text.pack() root.bind('<KeyPress>', onKeyPr...
Use Tkinter there are a ton of tutorials online for this. basically, you can create events. Here is a [link](http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm) to a great site! This makes it easy to capture clicks. Also, if you are trying to make a game, Tkinter also has a GUI. Although, I wouldn't recommen...
Detect key input in Python
[ "", "python", "input", "tkinter", "keyboard", "" ]
Say I have a variable in python called `my_boolean = False` I want an end result to be: `my_bool = "0"` The only way i can think of doing this is. `my_bool = str(int(my_boolean))`, a double type-casting. Is there a better way of doing this? Disadvantages? Advantages? What happens internally?
You could try ``` my_bool = '01'[my_boolean] ``` --- There seems to be a time difference between your approach and what is above: ``` >>> from timeit import timeit >>> timeit("'01'[b]", "b = False") 0.10460775769296968 >>> timeit("str(int(b))", "b = False") 0.8879351199904466 ``` Is it something to lose sleep over...
Never assume performances of operations. Profile and benchmark: ``` In [7]: value = False In [8]: %%timeit bool_dict = {False: '0', True: '1'} ...: my_boolean = bool_dict[value] ...: 10000000 loops, best of 3: 47.7 ns per loop In [9]: %timeit my_boolean = str(int(value)) 1000000 loops, best of 3: 420 ns per l...
Is multiple type-casting in python bad?
[ "", "python", "casting", "" ]