Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
How can i achieve if i want to select an attribute ONLY and ONLY if another attribute is NULL. I know the long way of this: ``` select val1 from test_table where val1 is not null OR select val2 from test_table where val1 is null ``` The bad with this solution that if i have a very long and complicated select then i ...
``` select coalesce(val1, val2) from test_table ```
``` SELECT ISNULL(val1,val2) FROM test_table ``` Or ``` SELECT COALESCE(val1,val2) FROM test_table ``` I prefer the latter because you can have multiple values like: ``` SELECT COALESCE(val1,val2,val3,val4,....,valn) FROM test_table ``` which means if val1 is null then take val2, if that is null too then take val3...
Select another attribute if the original attribute is NULL (Conditional select)
[ "", "sql", "select", "null", "oracle10g", "" ]
I have a Table With name "TmpTable", this table have the Parent Child Relationship, table have data look like: ``` Id | Name | ParentId 1 PCs 0 2 MACs 1 3 Keyboard 0 4 Mouse 0 5 Screen 3 6 Keyboard 4 7 Mouse 0 8 Screen 0 9 Key 0 ...
You can use [`DENSE_RANK()`](http://technet.microsoft.com/en-us/library/ms173825.aspx) function in combination with `ORDER BY CASE`: ``` SELECT *, DENSE_RANK() OVER (ORDER BY CASE WHEN ParentID = 0 THEN ID ELSE ParentID END) FROM TmpTable ORDER BY Id ``` **[SQLFiddle DEMO](http://sqlfiddle.com/#!3/76120/10)**
You can try like this. ``` ;with cte as (Select Row_Number() Over(Order by Id) as Row,Id from Table1 where Parentid=0 ) Select A.*,b.row as Sno from Table1 A inner join cte as b on b.id=a.parentid or (b.id=a.id and a.parentid=0) order by a.id; ``` [**Sql Fiddle Demo**](http://sqlfiddle.com/#!3/d88cc/12)
Assign Same SNo to Parent and its Child
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm creating tables using the pandas to\_html function, and I'd like to be able to highlight the bottom row of the outputted table, which is of variable length. I don't have any real experience of html to speak of, and all I found online was this ``` <table border="1"> <tr style="background-color:#FF0000"> <th>M...
You can do it in javascript using jQuery: ``` $('table tbody tr').filter(':last').css('background-color', '#FF0000') ``` Also newer versions of pandas add a class `dataframe` to the table html so you can filter out just the pandas tables using: ``` $('table.dataframe tbody tr').filter(':last').css('background-colo...
Since pandas has styling functionality now, you don't need JavaScript hacks anymore. This is a pure pandas solution: ``` import pandas as pd df = [] df.append(dict(date='2016-04-01', sleep=11.2, calories=2740)) df.append(dict(date='2016-04-02', sleep=7.3, calories=3600)) df.append(dict(date='2016-04-03', sleep=8.3, c...
Pandas Dataframes to_html: Highlighting table rows
[ "", "python", "html", "pandas", "" ]
I am trying to create a list named "userlist" with all the usernames listed beside "List:", my idea is to parse the line with "List:" and then split based on "," and put them in a list, however am not able to capture the line ,any inputs on how can this be achieved? ``` output=""" alias: tech.sw.host ...
Using `regex`, `str.translate` and `str.split` : ``` >>> import re >>> from string import whitespace >>> strs = re.search(r'List:(.*)(\s\S*\w+):', ph, re.DOTALL).group(1) >>> strs.translate(None, ':'+whitespace).split(',') ['username1', 'username2', 'username3', 'username4', 'username5'] ``` You can also create a dic...
If it were me, I'd parse the entire input so as to have easy access to every field: ``` inFile = StringIO.StringIO(ph) d = collections.defaultdict(list) for line in inFile: line = line.partition(':') key = line[0].strip() or key d[key] += [part.strip() for part in line[2].split(',')] print d['List'] ```
capturing the usernames after List: tag
[ "", "python", "" ]
In Visual Studio I want to state that if a calculation box is blank due to there being no figures available on that particluar project, then show zero. My calculation is a very simple: ``` =(ReportItems!textbox21.Value) / (ReportItems!textbox19.Value) ``` For this I wrote an IIf statement: ``` =IIf( IsNothing(R...
I have managed to fix it by inserting the below function:- ``` Function Divide(Numerator as Double, Denominator as Double) If Denominator = 0 Then Return 0 Else Return Numerator/Denominator End If End Function ``` and then re-writing my calculation as :- ``` =Code.Divide(ReportItems!textbox21.Value, ReportItems!text...
Can you try instead of IsNothing convert the value as string and compare with string.empty `IsNothing(ReportItems!textbox21.Value)` changed as, `ReportItems!textbox21.Value.ToString() = ""`
Trying to show zero instyead of #Error in visual studio
[ "", "sql", "visual-studio", "visual-studio-2008", "" ]
I'm using Pervasive SQL 10.3 (let's just call it MS SQL since almost everything is the same regarding syntax) and I have a query to find duplicate customers using their email address as the duplicate key: ``` SELECT arcus.idcust, arcus.email2 FROM arcus INNER JOIN ( SELECT arcus.email2, ...
If your database is set up to be case sensitive, then your inner query will have to take account of this to perform the grouping as you intended. If it is not case sensitive, then you won't require UPPER functions. Assuming your database IS case sensitive, you could try the query below. Maybe this will run faster... ...
The collation of a character string will determine how SQL Server compares character strings. If you store your data using a case-insensitive format then when comparing the character string “AAAA” and “aaaa” they will be equal. You can place a collate Latin1\_General\_CI\_AS for your email column in the where clause. ...
Need to UPPER SQL statement with INNER JOIN SELECT
[ "", "sql", "select", "inner-join", "" ]
At my organization clients can be enrolled in multiple programs at one time. I have a table with a list of all of the programs a client has been enrolled as unique rows in and the dates they were enrolled in that program. Using an External join I can take any client name and a date from a table (say a table of tests t...
You can simplify (replace) your `CASE` by using [`COALESCE()`](http://technet.microsoft.com/en-us/library/ms190349.aspx) instead: ``` SELECT COALESCE(PreviousPrograms1.name, PreviousPrograms2.name, PreviousPrograms3.name, PreviousPrograms4.name) AS PreviousProgram ``` `COALESCE()` returns the first non-null val...
You can simplify the Join by using a bridge table containing all the program types and their priority (my sql server syntax is a bit rusty): ``` create table BridgeTable ( programType varchar(30), programPriority smallint ); ``` This table will hold all the program types and the program priority will reflect ...
More efficient way of doing multiple joins to the same table and a "case when" in the select
[ "", "sql", "sql-server-2008", "" ]
I'd like to retrieve some rows utilizing my index on Columns A and B. I was told the only way to ensure my index is being used to retrieve the rows is to use an ORDER by clause, for example: ``` A B offset 1 5 1 1 4 2 2 5 3 2 4 4 SELECT A,B FROM TableX WHERE offset > 0 AND offset < 5 ORDER BY A,B ASC ...
Any index that includes A or B cloumns will have no effect on your query, regardless of your `ORDER BY`. You need an index on `offset` as that is the field that is being used in hte `WHERE` clause.
Sorry, but maybe I did not understand the question.. The above output query should result: ``` A B 1 4 1 5 2 4 2 5 ``` For avoiding table scan, you should add an index for the offset and use it in your WHERE clause. If possible to use unique then use it. > CREATE UNIQUE INDEX offsetidx ON TableX (offset)...
Using ORDER BY while still maintaining use of index
[ "", "mysql", "sql", "sql-order-by", "" ]
I am trying to print the date and month as 2 digit numbers. ``` timestamp = date.today() difference = timestamp - datetime.timedelta(localkeydays) localexpiry = '%s%s%s' % (difference.year, difference.month, difference.day) print localexpiry ``` This gives the output as `201387`. This there anyway to get the output a...
Use date formatting with [`date.strftime()`](http://docs.python.org/2/library/datetime.html#datetime.date.strftime): ``` difference.strftime('%Y%m%d') ``` Demo: ``` >>> from datetime import date >>> difference = date.today() >>> difference.strftime('%Y%m%d') '20130807' ``` You can do the same with the separate inte...
You can also use [format](http://docs.python.org/2/library/functions.html#format) ([datetime](http://docs.python.org/2/library/datetime.html#datetime.datetime.__format__), [date](http://docs.python.org/2/library/datetime.html#datetime.date.__format__) have \_\_format\_\_ method): ``` >>> import datetime >>> dt = datet...
Two-Digit dates in Python
[ "", "python", "date", "" ]
I've applied the basic example of django-filters with the following setup: models.py ``` class Shopper(models.Model): FirstName = models.CharField(max_length=30) LastName = models.CharField(max_length=30) Gender_CHOICES = ( ('','---------'), ('Male','Male'), ('Female','Fe...
You can accomplish this within the `__init__` by updating the `empty_label` directly on the filter, thus avoiding the need to redefine *all* options. ``` class FooFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters["some_choice_field...
First of all, you should not add the blank choice to your choices set. So please remove the following lines: ``` ('','---------'), ``` Django will automatically add these when the Field is not required and everything (django models, django forms, django views etc) *except* django-filter will work as expected. Now, c...
How to display empty_label for non-mandatory fields with django-filter?
[ "", "python", "django", "django-filters", "" ]
I have been working at learning Python over the last week and it has been going really well, however I have now been introduced to custom functions and I sort of hit a wall. While I understand the basics of it, such as: ``` def helloworld(): print("Hello World!") helloworld() ``` I know this will print "Hello Wo...
`Functions` in python can be both, a regular `procedure` and a `function` with a return value. Actually, every Python's function will return a value, which might be `None`. If a return statement is not present, then your function will be executed completely and leave normally following the code flow, yielding `None` a...
The primary way to pass information between functions is with arguments and return values. Functions can't see each other's variables. You might think that after ``` def my_function(): my_dict = {"Key1":Value1, "Key2":Value2, "Key3":Value3, "Key4":Value4,} my_function() ``...
Python custom function
[ "", "python", "function", "python-3.x", "" ]
I have two series `s1` and `s2` in pandas and want to compute the intersection i.e. where all of the values of the series are common. How would I use the `concat` function to do this? I have been trying to work it out but have been unable to (I don't want to compute the intersection on the indices of `s1` and `s2`, bu...
Place both series in Python's [set container](https://docs.python.org/2/library/stdtypes.html#set) then use the set intersection method: ``` s1.intersection(s2) ``` and then transform back to list if needed. Just noticed pandas in the tag. Can translate back to that: ``` pd.Series(list(set(s1).intersection(set(s2))...
Setup: ``` s1 = pd.Series([4,5,6,20,42]) s2 = pd.Series([1,2,3,5,42]) ``` Timings: ``` %%timeit pd.Series(list(set(s1).intersection(set(s2)))) 10000 loops, best of 3: 57.7 µs per loop %%timeit pd.Series(np.intersect1d(s1,s2)) 1000 loops, best of 3: 659 µs per loop %%timeit pd.Series(np.intersect1d(s1.values,s2.val...
Finding the intersection between two series in Pandas
[ "", "python", "pandas", "series", "intersection", "" ]
I am working with a NAO-robot on a Windows-XP machine and Python 2.7. I want to detect markers in speech. The whole thing worked, but unfortunately I have to face now a 10 Secounds delay and my events aren't detected (the callback function isnt invoked). First, my main-function: ``` from naoqi import ALProxy, ALBrok...
You are subscribing to the event outside your module. if I am not wrong you have to do it into the `__init__` method. ``` class SpeechEventModule(ALModule): def __init__(self, name, ext_memory): ALModule.__init__(self, name) memory = ALProxy("ALMemory") leds = ALProxy("ALLeds") ``` Anyway...
Here is how it would be done with a more recent Naoqi version: ``` import qi import argparse class SpeechEventListener(object): """ A class to react to the ALTextToSpeech/CurrentBookMark event """ def __init__(self, session): super(SpeechEventListener, self).__init__() self.memory = session....
Naoqi eventhandling 10 Secounds delay
[ "", "python", "event-handling", "delay", "led", "nao-robot", "" ]
I have to use `DECODE` to implement custom sort: ``` SELECT col1, col2 FROM tbl ORDER BY DECODE(col1, 'a', 3, 'b', 2, 'c', 1) DESC ``` What will happen if col1 has more values that the three specified in decode clause?
DECODE will return NULL, for the values of col1 which are not specified. The NULL-Values will be placed at the front per default . if you want to change this behavior you can either define the default value in DECODE ``` SELECT col1, col2 FROM tbl ORDER BY DECODE(col1, 'a', 3, 'b', 2, 'c', 1, 0) DESC ``` or NULLS ...
the decode function will return NULL value and it is at the bottom of your sort. You can verify it: select decode('z','a', 3, 'b', 2, 'c', 1) from dual; you can also control the appearance of the null value with NULLS LAST/NULLS FIRST in the order clause.
Oracle - DECODE - How will it sort when not every case is specified?
[ "", "sql", "oracle", "" ]
I am new to python. I am trying to create a retry decorator that, when applied to a function, will keep retrying until some criteria is met (for simplicity, say retry 10 times). ``` def retry(): def wrapper(func): for i in range(0,10): try: func() break ...
You can supply a `tuple` of exceptions to the `except ..` block to catch: ``` from functools import wraps def retry(*exceptions, **params): if not exceptions: exceptions = (Exception,) tries = params.get('tries', 10) def decorator(func): @wraps(func) def wrapper(*args, **kw): ...
``` from functools import wraps class retry(object): def __init__(self, *exceptions): self.exceptions = exceptions def __call__(self, f): @wraps(f) # required to save the original context of the wrapped function def wrapped(*args, **kwargs): for i in range(0,10): ...
Can I pass an exception as an argument to a function in python?
[ "", "python", "decorator", "python-decorators", "" ]
Is it posible to CAST or CONVERT with string data type (method that takes data type parametar as string), something like: ``` CAST('11' AS 'int') ``` but not ``` CAST('11' AS int) ```
You would have to use dynamic sql to achieve that: ``` DECLARE @type VARCHAR(10) = 'int' DECLARE @value VARCHAR(10) = '11' DECLARE @sql VARCHAR(MAX) SET @sql = 'SELECT CAST(' + @value + ' AS ' + @type + ')' EXEC (@sql) ``` **[SQLFiddle DEMO with INT](http://sqlfiddle.com/#!3/d41d8/18554)** // [with datetime](http:/...
No. There are many places in T-SQL where it wants, specifically, a name given to it - not a string, nor a variable *containing* a name.
CAST and CONVERT in T-SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I'm running Pycharm 2.6.3 with python 2.7 and django 1.5.1. When I try to run django's manage.py task from Pycharm (Tools / Run manage.py task), syncdb, for instance, I get the following: ``` bash -cl "/usr/bin/python2.7 /home/paulo/bin/pycharm-2.6.3/helpers/pycharm/django_manage.py syncdb /home/paulo/Projetos/repo2/P...
it's known bug <http://youtrack.jetbrains.com/issue/PY-8449> Fixed in PyCharm 2.7
In UNIX you can escape whitespaces with a backslash: ``` /home/paulo/Projetos/repo2/Paulo\ Brito/phl ```
Pycharm: Run manage task won't work if path contains space
[ "", "python", "django", "pycharm", "" ]
Or how do I make this thing work? I have an Interval object: ``` class Interval(Base): __tablename__ = 'intervals' id = Column(Integer, primary_key=True) start = Column(DateTime) end = Column(DateTime, nullable=True) task_id = Column(Integer, ForeignKey('tasks.id')) @hybrid_property #used to just...
SQLAlchemy is not smart enough to build SQL expression tree from these operands, you have to use explicit `propname.expression` decorator to provide it. But then comes another problem: there is no portable way to convert interval to hours in-database. You'd use `TIMEDIFF` in MySQL, `EXTRACT(EPOCH FROM ... ) / 3600` in ...
For a simple example of SQLAlchemy's coalesce function, this may help: [Handling null values in a SQLAlchemy query - equivalent of isnull, nullif or coalesce](http://progblog10.blogspot.com/2014/06/handling-null-values-in-sqlalchemy.html). Here are a couple of key lines of code from that post: ``` from sqlalchemy.sql...
How do I implement a null coalescing operator in SQLAlchemy?
[ "", "python", "sqlalchemy", "null-coalescing-operator", "" ]
I'm trying to set up Django-Celery. I'm going through the tutorial <http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html> when I run $ python manage.py celery worker --loglevel=info I get ``` [Tasks] /Users/msmith/Documents/dj/venv/lib/python2.7/site-packages/djcelery/loaders.py:133: Us...
**Update Jan 2022**: This answer is outdated. As suggested in comments, please refer to [this link](https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-celery-with-django) The problem is that you are trying to connect to a local instance of RabbitMQ. Look at this line in your `settings.p...
I got this error because `rabbitmq` was not started. If you installed `rabbitmq` via brew you can start it using `brew services start rabbitmq`
Django Celery - Cannot connect to amqp://guest@127.0.0.8000:5672//
[ "", "python", "django", "celery", "" ]
``` dict1={'s1':[1,2,3],'s2':[4,5,6],'a':[7,8,9],'s3':[10,11]} ``` how can I get all the value which key is with 's'? like `dict1['s*']`to get the result is `dict1['s*']=[1,2,3,4,5,6,10,11]`
``` >>> [x for d in dict1 for x in dict1[d] if d.startswith("s")] [1, 2, 3, 4, 5, 6, 10, 11] ``` or, if it needs to be a regex ``` >>> regex = re.compile("^s") >>> [x for d in dict1 for x in dict1[d] if regex.search(d)] [1, 2, 3, 4, 5, 6, 10, 11] ``` What you're seeing here is a nested [list comprehension](http://do...
``` >>> import re >>> from itertools import chain def natural_sort(l): # http://stackoverflow.com/a/4836734/846892 convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] return sorted(l, key = alphanum_key)...
how to get dict value by regex in python
[ "", "python", "regex", "dictionary", "" ]
I have 2 tables, A and B. I want to insert the name and 'notInTime' into table B if that name IS NOT currently falling into the period between time\_start and time\_end. eg: time now = 10:30 ``` TABLE A NAME TIME_START (DATETIME) TIME_END (DATETIME) A 12:00 14:00 A 10:00 13:00 B 09:00 11:00 B 10:00 11:00 C 12:00 14:0...
This will add those in time and those not in time to table\_b ``` declare @now time = '10:30' INSERT INTO TABLE_B(Name, Indicator) select a.NAME, case when b.chk = 1 THEN 'intime' else 'notInTime' end from ( select distinct NAME from TABLE_A ) a outer apply (select top 1 1 chk from TABLE_A where @now between TIME_...
``` INSERT INTO TABLE_B b (column_name_1, column_name_2) SELECT 'C', CASE WHEN EXISTS (SELECT 1 FROM TABLE_A a WHERE a.NAME = 'C' AND '10:30' BETWEEN TIME(a.TIME_START) AND TIME(a.TIME_END)) THEN 'intime' ELSE 'notinTime' END UNION ALL SELECT 'D', CASE WHEN EXISTS (SELECT 1 FROM TABLE_A a WHERE a.NAME = 'D' AND '1...
Sql Server Insert a new row if 1 value does not exist in dest table
[ "", "sql", "insert", "" ]
I have a column which contains dates in varchar2 with varying formats such as 19.02.2013, 29-03-2013, 30/12/2013 and so on. But the most annoying of all is 20130713 (which is July 13, 2013) and I want to convert this to dd-mm-yyyy or dd-mon-yyyy.
If the column contains all those various formats, you'll need to deal with each one. Assuming that your question includes *all* known formats, then you have a couple of options. You can use to\_char/to\_date. This is dangerous because you'll get a SQL error if the source data is not a valid date (of course, getting an...
Convert to date, then format to char: ``` select to_char(to_date('20130713', 'yyyymmdd'), 'dd MON yyyy') from dual; ``` gives `13 JUL 2013`.
How to convert yyyymmdd to dd-mm-yyyy in Oracle?
[ "", "sql", "oracle", "date", "datetime", "oracle-sqldeveloper", "" ]
I must create two functions. One that can tell whether one number is odd or even by returning t/f, and the other will call the first function then return how many even numbers there are. This is my code so far: ``` Even = [0,2,4,6,8] IsEvenInput = int(input("Please enter a number: ")) def IsEvenDigit(a):...
Here is another approach: ``` def is_even(number): return number % 2 == 0 def even_count(numbers_list): count = 0 for number in numbers_list: if is_even(number): count += 1 return count raw_numbers = input("Please enter more than one number: ") numbers_list = [int(i) for i in raw_numbers.sp...
``` d = input("Please enter more than one number: ") ``` This is going to return a string of numbers, perhaps separated by spaces. You'll need to `split()` the string into the sequence of text digits and then turn those into integers. --- There's a general approach to determining whether a number is odd or even usin...
Count Even Numbers User has Inputted PYTHON 3
[ "", "python", "count", "" ]
I'm trying to do a query on this table: ``` Id startdate enddate amount 1 2013-01-01 2013-01-31 0.00 2 2013-02-01 2013-02-28 0.00 3 2013-03-01 2013-03-31 245 4 2013-04-01 2013-04-30 529 5 2013-05-01 2013-05-31 0.00 6 2013-06-0...
Here's one idea (and [a fiddle](http://sqlfiddle.com/#!6/ea3e0/1) to go with it): ``` ;WITH MoneyComingIn AS ( SELECT MIN(startdate) AS startdate, MAX(enddate) AS enddate, SUM(amount) AS amount FROM myTable WHERE amount > 0 ) SELECT MIN(startdate) AS startdate, MAX(enddate) AS enddate, SUM(am...
``` with CT as ( select t1.*, ( select max(endDate) from t where startDate<t1.StartDate and SIGN(amount)<>SIGN(t1.Amount) ) as GroupDate from t as t1 ) select min(StartDate) as StartDate, max(EndDate) as EndDate, sum(Amount) as Amount from CT gro...
grouping by date range in t-sql
[ "", "sql", "sql-server", "t-sql", "" ]
I have data in a file that has two sets of values and then an unspecified series of arrays (each with 3 sub items in them) For example: ``` ('January', 2, [('curly', 30), ('larry',10), ('moe',20)]) ``` I need the data read and present back and partially re-assign the data to new variables. For example: ``` Month: ...
You could use a dictionary to store your workers. **Edit** ``` work = [('January', 2, [('curly', 30, 5), ('larry',10, 5), ('moe',20, 10)])] workers = dict() month = "" section = "" for w in work: month = w[0] section = w[1] for worker, time, overtime in w[2]: workers[worker] = (time, overtime) ...
You need to iterate over the third item in the sequence. ``` for item in filecontent: print 'Month %s' % item[0] print 'Section %d' % item[1] for name, hours in item[2]: print "%s has worked %d hours" % (name, hours) ```
break string and arrays down intro separate items
[ "", "python", "arrays", "file", "python-3.x", "tuples", "" ]
I have table `A` with a primary key on column `ID` and tables `B,C,D...` that have 1 or more columns with foreign key relationships to `A.ID`. How do I write a query that shows me all tables that contain a specific value (eg `17`) of the primary key? I would like to have **generic sql code that can take a table name ...
Not an ideal one, but should return what is needed (list of tables): ``` declare @tableName sysname, @value sql_variant set @tableName = 'A' set @value = 17 declare @sql nvarchar(max) create table #Value (Value sql_variant) insert into #Value values (@value) create table #Tables (Name sysname, [Column] sysname) cr...
You want to look at `sys.foreignkeys`. I would start from <http://blog.sqlauthority.com/2009/02/26/sql-server-2008-find-relationship-of-foreign-key-and-primary-key-using-t-sql-find-tables-with-foreign-key-constraint-in-database/> to give something like ``` declare @value nvarchar(20) = '1' SELECT 'select * from...
SQL how do you query for tables that refer to a specific foreign key value?
[ "", "sql", "sql-server", "foreign-keys", "sql-server-2012", "" ]
I have a django-rest-framework REST API with hierarchical resources. I want to be able to create subobjects by POSTing to `/v1/objects/<pk>/subobjects/` and have it automatically set the foreign key on the new subobject to the `pk` kwarg from the URL without having to put it in the payload. Currently, the serializer is...
Make the parent object serializer field read\_only. It's not optional but it's not coming from the request data either. Instead you pull the pk/slug from the URL in `pre_save()`... ``` # Assuming list and detail URLs like: # /v1/objects/<parent_pk>/subobjects/ # /v1/objects/<parent_pk>/subobjects/<pk>/ def pre_sav...
Here's what I've done to solve it, although it would be nice if there was a more general way to do it, since it's such a common URL pattern. First I created a mixin for my ViewSets that redefined the `create` method: ``` class CreatePartialModelMixin(object): def initial_instance(self, request): return Non...
Django REST Framework: creating hierarchical objects using URL arguments
[ "", "python", "django", "rest", "django-rest-framework", "" ]
I'm trying to make a simple script in python that will scan a tweet for a link and then visit that link. I'm having trouble determining which direction to go from here. From what I've researched it seems that I can Use Selenium or Mechanize? Which can be used for browser automation. Would using these be considered web ...
There are many different ways to go when doing web automation. Since you're doing stuff with Twitter, you could try the Twitter API. If you're doing any other task, there are more options. * [`Selenium`](https://pypi.python.org/pypi/selenium) is very useful when you need to click buttons or enter values in forms. The ...
I am not expect in web scraping. But I had some experience with both Mechanize and Selenium. I think in your case, either Mechanize or Selenium will suit your needs well, but also spend some time look into these Python libraries Beautiful Soup, urllib and urlib2. From my humble opinion, I will recommend you use Mechan...
Can anyone clarify some options for Python Web automation
[ "", "python", "selenium-webdriver", "browser-automation", "pyjamas", "" ]
I'd like to save to disk all the variables I create within a particular function in one go, so that I can load them later. Something of the type: ``` >>> def test(): a=1 b=2 save.to.file(filename='file', all.variables) >>> load.file('file') >>> a >>> 1 ``` Is there a way to do this in python? I kno...
Assuming all of the variables you want to save are local to the current function, you *can* get at them via the [`locals`](http://docs.python.org/3.3/library/functions.html#locals) function. This is almost always a very bad idea, but it is doable. For example: ``` def test(): a=1 b=2 pickle.dump(file, loc...
If you are not satisfied with the API of `pickle`, consider [shelve](http://docs.python.org/2/library/shelve.html) which does the pickling for you with a nicer `dict`-like front end. ex. ``` >>> import shelve >>> f = shelve.open('demo') >>> f <shelve.DbfilenameShelf object at 0x000000000299B9E8> >>> list(f.keys()) ['...
saving variables within function - python
[ "", "python", "function", "save", "" ]
I have a set of a numbers that are related to a key. When the key is not in the dictionary I want to add it along with its value a set() and it the key exists I would like to just a number to the existing set for that key. The way I did is like this: ``` for num in datasource: if not key in dict.keys(): ...
Try this, for adding new set elements as values for a given key: ``` d = {} d.setdefault(key, set()).add(value) ``` Alternatively, use a `defaultdict`: ``` from collections import defaultdict d = defaultdict(set) d[key].add(value) ``` Either solution will effectively create a [multimap](https://en.wikipedia.org/wik...
Use [dict.setdefault](http://docs.python.org/2/library/stdtypes.html#dict.setdefault): ``` d.setdefault(key, set()).add(num) ``` Or use [collections.defaultdict](http://docs.python.org/2/library/collections.html#collections.defaultdict): ``` d = collections.defaultdict(set) ... d[key].add(num) ```
Creating a dictionary and adding a set as its value
[ "", "python", "python-2.7", "" ]
Is there a way to have the items of a Tkinter Listbox be Entry Widgets? The result would be that you could dynamically modify the text in an Listbox entry. If your Listbox looks like: ``` -------- | Apples | | Pears | | Oranges | --------- ``` then you would want to be able to click on Apples and write some arbi...
you could give the user some entries then create a listbox from that input but you cant just change a listboxes text like that maybe try a different GUI Library like WX **EDIT** here is something you can do: ``` from Tkinter import * root = Tk() opt_list = ['opt1','opt2','opt3','opt4','opt5'] sel_list = [] def ...
I know it has been a while since this question, but I have created a widget called 'ListboxEditable', which is able to act as a listbox and, when double-clicking on an item, the user can type anything inside an entry. Then, when the user clicks another row, the information is saved on the corresponding modified cell. N...
Tkinter Listbox with Entry
[ "", "python", "tkinter", "listbox", "tkinter-entry", "" ]
I have a long list of xy coordinates, and would like to convert it into numpy array. ``` >>> import numpy as np >>> xy = np.random.rand(1000000, 2).tolist() ``` The obvious way would be: ``` >>> a = np.array(xy) # Very slow... ``` However, the above code is unreasonably slow. Interestingly, to transpose the long li...
Implementing this in Cython without the extra checking involved to determine dimensionality, etc. nearly eliminates the time difference you are seeing. Here's the `.pyx` file I used to verify that. ``` from numpy cimport ndarray as ar import numpy as np cimport cython @cython.boundscheck(False) @cython.wraparound(Fal...
This is because the fastest-varying index of your list is the last one, so `np.array()` has to traverse the array many times because the first index is much larger. If your list was transposed, `np.array()` would be faster than your `longlist2array`: ``` In [65]: import numpy as np In [66]: xy = np.random.rand(10000,...
why is converting a long 2D list to numpy array so slow?
[ "", "python", "performance", "numpy", "" ]
I'm trying to use pandas to manipulate a .csv file but I get this error: > pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3, saw 12 I have tried to read the pandas docs, but found nothing. My code is simple: ``` path = 'GOOG Key Ratios.csv' #print(open(path).read()) data = pd....
you could also try; ``` data = pd.read_csv('file1.csv', on_bad_lines='skip') ``` Do note that this will cause the offending lines to be skipped. If you don't expect many bad lines and want to (at least) know their amount and IDs, use `on_bad_lines='warn'`. For advanced handling of bads, you can pass a callable. **Ed...
It might be an issue with * the delimiters in your data * the first row, as @TomAugspurger noted To solve it, try specifying the `sep` and/or `header` arguments when calling `read_csv`. For instance, ``` df = pandas.read_csv(filepath, sep='delimiter', header=None) ``` In the code above, `sep` defines your delimiter...
pandas.parser.CParserError: Error tokenizing data
[ "", "python", "csv", "pandas", "" ]
I'm running test cases and I'd like to set up a my logging in such a way that it automatically logs all cases where tests fails - but I'd like to get a custom response, for example if an assertion fails I'd like to get the response to a request made by my test, not just default message which assertion failed. At presen...
``` self.assertIn('Edit your profile admin', rv.data, msg=rv.data) ``` Use the `assertWhatever` methods. I don't fully understand why, but you're not supposed to use `assert` statements for assertions in `unittest`. (Other frameworks let you assert with `assert`.) For reference, adding a message to an `assert` assert...
You can do something like this: ``` def test_edit_profile(self): rv = self.edit_profile() try: assert "Edit your profile admin" in rv.data except AssertionError: # Do your logging here ``` Edit: Was pointed out that this takes the assert functionality away basically, since the assertion is...
Is there a way to configure Python logging to log content or context of assert failures?
[ "", "python", "testing", "logging", "flask", "assertions", "" ]
I have a string, and i need to check whether it contains a `number/digit at the end` of the string, and need to increment that `number/digit` at the end of the string with `+1` I will get the strings as below ``` string2 = suppose_name_1 string3 = suppose_name_22 string4 = supp22ose45_na56me_45 ``` for sure i wil...
You don't need regex. You can just use simple `str.replace`: ``` >>> s = 'suppose_name_1' >>> index = s.rfind('_') # Last index of '_' >>> s.replace(s[index+1:], str(int(s[index+1:]) + 1)) 'suppose_name_2' ``` If you need to first check whether you have digits at the end, you can check that using `str.isdigit()` met...
How about using regular expressions: ``` import re def process_string(s): try: part1, part2 = re.search('^(.*_)(\d+)$', s).groups() part2 = str(int(part2) + 1) return part1 + part2 except AttributeError: return s print process_string("suppose_name_1") print process_string("su...
Check whether a string contains a numeric/digit/number in python
[ "", "python", "string", "digit", "" ]
My table has a `TIME` field. I want to keep only 5 newest rows. Can I delete the old rows without using `SELECT`? I think logic should be something like this: ``` DELETE FROM tbl WHERE row_num > 5 ORDER BY TIME ``` How can I implement this in MySQL whitout using `SELECT` to get list of `TIME` values?
Without proper `ORDER BY` clause, SQL result set have to be considered as *unordered*. You have to provide a column to explicitly store your rows sequence numbers. This could be a time stamp or the auto\_increment column of your table. Please keep in mind you could have concurrent access to your table as well. What s...
Maybe this would be an alternative: ``` DELETE FROM tbl WHERE primary_key NOT IN (SELECT primary_key FROM tbl ORDER BY time DESC LIMIT 5) ```
Correct way to delete 'older' rows in MySQL
[ "", "mysql", "sql", "" ]
What is the most **Pythonic** way to right split into groups of threes? I've seen this answer <https://stackoverflow.com/a/2801117/1461607> but I need it to be right aligned. Preferably a simple efficient one-liner without imports. * '123456789' = ['123','456','789'] * '12345678' = ['12','345','678'] * '1234567' = ['1...
Another way, not sure about efficiency (it'd be better if they were already numbers instead of strings), but is another way of doing it in 2.7+. ``` for i in map(int, ['123456789', '12345678', '1234567']): print i, '->', format(i, ',').split(',') #123456789 -> ['123', '456', '789'] #12345678 -> ['12', '345', '678...
simple (iterated from the answer in your link): `[int(a[::-1][i:i+3][::-1]) for i in range(0, len(a), 3)][::-1]` Explanation : `a[::-1]` is the reverse list of `a` We will compose the inversion with the slicing. ## Step one : reverse the list ``` a = a[::-1] '123456789' - > '987654321' ``` ## Step Two...
Right split a string into groups of 3
[ "", "python", "python-3.x", "" ]
I have a list something like the following: ``` [{'modified': 'Thu, 08 Aug 2013 18:28:13 +0000', 'path': '/test4.txt'}, {'modified': 'Thu, 06 Aug 2013 18:28:17 +0000', 'path': '/test5.txt'}, ... ] ``` and so on. I want to sort the list by 'modified', in chronological (or reverse chronological) order What is the bes...
Your sort function needs to understand the dates first, else it will just sort by the letters of the weekday. The [dateutil](http://labix.org/python-dateutil) package is perfect for this task. It will automatically identify the date and doesn't require a format string like `datetime.strptime`. ``` from dateutil impor...
``` from datetime import datetime strfmt = '%a, %d %b %Y %H:%M:%S +0000' res = sorted(files, key=lambda e: datetime.strptime(e['modified'], strfmt)) ``` For the reverse, use the optional boolean `reverse` argument: ``` rev = sorted(files, key=..., reverse=True) ``` See [`sorted()`](http://docs.python.org/3/library/f...
How to sort files by list elements by date modified, in Python?
[ "", "python", "list", "sorting", "" ]
Hello Dear StackOverfloooow Members, I am having trouble understanding the FuncAnimation module of matplotlib. Would you mind helping me out a bit? I have two questions: 1. Why does both die `init` and `animate` function need a comma after giving back only `PLOT`? 2. Why does my code not update the `time_text`? If I l...
1) Not really sure what you mean. In both `init` and `animate` you need to return both `PLOT` and `time_text`, so you seperate them with a comma so each function will return a tuple. For the 'hanging' comma in `PLOT, = sub.plot([],[])`, `sub.plot` is returning a list with a single element, a `matplotlib.lines.Line2D` ...
The other answers do not entirely answer the first question. The return statement of `init` and `animate` is needed strictly only when `blit=True` is used. Those functions are expected to return an iterable of artists to update for the animation. Having two artists, the return could look like ``` return artist1, arti...
Python Matplotlib FuncAnimation
[ "", "python", "animation", "matplotlib", "" ]
Let's say I have a file 'test.csv' containing the following headers and data: ``` h1 c1 h2 h3 c2 1 0 2 3 1 3 0 2 1 0 0 1 2 3 3 ``` What is the best option in python to only select and save the columns of interest and discard all others? Assuming I'm only interested in saving the h columns...
I found a very straightforward way of doing this: ``` import pandas as pd selectColumns = ['h1','h2','h3'] table = pd.read_csv('test.csv') tableNew = table[selectColumns] pd.to_csv('tableNew') ```
``` f = open("test.csv") header = {i: x for i, x in enumerate(f.readline().split())} columns = ('h1','h2','h3') for l in f: print [x for i, x in enumerate(l.split()) if header[i] in columns] ```
selecting only relevant columns within a file - python
[ "", "python", "file", "save", "" ]
I have a descriptor on a class, and its `__set__` method does not get called. I have been looking long and hard on this for a few hours and have no answer for this. But what I noticed below is that when I assign 12 to MyTest.X, it erases the property descriptor for X, and replaces it with the value of 12. So the print ...
The other two answers allude to using metaclasses to accomplish what you want to do. To help learn about them, here's an example of applying one to the code in your question that makes it do what you want: ``` class _static_property(object): """Descriptor class used for declaring computed properties that do...
Descriptors work on instances of classes, not classes themselves. If you had an instance of `MyTest`, `X` would work as you expect, but accessing it as a class attribute actually sets the attribute of the class object itself. You could try defining a custom metaclass to add the descriptor to, then creating `MyTest` wit...
Why does the Python descriptor __set__ not get called
[ "", "python", "" ]
I using next queries for extracting top 100 and 101 lines from DB and gettings following elapsing times, which completely different (second query ~8 slower than first): ``` SELECT TOP (100) * FROM PhotoLike WHERE photoAccountId=@accountId AND accountId<>@accountId ORDER BY createDate DESC GO ``` SQL Server Executio...
There are a couple of things going on here. When you use variables SQL Server doesn't sniff the values at all except if you also add `OPTION (RECOMPILE)`. The estimate for the number of rows matching `photoAccountId=@accountId` is much smaller with the guess than is actually the case. (Note the thick line coming out ...
I wonder if this could be parameter sniffing related. How fast does the following query go? ``` DECLARE @accountIdParam int; SELECT @accountIdParam = @accountId; SELECT TOP (101) * FROM PhotoLike WHERE photoAccountId=@accountIdParam AND accountId<>@accountIdParam ORDER BY createDate DESC GO ```
Low performance query while using database variables
[ "", "sql", "sql-server", "performance", "" ]
I would like to be able to use a USB device from several applications (for instance I run a Flask web application), making sure only one uses it at a time. In my case I am using a relay to open / close a door. The door takes about 20 seconds to open. During that time the relay should not be activated, because this wou...
You have a number of possible solutions. The [posix\_ipc](http://semanchuk.com/philip/posix_ipc/) or [sysv\_ipc](http://semanchuk.com/philip/sysv_ipc/) Python modules provide a named semaphore class. You can initialize a semaphore to 1 and have all your web processes acquire the semaphore while they send a command to ...
Not exactly an answer to your question, but maybe another idea about how to tackle this with out using globals. Why don't you write a small program for controlling your USB device. This script runs once (one instance) on your server and takes care of communicating with the device in the manner you need. It also takes ...
How to prevent concurrent access to a resource such as a USB device?
[ "", "python", "concurrency", "locking", "semaphore", "superglobals", "" ]
I am trying to create a new text file in an empty folder. The path to the folder is: ``` C:\Users\Tor\Desktop\Python files\retning ``` When I type this in the command line in windows explorer, I get straight to the empty folder. When I type my code in Python I get an errormessage and it looks like Python has replace...
`\` needs to be escaped in the strings. That is why `\\` or raw strings are used (`r'test String'`) Using raw strings solves the problem here. Something like, ``` open(r'C:\Programming Test Folder\test_file.py') ``` So, your code gets changed to ``` g=open(r'C:\Users\Tor\Desktop\Python files\retning\retning{}.txt'....
This is *normal* behaviour; Python is giving you a string representation that can be pasted right back into a Python script or interpreter prompt. Since `\` is a character used in Python string literals to start an escape sequence (such as `\n` or `\xa0`) the backslashes are doubled. In fact, it is the characters *wit...
Python reads \\ when \ is the input
[ "", "python", "string", "append", "" ]
I have a database of parent-child connections. The data look like the following but could be presented in whichever way you want (dictionaries, list of lists, JSON, etc). ``` links=(("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Bob","Leroy"),("Bob","Earl")) ``` The output that I need is a hierarchical JSON tree, ...
To identify the root nodes you can unzip `links` and look for parents who are not children: ``` parents, children = zip(*links) root_nodes = {x for x in parents if x not in children} ``` Then you can apply the recursive method: ``` import json links = [("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Bob","Leroy")...
Try follwing code: ``` import json links = (("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Tom","Hurbert"),("Tom","Neil"),("Bob","Leroy"),("Bob","Earl"),("Tom","Reginald")) name_to_node = {} root = {'name': 'Root', 'children': []} for parent, child in links: parent_node = name_to_node.get(parent) if not p...
Recursively build hierarchical JSON tree?
[ "", "python", "django", "json", "recursion", "d3.js", "" ]
Two transactions in two sessions are operating on same item as: In session 1: ``` begin tran T1 insert into Invoice with (item,OrderNumber) select 'ItemA', max(OrderNumber)+1 from Orders where item='ItemA' waitfor delay '00:00:05' commit T1 ``` In session 2: ``` begin tran T2 insert i...
You can use serializable isolation level for your transaction. Ex: ``` set transaction isolation level serializable begin tran insert into Invoice with (item,OrderNumber) select 'ItemA', max(OrderNumber)+1 from Orders where item='ItemA' waitfor delay '00:00:05' commit tran ``` Serializable...
Database locking schemes are integral part of any database management application. For integrity of data stored in databases there are different locking schemes provided by different database vendors. You should check the following links [First Link](http://www.mssqltips.com/sqlservertip/1968/understanding-sql-server-l...
How do locks work in a insert...select statement?
[ "", "sql", "sql-server", "t-sql", "" ]
I need to write a query for my search page. My filters look like this: ``` @StartDateForColumn1 datetime, @FinishDateForColumn1 datetime, @StartDateForColumn2 datetime, @FinishDateForColumn2 datetime, ``` All of them can be null. If so, I need all data: ``` select * from Table1 ``` For example: If only`@FinishDateF...
the following assumes that you don't have any dates outside the range 01/01/1971 and 31/12/2099. ``` select * from Table1 where Column1< ISNULL(@FinishDateForColumn1,'31/Dec/2099') and Column1 > ISNULL(@StartDateForColumn1, '01/Jan/1971') and Column2< ISNULL(@FinishDateForColumn2,'31/Dec/2099') and Column2 > ISNUL...
You can use `coalesce`, or `isnull`, in the following fashion ``` select * from Table1 where Column1<= isnull(@FinishDateForColumn1, Column1) ``` NB. This does assume that your column1 data does not contain nulls.
Search query for multiple date filters
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "coalesce", "" ]
I have a messages table with 5 millions rows, I want to retrieve the last 10 rows of two users conversation ``` +---------------------------------------------------------------+ | messages | +---------------------------------------------------------------+ | message...
This is your query: ``` SELECT * FROM (SELECT * FROM messages WHERE (id_sender = id1 AND id_dest = id2) or (id_dest = id1 AND id_sender = id2) ORDER BY message_id DESC LIMIT 10 ) ttbl ORDER BY message_id ASC; ``` Create an index on `message(id_sender, id_dest, message_id)`. T...
First note on optimization, it's a lot more involved than *how can I optimize this?* Secondly, some ideas: * Don't use `SELECT *` if it's not necessary. Just bring back the fields needed. * This builds off the first one. Build a covering index. This means that if the fields `a, b, c` are used in the query *anywhere*,...
optimize query sql for messenger
[ "", "mysql", "sql", "postgresql", "" ]
I am trying to figure out how I can count the uppercase letters in a string. I have only been able to count lowercase letters: ``` def n_lower_chars(string): return sum(map(str.islower, string)) ``` Example of what I am trying to accomplish: ``` Type word: HeLLo Capital L...
You can do this with [`sum`](https://docs.python.org/3/library/functions.html#sum), a [generator expression](https://docs.python.org/3/reference/expressions.html#grammar-token-generator_expression), and [`str.isupper`](https://docs.python.org/3/library/stdtypes.html#str.isupper): ``` message = input("Type word: ") pr...
You can use `re`: ``` import re string = "Not mAnY Capital Letters" len(re.findall(r'[A-Z]',string)) ``` > *5*
Count the uppercase letters in a string with Python
[ "", "python", "string", "python-3.x", "count", "uppercase", "" ]
I am learning how to use the `threading` and the `multiprocessing` modules in Python to run certain operations in parallel and speed up my code. I am finding it hard (maybe because I don't have any theoretical background about it) to understand what the difference is between a `threading.Thread()` object and a `multip...
[What Giulio Franco says](https://stackoverflow.com/a/18114475) is true for multithreading vs. multiprocessing *in general*. However, Python\* has an added issue: There's a Global Interpreter Lock that prevents two threads in the same process from running Python code at the same time. This means that if you have 8 cor...
Multiple threads can exist in a single process. The threads that belong to the same process share the same memory area (can read from and write to the very same variables, and can interfere with one another). On the contrary, different processes live in different memory areas, and each of them has its own variables. In...
What are the differences between the threading and multiprocessing modules?
[ "", "python", "multithreading", "parallel-processing", "process", "multiprocessing", "" ]
How to get occurrence counts for for the elements of a float array?. If the array is [-1,2,3,-1,3,4,4,4,4,4], the result should be [2,1,2,5], not necessarily in that order, and the mapping from counts to the elements that are counted is not needed, only counts matter. numpy.histogram would do something similar, but ...
For Python 2.7+: ``` >>> from collections import Counter >>> counts = Counter([-1,2,3,-1,3,4,4,4,4,4]) >>> counts.viewvalues() # counts.values() in Python 3+ dict_values([1, 2, 5, 2]) ``` <http://docs.python.org/library/collections.html#collections.Counter> (There are implementations for 2.4 and 2.5 if you're stuck w...
If you do want a numpy solution: ``` >>> a=np.array( [-1,2,3,-1,3,4,4,4,4,4]) >>> ua,uind=np.unique(a,return_inverse=True) #This returns the unique values and indices of those values. >>> ua array([-1, 2, 3, 4]) >>> uind array([0, 1, 2, 0, 2, 3, 3, 3, 3, 3]) >>> np.bincount(uind) array([2, 1, 2, 5]) ``` This has...
exact histogram of an array
[ "", "python", "numpy", "" ]
This is a structure I'm getting from elsewhere, that is, a list of deeply nested dictionaries: ``` { "foo_code": 404, "foo_rbody": { "query": { "info": { "acme_no": "444444", "road_runner": "123" }, "error": "no_lunch", "me...
You can try this rather trivial function to access nested properties: ``` import re def get_path(dct, path): for i, p in re.findall(r'(\d+)|(\w+)', path): dct = dct[p or int(i)] return dct ``` Usage: ``` value = get_path(data, "xyzzy_rbody.api.items[0].params.bicycle") ```
Maybe the function `byPath` in my answer to [this post](https://stackoverflow.com/questions/18069262/count-non-empty-end-leafs-of-a-python-dicitonary-array-data-structure-recursiv/18069577#18069577) might help you.
Extracting values from deeply nested JSON structures
[ "", "python", "json", "" ]
I am selecting from tables that have retail and corporate customers. I want My result set to return the names of both corporate and retail customers in one column. Currently I am returning them in two different columns like this: ``` select e.cust_id, e.cust_location, f.location max(case ...
If only one of the two fields is ever populated, then returning whichever is populated as a single column is pretty simple: ``` select e.cust_id, e.cust_location, f.location coalesce(e.preferredname, e.CORP_NANME) as CUST_NAME, from Mytable e join myothertable f on e.cust_id = f.cust_id ``` `...
Write query as below and you can get both cust\_name in one column ``` select e.cust_id, e.cust_location, f.location max(case when e.preferredname is not null then e.preferredname Whene preferredname is null then e.CORP_NANME end )CUST_NAME ```
Different table fields in one result set Oracle
[ "", "sql", "oracle", "" ]
Lets say I have a **list of tuples** as follows ``` l = [(4,1), (5,1), (3,2), (7,1), (6,0)] ``` I would like to iterate over the items where the 2nd element in the tuple is 1? I can do it using an if condition in the loop, but I was hoping there will a be amore *pythonic* way of doing it? Thanks
You can use a list comprehension: ``` [ x for x in l if x[1] == 1 ] ``` You can iterate over tuples using generator syntax as well: ``` for tup in ( x for x in l if x[1] == 1 ): ... ```
How about ``` ones = [(x, y) for x, y in l if y == 1] ``` or ``` ones = filter(lambda x: x[1] == 1, l) ```
python - iterating over a subset of a list of tuples
[ "", "python", "" ]
I have a python code which looks something like this: ``` os.system("...../abc.bat") open("test.txt") ..... ``` Where the abc.bat upon complete run creates test.txt. Now the problem is that since there is no "wait" here code directly goes to open("file.txt") and naturally does not find it and hence the pr...
Maybe you could try to put it on a while loop. ``` import os import time os.system("...../abc.bat") while True: try: o = open("test.txt", "r") break except: print "waiting the bat.." time.sleep(15) # Modify (seconds) to se sufficient with your bat to be ready continue ...
I'm unsure of the wait semantics of `os.system` on all platforms, but you could just use [subprocess.call()](http://docs.python.org/2/library/subprocess.html#subprocess.call) which the documentation for `os.system` is pointing to; > Run the command described by args. **Wait for command to complete**, then return the r...
wait statement in python
[ "", "python", "batch-file", "" ]
I store a log as follows: ``` LOG ID | MODELID | EVENT 1 | 1 | Upped 2 | 1 | Downed 3 | 2 | Downed 4 | 1 | Upped 5 | 2 | Multiplexed 6 | 1 | Removed ``` Then I have the models as: ``` MODEL ID | NAME 1 | Model 1 2 | Model 2 ``` I want to end up with the LOG entry with the...
Try this ``` SELECT M.NAME,L.EVENT FROM LOG L INNER JOIN MODEL M ON L.MODELID = M.ID WHERE L.ID IN ( SELECT MAX(ID) FROM LOG GROUP BY MODELID ) ```
Maybe you need a subselect. Let's start by breaking down the problem. First you want the HIGHEST ID for a given MODELID in the LOG table. ``` SELECT MODELID ,MAX(ID) FROM LOG GROUP BY MODELID ``` Now if we use this as a subselect (virtual table) then you can also get the model name. E.g. ``` SELECT...
Postgres: Getting the highest matching log associated with a record?
[ "", "sql", "postgresql", "" ]
Assuming you have "table" already in Hive, is there a quick way like other databases to be able to get the "CREATE" statement for that table?
[As of Hive 0.10](https://cwiki.apache.org/Hive/languagemanual-ddl.html#LanguageManualDDL-ShowCreateTable) this [patch-967](https://issues.apache.org/jira/browse/HIVE-967) implements `SHOW CREATE TABLE` which "shows the `CREATE TABLE` statement that creates a given table, or the `CREATE VIEW` statement that creates a g...
Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later: ***step 1)*** create a `.sh` file with the below content, say `hive_table_ddl.sh` ``` #!/bin/bash rm -f tableNames.txt rm -f HiveTableDDL.txt hive -e "use $1; show tables;" > tableNames.txt wait cat...
How to get/generate the create statement for an existing hive table?
[ "", "sql", "hive", "hiveql", "" ]
I'm looking for a way to view all of the variables during running so I can debug easier. I've tried the following but it doesn't work how I want it to: ``` import inspect a = False b = "" c = "test" d = {} e = [] f = ["Test", "Test"] g = ("One", "1", "Two", "2") h = inspect.currentframe() print h.f_locals ``` Ide...
You can use `vars()`: ``` a = False b = "" c = "test" d = {} e = [] f = ["Test", "Test"] g = ("One", "1", "Two", "2") for k, v in vars().items(): if not (k.startswith('__') and k.endswith('__')): print k,'--',v ``` **Output:** ``` a -- False c -- test b -- e -- [] d -- {} g -- ('One', '1', 'Two', '2') f...
A couple of non-stdlib things that I use frequently: First, one of ipython's more useful magic functions: `%whos` ``` In [21]: a = 'hi' ...: bob = list() ...: In [22]: %whos Variable Type Data/Info ---------------------------- a str hi bob list n=0 ``` `%who` just lists the vars...
Print / view all variables whilst a script is running in python
[ "", "python", "debugging", "python-2.7", "error-handling", "" ]
I'm following an api and I need to use a Base64 authentication of my User Id and password. 'User ID and Password need to both be concatenated and then Base64 encoded' it then shows the example ``` 'userid:password' ``` It then proceeds to say 'Provide the encoded value in an "Authorization Header"' 'for example: *...
You can encode the data and make the request by doing the following: ``` import requests, base64 usrPass = "userid:password" b64Val = base64.b64encode(usrPass) r=requests.post(api_URL, headers={"Authorization": "Basic %s" % b64Val}, data=payload) ``` I'm not sure if you've to add the...
The requests library has [Basic Auth support](http://docs.python-requests.org/en/latest/user/authentication/) and will encode it for you automatically. You can test it out by running the following in a python repl ``` from requests.auth import HTTPBasicAuth r = requests.post(api_URL, auth=HTTPBasicAuth('user', 'pass')...
Base64 Authentication Python
[ "", "python", "api", "authentication", "passwords", "request", "" ]
I'm using the following to try and insert a record into a postgresql database table, but it's not working. I don't get any errors, but there are no records in the table. Do I need a commit or something? I'm using the postgresql database that was installed with the Bitnami djangostack install. ``` import psycopg2 try:...
If don't want to have to commit each entry to the database, you can add the following line: ``` conn.autocommit = True ``` So your resulting code would be: ``` import psycopg2 try: conn = psycopg2.connect("dbname='djangostack' user='bitnami' host='localhost' password='password'") conn.autocommit = True exce...
Turns out I needed `conn.commit()` at the end
Python psycopg2 not inserting into postgresql table
[ "", "python", "postgresql", "insert", "psycopg2", "" ]
I have the follwong Query on multi tables ``` SELECT DISTINCT b.BoxBarcode as [Box Barcode], (select case when b.ImagesCount IS NULL then 0 else b.ImagesCount end) as [Total Images], s.StageName as [Current Stage] ,d.DocuementTypeName as [Document Type], u.UserName as [Start User],uu.UserN...
You are doing a one-to-many join, i.e. at least one of the tables have multiple rows that match the join criteria. Step one is to find which table(s) that give the "duplicates". Once you have done that you may be able to fix the problem by adding additional criteria to the join. I'm taking a guess that the same `boxi...
Try this one - ``` SELECT Box_Barcode = b.BoxBarcode , Total_Images = ISNULL(b.ImagesCount, 0) , Current_Stage = s.StageName , Document_Type = d.DocuementTypeName , Start_User = u.UserName , Finished_User = uu.UserName FROM ( SELECT DISTINCT o.stageid , o.boxid ...
Get DISTINCT record using INNER JOIN
[ "", "sql", "sql-server", "database", "sql-server-2008", "t-sql", "" ]
I have two tables MANUAL\_TRANSACTIONS and MANUAL\_LIST\_TEMP. What I wanted to achieve is to update the MANUAL\_TRANSACTIONS with the information from MANUAL\_LIST\_TEMP. Here only records which is present in the MANUAL\_LIST\_TEMP table should be updated to MANUAL\_TRANSACTIONS. I have done something like below but ...
You should also add the WHERE clause to your UPDATE statement: ``` UPDATE MANUAL_TRANSACTIONS SET ( "Age", "Assigned_To", "Attachments", "Comments", "Completed_Date_Time" , "Content_Type", "Created", "Created_By","Cycle_Time (Crt to Complete)" , "Cycle_Time (First reply)", "DISTRIBUTION_CHANNEL")= (SELECT MAN...
You need one more where clause for UPDATE
Update query with INNER Join
[ "", "sql", "oracle", "" ]
I'm trying to parse out content from specific meta tags. Here's the structure of the meta tags. The first two are closed with a backslash, but the rest don't have any closing tags. As soon as I get the 3rd meta tag, the entire contents between the `<head>` tags are returned. I've also tried `soup.findAll(text=re.compil...
Edited: Added regex for case sensitivity as suggested by @Albert Chen. Python 3 Edit: ``` from bs4 import BeautifulSoup import re import urllib.request page3 = urllib.request.urlopen("https://angel.co/uber").read() soup3 = BeautifulSoup(page3) desc = soup3.findAll(attrs={"name": re.compile(r"description", re.I)}) ...
Description is Case-Sensitive.So, we need to look for both 'Description' and 'description'. Case1: 'Description' in [Flipkart.com](http://view-source:http://www.flipkart.com/) Case2: 'description' in [Snapdeal.com](http://view-source:http://www.snapdeal.com/) ``` from bs4 import BeautifulSoup import requests url= '...
Extracting contents from specific meta tags that are not closed using BeautifulSoup
[ "", "python", "beautifulsoup", "" ]
In python, how do I concatenate 3 lists using a list comprehension? Have: ``` list1 = [1,2,3,4] list2 = [5,6,7,8] list3 = [9,10,11,12] ``` Want: ``` allList = [1,2,3,4,5,6,7,8,9,10,11,12] ``` I tried using a list comprehension, but I'm not very good at them yet. These are what I have tried: ``` ...
A better solution is to use [`itertools.chain`](http://docs.python.org/3.3/library/itertools.html#itertools.chain) instead of addition. That way, instead of creating the intermediate list `list1 + list2`, and then another intermediate list `list1 + list2 + list3`, you just create the final list with no intermediates: ...
Here are some options: ``` >>> sum([list1, list2, list3], []) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> list1 + list2 + list3 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ``` With comprehension: (it's really not necessary) ``` >>> [x for x in sum([list1, list2, list3], [])] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ```
how do I concatenate 3 lists using a list comprehension?
[ "", "python", "list", "list-comprehension", "" ]
I have a web application which acts as an interface to an offsite server which runs a very long task. The user enters information and hits submit and then chrome waits for the response, and loads a new webpage when it receives it. However depending on the network, input of the user, the task can take a pretty long time...
While you could change your timeout on the server or other tricks to try to keep the page "alive", keep in mind that there might be other parts of the connection that you have no control over that could timeout the request (such as the timeout value of the browser, or any proxy between the browser and server, etc). Als...
Let's assume: 1. This is not a server issue, so we don't have to go fiddle with Apache, nginx, etc. timeout settings. 2. The delay is minutes, not hours or days, just to make the scenario manageable. 3. You control the web page on which the user hits submit, and from which user interaction is managed. If those obtain...
Time out issues with chrome and flask
[ "", "python", "google-chrome", "web-applications", "flask", "" ]
Currently I am trying to read in a csv file using the csv module in python. When I run the piece of code below I get an error that states the file does not exist. My first guess is that maybe, I have the file saved in the wrong place or I need to provide pyton with a file path. currently I have the file saved in C:\Doc...
Your code is using a relative path; python is looking in the current directory (whatever that may be) to load your file. What the current directory *is* depends on how you started your Python script and if you executed any code that may have changed the current working directory. Use a full absolute path instead: ```...
You can hit this error when you're running a Python script from a Directory where the file is not contained. Sounds simple to fix, put the CSV file in the same folder as the .PY file. However when you're running under an IDE like VSCode the command output might `cd` to another directory when it executes your python fi...
error "no such file or directory" when reading in csv file in python
[ "", "python", "csv", "filepath", "" ]
As the title suggests... I'm trying to figure out the fastest way with the least overhead to determine if a record exists in a table or not. Sample query: ``` SELECT COUNT(*) FROM products WHERE products.id = ?; vs SELECT COUNT(products.id) FROM products WHERE products.id = ?; vs SELECT products.id FROM p...
`SELECT TOP 1 products.id FROM products WHERE products.id = ?;` will outperform all of your suggestions as it will terminate execution after it finds the first record.
`EXISTS` (or `NOT EXISTS`) is specially designed for checking if something exists and therefore should be (and is) the best option. It will halt on the first row that matches so it does not require a `TOP` clause and it does not actually select any data so there is no overhead in size of columns. You can safely use `SE...
Fastest way to determine if record exists
[ "", "sql", "sql-server", "performance", "select", "count", "" ]
I'm working scientifically with images from a microscope, where each of the 3 RGB channels are encoded as uint16 (0-65536). Currently I use OpenCV2 and NumPy to work with the images, and using the flag "cv2.IMREAD\_UNCHANGED" everything works fine with the reading, and I can do some work on the image and return it to u...
OpenCV does support writing 16 Bit TIFF images. Make sure you are using a current version (>= 2.2). The truncation probably happens to img in your code before saving with OpenCV.
Maybe it helps if the numpy.uint16 is replace by cv2.CV\_16U. In some example the parameter is passed in as a string e.g. 'uint16'. Sry, reputation too low for a comment.
Python: How to save image with 16 bit channels (e.g. 48 RGB)?
[ "", "python", "opencv", "" ]
I saw this complex select statement that has several components: aliases and subqueries ``` SELECT u.ID, u.username, u.active, u.email, u.admin, u.banned, u.name, (SELECT GROUP_CONCAT( g.name SEPARATOR'-groupsep-' ) FROM groups g, group_memberships gm WHERE g.ID = gm.group AND gm.user =...
This query is using a subquery in the `FROM` clause of the query. The subquery returns a set of rows which is in turn used as a table by the rest of the query. In MySQL, it is mandatory to give an alias to this 'virtual table'. So concretely, the name `groupmemberships` refers to the result set from ``` SELECT ...
From the [Mysql manual](http://dev.mysql.com/doc/refman/5.0/en/from-clause-subqueries.html) > Subqueries are legal in a SELECT statement's FROM clause. The actual syntax is: > > SELECT ... FROM (subquery) [AS] name ... > > The [AS] name clause is mandatory, because every table in a FROM clause must have a name. So ba...
Complex SQL query with an alias
[ "", "mysql", "sql", "alias", "" ]
I have two tables in two schemas - schema1 and schema2. Both the tables have the same design, except that Schema2 has a clustered index on the primary key of the tables. Schema1 tables don't have primary key (That's how the old design was and I've to revamp it with a new schema design which is schema2) In schema 2, C...
Table 1/Schema 1 is a heap table, you insert a record it's added to the end of that table. When you query that table the records are (but don't count it) returned in the same order they are inserted. Table 2/Schema 2 is a clustered index table, i.e. when you insert a record into that table it's inserted in between rec...
> But the order of the rows are not the same and I don't know how to compare the data in both Of course. You added a clustered index - this means that the indexed table is stored sorted according to the index. But without an `ORDER BY` clause, there is not defined order. > I don't know how to compare the data in both...
How does index affect the result of two tables - one with index and another without index?
[ "", "sql", "sql-server-2008", "select", "clustered-index", "" ]
The date column that I have is in `varchar2` and I want to convert those values in `YYYY-MM-DD` ``` DATE 7/26/2013 7/29/2013 8/1/2013 8/4/2013 7/28/2013 7/31/2013 8/3/2013 7/30/2013 8/5/2013 7/25/2013 8/2/2013 8/6/2013 7/27/2013 ```
## You should ***never*** store dates in a `VARCHAR` column So in order to display it differently now, you need to first convert the string to a date and then back to a string If you are certain that all "dates" do have the right (and same) format, then the following should work: ``` select to_char(to_date(date, 'mm...
You have to convert your string to `date` and than convert to `char` with expected format ``` select TO_CHAR(TO_DATE(datecol, 'MM/DD/YYYY'),'YYYY-MM-DD') from your_table ``` [**Sql Fiddle Demo**](http://sqlfiddle.com/#!4/d41d8/15531/0)
Convert mm/dd/yyyy to yyyy-mm-dd in Oracle
[ "", "sql", "oracle", "datetime", "" ]
I have table called '**system**' has 2 columns '**variable**' and '**value**' with the following data: * variable = 'username' => value = 'myuser' * variable = 'password' => value = 'mypass' *I want to update these 2 fields in 1 query.* **the 2 queries are:** ``` UPDATE System SET Value = 'myuser' WHERE Variable = ...
``` UPDATE System SET Value = (CASE WHEN Variable = 'Username' THEN 'myuser' WHEN Variable = 'Password' THEN 'mypass' END) WHERE Variable = 'Username' or Variable = 'Password' ```
Yes, using he case statement: ``` UPDATE System SET Value = (case when Variable = 'UserName' then 'myuser' when Variable = 'Password' then 'mypass' else Value end) WHERE Variable in ('Username', 'Password'); ```
is it possible to update 2 fields in the same column in one query (mysql)
[ "", "mysql", "sql", "sql-update", "" ]
Is there any methods for python+selenium to find parent elements, brother elements, or child elements just like `driver.find_element_parent?` or `driver.find_element_next?` or `driver.find_element_previous`? eg: ``` <tr> <td> <select> <option value=0, selected='selected'> </option> <opti...
You can find a parent element by using `..` xpath: ``` input_el = driver.find_element_by_name('A') td_p_input = input_el.find_element_by_xpath('..') ``` --- What about making a separate xpath for getting selected option, like this: ``` selected_option = driver.find_element_by_xpath('//option[@selected="selected"]')...
From your example, I figure you only want the selected option within a table-row if and only if this row also has an input element with the name "A", no matter where in the html-tree this element resides below the row-element. You can achieve this via the xpath ancestor-axis. For the sake of better readability I will...
How to find parent elements by python webdriver?
[ "", "python", "selenium", "xpath", "selenium-webdriver", "parent-child", "" ]
I have done two algorithms and I want to check which one of them is more 'efficient' and uses less memory. The first one creates a numpy array and modifies the array. The second one creates a python empty array and pushes values into this array. Who's better? First program: ``` f = open('/Users/marcortiz/Documents/vL...
Well finally I made some changes thanks to the answers. My two programs: ``` f = open('/Users/marcortiz/Documents/vLex/pylearn2/mlearning/classify/files/models/model_training.txt') zeros = np.zeros((60343,4917)) counter = 0 start = timeit.default_timer() for l in f: row = l.split(",") ...
The problem with both codes is that you're loading the whole file in memory first using `file.readlines()`, you should iterate over the file object directly to get one line at a time. ``` from itertools import izip #generator function def func(): with open('filename.txt') as f: for line in f: row =...
Python: push item vs creating empty list (efficiency)
[ "", "python", "arrays", "performance", "memory", "stability", "" ]
I've found a great python library implementing Levenshtein functions (distance, ratio, etc.) at <http://code.google.com/p/pylevenshtein/> but the project seems inactive and the documentation is nowhere to be found. I was wondering if anyone knows better than me and can point me to the documentation.
You won't have to generate the docs yourself. There's an online copy of the original Python Levenshtein API: <http://www.coli.uni-saarland.de/courses/LT1/2011/slides/Python-Levenshtein.html>
Here is an example: ``` # install with: pip install python-Levenshtein from Levenshtein import distance edit_dist = distance("ah", "aho") ```
Where can the documentation for python-Levenshtein be found online?
[ "", "python", "documentation", "levenshtein-distance", "" ]
Is there a way to programatically get the line number and name of a function? For example, I want to pass a list of strings to a function : ``` s = [calling_module, calling_function, line_number] report(s) ``` Currently I just put it all in manually : ``` s = ["module abc", "func()", "line 22", "notes"] report(s) `...
Use [`inspect`](http://docs.python.org/2/library/inspect.html) module functions. For example, ``` import inspect def b(): f = inspect.currentframe() current = inspect.getframeinfo(f) caller = inspect.getframeinfo(f.f_back) #caller = inspect.getframeinfo(inspect.getouterframes(f)[1][0]) print(__nam...
You may want something along the lines of `traceback.extract_stack()`: ``` >>> def test(): ... print "In Function" ... print traceback.extract_stack() ... >>> >>> test() In Function [('<stdin>', 1, '<module>', None), ('<stdin>', 3, 'test', None)] ``` Though the results would need to be parsed.
getting the module and line that a function was called from
[ "", "python", "" ]
I have a column called `Cities`, this column has data as the following: ``` City 1 CITY 1 CITY 1 ``` I want to Select only the `CITY` (Capitalized) This is not doing the job: ``` SELECT * FROM Location WHERE Cities LIKE 'CITY 1' ``` This is giving me all the `CITY 1` includes `City 1`
By default, SQL Server will use a case insensitive collation. ``` SELECT * FROM Location WHERE Cities LIKE 'CITY 1' COLLATE Latin1_General_CS_AI ``` Mark your comparison operator with a case-sensitive collation to apply a case sensitive filter
I assume your SQL is in a non case-sensitive collation in which case a search for 'C' and 'c' will return the same result. You need to do a case-sensitive search by collating the query: ``` SELECT * FROM Location WHERE Cities LIKE 'CITY 1' COLLATE <Insert case sensitive collation here> ``` e.g. ``` SELECT * FROM Loc...
SELECT Only the words that are capitalized
[ "", "sql", "sql-server", "" ]
I am trying to find out whether a list of integers is coherent or 'at one stretch', meaning that the difference between two neighboring elements must be exactly one and that the numbers must be increasing monotonically. I [found](https://stackoverflow.com/a/3149493/145400) a neat approach where we can group by the numb...
how bout ``` sorted_list = sorted(my_list) return sorted_list == range(sorted_list[0],sorted_list[-1]+1) ``` or if its only coherent if it is already sorted ``` return my_list == range(my_list[0],my_list[-1]+1) ``` if you are using python 3 you will need `list(range(...))`
Unless I'm overlooking something in your examples, this simpler solution is actually shorter. ``` >>> l1 = [1, 2, 3, 4, 5, 6] >>> l2 = [1, 2, 3, 4, 5, 7] >>> l3 = [1, 2, 3, 4, 5, 5] >>> l4 = [1, 2, 3, 4, 5, 4] >>> l5 = [6, 5, 4, 3, 2, 1] >>> >>> def is_coherent(seq): ... return seq == range(seq[0], seq[0]+len(seq...
Python: find out whether a list of integers is coherent
[ "", "python", "sequence", "python-itertools", "" ]
I need a small billing report for the usage of the VMs inside openstack after it is stopped, so far I already find the way to get flavor information (vCPU, disk, memory) from instance name. And I want to know the VM's startup time to calculate now. Are there any good ways to fetch it from openstack python API ? It w...
(I got the answer from [china-openstack community](http://groups.google.com/group/china-openstack-user-group), and shared here) In the [novaclient usage module](http://docs.openstack.org/developer/python-novaclient/api/novaclient.v1_1.usage.html#novaclient.v1_1.usage.Usage), all the instance (active or terminated) can...
I just wanted to retrieve server's uptime. I mean real uptime for the time the server has been UP, not since its creation. * I created a new machine, the machine was running and I was getting some *update* value; this was nicely incremented * Then I stopped the machine and issued the request again: The response correc...
How can I get VM instance running time in openstack via python API?
[ "", "python", "openstack-nova", "" ]
I have two tables: CustomerInformation ``` CustomerName CustomerAddress CustomerID LocationID BillDate CITY - 1 500 N ST 47672001 29890 2012-07-20 00:00:00.000 0 CITY - 1 500 N ST 47672001 29890 2012-07-20 00:00:00.000 6890 CITY - 1 500 N ST 47672001 29890 2012-08-17 00:00:00.000 0 C...
``` select C.grp, count(*) from CustomerInformation as ci left outer join CustomerMeters as cm on cm.CustomerAddress = ci.Address outer apply ( select case when cm.ID is not null then 'Number of records in both tabless' else 'not in CustomerMeters' ...
Count of records that resulted from the join: ``` SELECT COUNT(*) FROM CustomerInformation JOIN CustomerMeters ON CustomerAddress = Address ``` Number of records *exclusively* in the `CustomerInformation` table: ``` SELECT COUNT(*) FROM CustomerInformation AS CI -- Records in CustomerInformation WHERE NOT EXIS...
SQL Server Comparing how many data matches, and only in one tables
[ "", "sql", "sql-server", "" ]
I have looked around StackOverflow and couldn't find an answer to my specific question so forgive me if I have missed something. ``` import re target = open('output.txt', 'w') for line in open('input.txt', 'r'): match = re.search(r'Stuff', line) if match: match_text = match.group() target.wri...
Write the newline of each line at the beginning of the *next* line. To avoid writing a newline at the beginning of the first line, use a variable that is initialized to an empty string and then set to a newline in the loop. ``` import re with open('input.txt') as source, open('output.txt', 'w') as target: newlin...
Another thing you can do, is to `truncate` the file. `.tell()` gives us the current byte number in the file. We then subtract one, and truncate it there to remove the trailing newline. ``` with open('a.txt', 'w') as f: f.write('abc\n') f.write('def\n') f.truncate(f.tell()-1) ``` On Linux and MacOS, the `-...
Don't write final new line character to a file
[ "", "python", "" ]
I am surprised I have not been able to find a solution to this. We have a table ``` ORDER # | PRODUCT ID | PRICE 1 | 1 | 1.00 1 | 2 | 2.00 2 | 3 | 3.00 2 | 4 | 4.00 3 | 1 | 5.00 3 | 4 | 6.00 ``` ...
Try: ``` select sum(price) as total_price from orders where prod_order in (select prod_order from orders where product_id = 1) ``` Check [this SQLFiddle](http://sqlfiddle.com/#!3/29bf4/3) to confirm the result.
Here is a query that gives the results you are looking for: ``` SELECT OrderNum, SUM(PRICE) as TotalPrice FROM MyTable AS M WHERE EXISTS (SELECT 1 -- Include only orders that contain product 1 FROM MyTable AS M2 WHERE M2.OrderNum=M.OrderNum AND M2.ProductId=1) GROUP BY OrderNum ```
SQL Query - Sum of Order tha Contain an Item
[ "", "sql", "select", "where-clause", "" ]
I have a large function in my script that contains the bulk of the logic of my program. At one point, it used to span ~100 lines which I then tried to refactor into multiple smaller functions. However, I had many local variables that were eventually being modified in the smaller functions, and I needed some way to kee...
Without more information, it's hard to know whether this is appropriate or not, but… An object is a namespace. In particular, you can turn each of those local variables into attributes on an object. For example: ``` class LargeThing(object): def __init__(self): self.x = 6 def large_func(self): ...
Closures will work here: ``` def large_func() x = 6 def func_that_uses_x(): print x def func_that_modifies_x(): nonlocal x # python3 only x += 1 func_that_uses_x() func_that_modifies_x() ```
Python Large Functions Many Variables (Refactoring)
[ "", "python", "" ]
Did my research and made several improvements, got very close to solving this issue but now I'm stuck and need help please. Task: To convert a list of strings floats to floats with 2 decimal points Original list: ``` mylist = ['17.21', '33.40', '24.39', '3.48', '1.02', '0.61', '18.03', '1.84'] ``` Aim ``` mylist =...
`[round(float(i), 2) for i in mylist]` This should work. Format is for inserting strings in other strings, as in `"Hello, {}! What is your favourite {}?".format("Jim", "colour")`. If you want to the numbers to only exist to 2 decimal places, you could use the decimal module.
You asked a question "What am I doing wrong here?". I think, what you are doing wrong is passing as an argument to: ``` floatlist.append() ``` this: ``` "{0:.2f}".format(item) ``` Format method of str class is simply returning formatted string, and you are expecting to get fixed two decimal points float. Float does...
Convert a list of string floats to a list of floats with 2 decimal points
[ "", "python", "list", "floating-point", "decimal", "" ]
I'm using SQL server 2008. ``` SELECT resultTable.OrderNumber, resultTable.ProjectId, resultTable.BatchId, resultTable.CustomerId, resultTable.City, resultTable.Street, resultTable.PostalCode, resultTable.Co...
Try something like this: ``` ORDER BY CASE WHEN @sortBy = 'OrderNumber' THEN resultTable.OrderNumber END, CASE WHEN @sortBy = 'ProjectId' THEN resultTable.ProjectId END, CASE WHEN @sortBy = 'Address' THEN resultTable.Country END, CASE WHEN @sortBy = 'Address' THEN resultTable.City END...
You probably want ``` CASE WHEN @sortBy = 'Address' THEN isnull(resultTable.Country,'') + isnull( resultTable.City,'') + isnull( resultTable.Street,'') + isnull( resultTable.PostalCode,'') end ```
SQL server: Order by multiple columns incorrect syntax
[ "", "sql", "sql-server-2008", "" ]
![enter image description here](https://i.stack.imgur.com/BpLII.png) In the above t-sql table I would like very much for the Total row to appear at the bottom. I have been wracking my head against this and in all of my other Queries simply using ORDER BY Status works as Total is alphabetically much farther down the lis...
The results of a `select` query, unless an order is explicitly specified via an 'order by' clause, can be returned in *any* order. Moreover, the order in which they are returned is not even deterministic. Running the exact same query 3 times in succession might return the exact same result set in 3 different orderings....
In SQL Server (and most other databases), you can use `case` to sort certain [statūs](http://en.wiktionary.org/wiki/status#Noun_3) above others: ``` order by case Status when 'Total' then 2 else 1 end , Status ``` In MS Access, you can use `iif`: ``` order by iif(Status ...
Changing position of a row in sql
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I am trying to insert some data from an excel sheet on to SQL Server 2008 R2. Can I Create a table which on insertion of the data can insert leading 0 if the length is less than 5 --- ``` FirstName Lastname State Country Zip XY z VA USA 22031 AB Y MO USA ...
Leave the ZIP in the int format, and add the leading zeroes when you select it. Like this: ``` select right('0000'+convert(varchar(5), ZIP), 5) ```
You can pad the Zip in a varchar field using a pad function like ``` INSERT INTO TableName (FirstName, Lastname, State, Country, Zip) VALUES ('AB', 'Y', 'MO'. 'USA', REPLACE(STR(423, 5), SPACE(1), '0') ) ``` or selecting it formatted if you want to keep the field as INT ``` SELECT FirstName, Lastname, State, Country...
Can we create a table which Can insert leading Zeros on operation
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I'm trying desperately to get Celery to play nicely with Django, but to no avail. I am getting tripped up on the following: project/settings.py: ``` ... import djcelery djcelery.setup_loader() BROKER_URL = 'django://' CELERY_RESULT_BACKEND = 'django://' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'js...
*(Converted to an answer from comments)* From the [stack trace](http://pastebin.com/Qgcr6EDB) I take it that the line `return backend(app=self, url=url)` is where the exception happens. So whatever `backend` is, it doesn't seem to be a callable. I would try to set a pdb breakpoint in that file (`celery/app/base.py`) ...
Just in case somebody is using Celery beat and gets the same error message. In my app I used ``` command=/opt/python/run/venv/bin/celery beat -A appname --loglevel=INFO --workdir=/tmp -S django --pidfile /tmp/celerybeat.pid ``` and got this error message. Since I copied most of the code for daemonizing Celery beat us...
celery task decorator throws "TypeError: 'Module object is not callable"
[ "", "python", "django", "celery", "django-celery", "" ]
I'm trying to define a method to check whether or not every element of a list is a factor of the parameter. Here's what I have: ``` def factorall(x): if all(x % num for num in nums) == 0: return True else: return False ``` (In this case nums is a list of the integers from 1 to 10) However, this returns tru...
You should do the comparison inside the `all` function, or simply remove it, and use negation of the result `x % num`: ``` def factorall(x): return all(not x % num for num in nums) ``` The return statement works same as: ``` return all(x % num == 0 for num in nums) ``` I agree that the 2nd one seems clearer.
you should use `not any` instead of all ``` def factorall(x): return not any(x%num for num in nums) #if any of these is a value other than 0 ``` or if you want it like you currently have it ``` def factorall(x): return all(x%num==0 for num in nums) ```
Trying to check a condition for every element in a list of integers
[ "", "python", "" ]
The table I am dealing with has multiple rows which have the same values for `lat` and `lon`. The example shows that `1`, `3`, `5` have the same location but the `name` attribute differs. The `hash` is built from `name`, `lat` and `lon` and differs therefore. ``` BEFORE: id | name | lat | lon | flag | hash ----+----...
Not sure this is very efficient, but it [works in just one query](http://sqlfiddle.com/#!2/091ec/2): ``` UPDATE t JOIN ( SELECT MAX(t.id) AS maxid, lat, lon FROM t JOIN t AS duplicates USING (lat, lon) GROUP BY lat, lon HAVING COUNT(*) > 1 ) AS maxima USING (lat, lon) SET flag = IF(id = maxid, 1, 2); ```
Assuming you want all canonical records to have a `flag=1` (and not just those records that have duplicates) you can do: ``` UPDATE table t1 SET t1.flag = 1 WHERE t1.id in ( SELECT min(id) FROM table t2 WHERE t1.lat = t2.lat AND t1.lon = t2.lon ); UPDATE table SET flag = 2 WHERE flag is null; COMMIT;...
How to update multiple duplicates with different values on the same table?
[ "", "mysql", "sql", "join", "duplicates", "" ]
I have been trying to optimize a python script I wrote for the last two days. Using several profiling tools (cProfile, line\_profiler etc.) I narrowed down the issue to the following function below. `df` is a numpy array with 3 columns and +1,000,000 rows (data type is float). Using line\_profiler, I found out that th...
As noted by other people, this isn't vectorized at all, so your slowness is really due to slowness of the Python interpreter. [Cython](http://cython.org) can help you a lot here with minimal changes: ``` >>> %timeit MonteCarlo(df, 5, 1000) 10000 loops, best of 3: 48 us per loop >>> %timeit MonteCarlo_cy(df, 5, 1000) ...
Using cython to compile the function gives a very substantial improvement to runtime. In a separate file called "funcs.pyx" I have the following code: ``` cimport cython import numpy as np cimport numpy as np def MonteCarlo(np.ndarray[np.float_t, ndim=2] df, float head, float span): # Pick initial truck cde...
Optimizing a python function with numpy arrays
[ "", "python", "function", "loops", "optimization", "numpy", "" ]
I'm currently trying to port some Scala code to a Python project and I came across the following bit of Scala code: ``` lazy val numNonZero = weights.filter { case (k,w) => w > 0 }.keys ``` `weights` is a really long list of tuples of items and their associated probability weighting. Elements are frequently added a...
In Scala, `lazy val` is a final variable that is evaluated once at the time it is first accessed, rather than at the time it is declared. It is essentially a [memoized](http://en.wikipedia.org/wiki/Memoization) function with no arguments. Here's one way you can implement a memoization decorator in Python: ``` from fun...
Essentially, you want to change how attribute access works for `numNonZero`. Python does that with a [descriptor](http://docs.python.org/2/howto/descriptor.html). In particular, take a look at their application to [Properties](http://docs.python.org/2/howto/descriptor.html#properties). With that, you can defer calcula...
Python equivalent of Scala's lazy val
[ "", "python", "scala", "" ]
I've got a file that I've already opened, and I want to auto-close it. Is there any existing way to wrap the file in a `with` statement?
This works fine: ``` f = open('file') with f: print >> f, "Open" print f.closed # True ``` But this will fail, as `file.__enter__` does not behave like a recursive mutex: ``` f = open('file') with f: print >> f, "Open" with f: print >> f, "Open" print >> f, "This errors, as the file is alr...
Tested in Python 3: ``` >>> f = open('test.txt', 'w') >>> with f: ... f.closed ... f.write('a') False 1 >>> f.closed True ``` So yes, you can. It doesn't reopen files that have already been closed, though: ``` >>> f.closed True >>> with f: ... f.write('a') Traceback (most recent call last): File "<pys...
Can I use a with statement on a file that already exists?
[ "", "python", "" ]
I have a table with a number of dates (some dates will be NaN) and I need to find the oldest date so a row may have DATE\_MODIFIED, WITHDRAWN\_DATE, SOLD\_DATE, STATUS\_DATE etc.. So for each row there will be a date in one or more of the fields I want to find the oldest of those and make a new column in the dataframe...
Just apply the `min` function along the axis=1. ``` In [1]: import pandas as pd In [2]: df = pd.read_csv('test.cvs', parse_dates=['d1', 'd2', 'd3']) In [3]: df.ix[2, 'd1'] = None In [4]: df.ix[1, 'd2'] = None In [5]: df.ix[4, 'd3'] = None In [6]: df Out[6]: d1 d2 d...
If `table`is your DataFrame, then use its `min` method on the relevant columns: ``` table['END_DATE'] = table[['DATE_MODIFIED','SOLD_DATE']].min(axis=1) ```
Finding the min date in a Pandas DF row and create new Column
[ "", "python", "pandas", "" ]
I am trying to call a python script in another python script. The directories are different. I tried ``` import subprocess subprocess.call("C:\temp\hello2.py", shell=True) ``` But got nothing. It does not work. I reviewed many forums, but all of them are about calling it when both scripts are on the same directory. ...
Escape backslash (`\`) ``` "C:\\temp\\hello2.py" ``` or use raw string ``` r"C:\temp\hello2.py" ``` --- ``` >>> print "C:\temp\hello2.py" C: emp\hello2.py >>> print "C:\\temp\\hello2.py" C:\temp\hello2.py >>> print r"C:\temp\hello2.py" C:\temp\hello2.py ```
First the backslash thing, and second you should **always** call python scripts with the python interpreter. You never know what are `*.py` files associated with. So: ``` import sys import subprocess subprocess.call([sys.executable, 'C:\\temp\\hello2.py'], shell=True) ```
Call a python script in a python script
[ "", "python", "call", "subprocess", "" ]
I want make a specific element of each dictionary the first element in a list of dictionaries. How would I do this, or is it even possible given that dictionaries are unordered? I don't want to use .sort() by itself or OrderedDict because both will not bring the desired element to the top of the keys as the keys are a...
Wrap your dict in a list and move your code out. Instead of ``` data = {'code':'this is the code', 'some':'other', 'stuff':'here'} ``` do ``` data = ['this is the code', {'some':'other', 'stuff':'here'}] ```
As others have pointed out, Python's dictionaries are now ordered (by insertion order) since Python 3.6. The cleanest way I know to move a single item to the front of a dictionary is to use `pop()`: ``` d = {'a': 1, 'b': 2, 'c': 3} # original dict d = {'b': d.pop('b'), **d} # new order print(d) # {'b': 2, 'a': 1, 'c...
How to make a specific key the first key in a dictionary?
[ "", "python", "sorting", "dictionary", "" ]
I'm still new to SQL and am kind of stumped on this one. I would greatly appreciate any help or advice. I have a table with a value column and an ID column that I then order by the value column in descending order. i.e: ``` Value | ID 12 | A 09 | A 08 | B 08 | C 07 | A 06 |...
For SQL Server 2008 ``` ;WITH CTE AS ( SELECT Value ,ID ,CONVERT(DECIMAL(10,2),Value/CONVERT(DECIMAL(10,2),SUM(Value) OVER(PARTITION BY [ID]))) AS [Unit Value] FROM Table1 ) SELECT a.Value,a.ID,a.[Unit Value], (SELECT SUM(b.[Unit Value]) FROM CTE b ...
Try to use over() partition by () statement
SQL unit value and cumulative sum by groups
[ "", "sql", "" ]
I'm having great difficulty in finding how to do this. I've been searching for hours but can't come up with a working solution. I have two tables. ``` TableA - Code, TranDate, Amount TableB - Code Amount ``` I wish to Update TableB Amount by deducting the sum of Amount in TableA (where a.code = b.code and a.TranDat...
Easy way with Common Table Extensions: ``` with cte as ( select A.Code, sum( A.Amount ) as Amount from TableA A inner join TableB B on A.Code = B.Code where A.TranDate > *someDete* Group by A.Code ) update B Set B.amount = CTE.amount from TableB B inner join CTE on B.Code = CTE.Code ``` **Edited** Due OP...
Try: ``` @Date = 'A GIVEN DATE' UPDATE TableB SET TableB.Amount = TableB.Amount - (SELECT SUM(TableA.Amount) FROM TableA as A, TableB WHERE A.Code = B.Code AND A.TranDate > @Date) ```
updating a field with sum of fields in another table
[ "", "sql", "sql-server-2005", "" ]
I am new to programming. I have hundreds of CSV files in a folder and certain files have the letters DIF in the second column. I want to rewrite the CSV files without those lines in them. I have attempted doing that for one file and have put my attempt below. I need also need help getting the program to do that dfor al...
I made some changes to your code: ``` import csv import glob import os fns = glob.glob('*.csv') for fn in fns: reader=csv.reader(open(fn,"rb")) with open (os.path.join('out', fn), 'wb') as f: w = csv.writer(f) for row in reader: if not 'DIF' in row: w.writerow(ro...
[Most sequence types support the **in** or **not in** operators](http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange), which are much simpler to use to test for values than figuring index positions. ``` for row in reader: if not 'DIF' in row: csv.wri...
Reading CSV files and rewriting them without certain rows Python
[ "", "python", "csv", "if-statement", "for-loop", "" ]
I want to save an ID between requests, using Flask `session` cookie, but I'm getting an `Internal Server Error` as result, when I perform a request. I prototyped a simple Flask app for demonstrating my problem: ``` #!/usr/bin/env python from flask import Flask, session app = Flask(__name__) @app.route('/') def run...
According to [Flask sessions documentation](http://flask.pocoo.org/docs/quickstart/#sessions): > ... > What this means is that the user could look at the contents of your > cookie but not modify it, unless they know the secret key used for > signing. > > In order to use sessions you **have to set a secret key**. Set ...
As **@falsetru** mentioned, you have to set a secret key. Before sending the `session` cookie to the user's browser, Flask signs the cookies cryptographically, and that doesn't mean that you cannot decode the cookie. I presume that Flask keeps track of the signed cookies, so it can perform it's own 'magic', in order t...
Internal Server Error when using Flask session
[ "", "python", "session", "cookies", "flask", "" ]