Search Results

Search found 8344 results on 334 pages for 'count'.

Page 11/334 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Sort and limit queryset by comment count and date using queryset.extra() (django)

    - by thornomad
    I am trying to sort/narrow a queryset of objects based on the number of comments each object has as well as by the timeframe during which the comments were posted. Am using a queryset.extra() method (using django_comments which utilizes generic foreign keys). I got the idea for using queryset.extra() (and the code) from here. This is a follow-up question to my initial question yesterday (which shows I am making some progress). Current Code: What I have so far works in that it will sort by the number of comments; however, I want to extend the functionality and also be able to pass a time frame argument (eg, 7 days) and return an ordered list of the most commented posts in that time frame. Here is what my view looks like with the basic functionality in tact: import datetime from django.contrib.comments.models import Comment from django.contrib.contenttypes.models import ContentType from django.db.models import Count, Sum from django.views.generic.list_detail import object_list def custom_object_list(request, queryset, *args, **kwargs): '''Extending the list_detail.object_list to allow some sorting. Example: http://example.com/video?sort_by=comments&days=7 Would get a list of the videos sorted by most comments in the last seven days. ''' try: # this is where I started working on the date business ... days = int(request.GET.get('days', None)) period = datetime.datetime.utcnow() - datetime.timedelta(days=int(days)) except (ValueError, TypeError): days = None period = None sort_by = request.GET.get('sort_by', None) ctype = ContentType.objects.get_for_model(queryset.model) if sort_by == 'comments': queryset = queryset.extra(select={ 'count' : """ SELECT COUNT(*) AS comment_count FROM django_comments WHERE content_type_id=%s AND object_pk=%s.%s """ % ( ctype.pk, queryset.model._meta.db_table, queryset.model._meta.pk.name ), }, order_by=['-count']).order_by('-count', '-created') return object_list(request, queryset, *args, **kwargs) What I've Tried: I am not well versed in SQL but I did try just to add another WHERE criteria by hand to see if I could make some progress: SELECT COUNT(*) AS comment_count FROM django_comments WHERE content_type_id=%s AND object_pk=%s.%s AND submit_date='2010-05-01 12:00:00' But that didn't do anything except mess around with my sort order. Any ideas on how I can add this extra layer of functionality? Thanks for any help or insight.

    Read the article

  • where is the best palce to count the lazy load property using JPA

    - by Ke
    Let's say we have a "Question" and "Answer" entity, @Entity public class Question extends IdEntity { @Lob private String content; @Transient private int answerTotal; @OneToMany(fetch = FetchType.LAZY) private List<Answer> answers = new ArrayList<Answer>(); ...... I need to tell how many answers for the question every time Question is queryed. So I need to do count: String count = "select count(o) from Answer o WHERE o.question=:q"; My question is, where is the best place to do the count? (Because I did a lot of query about Question entity, by date, by tag, by category, by asker, etc. It is obviously not a good solution to add count operation in each query. My first attempt is to implement a @PostLoad listener, so every time Question entity is loaded, I do count. However, EntityManager cannot be injected in listener. So this way does not work. Any hint?

    Read the article

  • count of last item of the day

    - by frenchie
    I have a query in which one of the fields contains the count of status. The status can change several times a day and the count should be based on the final status of the day. For instance, this is what I have for Status1. CountStatus1 = (from status in MyDataContext.StatusHistories where status.UserID == TheUserID where status.StatusDateTime.Month == TheMonth.Month where status.StatusDateTime.Year == TheMonth.Year where status.NewStatus == 1 // where the LAST STATUS OF THE DAY == 1 select status.StatusID).Count() The problem is that I want to select the last status of the day to be equal to 1, and count those. The status for a day can change from 1 to 4 to 2 to 5 to 3 and then to finally to 1; if I write the query like this, the count will include 2 1's and then the 4,2,5 and 3 will also be counted in CountStatus4, CountStatus3, CountStatus"n". The return data is a monthly report grouped by day, where each day is a row. The structure of the query looks like this: var OutputStatusReport = from w in MyDataContext.WorkHistory where w.UserID == TheUserID where w.WorkDatetime.Month == TheMonth.Month where w.WorkDatetime.Year == TheMonth.Year group w by w.Datetime.Date into daygroups select new MyObjectModel { CountStatus1 = ...., CountStatus2 = ...., CountStatus3 =...... }; So I need the day of the count to match the day of daygroups. I'm struggling to figure this one out and any help is very welcome. Thanks.

    Read the article

  • Counting character count in Access database column ins SQL

    - by jzr
    Good Evening. My problem is possibly very easy, I just have spent some time researching now and probably have a brain lock and unable to solve this, help would be much appreciated. database structure: col1 col2 col3 col4 ==================== 1233+4566+ABCD+CDEF 1233+4566+ACD1+CDEF 1233+4566+D1AF+CDEF I need to count character count in col3, wanted result in from the previous table would be: char count =========== A 3 B 1 C 2 D 3 F 1 1 2 is this possible to achieve by using SQL only? at the moment I am thinking of passing a parameter in to SQL query and count the characters one by one and then sum, however I did not start the VBA part yet, and frankly wouldn't want to do that. this is my query at the moment: PARAMETERS X Long; SELECT First(Mid(TABLE.col3,X,1)) AS [col3 Field], Count(Mid(TABLE.col3,X,1)) AS Dcount FROM TEST GROUP BY Mid(TABLE.col3,X,1) HAVING (((Count(Mid([TABLE].[col3],[X],1)))>=1)); ideas and help are much appreciated, as being said this is probably very for some of your guys, I don't usually work with access and SQL. Thanks.

    Read the article

  • Count Items in Access 2003

    - by Anna
    I have a table which contains a column with different items which i would like to count by there type. For example the table looks like the following: Id Type 1 Table 2 Table 3 TV 4 TV 5 Table 6 TV 7 TV The result should looks like: Type NumOfItems Table 3 TV 4 I use the following code which doesn't work for my Access 2003: SELECT Table1.Type, Count(Table1.Type) AS NumOfItems FROM Table1

    Read the article

  • OS X: fsck_hfs unable to fix volume directory count

    - by Charles Duffy
    I'm running fsck_hfs on a very large volume. Unfortunately, there's an issue it appears to be unable to fix -- it reports it, loops back to start with Rechecking..., and reports it again, ad infinitum. ** Checking catalog hierarchy. Invalid volume directory count (It should be 513997 instead of 513998) Incorrect folder count in a directory (id = 27444570) (It should be 1 instead of 0) I've tried adding the -r ("rebuild catalog btree") flag to fsck, but the issue still recurs.

    Read the article

  • JavaScript: this

    - by bdukes
    JavaScript is a language steeped in juxtaposition.  It was made to “look like Java,” yet is dynamic and classless.  From this origin, we get the new operator and the this keyword.  You are probably used to this referring to the current instance of a class, so what could it mean in a language without classes? In JavaScript, this refers to the object off of which a function is referenced when it is invoked (unless it is invoked via call or apply). What this means is that this is not bound to your function, and can change depending on how your function is invoked. It also means that this changes when declaring a function inside another function (i.e. each function has its own this), such as when writing a callback. Let's see some of this in action: var obj = { count: 0, increment: function () { this.count += 1; }, logAfterTimeout = function () { setTimeout(function () { console.log(this.count); }, 1); } }; obj.increment(); console.log(obj.count); // 1 var increment = obj.increment; window.count = 'global count value: '; increment(); console.log(obj.count); // 1 console.log(window.count); // global count value: 1 var newObj = {count:50}; increment.call(newObj); console.log(newObj.count); // 51 obj.logAfterTimeout();// global count value: 1 obj.logAfterTimeout = function () { var proxiedFunction = $.proxy(function () { console.log(this.count); }, this); setTimeout(proxiedFunction, 1); }; obj.logAfterTimeout(); // 1 obj.logAfterTimeout = function () { var that = this; setTimeout(function () { console.log(that.count); }, 1); }; obj.logAfterTimeout(); // 1 The last couple of examples here demonstrate some methods for making sure you get the values you expect.  The first time logAfterTimeout is redefined, we use jQuery.proxy to create a new function which has its this permanently set to the passed in value (in this case, the current this).  The second time logAfterTimeout is redefined, we save the value of this in a variable (named that in this case, also often named self) and use the new variable in place of this. Now, all of this is to clarify what’s going on when you use this.  However, it’s pretty easy to avoid using this altogether in your code (especially in the way I’ve demonstrated above).  Instead of using this.count all over the place, it would have been much easier if I’d made count a variable instead of a property, and then I wouldn’t have to use this to refer to it.  var obj = (function () { var count = 0; return { increment: function () { count += 1; }, logAfterTimeout = function () { setTimeout(function () { console.log(count); }, 1); }, getCount: function () { return count; } }; }()); If you’re writing your code in this way, the main place you’ll run into issues with this is when handling DOM events (where this is the element on which the event occurred).  In that case, just be careful when using a callback within that event handler, that you’re not expecting this to still refer to the element (and use proxy or that/self if you need to refer to it). Finally, as demonstrated in the example, you can use call or apply on a function to set its this value.  This isn’t often needed, but you may also want to know that you can use apply to pass in an array of arguments to a function (e.g. console.log.apply(console, [1, 2, 3, 4])).

    Read the article

  • Problem counting item frequency on T-SQL

    - by Raúl Roa
    I'm trying to count the frequency of numbers from 1 to 100 on different fields of a table. Let's say I have the table "Results" with the following data: LottoId Winner Second Third --------- --------- --------- --------- 1 1 2 3 2 1 2 3 I'd like to be able to get the frequency per numbers. For that I'm using the following code: --Creating numbers temp table CREATE TABLE #Numbers( Number int) --Inserting the numbers into the temp table declare @counter int set @counter = 0 while @counter < 100 begin set @counter = @counter + 1 INSERT INTO #Numbers(Number) VALUES(@counter) end -- SELECT #Numbers.Number, Count(Results.Winner) as Winner,Count(Results.Second) as Second, Count(Results.Third) as Third FROM #Numbers LEFT JOIN Results ON #Numbers.Number = Results.Winner OR #Numbers.Number = Results.Second OR #Numbers.Number = Results.Third GROUP BY #Numbers.Number The problem is that the counts are repeating the same values for each number. In this particular case I'm getting the following result: Number Winner Second Third --------- --------- --------- --------- 1 2 2 2 2 2 2 2 3 2 2 2 ... When I should get this: Number Winner Second Third --------- --------- --------- --------- 1 2 0 0 2 0 2 0 3 0 0 2 ... What am I missing?

    Read the article

  • WPF ContextMenu with bound items: Items.Count == 0 in ContextMenuOpening event

    - by OregonGhost
    I have a ContextMenu with the ItemsSource bound to the selected item of a list view, like this: <ContextMenu ItemsSource="{Binding Path=PlacementTarget.SelectedItem, RelativeSource={RelativeSource Self}, Converter={StaticResource possibleConverter}}"/> The possibleConverter enumerates all possible values for a property of the the selected item, which are shown in the context menu. In the Opened event of the context menu, I select the current value like this: var cm = e.OriginalSource as ContextMenu; if (cm != null) { var lv = cm.PlacementTarget as ListView; var field = lv.SelectedItem as Field; var item = cm.ItemContainerGenerator.ContainerFromItem(cm.Items.OfType<object>().Where(o => o.ToString().Equals(field.StringValue)).FirstOrDefault()) as MenuItem; if (item != null) { item.IsChecked = true; } } Not particularly elegant, but it works. With the debugger I verified that the ContextMenu.Items.Count property has a non-zero value when expected (i.e. cm.Items.Count is non-zero in the if). So far, so good. There are, however, items in the listview where the context menu will have no items. In this case, an empty menu is shown. I tried to suppress this in the ContextMenuOpening event in the list view, like this: var lv = sender as ListView; if (lv != null) { var cm = lv.ContextMenu; if ((cm != null) && (cm.Items.Count > 0)) { // Here we want to check the current item, which is currently done in the Opened event. } else { e.Handled = true; } } Seems like it should work. However, cm.Items.Count is always zero. This is true even if ListView.SelectedItem did not change: For an item with menu entries, the menu is shown correctly after the first click, so the data binding has already happend. It is shown correct the second time as well, but in any case, Items.Count is zero in the ContextMenuOpening event. What am I missing? How can I suppress empty context menus? Why is the count zero in the ContextMenuOpening handler, which is in Windows Forms (ContextMenuStrip.Opening) the canonical point where to do these things? EDIT: Upon further investigating, it turns out that in the ContextMenuOpening handler, any binding to the listview fails, which is why ItemsSource is null. I tried to bind via ElementName, via a FindAncestor relationship, all to no avail. The PlacementTarget is null during that event. An ugly hack worked though: In the ContextMenuOpening event, I assign the list view to the ContextMenu.Tag property, while the ItemsSource binding now binds to Tag.SelectedItem. This updates the binding, so Items.Count is what it should be. It's still strange. How can you do meaningful things in ContextMenuOpening other than replacing the menu or something, if the binding fails because somehow the context menu is out of context during the event? Was it only tested with static pre-defined menu items?

    Read the article

  • Probability algorithm: Finding probable correct item in a list (e.g John, John, Jon)

    - by Andrew White
    Hi, Take for example the list (L): John, John, John, John, Jon We are to presume one item is to be correct (e.g. John in this case), and give a probability it is correct. First (and good!) attempt: MostFrequentItem(L).Count / L.Count (e.g. 4/5 or 80% likelihood) But consider the cases: John, John, Jon, Jonny John, John, Jon, Jon I want to consider the likelihood of the correct item being John to be higher in the first list! I know I have to count the SecondMostFrequent Item and compare them. Any ideas? This is really busting my brain! Thx, Andrew

    Read the article

  • Use Any() and Count() in Dynamic Linq

    - by ArpanDesai
    I am trying to write dynamic Linq Library query to fetch record on condition, Customers who has order count is greater than 3 and ShipVia field equal 2. Below is my syntax what i have tried. object[] objArr = new object[10]; objArr[0] = 1; IQueryable<Customer> test = db.Customers.Where("Orders.Count(ShipVia=2)", objArr); and IQueryable<Customer> test = db.Customers.Where("Orders.Any(ShipVia=2).Count()", objArr); But both are not working. In second query Any returns true so it won't work with Count. Suggest me a way to implement this.

    Read the article

  • Retain count problem iphone sdk

    - by neha
    Hi all, I'm facing a memory leak problem which is like this: I'm allocating an object of class A in class B. // RETAIN COUNT OF CLASS A OBJECT BECOMES 1 I'm placing the object in an nsmutablearray. // RETAIN COUNT OF CLASS A OBJECT BECOMES 2 In an another class C, I'm grabbing this nsmutablearray, fetching all the elements in that array in a local nsmutablearray, releasing this first array of class B. // RETAIN COUNT OF CLASS A OBJECTS IN LOCAL ARRAY BECOMES 1 Now in this class C, I'm creating an object of class A and fetching the elements in local nsmutable array. //RETAIN COUNT OF NEW CLASS A OBJECT IN LOCAL ARRAY BECOMES 2 [ALLOCATION + FETCHED OBJECT WITH RETAIN COUNT 1] My question is, I want to retain this array which I'm displaying in tableview, and want to release it after new elements are filled in the array. I'm doing this in class B. So before adding new elements, I'm removing all the elements and releasing this array in class B. And in class C I'm releasing object of class A in dealloc. But in Instruments-Leaks it's showing me leak for this class A object in class C. Can anybody please tell me wheather where I'm going wrong. Thanx in advance.

    Read the article

  • Show count of all google map markers

    - by aland
    Is there any easy way using the api to get a count of all markers on a map? I have a page similar to this http://www.gorissen.info/Pierre/maps/googleMapLocationv3.php where a user can add markers by clicking on the map. I'd also like to show a count of all the markers. I could do this by declaring a global count var and incrementing it in the event listener, but I thought it would be better if there was an API method I could use and I can find it in the docs.

    Read the article

  • help converting sql to linq expression with count

    - by Philip
    I am trying to convert the following SQL into a LINQ expression SELECT COUNT(ID) AS Count, MyCode FROM dbo.Archive WHERE DateSent=@DateStartMonth AND DateSent<=@DateEndMonth GROUP BY MyCode and I have been trying to follow this webpage as an example http://stackoverflow.com/questions/606124/converting-sql-containing-top-count-group-and-order-to-linq-2-entities I got this so far but I am stuck on understanding the new part var res=(from p in db.Archives where (p.DateSent>= dateStartMonth) && (p.DateSent< dateToday) group p by p.MyCode into g select new { ??????MyCode = g.something?, MonthlyCount= g.Count() }); Thanks in advance for helping greatly appreciated Philip

    Read the article

  • IEnumerable doesn't have Count

    - by Alexander
    I have the following method: public bool IsValid { get { return (GetRuleViolations().Count() == 0); } } public IEnumerable<RuleViolation> GetRuleViolations(){ //code here } Why is it that when I do .Count above it is underlined in red? I got the following error: Error 1 'System.Collections.Generic.IEnumerable' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?) c:\users\a\documents\visual studio 2010\Projects\NerdDinner\NerdDinner\Models\Dinner.cs 15 47 NerdDinner

    Read the article

  • MySql: Select all entries with count...

    - by Scarface
    Hey guys quick question, I have a query that I want to count all entries it finds, and select all so when I use while($row=mysql_fetch_assoc($query)){ it will list all entries. The problem I am encountering is that while, all the entries are successfully counted and the right number is listed, only the latest entry is select and listed when I echo $row['title']. If I delete , COUNT(*) as total then it selects all but I was wondering if it was possible to use count and select *. I was wondering if anyone knew what I am doing wrong? SELECT *, COUNT(*) as total FROM new_messages WHERE username='$session->username

    Read the article

  • ActionScript find LineBreak in XML and count them

    - by Pepe Sanchez
    Hi, i have an XML that has line breaks like this: This is a text that has line breaks im reading that xml in action script.. and trying to count how many linebreaks are in the text. Here is my code.. it returns 0 , it should return 5 for the example. function countBreaks(str:String) : Number { var count:Number = 0; for (var i:Number = 0; i < str.length-1; i++) { if(str.charAt(i)+str.charAt(i+1) eq "\n") count++; } return count; } I appreciate any help :)

    Read the article

  • Postfix count relayed messages per user

    - by Martino Dino
    I would like to know if it's possible to count the outgoing (relayed) messages on a per user basis in postfix. I'm managing a small commercial SMTP relay and decided that it would be nice to have a detailed daily report on how much mail a single user have sent (and eventually enforce some limits) possibly in realtime. I've looked almost everywhere and started to think that writing my own milter would be the way to go... Are you aware of anything that already exists for postfix that can count and report relayed mail for authenticated users (a script, milter or whatever)?

    Read the article

  • Issue with maxWorkerThreads and thread count

    - by Kartik M
    I have created an ASP.NET application which creates threads in an infinite loop. I set maxWorkerThreads to 20 in processModel in machine.config. When I checked the Thread count in perfmon there was around 7000 threads created in worker process. In PageLoad() I have: using System.Threading; ... int count = 0; var threadList = new System.Collections.Generic.List<System.Threading.Thread>(); try { while (true) { Thread newThread = new Thread(ThreadStart(DummyCall), 1024); newThread.Start(); threadList.Add(newThread); count++; } } catch (Exception ex) { Response.Write(count + " : " + ex.ToString()); } Function: void DummyCall() { System.Threading.Thread.Sleep(1000000000); } How do I restrict thread creation in ASP.NET with IIS6/7?

    Read the article

  • How to use group by and having count in Linq

    - by Luke
    I am having trouble trying to convert the following query from SQL to Linq, in particular with the having count and group by parts of the query: select ProjectID from ProjectAssociation where TeamID in ( select TeamID from [User] where UserID in (4)) group by ProjectID having COUNT(TeamID) = (select distinct COUNT(TeamID) from [User] where UserID in (4)) Any advice on how to do so would be much appreciated.

    Read the article

  • count(*) is it really expensive ?

    - by Anil Namde
    I have a page where i have 4 tabs displaying 4 different reports based of different tables. Now i get row count of each tabled using select count() from table query and display number of rows available in each table on the tabs. Now with each page post back 5 count() queries are executed (4 to get counts and 1 for pagination) and 1 query for getting report. Now my question is should is count(*) query really expensive that i should keep the row counts (at least which are displayed on tab) in view state of page instead of queering each time? How much expensive it is ?

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >