Search Results

Search found 17924 results on 717 pages for 'z order'.

Page 186/717 | < Previous Page | 182 183 184 185 186 187 188 189 190 191 192 193  | Next Page >

  • NSFetchedResultsController sort different sections differently (ascending/descending)?

    - by PartiallyFinite
    In my app, I have a task list (no, it's not just another todo app), and I display the tasks in a UITableView using an NSFetchedResultsController. Here is the relevant initialisation code: NSSortDescriptor *dueDateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"due" YES]; NSSortDescriptor *completionSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"completed" ascending:YES]; [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:completionSortDescriptor, dueDateSortDescriptor, nil]]; _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:@"completed" cacheName:nil]; What this does is sorts the tasks such that I have an incomplete tasks section at the top, sorting with the tasks due first on top, and tasks due later further down. This all works. However, this means that the second section, the one with the completed tasks, also sorts this way, so the earliest due tasks are on top. What I want to do is change it so the second section sorts the other way around (in descending order), but the first section stays sorted in ascending order. Is this even possible? How would I go about this? Why I want to do this: The way it currently works, the tasks at the top of the second section (and therefore the most visible) are the ones that were completed ages ago. It is more likely that the user would want to see the tasks that are more recently completed (and uncheck one if it was accidentally checked), and presumably the tasks with a more recent due date were more recently completed. I am happy to add a separate completion date field to the Core Data task object if necessary (This isn't a shipping application yet, so I can change the data format however I like).

    Read the article

  • sort elements in jQuery object

    - by Fresheyeball
    <div class="myClass">1</div> <div class="myClass">2</div> <div class="myClass">3</div> <div class="myClass">4</div> <div class="myClass">5</div> <div class="myClass">6</div> var $myClass = $('.myClass'); $myClass.eq(0).text() //returns '1' $myClass.eq(4).text() //returns '5' $myClass.eq(5).text() //returns '6' What I want to do is reorder the objects in jQuery manually. //fantasy command reversing $myClass.eqSorter([5,4,3,2,1,0]); $myClass.eq(0).text() //returns '6' $myClass.eq(5).text() //returns '1' What I really want is to allow a fully custom order input //fantasy command custom ordering $myClass.eqSorter([3,5,4,2,0,1]); $myClass.eq(0).text() //returns '4' $myClass.eq(5).text() //returns '2' Now I've looked at basic ways of doing this like .sort as a part of javascript, but .sort takes a dynamic argument the compares things, and does not allow for a fully custom order. I also looked at making a new blank jquery object that I could pass elements into like this $newObjectVar.eq(0) = $myClass.eq(3); for example. But as of yet I have not found a way to make a blank jQuery object like this.

    Read the article

  • Unable to Get values from Web Form to a PHP Class to Display

    - by kentrenholm
    I am having troubles getting the value from my variables submitted via a web form using a PHP class file. Here is my structure of the web page: Order Form Page Process.php Page Book.php Page I can easily get the user data entered (on Order Form Page), process, and display it on the Process.php page. The issue is that I must create a Book class and print the details of the data using the Book class. I have an empty constructor printing out "created" so I know my constructor is being called. I also am able to print the word "title" so I know I can print to the screen by using the Book class. My issue is that I can't get values in my variables in the Book class. Here is my variable declaration: private $title; Here is my printDetails function: public function printDetails () { echo "Title: " . $this->title . "<br />"; } Here is my new instance of the book class: $bookNow = new book; Here are my get and set functions: function __getTitle($title) { return $this->$title; } function __setTitle($title,$value) { $this->$title = $value; } I do have four other variables that I'm looking to display as well. Each of those have their own variable declaration, a line in printDetails, and their own setter and getter. Lastly, I also have a call to the Book class in my process PHP. It looks like this: function __autoload($book) { include $book . '.php'; } $bookNow = new book(); Any help, much appreciated. It must be something so very small (I'm hoping).

    Read the article

  • Creating a 'flexible' XML schema

    - by Fiona Holder
    I need to create a schema for an XML file that is pretty flexible. It has to meet the following requirements: Validate some elements that we require to be present, and know the exact structure of Validate some elements that are optional, and we know the exact structure of Allow any other elements Allow them in any order Quick example: XML <person> <age></age> <lastname></lastname> <height></height> </person> My attempt at an XSD: <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="person"> <xs:complexType> <xs:sequence> <xs:element name="firstname" minOccurs="0" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> <xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> Now my XSD satisfies requirements 1 and 3. It is not a valid schema however, if both firstname and lastname were optional, so it doesn't satisfy requirement 2, and the order is fixed, which fails requirement 4. Now all I need is something to validate my XML. I'm open to suggestions on any way of doing this, either programmatically in .NET 3.5, another type of schema etc. Can anyone think of a solution to satisfy all 4 requirements?

    Read the article

  • For-Loop and LINQ's deferred execution don't play well together

    - by Tim Schmelter
    The title suggests that i've already an idea what's going on, but i cannot explain it. I've tried to order a List<string[]> dynamically by each "column", beginning with the first and ending with the minimum Length of all arrays. So in this sample it is 2, because the last string[] has only two elements: List<string[]> someValues = new List<string[]>(); someValues.Add(new[] { "c", "3", "b" }); someValues.Add(new[] { "a", "1", "d" }); someValues.Add(new[] { "d", "4", "a" }); someValues.Add(new[] { "b", "2" }); Now i've tried to order all by the first and second column. I could do it statically in this way: someValues = someValues .OrderBy(t => t[0]) .ThenBy(t => t[1]) .ToList(); But if i don't know the number of "columns" i could use this loop(that's what I thought): int minDim = someValues.Min(t => t.GetLength(0)); // 2 IOrderedEnumerable<string[]> orderedValues = someValues.OrderBy(t => t[0]); for (int i = 1; i < minDim; i++) { orderedValues = orderedValues.ThenBy(t => t[i]); } someValues = orderedValues.ToList(); // IndexOutOfRangeException But that doesn't work, it fails with an IndexOutOfRangeException at the last line. The debugger tells me that i is 2 at that time, so the for-loop condition seems to be ignored, i is already == minDim. Why is that so?

    Read the article

  • Using a variable derived from a drop-down list as the column name in a select statement ... Access DB

    - by user1459698
    I'm working with the world's worst DB that was already here so don't blame me for that. So, here's what I have so far ... module = txtModule.value presstype = txtPressType.value SQL_query = "SELECT * FROM tbl_spareparts WHERE '"& module &"' <> '""' AND '"& module &"' = '"& presstype &"' AND Manufacturer = '"& txtsrch.value &"' ORDER BY SAP_Part_No" Set rsData = conn.Execute(SQL_query) This brings up the following SQL statement: SELECT * FROM tbl_spareparts WHERE 'Banyan_Module' <> '"' AND 'Banyan_Module' = 'PB' AND Manufacturer = 'Tester' ORDER BY SAP_Part_No Is there any way I can use the module variable as a column name - obviously the ''s around the column name are causing an error. This is really bothering me. BTW, I'm writing this in VBScript inside a .HTA application page as it has to run locally on tech PCs. Thanks. R.

    Read the article

  • What data stucture should I use for BigInt class

    - by user1086004
    I would like to implement a BigInt class which will be able to handle really big numbers. I want only to add and multiply numbers, however the class should also handle negative numbers. I wanted to represent the number as a string, but there is a big overhead with converting string to int and back for adding. I want to implement addition as on the high school, add corresponding order and if the result is bigger than 10, add the carry to next order. Then I thought that it would be better to handle it as a array of unsigned long long int and keep the sign separated by bool. With this I'm afraid of size of the int, as C++ standard as far as I know guarantees only that int < float < double. Correct me if I'm wrong. So when I reach some number I should move in array forward and start adding number to the next array position. Is there any data structure that is appropriate or better for this? Thanks in advance.

    Read the article

  • Reordering columns (fields) in a ADO Recordset

    - by Sukotto
    I have a classic asp webpage written in vbscript that outputs the results from a third-party stored procedure. My user wants the page to display the columns of data in a different order than they come in from the database. Is there an easy and safe way to re-order the columns in an ADO recordset? I did not write this page and cannot change the SP. What is the minimum change I can make here to get the job done and not risk screwing up all the other stuff in the page? The code looks something like dim Conn, strSQL, RS Set Conn = Server.CreateObject("ADODB.Connection") Conn.Open ServerName Set strSQL = "EXEC storedProc @foo = " & Request("fooParam") 'This stored procedure returns a date column, an arbitrary ' ' number of data columns, and two summation columns. We ' ' want the two summation columns to move so they appear ' ' immediately after the data column ' Set RS = Server.CreateObject("ADODB.RecordSet") RS.ActiveConnection = Nothing RS.CursorLocation = adUseClient RS.CursorType = adOpenStatic RS.LockType = adLockBatchOptimistic RS.Open strSQL, Conn, adOpenDynamic, adLockOptimistic dim A ' ----- ' ' Insert some code here to move the columns of the RS around ' ' to suit the whim of my user ' ' ----- ' ' Several blocks of code that iterate over the RS and display it various ways ' RS.MoveFirst For A = 0 To RS.Fields.Count -1 ' do stuff ' Next ... RS.MoveFirst For A = 0 To RS.Fields.Count -1 ' do more stuff ' Next RS.Close : Set RS = Nothing Conn.Close : Set Conn = Nothing

    Read the article

  • Further filter SQL results

    - by eric
    I've got a query that returns a proper result set, using SQL 2005. It is as follows: select case when convert(varchar(4),datepart(yyyy,bug.datecreated),101)+ ' Q' +convert(varchar(2),datepart(qq,bug.datecreated),101) = '1969 Q4' then '2009 Q2' else convert(varchar(4),datepart(yyyy,bug.datecreated),101)+ ' Q' +convert(varchar(2),datepart(qq,bug.datecreated),101) end as [Quarter], bugtypes.bugtypename, count(bug.bugid) as [Total] from bug left outer join bugtypes on bug.crntbugtypeid = bugtypes.bugtypeid and bug.projectid = bugtypes.projectid where (bug.projectid = 44 and bug.currentowner in (-1000000031,-1000000045) and bug.crntplatformid in (42,37,25,14)) or (bug.projectid = 44 and bug.currentowner in (select memberid from groupmembers where projectid = 44 and groupid in (87,88)) and bug.crntplatformid in (42,37,25,14)) group by case when convert(varchar(4),datepart(yyyy,bug.datecreated),101)+ ' Q' +convert(varchar(2),datepart(qq,bug.datecreated),101) = '1969 Q4' then '2009 Q2' else convert(varchar(4),datepart(yyyy,bug.datecreated),101)+ ' Q' +convert(varchar(2),datepart(qq,bug.datecreated),101) end, bugtypes.bugtypename order by 1,3 desc It produces a nicely grouped list of years and quarters, an associated descriptor, and a count of incidents in descending count order. What I'd like to do is further filter this so it shows only the 10 most submitted incidents per quarter. What I'm struggling with is how to take this result set and achieve that.

    Read the article

  • Paging using Linq-To-Sql based on two parameters in asp.net mvc...

    - by Pandiya Chendur
    As two parameters i say currentPage and pagesize .....I thus far used sql server stored procedures and implemented paging like this, GO ALTER PROCEDURE [dbo].[GetMaterialsInView] -- Add the parameters for the stored procedure here @CurrentPage INT, @PageSize INT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; SELECT *,ROW_NUMBER() OVER (ORDER BY Id) AS Row FROM ( SELECT *,ROW_NUMBER() OVER (ORDER BY Id) AS Row FROM InTimePagingView ) AS InTimePages WHERE Row >= (@CurrentPage - 1) * @PageSize + 1 AND Row <= @CurrentPage*@PageSize SELECT COUNT(*) as TotalCount FROM InTimePagingView SELECT CEILING(COUNT(*) / CAST(@PageSize AS FLOAT)) NumberOfPages FROM InTimePagingView END Now i am using Linq-to-sql and i use this, public IQueryable<MaterialsObj> FindAllMaterials() { var materials = from m in db.Materials join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id where m.Is_Deleted == 0 select new MaterialsObj() { Id = Convert.ToInt64(m.Mat_id), Mat_Name = m.Mat_Name, Mes_Name = Mt.Name, }; return materials; } Now i want to return the records,TotalCount where i use Total count to generate pagenumbers..... Is this possible... Any suggestion... EDIT: Just found this... NorthWindDataContext db = new NorthWindDataContext(); var query = from c in db.Customers select c.CompanyName; //Assuming Page Number = 2, Page Size = 10 int iPageNum = 2; int iPageSize = 10; var PagedData = query.Skip((iPageNum - 1) * iPageSize).Take(iPageSize); ObjectDumper.Write(PagedData);

    Read the article

  • Why does this javascript code have an infinite loop?

    - by asdas
    optionElements is a 2d array. Each element has an array of length 2. These are an integer number and an element. I have a select list called linkbox, and i want to add all of the elements to the select list. The order I want them to go in is important, and is determined by the number each element has. It should be smallest to highest. So think of it like this: optionElements is: [ [5, <option>], [3, <option], [4, <option], [1, <option], [2, <option]] and it would add them to link box in order of those numbers. BUT that is not what happens. It is an infinite loop after the first time. I added the x constraint just to stop it from freezing my browser but you can ignore it. var b; var smallest; var samllestIndex; var x = 0; while(optionElements.length > 0 && ++x < 100) { smallestIndex = 0; smallest = optionElements[0][0]; b = 0; while( ++b < optionElements.length) { if(optionElements[b][0] > smallest) { smallestIndex = b; smallest = optionElements[b][0]; } } linkbox.appendChild(optionElements[smallestIndex][1]); optionElements.unshift(optionElements[smallestIndex]); } can someone point out to me where my problem is?

    Read the article

  • Vectorize matrix operation in R

    - by Fernando
    I have a R x C matrix filled to the k-th row and empty below this row. What i need to do is to fill the remaining rows. In order to do this, i have a function that takes 2 entire rows as arguments, do some calculations and output 2 fresh rows (these outputs will fill the matrix). I have a list of all 'pairs' of rows to be processed, but my for loop is not helping performance: # M is the matrix # nrow(M) and k are even, so nLeft is even M = matrix(1:48, ncol = 3) # half to fill k = nrow(M)/2 # simulate empty rows to be filled M[-(1:k), ] = 0 cat('before fill') print(M) # number of empty rows to fill nLeft = nrow(M) - k nextRow = k + 1 # list of rows to process (could be any order of non-empty rows) idxList = matrix(1:k, ncol = 2) for ( i in 1 : (nLeft / 2)) { row1 = M[idxList[i, 1],] row2 = M[idxList[i, 2],] # the two columns in 'results' will become 2 rows in M # fake result, return 2*row1 and 3*row2 results = matrix(c(2*row1, 3*row2), ncol = 2) # fill the matrix M[nextRow, ] = results[, 1] nextRow = nextRow + 1 M[nextRow, ] = results[, 2] nextRow = nextRow + 1 } cat('after fill') print(M) I tried to vectorize this, but failed... appreciate any help on improving this code, thanks!

    Read the article

  • Django: Storing ordered, arbitrary references

    - by Sarah
    I'm new to Django, and I'm not sure what I want is possible: I have a number of items that I want each AppUser (extended User model) to be able to reference. That is, given an AppUser, I want to be able to extract its list of items in the way that AppUser has chosen to order them. In general, these items would actually be references to something else in the database, and this led me to one possible solution: Store the keys for the given objects in a CommaSeparatedIntegerField in AppUser. This way, a user could have stored {7, 3, 232, 42, 1} in their items field and both the references and their preferred order would be stored. However, this feels hacky. Since most db backends store CommaSeparatedIntegerField as a VARCHAR internally, the user is not only limited by a number of objects, but also the number of digits in their chosen items. Eg. "you may store 10 items if you choose items with itemID < 10, but only 5 items if 10 < itemID < 100". Is there a better way to do this?

    Read the article

  • Managing a log stream in C++ in a cout-like notation

    - by Andry
    Hello! I have a class in c++ in order to write log files for an application of mine. I have already built the class and it works, it is something like this: class Logger { std::string _filename; public: void print(std::string tobeprinted); } Well, it is intuitive that, in order to print a line in the log file, for an object of Logger, it is simply necessary to do the following: Logger mylogger("myfile.log"); mylogger.print(std::string("This is a log line")); Well. Using a method approach is not the same as using a much better pattern like << is. I would like to do the following: Logger mylogger("myfile.log"); mylogger << "This is a log line"; That's all. I suppose I must overload the << operator... But overloading using this signature (the classic one): ostream& operator<<(ostream& output, const MyObj& o); But I do not have a ostream... So, should I do as follows? Logger& operator<<(Logger& output, const std::string& o); Is this the right way? Thanks

    Read the article

  • creating an object within a function of a program

    - by user1066524
    could someone please tell me what I need to do in order to create an object in a function. I will try to explain by making up some sort of example... Let's say I have a program named TimeScheduler.cpp that implements the class Schedule.h (and I have the implementation in a separate file Schedule.cpp where we define the methods). In the declaration file we have declared two constructors Schedule(); //the default and Schedule(int, int, int);//accepts three arguments to get to the point--let's say in the main program file TimeScheduler.cpp we created our own functions in this program apart from the functions inherited from the class Schedule. so we have our prototypes listed at the top. /*prototypes*/ void makeSomeTime(); etc..... we have main(){ //etc etc... } we then define these program functions void makeSomeTime(){ //process } let's say that inside the function makeSomeTime(), we would like to create an array of Schedule objects like this Schedule ob[]={ summer(5,14, 49), fall(9,25,50) }; what do I have to do to the function makeSomeTime() in order for it to allow me to create this array of objects. The reason I ask is currently i'm having difficulty with my own program in that it WILL allow me to create this array of objects in main()....but NOT in a function like I just gave an example of. The strange thing is it will allow me to create a dynamic array of objects in the function..... like Schedule *ob = new Schedule[n+1]; ob[2]= Schedule(x,y,z); Why would it let me assign to a non-dynamic array in main(), but not let me do that in the function?

    Read the article

  • query not displaying proper result

    - by ravindra
    In my Rails 3 project I have the following code for My controller: class TasksController < ApplicationController def today @tasks = Task.today @task = Task.new respond_to do |format| format.html { render :text=> "Sorry , you don't have any task pending today." } format.html # new.html.erb format.xml { render :xml => @tasks } end end def this_week @tasks = Task.this_week @task = Task.new respond_to do |format| format.html { render :text => "Sorry , No content for selected period." } format.html # new.html.erb format.xml { render :xml => @tasks } end end end My model: class Task < ActiveRecord::Base def self.today Task.where(:due_date => "Date.today" , :task_status => "open").order("due_date ASC") end def self.this_week Task.where(:due_date =>"Time.now.this_week" , :task_status => "open" ).order("due_date ASC") end end Why it does not displaying anything in the relative view. Please help me. Thanks

    Read the article

  • Pre-done SQLs to be converted to Rails' style moduls

    - by Hoornet
    I am a Rails newbie and would really appreciate if someone converted these SQLs to complete modules for rails. I know its a lot to ask but I can't just use find_by_sql for all of them. Or can I? These are the SQLs (they run on MS-SQL): 1) SELECT STANJA_NA_DAN_POSTAVKA.STA_ID, STP_DATE, STP_TIME, STA_OPIS, STA_SIFRA, STA_POND FROM STANJA_NA_DAN_POSTAVKA INNER JOIN STANJA_NA_DAN ON(STANJA_NA_DAN.STA_ID=STANJA_NA_DAN_POSTAVKA.STA_ID) WHERE ((OSE_ID=10)AND (STANJA_NA_DAN_POSTAVKA.STP_DATE={d '2010-03-30'}) AND (STANJA_NA_DAN_POSTAVKA.STP_DATE<={d '2010-03-30'})) 2) SELECT ZIGI_OBDELANI.OSE_ID, ZIGI_OBDELANI.DOG_ID AS DOG_ID, ZIGI_OBDELANI.ZIO_DATUM AS DATUM, ZIGI_PRICETEK.ZIG_TIME_D AS ZIG_PRICETEK, ZIGI_KONEC.ZIG_TIME_D AS ZIG_KONEC FROM (ZIGI_OBDELANI INNER JOIN ZIGI ZIGI_PRICETEK ON ZIGI_OBDELANI.ZIG_ID_PRICETEK = ZIGI_PRICETEK.ZIG_ID) INNER JOIN ZIGI ZIGI_KONEC ON ZIGI_OBDELANI.ZIG_ID_KONEC = ZIGI_KONEC.ZIG_ID WHERE (ZIGI_OBDELANI.OSE_ID = 10) AND (ZIGI_OBDELANI.ZIO_DATUM = {d '2010-03-30'}) AND (ZIGI_OBDELANI.ZIO_DATUM <= {d '2010-03-30'}) AND (ZIGI_PRICETEK.ZIG_VELJAVEN < 0) AND (ZIGI_KONEC.ZIG_VELJAVEN < 0) ORDER BY ZIGI_OBDELANI.OSE_ID, ZIGI_PRICETEK.ZIG_TIME ASC 3) SELECT STA_ID, SUM(STP_TIME) AS SUM_STP_TIME, COUNT(STA_ID) FROM STANJA_NA_DAN_POSTAVKA WHERE ((STP_DATE={d '2010-03-30'}) AND (STP_DATE<={d '2010-03-30'}) AND (STA_ID=3) AND (OSE_ID=10)) GROUP BY STA_ID 4) SELECT DATUM, TDN_ID, TDN_OPIS, URN_OPIS, MOZNI_PROBLEMI, PRIHOD, ODHOD, OBVEZNOST, ZAKLJUCEVANJE_DATUM FROM OBRACUNAJ_DAN WHERE ((OSE_ID=10) AND (DATUM={d '2010-02-28'}) AND (DATUM<={d '2010-03-30'})) ORDER BY DATUM These SQLs are daily working hours and I got them as is. Also I got Database with it which (as you can see from the SQL-s) is not in Rails conventions. As a P.S.: 1)Things like STP_DATE={d '2010-03-30'}) are of course dates (in Slovenian date notation) and will be replaced with a variable (date), so that the user could choose date from and date to. 2) All of this data will be shown in the same page in the table,so maybe all in one module? Or many?; if this helps, maybe. So can someone help me? Its for my work and its my 1st project and I am a Rails newbie and the bosses are getting inpatient(they are getting quite loud actually) Thank you very very much!

    Read the article

  • Why aren't my threads start at the same time? Java

    - by Ada
    Hi, I have variable number of threads which are used for parallel downloading. I used this, for(int i = 0; i< sth; i++){ thrList.add(new myThread (parameters)); thrList.get(i).start(); thrList.get(i).join(); } I don't know why but they wait for each other to complete. When using threads, I am supposed get mixed print outs, since right then there are several threads running that code. However, when I print them out, they are always in order and one thread waits for the previous one to finish first. I only want them to join the main thread, not wait for each other. I noticed that when I measured time while downloading in parallel. How can I fix this? Why are they doing it in order? In my .java, there is MyThread class with run and there is Downloader class with static methods and variables. Would they be the cause of this? The static methods and variables? How can I fix this problem?

    Read the article

  • What happens if I just add a second IP to a domain?

    - by tntu
    We have two servers that are in constant sync. We have two applications that connect to them. Each app to different server. We devised a new version of those apps that will read a dns entry and get a list of IP addresses and try them in order. Now problem is old apps. We have noticed that some ppl still use the old ones even if we have released the new. If we were to add two IP's to each domain would they receive the IP's in the order we set them or random? Either way it will still work for us but I'm just curious. If first server goes offline will the client application try the other? To be noted for old version: Interruption does not affect in any way the continuation once connection is reestablished. Each communication is independent of previous ones. Applications connect at set intervals of time anywhere between 5 seconds to 1 hour. Connection is done simply using an http post to the URL in question.

    Read the article

  • question about permutation problem

    - by davit-datuashvili
    i have posted similar problem here http://stackoverflow.com/questions/2920315/permutation-of-array but i want following we know that with length n there is n! possible permutation from which one such that all element are in order they are in sorted variant so i want break permutation when array is in order and print result but something is wrong i think that problem is repeated of permutation here is my code import java.util.*; public class permut{ public static Random r=new Random(); public static void display(int a[],int n){ for (int i=0;i<n;i++){ System.out.println(a[i]); } } public static void Permut(int a[],int n){ int j=0; int k=0; while (j<fact(n)){ int s=r.nextInt(n); for (int i=0;i<n;i++){ k=a[i]; a[i]=a[s]; a[s]=k; } j++; if (sorted(a,n)) display(a,n); break; } } public static void main(String[]args){ int a[]=new int[]{3,4,1,2}; int n=a.length; Permut(a,n); } public static int fact(int n){ if (n==0 || (n==1) ) return 1; return n*fact(n-1); } public static boolean sorted(int a[],int n ){ boolean flag=false; for (int i=0;i<n-1;i++){ if (a[i]<a[i+1]){ flag=true; } else{ flag=false; } } return flag; } } can anybody help me? result is nothing

    Read the article

  • decoding jquery json data in php

    - by Mac Taylor
    hey guys recenlty i made a script to move objects and save the orders now i have a little to do to finish this script everything works fine , just one question : how can i save not numeric data in my json script this is my script : function updateWidgetData(){ var items=[]; $('.widget-title').each(function(){ var weightId=$(this).attr('id'); $('.column').each(function(){ var columnId=$(this).attr('id'); $('.widget', this).each(function(i){ var collapsed=0; if($(this).find('.widget-inside').css('display')=="none") collapsed=1; //Create Item object for current panel var item={ id: $(this).attr('id'), collapsed: collapsed, order : i, column: columnId, weight: weightId }; //Push item object into items array items.push(item); }); }); }); //Assign items array to sortorder JSON variable var sortorder={ items: items }; //Pass sortorder variable to server using ajax to save state $.post('updatePanels.php', 'data='+$.toJSON(sortorder), function(response){ if(response=="success") $("#console").html('<div class="success">Saved</div>').hide().fadeIn(1000); setTimeout(function(){ $('#console').fadeOut(1000); }, 2000); }); } and this is my php script : $data=json_decode($_POST["data"]); foreach($data->items as $item) { //Extract column number for panel $col_id=preg_replace('/[^\d\s]/', '', $item->column); //Extract id of the panel $widget_id=preg_replace('/[^\d\s]/', '', $item->id); $sql="UPDATE widgets SET column_id='$col_id', sort_no='".$item->order."', collapsed='".$item->collapsed."' WHERE id='".$widget_id."'"; mysql_query($sql) or die('Error updating widget DB'); } echo "success"; everything works fine till i use numeric value for columns' id but i need non numeric values forexample id='columnr' i want to extract r but i cant get it right any help plz !?

    Read the article

  • Most efficient way to make an activity log

    - by Nathan
    I am making a "recent activity" tab to profiles on my site and I also am going to have a log for moderators to see everything that happens on the site. This would require making an activity log of some sort. I just don't know what would be better. I have 2 options: Make a table called "activity" and then every time someone does something, add a record to it with the type of action, user id, timestamp, etc. Problem: table could get very long. Join all 3 tables (questions, answers, answer_comments) and then somehow show all these on the page in the order in which the action was taken. Problem: this would be extremely hard because I have no clue how I could make it say "John commented on an answer on Question Title Here" by just joining 3 tables. Does anyone know of a better way of making an activity log in this situation? I am using PHP and MySQL. If this is either too inefficient or hard I will probably just forget the Recent Activity tab on profiles but I still need an activity log for moderators. Here's some SQL that I started making for option 2, but this would not work because there is no way of detecting whether the action is a comment, question, or answer when I echo the info in a while loop: SELECT q.*, a.*, ac.* FROM questions q JOIN answers a ON a.questionid = q.qid JOIN answer_comments ac ON c.answerid = a.ans_id WHERE q.user = $userid AND a.userid = $userid AND ac.userid = $userid ORDER BY q.created DESC, a.created DESC, ac.created DESC Thanks in advance for any help!

    Read the article

  • Is there a concise way to map a string to an enum in Objective-C?

    - by zekel
    I have a string I want to parse and return an equivalent enum. I need to use the enum type elsewhere, and I think I like how I'm defining the class. The problem is that I don't know a good way to check the string against the enum values without being redundant about the order of the enums. typedef enum { ZZColorRed, ZZColorGreen, ZZColorBlue, } ZZColorType; - (ZZColorType)parseColor:(NSString *)inputString { // inputString will be @"red", @"green", or @"blue" (trust me) // how can I turn that into ZZColorRed, etc. without // redefining their order like this? NSArray *colors = [NSArray arrayWithObjects:@"red", @"green", @"blue", nil]; return [colors indexOfObject:inputString]; } In Python, I'd probably do something like the following, although to be honest I'm not in love with that either. ## maps url text -> constant string RED_CONSTANT = 1 BLUE_CONSTANT = 2 GREEN_CONSTANT = 3 TYPES = { 'red': RED_CONSTANT, 'green': GREEN_CONSTANT, 'blue': BLUE_CONSTANT, } def parseColor(inputString): return TYPES.get(inputString) ps. I know there are color constants in Cocoa, this is just an example.

    Read the article

  • MySQL: optimization of table (indexing, foreign key) with no primary keys

    - by Haradzieniec
    Each member has 0 or more orders. Each order contains at least 1 item. memberid - varchar, not integer - that's OK (please do not mention that's not very good, I can't change it). So, thera 3 tables: members, orders and order_items. Orders and order_items are below: CREATE TABLE `orders` ( `orderid` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `memberid` VARCHAR( 20 ), `Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , `info` VARCHAR( 3200 ) NULL , PRIMARY KEY (orderid) , FOREIGN KEY (memberid) REFERENCES members(memberid) ) ENGINE = InnoDB; CREATE TABLE `order_items` ( `orderid` INT(11) UNSIGNED NOT NULL, `item_number_in_cart` tinyint(1) NOT NULL , --- 5 items in cart= 5 rows `price` DECIMAL (6,2) NOT NULL, FOREIGN KEY (orderid) REFERENCES orders(orderid) ) ENGINE = InnoDB; So, order_items table looks like: orderid - item_number_in_cart - price: ... 1000456 - 1 - 24.99 1000456 - 2 - 39.99 1000456 - 3 - 4.99 1000456 - 4 - 17.97 1000457 - 1 - 20.00 1000458 - 1 - 99.99 1000459 - 1 - 2.99 1000459 - 2 - 69.99 1000460 - 1 - 4.99 ... As you see, order_items table has no primary keys (and I think there is no sense to create an auto_increment id for this table, because once we want to extract data, we always extract it as WHERE orderid='1000456' order by item_number_in_card asc - the whole block, id woudn't be helpful in queries). Once data is inserted into order_items, it's not UPDATEd, just SELECTed. The questions are: I think it's a good idea to put index on item_number_in_cart. Could anybody please confirm that? Is there anything else I have to do with order_items to increase the performance, or that looks pretty good? I could miss something because I'm a newbie. Thank you in advance.

    Read the article

  • DB optimization to use it as a queue

    - by anony
    We have a table called worktable which has some columns(key(primary key), ptime, aname, status, content) we have something called producer which puts in rows in this table and we have consumer which does an order-by on the key column and fetches the first row which has status as 'pending'. The consumer does some processing on this row: 1. updates status to "processing" 2. does some processing using content 3. deletes the row we are facing contention issues when we try to run multiple consumers(probably due to the order-by which does a full table scan)... using Advanced queues would be our next step but before we go there we want to check what is the max throughput we can achieve with multiple consumers and producer on the table. What are the optimizations we can do to get the best numbers possible? Can we do an in-memory processing where a consumer fetches 1000 rows at a time processes and deletes? will that improve? What are other possibilities? partitioning of table? parallelization? Index organized tables?...

    Read the article

< Previous Page | 182 183 184 185 186 187 188 189 190 191 192 193  | Next Page >