Search Results

Search found 31971 results on 1279 pages for 'initializer list'.

Page 14/1279 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • Ask the Readers: What’s on Your Geeky Christmas List?

    - by Jason Fitzpatrick
    From tablets to replicas of Tattoine, visions of geeky and technology-loaded gifts surely dance in many of your heads. This week’s question is all about you and the loot you’d love to find in your stocking this year. Whether you’re dreaming of tech goodies like a new ultrabook or ebook reader, or of more geeky pursuits like a Star Trek themed chess set or a tour of Africa to visit abandoned Star Wars sets, we want to hear all about it. Don’t be bashful, hop into the comments and let loose with your wish list; check back on Friday for a What You Said roundup highlighting wishes from the endearing to the extravagant. Our Geek Trivia App for Windows 8 is Now Available Everywhere How To Boot Your Android Phone or Tablet Into Safe Mode HTG Explains: Does Your Android Phone Need an Antivirus?

    Read the article

  • How do I figure out the minimum number of swaps to sort a list in-place?

    - by sova
    In-place sorting is essentially swapping elements without using extra storage, correct? How can I find the minimum number of swaps required for a list? A C D Q R Z E // input | | | > > > <<< // movement A C D E Q R Z // output Swapping: A C D Q R Z E swap Q with E, ACDERZQ swap R with Q, ACDEQZR swap R with Z, ACDEQRZ. done. 3 swaps. Shifting items left or right is essentially swapping, but I want the optimal number for plucking an item out of line and switching its place with another.

    Read the article

  • LINQ query to find if items in a list are contained in another list

    - by cjohns
    I have the following code: List<string> test1 = new List<string> { "@bob.com", "@tom.com" }; List<string> test2 = new List<string> { "[email protected]", "[email protected]" }; I need to remove anyone in test2 that has @bob.com or @tom.com. What I have tried is this: bool bContained1 = test1.Contains(test2); bool bContained2 = test2.Contains(test1); bContained1 = false but bContained2 = true. I would prefer not to loop through each list but instead use a Linq query to retrieve the data. bContained1 is the same condition for the Linq query that I have created below: List<string> test3 = test1.Where(w => !test2.Contains(w)).ToList(); The query above works on an exact match but not partial matches. I have looked at other queries but I can find a close comparison to this with Linq. Any ideas or anywhere you can point me to would be a great help.

    Read the article

  • Link List Problem,

    - by david
    OK i have a problem with a Link List program i'm trying to Do, the link List is working fine. Here is my code #include <iostream> using namespace std; struct record { string word; struct record * link; }; typedef struct record node; node * insert_Node( node * head, node * previous, string key ); node * search( node *head, string key, int *found); void displayList(node *head); node * delete_node( node *head, node * previous, string key); int main() { node * previous, * head = NULL; int found = 0; string node1Data,newNodeData, nextData,lastData; //set up first node cout <<"Depature"<<endl; cin >>node1Data; previous = search( head, node1Data, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, node1Data); cout <<"Depature inserted"<<endl; //insert node between first node and head cout <<"Destination"<<endl; cin >>newNodeData; previous = search( head, newNodeData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, newNodeData); cout <<"Destinationinserted"<<endl; //insert node between second node and head cout <<"Cost"<<endl; cin >>newNodeData; previous = search( head, newNodeData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, newNodeData); cout <<"Cost inserted"<<endl; cout <<"Number of Seats Required"<<endl; //place node between new node and first node cin >>nextData; previous = search( head, nextData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, nextData); cout <<"Number of Seats Required inserted"<<endl; //insert node between first node and head cout <<"Name"<<endl; cin >>newNodeData; previous = search( head, newNodeData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, newNodeData); cout <<"Name inserted"<<endl; //insert node between node and head cout <<"Address "<<endl; cin >>newNodeData; previous = search( head, newNodeData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, newNodeData); cout <<"Address inserted"<<endl; //place node as very last node cin >>lastData; previous = search( head, lastData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, lastData); cout <<"C"<<endl; displayList(head); char Ans = 'y'; //Delete nodes do { cout <<"Enter Keyword to be delete"<<endl; cin >>nextData; previous = search( head, nextData, &found); if (found == 1) head = delete_node( head, previous,nextData); displayList(head); cout <<"Do you want to Delete more y /n "<<endl; cin >> Ans; } while( Ans =='y'); int choice, i=0, counter=0; int fclass[10]; int coach[10]; printf("Welcome to the booking program"); printf("\n-----------------"); do{ printf("\n Please pick one of the following option:"); printf("\n 1) Reserve a first class seat on Flight 101."); printf("\n 2) Reserve a coach seat on Flight 101."); printf("\n 3) Quit "); printf("\n ---------------------------------------------------------------------"); printf("\nYour choice?"); scanf("%d",&choice); switch(choice) { case 1: i++; if (i <10){ printf("Here is your seat: %d " , fclass[i]); } else if (i = 10) { printf("Sorry there is no more seats on First Class. Please wait for the next flight"); } break; case 2: if (i <10){ printf("Here is your Seat Coach: %d " , coach[i]); } else if ( i = 10) { printf("Sorry their is no more Seats on Coach. Please wait for the next flight"); } break; case 3: printf("Thank you and goodbye\n"); //exit(0); } } while (choice != 3); } /******************************************************* search function to return previous position of node ******************************************************/ node * search( node *head, string key, int *found) { node * previous, * current; current = head; previous = current; *found = 0;//not found //if (current->word < key) move through links until the next link //matches or current_word > key while( current !=NULL) { //compare exactly if (key ==current->word ) { *found = 1; break; } //if key is less than word else if ( key < current->word ) break; else { //previous stays one link behind current previous = current; current = previous -> link; } } return previous; } /******************************************************** display function as used with createList ******************************************************/ void displayList(node *head) { node * current; //current now contains the address held of the 1st node similar //to head current = head; cout << "\n\n"; if( current ==NULL) cout << "Empty List\n\n"; else { /*Keep going displaying the contents of the list and set current to the address of the next node. When set to null, there are no more nodes */ while(current !=NULL) { cout << current->word<<endl; current = current ->link; } } } /************************************************************ insert node used to position node (i) empty list head = NULL (ii) to position node before the first node key < head->word (iii) every other position including the end of the list This is done using the following steps (a) Pass in all the details to create the node either details or a whole record (b) Pass the details over to fill the node (C) Use the if statement to add the node to the list **********************************************************/ node * insert_Node( node * head, node * previous, string key ) { node * new_node, * temp; new_node = new node; //create the node new_node ->word = key; new_node -> link = NULL; if (head == NULL || key < head->word ) //empty list { //give address of head to temp temp = head; //head now points to the new_node head = new_node; //new_node now points to what head was pointing at new_node -> link = temp; } else { //pass address held in link to temp temp = previous-> link; //put address of new node to link of previous previous -> link = new_node; //pass address of temp to link of new node new_node -> link = temp; } return head; } node * delete_node( node *head, node * previous, string key) { /* this function will delete a node but will not return its contents */ node * temp; if(key == head->word) //delete node at head of list { temp = head; //point head at the next node head = head -> link; } else { //holds the address of the node after the one // to be deleted temp = previous-> link; /*assign the previous to the address of the present node to be deleted which holds the address of the next node */ previous-> link = previous-> link-> link; } delete temp; return head; }//end delete The problem i have is when i Enter in the Number 2 in the Node(Seats) i like to get a Counter Taken 2 off of 50, some thing like what i have here enter code here int choice, i=0, counter=0; int fclass[10]; int coach[10]; printf("Welcome to the booking program"); printf("\n-----------------"); do{ printf("\n Please pick one of the following option:"); printf("\n 1) Reserve a first class seat on Flight 101."); printf("\n 2) Reserve a coach seat on Flight 101."); printf("\n 3) Quit "); printf("\n ---------------------------------------------------------------------"); printf("\nYour choice?"); scanf("%d",&choice); switch(choice) { case 1: i++; if (i <10){ printf("Here is your seat: %d " , fclass[i]); } else if (i = 10) { printf("Sorry there is no more seats on First Class. Please wait for the next flight"); } break; case 2: if (i <10){ printf("Here is your Seat Coach: %d " , coach[i]); } else if ( i = 10) { printf("Sorry their is no more Seats on Coach. Please wait for the next flight"); } break; case 3: printf("Thank you and goodbye\n"); //exit(0); } } while (choice != 3); How can i get what the User enters into number of Seats into this function

    Read the article

  • Data base structure of a subscriber list

    - by foodil
    I am building a application that allow different user to store the subscriber information To store the subscriber information , the user first create a list For each list, there is a ListID. Subscriber may have different attribute : email phone fax .... For each list, their setting is different , so a require_attribute table is introduced. It is a bridge between subscriber and List That store Listid ,subid , attribute, datatype That means the system have a lot of list, each user have their own list, and the list have different attribute, some list have email , phone , some may have phone, address, name mail.. And the datatype is different, some may use 'name' as integer , some may use 'name' as varchar attribute means email phone, it is to define for which list have which subscriber attribute datatype means for each attribute, what is its datatype Table :subscriber : Field :subid , name,email Table :Require Attribute: Field : Listid ,subid , attribute, datatype The attribute here is {name, email} So a simple data is Subscriber: 1 , MYname, Myemail Require Attribute : Listid , 1 , 'email', 'intger' Listid , 1 , 'name', 'varchar' I found that this kind of storage is too complex too handle with, Since the subscriber is share to every body, so if a person want to change the datatype of name, it will also affect the data of the other user. Simple error situation: Subscriber: list1, Subscriber 1 , name1, email1 list2, Subscriber 2 , name2 , email2 Require Attribute : List1 , Subscriber 1 , 'email', 'varchar', List1 , Subscriber 1 , 'name', 'varchar', Listid , Subscriber 2 , 'email', 'varchar', Listid , Subscriber 2, 'name', 'integer', if user B change the data type of name in require attribute from varchar to integer, it cause a problem. becasue list 1 is own by user A , he want the datatype is varchar, but list 2 is won by user B , he want the datatype to be integer So how can i redesign the structure?

    Read the article

  • SharePoint: UI for ordering list items

    - by svdoever
    SharePoint list items have in the the base Item template a field named Order. This field is not shown by default. SharePoint 2007, 2010 and 2013 have a possibility to specify the order in a UI, using the _layouts page: {SiteUrl}/_layouts/Reorder.aspx?List={ListId} In SharePoint 2010 and 2013 it is possible to add a custom action to a list. It is possible to add a custom action to order list items as follows (SharePoint 2010 description): Open SharePoint Designer 2010 Navigate to a list Select Custom Actions > List Item Menu Fill in the dialog box: Open List Settings > Advanced Settings > Content Types, and set Allow management of content types to No  On List Settings select Column Ordering This results in the following UI in the browser: Selecting the custom Order Items action (under List Tools > Items) results in: You can change your custom action in SharePoint designer. On the list screen in the bottom right corner you can find the custom action: We now need to modify the view to include the order by adding the Order field to the view, and sorting on the Order field. Problem is that the Order field is hidden. It is possible to modify the schema of the Order field to set the Hidden attribute to FALSE. If we don’t want to write code to do it and still get the required result it is also possible to modify the view through SharePoint Designer: Modify the code of the view: This results in: Note that if you change the view through the web UI these changes are partly lost. If this is a problem modify the Order field schema for the list.

    Read the article

  • Chunking a List - .NET vs Python

    - by Abhijeet Patel
    Chunking a List As I mentioned last time, I'm knee deep in python these days. I come from a statically typed background so it's definitely a mental adjustment. List comprehensions is BIG in Python and having worked with a few of them I can see why. Let's say we need to chunk a list into sublists of a specified size. Here is how we'd do it in C#  static class Extensions   {       public static IEnumerable<List<T>> Chunk<T>(this List<T> l, int chunkSize)       {           if (chunkSize <0)           {               throw new ArgumentException("chunkSize cannot be negative", "chunkSize");           }           for (int i = 0; i < l.Count; i += chunkSize)           {               yield return new List<T>(l.Skip(i).Take(chunkSize));           }       }    }    static void Main(string[] args)  {           var l = new List<string> { "a", "b", "c", "d", "e", "f","g" };             foreach (var list in l.Chunk(7))           {               string str = list.Aggregate((s1, s2) => s1 + "," + s2);               Console.WriteLine(str);           }   }   A little wordy but still pretty concise thanks to LINQ.We skip the iteration number plus chunkSize elements and yield out a new List of chunkSize elements on each iteration. The python implementation is a bit more terse. def chunkIterable(iter, chunkSize):      '''Chunks an iterable         object into a list of the specified chunkSize     '''        assert hasattr(iter, "__iter__"), "iter is not an iterable"      for i in xrange(0, len(iter), chunkSize):          yield iter[i:i + chunkSize]    if __name__ == '__main__':      l = ['a', 'b', 'c', 'd', 'e', 'f']      generator = chunkIterable(l,2)      try:          while(1):              print generator.next()      except StopIteration:          pass   xrange generates elements in the specified range taking in a seed and returning a generator. which can be used in a for loop(much like using a C# iterator in a foreach loop) Since chunkIterable has a yield statement, it turns this method into a generator as well. iter[i:i + chunkSize] essentially slices the list based on the current iteration index and chunksize and creates a new list that we yield out to the caller one at a time. A generator much like an iterator is a state machine and each subsequent call to it remembers the state at which the last call left off and resumes execution from that point. The caveat to keep in mind is that since variables are not explicitly typed we need to ensure that the object passed in is iterable using hasattr(iter, "__iter__").This way we can perform chunking on any object which is an "iterable", very similar to accepting an IEnumerable in the .NET land

    Read the article

  • Add a non-Google Tasks List to Chrome

    - by Asian Angel
    Most people rely on a task list to help them remember what they need to do but not everyone wants one that is tied to a Google account. If you have been wanting an independent tasks list then join us as we look at the Tasks extension for Google Chrome. Tasks in Action As soon as you have finished installing the extension you are ready to start adding new tasks to your list. Enter your task into the “Text Area” and press “Enter” to add the task to the list. Note: Your tasks list will be retained (in the order you set) when you close and then reopen your browser. In just moments you can have your task list ready to go. Notice that there is also a “numerical indicator” attached to the “Toolbar Button” so that you will always know how many tasks you have left to complete. You can use the “drag and drop” function to rearrange your list into a more proper order if needed. When you are finished with a task all that you will need to do is click on the “Checkmark” to remove it from the list. If you need to make a new entry similar to an existing one simply right click and the text is automatically pasted into the “Text Area”. Make any desired changes and press “Enter” to add your new task to the list. Prefer to skip using the drop-down window? Click on “Tasks” at the top to open your list in a new tab instead. The tasks list looked very nice in our new tab. Being able to use the style that best suits your needs makes this a very convenient extension. Conclusion The Tasks extension is a perfect fit for anyone who needs a tasks list available but does not want to be tied down with an online account. Quick, simple and best of all hassle free. Links Download the Tasks extension (Google Chrome Extensions) Similar Articles Productive Geek Tips Turn Chrome’s New Tab Page into a Google Tasks PageAccess Google Tasks in Chrome the Easy WayHow to Make Google Chrome Your Default BrowserAdd a To-Do List to Chrome’s New Tab PageAccess Remember The Milk in Google Chrome the Easy Way TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips Revo Uninstaller Pro Registry Mechanic 9 for Windows PC Tools Internet Security Suite 2010 PCmover Professional Test Drive Mobile Phones Online With TryPhone Ben & Jerry’s Free Cone Day, 3/23/10 New Stinger from McAfee Helps Remove ‘FakeAlert’ Threats Google Apps Marketplace: Tools & Services For Google Apps Users Get News Quick and Precise With Newser Scan for Viruses in Ubuntu using ClamAV

    Read the article

  • Generate MERGE statements from a table

    - by Bill Graziano
    We have a requirement to build a test environment where certain tables get reset from production every night.  These are mainly lookup tables.  I played around with all kinds of fancy solutions and finally settled on a series of MERGE statements.  And being lazy I didn’t want to write them myself.  The stored procedure below will generate a MERGE statement for the table you pass it.  If you have identity values it populates those properly.  You need to have primary keys on the table for the joins to be generated properly.  The only thing hard coded is the source database.  You’ll need to update that for your environment.  We actually used a linked server in our situation. CREATE PROC dba_GenerateMergeStatement (@table NVARCHAR(128) )ASset nocount on; declare @return int;PRINT '-- ' + @table + ' -------------------------------------------------------------'--PRINT 'SET NOCOUNT ON;--'-- Set the identity insert on for tables with identitiesselect @return = objectproperty(object_id(@table), 'TableHasIdentity')if @return = 1 PRINT 'SET IDENTITY_INSERT [dbo].[' + @table + '] ON; 'declare @sql varchar(max) = ''declare @list varchar(max) = '';SELECT @list = @list + [name] +', 'from sys.columnswhere object_id = object_id(@table)SELECT @list = @list + [name] +', 'from sys.columnswhere object_id = object_id(@table)SELECT @list = @list + 's.' + [name] +', 'from sys.columnswhere object_id = object_id(@table)-- --------------------------------------------------------------------------------PRINT 'MERGE [dbo].[' + @table + '] AS t'PRINT 'USING (SELECT * FROM [source_database].[dbo].[' + @table + ']) as s'-- Get the join columns ----------------------------------------------------------SET @list = ''select @list = @list + 't.[' + c.COLUMN_NAME + '] = s.[' + c.COLUMN_NAME + '] AND 'from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk , INFORMATION_SCHEMA.KEY_COLUMN_USAGE cwhere pk.TABLE_NAME = @tableand CONSTRAINT_TYPE = 'PRIMARY KEY'and c.TABLE_NAME = pk.TABLE_NAMEand c.CONSTRAINT_NAME = pk.CONSTRAINT_NAMESELECT @list = LEFT(@list, LEN(@list) -3)PRINT 'ON ( ' + @list + ')'-- WHEN MATCHED ------------------------------------------------------------------PRINT 'WHEN MATCHED THEN UPDATE SET'SELECT @list = '';SELECT @list = @list + ' [' + [name] + '] = s.[' + [name] +'],'from sys.columnswhere object_id = object_id(@table)-- don't update primary keysand [name] NOT IN (SELECT [column_name] from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk , INFORMATION_SCHEMA.KEY_COLUMN_USAGE c where pk.TABLE_NAME = @table and CONSTRAINT_TYPE = 'PRIMARY KEY' and c.TABLE_NAME = pk.TABLE_NAME and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME)-- and don't update identity columnsand columnproperty(object_id(@table), [name], 'IsIdentity ') = 0 --print @list PRINT left(@list, len(@list) -3 )-- WHEN NOT MATCHED BY TARGET ------------------------------------------------PRINT ' WHEN NOT MATCHED BY TARGET THEN';-- Get the insert listSET @list = ''SELECT @list = @list + '[' + [name] +'], 'from sys.columnswhere object_id = object_id(@table)SELECT @list = LEFT(@list, LEN(@list) - 1)PRINT ' INSERT(' + @list + ')'-- get the values listSET @list = ''SELECT @list = @list + 's.[' +[name] +'], 'from sys.columnswhere object_id = object_id(@table)SELECT @list = LEFT(@list, LEN(@list) - 1)PRINT ' VALUES(' + @list + ')'-- WHEN NOT MATCHED BY SOURCEprint 'WHEN NOT MATCHED BY SOURCE THEN DELETE; 'PRINT ''PRINT 'PRINT ''' + @table + ': '' + CAST(@@ROWCOUNT AS VARCHAR(100));';PRINT ''-- Set the identity insert OFF for tables with identitiesselect @return = objectproperty(object_id(@table), 'TableHasIdentity')if @return = 1 PRINT 'SET IDENTITY_INSERT [dbo].[' + @table + '] OFF; 'PRINT ''PRINT 'GO'PRINT '';

    Read the article

  • Generic linked list in c++

    - by itsaboy
    I have been struggling for too long a time now with a rather simple question about how to create a generic linked list in c++. The list should be able contain several types of structs, but each list will only contain one type of struct. The problem arises when I want to implement the getNode() function [see below], because then I have to specify which of the structs it should return. I have tried to substitute the structs with classes, where the getNode function returns a base class that is inherited by all the other classes, but it still does not do the trick, since the compiler does not allow the getNode function to return anything but the base class then. So here is some code snippet: typedef struct struct1 { int param1; (...) } struct1; typedef struct struct2 { double param1; (...) } struct2; typedef struct node { struct1 data; node* link; } node; class LinkedList { public: node *first; int nbrOfNodes; LinkedList(); void addNode(struct1); struct1 getNode(); bool isEmpty(); }; LinkedList::LinkedList() { first = NULL; nbrOfNodes = 0; } void LinkedList::addNode(struct1 newData) { if (nbrOfNodes == 0) { first = new node; first->data = newData; } else { node *it = first; for (int i = 0; i < nbrOfNodes; i++) { it = it->link; } node *newNode = new node; newNode->data = newData; it->link = newNode; } nbrOfNodes++; } bool LinkedList::isEmpty() { return !nbrOfNodes; } struct1 LinkedList::getNode() { param1 returnData = first->data; node* deleteNode = first; nbrOfNodes--; if (nbrOfNodes) first = deleteNode->link; delete deleteNode; return returnData; } So the question, put in one sentence, is as follows: How do I adjust the above linked list class so that it can also be used for struct2, without having to create a new almost identical list class for struct2 objects? As I said above, each instance of LinkedList will only deal with either struct1 or struct2. Grateful for hints or help

    Read the article

  • .NET XmlSerializer fails with List<T>

    - by Redshirt
    I'm using a singleton class to save all my settings info. It's first utilized by calling Settings.ValidateSettings(@"C:\MyApp"). The problem I'm having is that 'List Contacts' is causing the xmlserializer to fail to write the settings file, or to load said settings. If I comment out the List<T> then I have no problems saving/loading the xml file. What am I doing wrong? // The actual settings to save public class MyAppSettings { public bool FirstLoad { get; set; } public string VehicleFolderName { get; set; } public string ContactFolderName { get; set; } public List<ContactInfo> Contacts { get { if (contacts == null) contacts = new List<ContactInfo>(); return contacts; } set { contacts = value; } } private List<ContactInfo> contacts; } // The class in which the settings are manipulated public static class Settings { public static string SettingPath; private static MyAppSettings instance; public static MyAppSettings Instance { get { if (instance == null) instance = new MyAppSettings(); return instance; } set { instance = value; } } public static void InitializeSettings(string path) { SettingPath = Path.GetFullPath(path + "\\MyApp.xml"); if (File.Exists(SettingPath)) { LoadSettings(); } else { Instance.FirstLoad = true; Instance.VehicleFolderName = "Cars"; Instance.ContactFolderName = "Contacts"; SaveSettingsFile(); } } // load the settings from the xml file private static void LoadSettings() { XmlSerializer ser = new XmlSerializer(typeof(MyAppSettings)); TextReader reader = new StreamReader(SettingPath); Instance = (MyAppSettings)ser.Deserialize(reader); reader.Close(); } // Save the settings to the xml file public static void SaveSettingsFile() { XmlSerializer ser = new XmlSerializer(typeof(MyAppSettings)); TextWriter writer = new StreamWriter(SettingPath); ser.Serialize(writer, Settings.Instance); writer.Close(); } public static bool ValidateSettings(string initialFolder) { try { Settings.InitializeSettings(initialFolder); } catch (Exception e) { return false; } // Do some validation logic here return true; } } // A utility class to contain each contact detail public class ContactInfo { public string ContactID; public string Name; public string PhoneNumber; public string Details; public bool Active; public int SortOrder; }

    Read the article

  • C++ keeping a list of objects and calling a contructor through another function

    - by Nona Urbiz
    why isnt my object being created? When I do it like so, I am told error C2065: 'AllReferrals' : undeclared identifier as well as error C2228: left of '.push_back' must have class/struct/union. If I put the list initialization before the class I get error C2065: 'AllReferrals' : undeclared identifier. Thanks! #include <iostream> #include <fstream> #include <regex> #include <string> #include <list> #include <map> using namespace std; using namespace tr1; class Referral { public: string url; map<string, int> keywords; static bool submit(string url, string keyword, int occurrences) { //if(lots of things i'll later add){ Referral(url, keyword, occurrences); return true; //} //else // return false; } private: list<string> urls; Referral(string url, string keyword, int occurrences) { url = url; keywords[keyword] = occurrences; AllReferrals.push_back(this); } }; static list<Referral> AllReferrals; int main() { Referral::submit("url", "keyword", 1); cout << AllReferrals.size(); cout << "\n why does that ^^ say 0 (help me make it say one)?"; cout << "\n and how can i AllReferrals.push_back(this) from my constructor?"; cout << " When I do it like so, I am told error C2065: 'AllReferrals' : undeclared identifier"; cout << " as well as error C2228: left of '.push_back' must have class/struct/union."; cout << " If I put the list initialization before the class I get error C2065: 'AllReferrals' : undeclared identifier."; cout << "\n\n\t Thanks!"; getchar(); }

    Read the article

  • Java Sorting "queue" list based on DateTime and Z Position (part of school project)

    - by Kuchinawa
    For a school project i have a list of 50k containers that arrive on a boat. These containers need to be sorted in a list in such a way that the earliest departure DateTimes are at the top and the containers above those above them. This list then gets used for a crane that picks them up in order. I started out with 2 Collection.sort() methods: 1st one to get them in the right XYZ order Collections.sort(containers, new Comparator<ContainerData>() { @Override public int compare(ContainerData contData1, ContainerData contData2) { return positionSort(contData1.getLocation(),contData2.getLocation()); } }); Then another one to reorder the dates while keeping the position in mind: Collections.sort(containers, new Comparator<ContainerData>() { @Override public int compare(ContainerData contData1, ContainerData contData2) { int c = contData1.getLeaveDateTimeFrom().compareTo(contData2.getLeaveDateTimeFrom()); int p = positionSort2(contData1.getLocation(), contData2.getLocation()); if(p != 0) c = p; return c; } }); But i never got this method to work.. What i got working now is rather quick and dirty and takes a long time to process (50seconds for all 50k): First a sort on DateTime: Collections.sort(containers, new Comparator<ContainerData>() { @Override public int compare(ContainerData contData1, ContainerData contData2) { return contData1.getLeaveDateTimeFrom().compareTo(contData2.getLeaveDateTimeFrom()); } }); Then a correction function that bumps top containers up: containers = stackCorrection(containers); private static List<ContainerData> stackCorrection(List<ContainerData> sortedContainerList) { for(int i = 0; i < sortedContainerList.size(); i++) { ContainerData current = sortedContainerList.get(i); // 5 = Max Stack (0 index) if(current.getLocation().getZ() < 5) { //Loop through possible containers above current for(int j = 5; j > current.getLocation().getZ(); --j) { //Search for container above for(int k = i + 1; k < sortedContainerList.size(); ++k) if(sortedContainerList.get(k).getLocation().getX() == current.getLocation().getX()) { if(sortedContainerList.get(k).getLocation().getY() == current.getLocation().getY()) { if(sortedContainerList.get(k).getLocation().getZ() == j) { //Found -> move container above current sortedContainerList.add(i, sortedContainerList.remove(k)); k = sortedContainerList.size(); i++; } } } } } } return sortedContainerList; } I would like to implement this in a better/faster way. So any hints are appreciated. :)

    Read the article

  • Ruby on Rails cannot find Initializer?

    - by Ryan M.
    Hello, I am trying to deploy an app to a fresh Ubuntu 10 installation using Passenger 2.2.15, Rails 2.3.5, Ruby 1.8.7, and Apache 2.2.14. However, even with a default rails app (sudo rails defaultapp), I am receiving the following error: "no such file to load -- initializer". I'm not sure which files you might need copies of in order to diagnose this problem, so I'll copy a few here and hope that it will help. Thanks for any help you can provide. -RM /etc/apache2/sites-available/default <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/appname/public <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined Alias /doc/ "/usr/share/doc/" <Directory "/usr/share/doc/"> Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 </Directory> </VirtualHost> /etc/apache2/mods-available/passenger.conf <IfModule passenger_module> PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-2.2.15 PassengerRuby /usr/bin/ruby1.8 </IfModule> /etc/apache2/mods-available/passenger.load LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-2.2.15/ext/apache2/mod_passenger.so

    Read the article

  • c# linq to xml to list

    - by WtFudgE
    I was wondering if there is a way to get a list of results into a list with linq to xml. If I would have the following xml for example: <?xml version="1.0"?> <Sports xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SportPages> <SportPage type="test"> <LinkPage> <IDList> <string>1</string> <string>2</string> </IDList> </LinkPage> </SportPage> </SportPages> </Sports> How could I get a list of strings from the IDList? I'm fairly new to linq to xml so I just tried some stuff out, I'm currently at this point: var IDs = from sportpage in xDoc.Descendants("SportPages").Descendants("SportPage") where sportpage.Attribute("type").Value == "Karate" select new { ID = sportpage.Element("LinkPage").Element("IDList").Elements("string") }; But the var is to chaotic to read decently. Isn't there a way I could just get a list of strings from this? Thanks

    Read the article

  • adjacency list creation , out of Memory error

    - by p1
    Hello , I am trying to create an adjacency list to store a graph.The implementation works fine while storing 100,000 records. However,when I tried to store around 1million records I ran into OutofMemory Error : Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOfRange(Arrays.java:3209) at java.lang.String.(String.java:215) at java.io.BufferedReader.readLine(BufferedReader.java:331) at java.io.BufferedReader.readLine(BufferedReader.java:362) at liarliar.main(liarliar.java:39) Following is my implementation HashMap<String,ArrayList<String>> adj = new HashMap<String,ArrayList<String>>(num); while ((str = in.readLine()) != null) { StringTokenizer Tok = new StringTokenizer(str); name = (String) Tok.nextElement(); cnt = Integer.valueOf(Tok.nextToken()); ArrayList<String> templist = new ArrayList<String>(cnt); while(cnt>0) { templist.add(in.readLine()); cnt--; } adj.put(name,templist); } //done creating a adjacency list I am wondering, if there is any better way to implement the adjacency list. Also, I know number of nodes right in the begining and , in the future I flatten the list as I visit nodes. Any suggestions ? Thanks

    Read the article

  • jQuery - manipulate dropped element in sortable list

    - by WastedSpace
    Hi there, I have a draggable list (.field) where you can drag & drop items from it into a sortable list (.sortlist). I did it this way because I didn't want the master list (.field) altered in any way. It works fine, except I cannot work out how to manipulate the dropped field in a sortable list. I can do it from a draggable into a droppable area by using the following in a function for 'drop:' in droppable(): $(this).append('html code here to change content of dragged field'); However this doesn't work inside a sortable(). My code looks like this: $(".sortlist").sortable({ receive: function(event, ui) { var dropElemTxt = $(ui.item).text(); var dropElemId = $(ui.item).attr('id'); $(ui.item).replaceWith('<li class="box" id="'+dropElemId+'">Updated field! '+dropElemTxt+'</li>'); } }); $(ui.item).replaceWith changes the master field that was being dragged, so this doesn't work. And I tried $(this).replaceWith, but that updates the sortable area (.sortlist). Any idea what code I need to reference the dragged item? Many thanks, Ali.

    Read the article

  • Most efficient way of creating tree from adjacency list

    - by Jeff Meatball Yang
    I have an adjacency list of objects (rows loaded from SQL database with the key and it's parent key) that I need to use to build an unordered tree. It's guaranteed to not have cycles. This is taking wayyy too long (processed only ~3K out of 870K nodes in about 5 minutes). Running on my workstation Core 2 Duo with plenty of RAM. Any ideas on how to make this faster? public class StampHierarchy { private StampNode _root; private SortedList<int, StampNode> _keyNodeIndex; // takes a list of nodes and builds a tree // starting at _root private void BuildHierarchy(List<StampNode> nodes) { Stack<StampNode> processor = new Stack<StampNode>(); _keyNodeIndex = new SortedList<int, StampNode>(nodes.Count); // find the root _root = nodes.Find(n => n.Parent == 0); // find children... processor.Push(_root); while (processor.Count != 0) { StampNode current = processor.Pop(); // keep a direct link to the node via the key _keyNodeIndex.Add(current.Key, current); // add children current.Children.AddRange(nodes.Where(n => n.Parent == current.Key)); // queue the children foreach (StampNode child in current.Children) { processor.Push(child); nodes.Remove(child); // thought this might help the Where above } } } } public class StampNode { // properties: int Key, int Parent, string Name, List<StampNode> Children }

    Read the article

  • Remove duplicates from a list of nested dictionaries

    - by user2924306
    I'm writing my first python program to manage users in Atlassian On Demand using their RESTful API. I call the users/search?username= API to retrieve lists of users, which returns JSON. The results is a list of complex dictionary types that look something like this: [ { "self": "http://www.example.com/jira/rest/api/2/user?username=fred", "name": "fred", "avatarUrls": { "24x24": "http://www.example.com/jira/secure/useravatar?size=small&ownerId=fred", "16x16": "http://www.example.com/jira/secure/useravatar?size=xsmall&ownerId=fred", "32x32": "http://www.example.com/jira/secure/useravatar?size=medium&ownerId=fred", "48x48": "http://www.example.com/jira/secure/useravatar?size=large&ownerId=fred" }, "displayName": "Fred F. User", "active": false }, { "self": "http://www.example.com/jira/rest/api/2/user?username=andrew", "name": "andrew", "avatarUrls": { "24x24": "http://www.example.com/jira/secure/useravatar?size=small&ownerId=andrew", "16x16": "http://www.example.com/jira/secure/useravatar?size=xsmall&ownerId=andrew", "32x32": "http://www.example.com/jira/secure/useravatar?size=medium&ownerId=andrew", "48x48": "http://www.example.com/jira/secure/useravatar?size=large&ownerId=andrew" }, "displayName": "Andrew Anderson", "active": false } ] I'm calling this multiple times and thus getting duplicate people in my results. I have been searching and reading but cannot figure out how to deduplicate this list. I figured out how to sort this list using a lambda function. I realize I could sort the list, then iterate and delete duplicates. I'm thinking there must be a more elegant solution. Thank you!

    Read the article

  • How to move list items from two lists (from different areas) to one specific list by clicking the li

    - by pschorr
    I've been having some issues setting up a list of items and moving them between each other. Is it possible to have multiple lists, with a link inside each item to move it to a specified list? i.e. List of actions with a plus next to the action, click the plus and move to a specified box? Furthermore, would it be possible to then load a lightbox (code would have to be inline I'd guess) from that page and move those names to the specific list as well? Example Images Thanks much! More broad view of my efforts so far... The initial issue being that I could not use listboxes due to their being rendered natively inside each individual browser. Through listboxes I was able to set this up, but with a trigger via the code below (found on stackoverflow). While it gave me partial functionality it did not get the target I was looking for. document.getElementById('moveTrigger').onclick = function() { var listTwo = document.getElementById('secondList'); var options = document.getElementById('firstList').getElementsByTagName('option'); while(options.length != 0) { listTwo.appendChild(options[0]); } } I then moved onto jqueryui's sortable and it's ability to connect multiple, and most important, style-able lists and to be dragged between each other. This works for the side by side tables, but it does not offer the usability I was looking for overall. So, I've come to where I'm unsure as to where to move forward. While I can get around PHP, I wouldn't know where to start with this one personally. I'm open to any and all options! Thanks much!

    Read the article

  • Flex custom list selection not highlighting

    - by aip.cd.aish
    I want to create a custom list in Flex for an interface prototype. The list is supposed to have an image and 3 text fields. This is what I have done so far, the control displayed is what I want. But, when I click on one of the items, the item does not appear (visually) to be selected. I was not sure how I would implement this. Here is my code so far: <s:List width="400" height="220" dataProvider="{arrColl}" alternatingItemColors="[#EEEEEE, white]"> <s:itemRenderer> <fx:Component> <mx:Canvas height="100"> <mx:Image height="90" width="120" source="{data.imageSource}"></mx:Image> <mx:Label left="125" y="10" text="{data.title}" /> <mx:Label left="125" y="30" text="{data.type}" /> <mx:Label left="125" y="50" text="{data.description}" /> </mx:Canvas> </fx:Component> </s:itemRenderer> </s:List>

    Read the article

  • Appending unique values only in a linked list in C

    - by LuckySlevin
    typedef struct child {int count; char word[100]; inner_list*next;} child; typedef struct parent { char data [100]; inner_list * head; int count; outer_list * next; } parent; void append(child **q,char num[100],int size) { child *temp,*r,*temp2,*temp3; parent *out=NULL; temp = *q; temp2 = *q; temp3 = *q; char *str; if(*q==NULL) { temp = (child *)malloc(sizeof(child)); strcpy(temp->word,num); temp->count =size; temp->next=NULL; *q=temp; } else { temp = *q; while(temp->next !=NULL) { temp=temp->next; } r = (child *)malloc(sizeof(child)); strcpy(r->word,num); r->count = size; r->next=NULL; temp->next=r; } } This is my append function which I use for adding an element to my child list. But my problem is it only should append unique values which are followed by a string. Which means : Inputs : aaa bbb aaa ccc aaa bbb ccc aaa Append should act : For aaa string there should be a list like bbb->ccc(Not bbb->ccc->bbb since bbb is already there if bbb is coming more than one time it should be increase count only.) For bbb string there should be list like aaa->ccc only For ccc string there should be list like aaa only I hope i could make myself clear. Is there any ideas? Please ask for further info.

    Read the article

  • Handling Apache Thrift list/map Return Types in C++

    - by initzero
    First off, I'll say I'm not the most competent C++ programmer, but I'm learning, and enjoying the power of Thrift. I've implemented a Thrift Service with some basic functions that return void, i32, and list. I'm using a Python client controlled by a Django web app to make RPC calls and it works pretty well. The generated code is pretty straight forward, except for list returns: namespace cpp Remote enum N_PROTO { N_TCP, N_UDP, N_ANY } service Rcon { i32 ping() i32 KillFlows() i32 RestartDispatch() i32 PrintActiveFlows() i32 PrintActiveListeners(1:i32 proto) list<string> ListAllFlows() } The generated signatures from Rcon.h: int32_t ping(); int32_t KillFlows(); int32_t RestartDispatch(); int32_t PrintActiveFlows(); int32_t PrintActiveListeners(const int32_t proto); int64_t ListenerBytesReceived(const int32_t id); void ListAllFlows(std::vector<std::string> & _return); As you see, the ListAllFlows() function generated takes a reference to a vector of strings. I guess I expect it to return a vector of strings as laid out in the .thrift description. I'm wondering if I am meant to provide the function a vector of strings to modify and then Thrift will handle returning it to my client despite the function returning void. I can find absolutely no resources or example usages of Thrift list< types in C++. Any guidance would be appreciated.

    Read the article

  • Working with a list, performing arithmetic logic in Python

    - by haea ohoh
    Suppose I have made a large list of numbers, and I want to make another one which I will add, pairwise, with the first list. Here's the first list, A: [109, 77, 57, 34, 94, 68, 96, 72, 39, 67, 49, 71, 121, 89, 61, 84, 45, 40, 104, 68, 54, 60, 68, 62, 91, 45, 41, 118, 44, 35, 53, 86, 41, 63, 111, 112, 54, 34, 52, 72, 111, 113, 47, 91, 107, 114, 105, 91, 57, 86, 32, 109, 84, 85, 114, 48, 105, 109, 68, 57, 78, 111, 64, 55, 97, 85, 40, 100, 74, 34, 94, 78, 57, 77, 94, 46, 95, 60, 42, 44, 68, 89, 113, 66, 112, 60, 40, 110, 89, 105, 113, 90, 73, 44, 39, 55, 108, 110, 64, 108] And here's B: [35, 106, 55, 61, 81, 109, 82, 85, 71, 55, 59, 38, 112, 92, 59, 37, 46, 55, 89, 63, 73, 119, 70, 76, 100, 49, 117, 77, 37, 62, 65, 115, 93, 34, 107, 102, 91, 58, 82, 119, 75, 117, 34, 112, 121, 58, 79, 69, 68, 72, 110, 43, 111, 51, 102, 39, 52, 62, 75, 118, 62, 46, 74, 77, 82, 81, 36, 87, 80, 56, 47, 41, 92, 102, 101, 66, 109, 108, 97, 49, 72, 74, 93, 114, 55, 116, 66, 93, 56, 56, 93, 99, 96, 115, 93, 111, 57, 105, 35, 99] How might I generate the arithmatic addition logic, processing each pairwise value one by one (A[0] and B[0], through A[99], B[99]) and producing the list C (A[0] + B[0] through A[99]+ B[99])?

    Read the article

  • Creating a dictionary with list of lists in Python

    - by ghbhatt
    I have a huge file (with around 200k inputs). The inputs are in the form: A B C D B E F C A B D D I am reading this file and storing it in a list as follows: text = f.read().split('\n') This splits the file whenever it sees a new line. Hence text is like follows: [[A B C D] [B E F] [C A B D] [D]] I have to now store these values in a dictionary where the key values are the first element from each list. i.e the keys will be A, B, C, D. I am finding it difficult to enter the values as the remaining elements of the list. i.e the dictionary should look like: {A: B C D; B: E F; C: A B D; D: 0} I have done the following: inlinkDict = {} for doc in text: adoc= doc.split(' ') docid = adoc[0] inlinkDict[docid] = inlinkDict.get(docid,0) + {I do not understand what to put in here} Please help as to how should i add the values to my dictionary. It should be 0 if there are no elements in the list except for the one which will be the key value. Like in example for 0.

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >