text
stringlengths
8
267k
meta
dict
Q: Get value from listbox item I'm trying to get just the value from all items in a listbox using c# (winforms). I have a combobox with multiple items, this are filled from datasource and whem I commit a selection in the combo I want this values to be stored in the listbox. IQueryable clientes = getcompanies(); combo1.DataSource = companies; combo1.DisplayMember = "name"; combo1.ValueMember = "id"; private void combo1_SelectionChangeCommitted(object sender, EventArgs e) { listBox1.Items.Add(combo1.SelectedItem); listBox1.DisplayMember = "name"; listBox1.ValueMember = "id"; } public IQueryable getcompanies() { var company= from c in context.companies select new { c.id, name= c.fname+" "+ c.lname }; return company; } I have no problems with this code, when I select and item from the combo it is added to the listbox and only the displaymember property is visible, just as I wanted. The problem is that I don't know how to get all valuemember properties from all items in the listbox. Any ideas? A: if you do this. var items = ((List<string>)listBox1.Items); you ill need to change List to the data type of companies You should then be able to loop though items using a foreach loop, which you can then access the propertie id as normal A: Question answered here on stackoverflow: Get back anonymous type
{ "language": "en", "url": "https://stackoverflow.com/questions/7590369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: boost property tree, iterators to an element for inserting? I've searched a lot through the boost manual, and the internet, as I believe it is quite a standard feature? Well I'm looking into "merging" property trees. - I noticed the function insert, and I hope I can merge trees with this? Below is the line which I am trying to get working: base.insert(base.get_child("BRANCH"), t); base and t are "property trees", base has as (one of many) branch "BRANCH". Now I wish to insert t into this branch? More specifically: how can I get an iterator to "element" if I know that element by name? A: You can get an iterator to an element using the begin() method: base.get_child("BRANCH").begin(); In order to insert every element in t on that position, you should use: base.insert(base.get_child("BRANCH").begin(), t.begin(), t.end()); If t contains one parent node or you only want to insert the first node, you can use: base.insert(base.get_child("BRANCH").begin(), t.front());
{ "language": "en", "url": "https://stackoverflow.com/questions/7590370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get the latest 5 objects from 2 level deep I have 3 models class Category(models.Model): name = models.CharField(unique=True, max_length=150) ... class Group(models.Model): name = models.CharField(unique=True, max_length=150) category = models.ForeignKey(Category) ... class Item(models.Model): name = models.CharField(max_length=150) group = models.ForeignKey(Group) date = models.DateTimeField(editable=False) ... class Meta: ordering = ['-date'] Now I need to get latest 5 items which belongs to the Category in template, so for the groups inside known category its easy {% for x in category.group_set.all %} {{ x.name }} # get the group {% for y in x.item_set.all|slice:":5" %} {{ y.name }} # get the items from the group {% endfor %} {% endfor %} Problem is when I have list of categories and don't need groups, just latest 5 items joined which belong to the category. If I use {% for category in categories %} {% for x in category %} # gives me group again I hope that I'm explain the problem. I'm lost all day looking for the solution. Thanks A: I don't think this is a problem that can be easily solved with template code, because it requires a more complex queryset than those available by default. I would probably solve this problem by adding a method to the Category class: class Category(models.Model): name = models.CharField(unique=True, max_length=150) ... def latest_items(self): return Item.objects.filter(group__category=self) and then in the template code: {% for category in categories %} {% for item in category.latest_items %} {{ y.name }} {% endfor %} {% endfor %} Note that you might need to define the Category class after the Item class in this case, and create the ForeignKey relationships to Category with strings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent multiboxing in flash game? I have multiplayer flash game (AS3) and I would like to prevent multiboxing, e.g. prevent user running two (or more) instances of my game at one computer. Is there simple and reliable way how to do that? I don't want to filter them based on IP address. I tried to use LocalConnection, but it was unreliable. It worked most of the time but for some reason it failed sometimes. Then I tried to use SharedObject to write random value to it and than check for change in periodic interval. Idea is that when second instance starts, it will overwrite previous value and check in first instance will fail. public function MultiboxPreventer(callback:Function) { uniqueKey = Math.random() * uint.MAX_VALUE; so = SharedObject.getLocal("prefs"); so.data.multiboxKey = uniqueKey; so.flush(); trace("MB init: " + so.data.multiboxKey); so = null; this.callback = callback; var t:Timer = new Timer(10000, 0); t.addEventListener(TimerEvent.TIMER, checkKey); t.start(); } private function checkKey(event:TimerEvent):void { so = SharedObject.getLocal("prefs"); if(so.data.multiboxKey != uniqueKey) { callback(); } trace("MB check: " + so.data.multiboxKey); } but when I test this it behaves as if each instance had its own SharedObject so they never rewrite each other's value. What is best way to accomplish this? A: Use local connection If the connection already exists you know that there is another game open because the connection will fail if already in use. Of course this only applies to 1 computer. import flash.net.LocalConnection var lcReceiver:LocalConnection = new LocalConnection(); try { lcReceiver.allowDomain('*') lcReceiver.connect( '_tectcon'); } catch (error:ArgumentError) { trace('CONNECTION FAILURE ' + error.message ) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get error while I'm creating a library on Codeigniter I created this library: class Header { function __construct() { $this->user(); } function user() { $my_user = $this->session->userdata('my_user'); // True or False if($my_user) { echo 'user!'; } } } /* End of file Header.php */ I call it in any controller: public function __construct() { parent::__construct(); $this->load->library('Header'); } The error: Fatal error: Call to a member function userdata() on a non-object in ** on line 11 I don't know what is the problem, I'm sure that the library session is called (I call it from autoload)... what can I do? When this library code is in any controller it works great, the problem is anywhere with custom library. A: That won't work in a library, see the documentation. $CI =& get_instance(); $CI->load->library('session'); $my_user = $CI->session->userdata('my_user'); A: The issue you're running into is that in a library, the CI object (this) isn't loaded, you need to get it. So try this (a reference to the CI object is stored in the $CI variable): class Header { private $CI; function __construct() { $this->user(); if (!isset($this->CI)) $this->CI =& get_instance(); } function user() { $my_user = $this->CI->session->userdata('my_user'); // True or False if($my_user) { echo 'user!'; } } } In the constructor, you get a reference to the CI object, and store that in the $CI variable, then you use that when you want to access its methods etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error deleting from Azure Cloud Table - ResourceNotFound I'm having an intermittent problem deleting objects from an azure table. It only affects about 1% of my attempts, and if the same call is made again later then it works fine, but I'd love to find out the reason behind it! I've googled my fingers off and I've found the lack of documentation out there on how to create very reliable code for deleting, inserting and updating to be quite surprising ... it all seems to be a bit hit and miss, "try it, most of the time it will work" EDIT: I am deleting the text that was originally in this questions and replacing it with entirely new text to take into consideration things I have tried/that have been suggested. Do Azure Tables suffer from intermittent failures like SQL Azure. If so, I would have though the "saveChangesWithRetries" would have dealt with that? Is this wrong? So ... fairly simply code, being called about 250 times a minute on an Azure web-role. The azure tables are used as part of a messaging system. Messages are inserted by one user, downloaded by another, on successful download those messages are marked as read. Each user has a partition for unread messages, and a partition for read messages. So to mark a message as "read", it is deleted from the unread partition and moved into the read partition. Of the 250 time this code is called per minute, I'll receive between 2 and 10 of the following errors on the final SaveChangesWithRetries(). The inner exception is: ResourceNotFound The specified resource does not exist. RequestId:652a3e13-3911-4503-8e49-6fec32a3c044 Time:2011-09-28T22:09:39.0795651Z I do not imagine an individual partition being accessed more than a few times a minute. This is my code: public static void Message_MarkAsRead(int uid) { try { storageAccount = CloudStorageAccount.Parse(connectionString); tableClient = new CloudTableClient(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials); tableClient.RetryPolicy = RetryPolicies.Retry(retryAmount, TimeSpan.FromSeconds(retrySeconds)); TableServiceContext tableServiceContext = tableClient.GetDataServiceContext(); tableServiceContext.IgnoreResourceNotFoundException = true; //the messageUserJoinerTable let's us join messageId to userFromId and userToId //each message is inserted into the tables twice, once into the userFromId partition and also into the userToId partition #region get the userToId and userFromId for this message uid List<int> userIds = new List<int>(); var resultsUserIds = from messagesUserJoinerTable in tableServiceContext.CreateQuery<MessageUserJoinerDataEntity>(messageUserJoinerTableName) where messagesUserJoinerTable.PartitionKey == uid.ToString() select messagesUserJoinerTable; foreach (MessageUserJoinerDataEntity messageUserJoiner in resultsUserIds) { userIds.Add(messageUserJoiner.UserId); } #endregion #region then we need to check the partition for each of these users and mark the messages as read if (userIds.Count > 0) { foreach (int userId in userIds) { var resultsUnreadMessages = from messagesTable in tableServiceContext.CreateQuery<MessageDataEntity>(messageTableName) where messagesTable.PartitionKey == CreatePartitionKey(userId, false) && messagesTable.RowKey == CreateRowKey(uid) select messagesTable; //there should only ever be one as duplicate partition/rowkey is not allowed MessageDataEntity messageUnread = resultsUnreadMessages.FirstOrDefault(); if (messageUnread != null) { bool isUnreadMessageDeleted = false; //shallow copy the message for re-inserting as read MessageDataEntity messageRead = new MessageDataEntity(messageUnread); //delete the message try { tableServiceContext.Detach(messageUnread); tableServiceContext.AttachTo(messageTableName, messageUnread, "*"); tableServiceContext.DeleteObject(messageUnread); //this is where the error occurs tableServiceContext.SaveChangesWithRetries(); isUnreadMessageDeleted = true; } catch (Exception ex) { MyTrace.Trace("AzureCloudTable_" + Service.versionForTracing + ".Message_MarkAsRead. Error.Stage.1: MessageID:" + uid + ", UserID:" + userId + ". " + ex.Message + ex.StackTrace + ", " + ex.InnerException.Message + ex.InnerException.StackTrace, "Error. MarkAsRead"); //check to see if the message we tried to delete has already been deleted //if so, we just consume this error and continue by inserting the read message //else, we throw the exception outwards var resultsUnreadMessagesLastCheck = from messagesTable in tableServiceContext.CreateQuery<MessageDataEntity>(messageTableName) where messagesTable.PartitionKey == CreatePartitionKey(userId, false) && messagesTable.RowKey == CreateRowKey(uid) select messagesTable; //there should only ever be one as duplicate partition/rowkey is not allowed MessageDataEntity messageUnreadLastCheck = resultsUnreadMessages.FirstOrDefault(); if (messageUnreadLastCheck != null) { MyTrace.Trace("AzureCloudTable_" + Service.versionForTracing + ".Message_MarkAsRead. Error.Stage.2: MessageID:" + uid + ", UserID:" + userId + ". Message WAS deleted.", "Error. MarkAsRead"); //the message IS deleted, so although I don't understand why getting error in the first //place, the result should be the same throw ex; } else { //the message is NOT deleted, so we may as well give up now as I don't understand //what's going on MyTrace.Trace("AzureCloudTable_" + Service.versionForTracing + ".Message_MarkAsRead. Error.Stage.2: MessageID:" + uid + ", UserID:" + userId + ". Message was NOT deleted.", "Error. MarkAsRead"); } } //mark the new message as read if (isUnreadMessageDeleted) { messageRead.PartitionKey = CreatePartitionKey(userId, true); messageRead.IsRead = true; //check if read message already exists in storage, if not, insert var resultsReadMessages = from messagesTable in tableServiceContext.CreateQuery<MessageDataEntity>(messageTableName) where messagesTable.PartitionKey == CreatePartitionKey(userId, true) && messagesTable.RowKey == CreateRowKey(uid) select messagesTable; //do the insert if (resultsReadMessages.FirstOrDefault() == null) { tableServiceContext.AddObject(messageTableName, messageRead); tableServiceContext.SaveChangesWithRetries(); } } } } } #endregion } catch (Exception ex) { try { MyTrace.Trace("AzureCloudTable_" + Service.versionForTracing + ".Message_MarkAsRead. Error: " + ex.Message + ex.StackTrace + ", " + ex.InnerException.Message + ex.InnerException.StackTrace, "Error. MarkAsRead"); } catch (Exception) { MyTrace.Trace("AzureCloudTable_" + Service.versionForTracing + ".Message_MarkAsRead. Error: " + ex.Message + ex.StackTrace, "Error. MarkAsRead"); } } } I don't understand how the resource can possible not exist, when it's been returned to me as part of the query and then I've done a != null check on it. Based on previous responses, I added code to do an additional check in the try to see if the object has already been deleted somehow. it has not been deleted My tracing returns this on an error: AzureCloudTable_3_0_5.Message_MarkAsRead. Error.Stage.1: MessageID:146751012, BoyID:477296. An error occurred while processing this request. at Microsoft.WindowsAzure.StorageClient.Tasks.Task1.get_Result() at Microsoft.WindowsAzure.StorageClient.Tasks.Task1.ExecuteAndWait() at BenderRestfulService_3_0_5.AzureCloudTable.Message_MarkAsRead(Int32 uid) in ... ResourceNotFound The specified resource does not exist. RequestId:583c59df-fdac-47e4-a03c-7a4bc7d004c9 Time:2011-10-05T16:37:36.7940530Z at System.Data.Services.Client.DataServiceContext.SaveResult.d__1e.MoveNext() AzureCloudTable_3_0_5.Message_MarkAsRead. Error.Stage.2: MessageID:146751012, BoyID:477296. Message was NOT deleted. I am utterly baffled. Any advice greatly appreciated!!! Steven A: Is this code running in more than one role instance or in more than one app? (Maybe the entity is being deleted by another process between the time when you read it from the table and the time when you try to delete it.) A: Problem solved, and I'll explain what I found in case it benefits anyone else. It was due to threading (as eluded to by Smarx), the fact that I was thinking like a SQL developer, and what I would consider some rather odd/unexpected behaviour by the Azure code and a real lack of in-depth examples! So, to solve it I simplified the problem as much as possible. I created a table that contained one entity, PartitionKey 'a', RowKey '1'. I created a console app that selected 'a' from the table, deleted it, changed it to 'b' and re-inserted it. I ran the code on a loop, thousands of times, and it all worked fine. I then moved the code into a thread, and launched two threads. Immediately I was hit with errors and lost the entity somewhere between a delete and an insert. Problem 1: The two threads can both select the entity at the same, both can check to see if it exists, then both can try and delete it. Only one will succeed when deleting it. So you need to catch the error, check that the error contains "ResourceNotFound", and if so trust that the object is really gone and continue as normal. Problem 2: The tableContext remembers the last failed action, so the thread where the delete failed will throw another error on SaveChangesWithRetries after you call AddObject. So you need to use a new tableContext for the AddObject Problem 3: Both threads have a chance at adding the entity, but only one will succeed. Even if both threads check to see if the objects exists before adding it, they could both think that it does NOT exist and both attempt to add it. So for simplicity, let both threads try and add it, one will succeed and one will throw an "EntityAlreadyExists" error. Just catch this error and continue. Here is my working code for this simple example, I modified it for my more complex example in the original question and now receive no errors at all. //method for shifting an entity backwards and forwards between two partitions, a and b private static void Shift(int threadNumber) { Console.WriteLine("Launching shift thread " + threadNumber); //set up access to the tables _storageAccount = CloudStorageAccount.Parse(_connectionString); _tableClient = new CloudTableClient(_storageAccount.TableEndpoint.AbsoluteUri, _storageAccount.Credentials); _tableClient.RetryPolicy = RetryPolicies.Retry(_retryAmount, TimeSpan.FromSeconds(_retrySeconds)); int lowerLimit = threadNumber * _limit; int upperLimit = (threadNumber + 1) * _limit; for (int i = lowerLimit; i < upperLimit; i++) { try { TableServiceContext tableServiceContextDelete = _tableClient.GetDataServiceContext(); tableServiceContextDelete.IgnoreResourceNotFoundException = true; string partitionKey = "a"; if (i % 2 == 1) { partitionKey = "b"; } //find the object with this partition key var results = from table in tableServiceContextDelete.CreateQuery<TableEntity>(_tableName) where table.PartitionKey == partitionKey && table.RowKey == "1" select table; TableEntity tableEntity = results.FirstOrDefault(); //shallow copy it if (tableEntity != null) { TableEntity tableEntityShallowCopy = new TableEntity(tableEntity); if (tableEntityShallowCopy.PartitionKey == "a") { tableEntityShallowCopy.PartitionKey = "b"; } else { tableEntityShallowCopy.PartitionKey = "a"; } //delete original try { tableServiceContextDelete.Detach(tableEntity); tableServiceContextDelete.AttachTo(_tableName, tableEntity, "*"); tableServiceContextDelete.DeleteObject(tableEntity); tableServiceContextDelete.SaveChangesWithRetries(); Console.WriteLine("Thread " + threadNumber + ". Successfully deleted. PK: " + tableEntity.PartitionKey); } catch (Exception ex1) { if (ex1.InnerException.Message.Contains("ResourceNotFound")) { //trying to delete an object that's already been deleted so just continue } else { Console.WriteLine("Thread " + threadNumber + ". WTF?! Unexpected error during delete. Code: " + ex1.InnerException.Message); } } //move into new partition (a or b depending on where it was taken from) TableServiceContext tableServiceContextAdd = _tableClient.GetDataServiceContext(); tableServiceContextAdd.IgnoreResourceNotFoundException = true; try { tableServiceContextAdd.AddObject(_tableName, tableEntityShallowCopy); tableServiceContextAdd.SaveChangesWithRetries(); Console.WriteLine("Thread " + threadNumber + ". Successfully inserted. PK: " + tableEntityShallowCopy.PartitionKey); } catch (Exception ex1) { if (ex1.InnerException.Message.Contains("EntityAlreadyExists")) { //trying to add an object that already exists, so continue as normal } else { Console.WriteLine("Thread " + threadNumber + ". WTF?! Unexpected error during add. Code: " + ex1.InnerException.Message); } } } } catch (Exception ex) { Console.WriteLine("Error shifting: " + i + ". Error: " + ex.Message + ". " + ex.InnerException.Message + ". " + ex.StackTrace); } } Console.WriteLine("Done shifting"); } I'm sure there are much nicer ways of doing this, but due to the lack of good examples I'm just going with something that works for me! Thanks A: By default MergeOption.AppendOnly is used by your tableServiceContext.MergeOption, this means that Azure Table Storage will be tracking your table items. You should detach the item before deleting it, like this: tableServiceContext.Detach(messageUnread); tableServiceContext.AttachTo(messageTableName, messageUnread, "*"); tableServiceContext.DeleteObject(messageUnread); tableServiceContext.SaveChangesWithRetries(); This should get rid of any item tracking issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to cache some read only xml files in java I have some xml files that will be read-only that I need to access on a random basis. They are xml files that contain user data I need to merge with rtf documents. There will probably be less than 10 files, but more than 5. As I loop through a list of documents I will have to select the correct xml file for the merge. I have a cross mapping file that links the document name to the xml file, so I know which one I need as I loop, but I need all of them available as I will be switching constantly between the xml files during the looping process. Is there a simple solution for this rather than using some open source cache? Thanks, James A: If you're reading the XML in as DOM, then you can put the Document into your map instead of the file or file name. EDIT: I just realized you said "mapping file", not "map" as in java.util.Map. That would be your first step - processing your mapping file and generating that Map of names -> Documents. A: java.util.Map is your friend when you don't need a full-grown cache.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: copy subset of rows from one table to another, filtering on two columns I have the following MySql table containing my raw event data (about 1.5 million rows) userId | pathId | other stuff.... I have an index on userId, pathId (approx 50,000 unique combinations) During my processing, I identify 30,000 userId, pathId values that I don't want, but I do want to keep the original raw table. So I want to copy all rows into a processed event table, except the rows that match this 30,000 userId, pathId values. An approach I'm considering is to write the 30,000 userId,PathId values of the rows I do not want into a temp_table, and then doing something like this: [create table processed_table ...] insert into processed_table select * from raw_table r where not exists ( select * from temp_table t where r.userId=t.userid and r.pathId=t.pathId ) For info, processed_table generally ends up being half the size of raw_table. Anyway, this seems to work but my SQL skills are limited, so my question (finally) is - is this the most efficient way to do this? A: No, it's not the most efficient. Source That’s why the best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS. Here's an example with NOT IN: INSERT INTO processed_table SELECT * FROM raw_table WHERE (userId, pathId) NOT IN ( SELECT userId, pathId FROM temp_table ) And LEFT JOIN ... IS NULL: INSERT INTO processed_table SELECT * FROM raw_table r LEFT JOIN temp_table t ON r.userId = t.userid AND r.pathId = t.pathId WHERE t.userId IS NULL However, since your table is very small and has only 50,000 rows, your original query is probably fast enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: HTML: How to make mid-row text line up the same as other rows like "tabs" I am trying to build an HTML signature file and want the phone numbers and such to line up. Phone: (234) 567-8910 Cell:     (234) 567-8910 Fax:     (234) 567-8910 Email:  mike@example.com I can do different sized margins or number of &nbsp; for each line but that doesn't display the same on all email clients/web browsers. Phone: <span style="margin-left:12px;"><?=$phone ?></span><br/> Cell: <span style="margin-left:23px;"><?=$cell ?></span><br/> Fax: <span style="margin-left:25px;"><?=$fax ?></span><br/> Email: <span style="margin-left:14px;"><?=$email ?></span><br/> With tables depreciated I don't want to rely on using one. Also it's for an email signature so it has to be able to be displayed in outlook (which doesn't accept margin- or float among other things). A: I might get grilled for not listening to your question properly, but I think it's important that you realize that tables are not completely depreciated, but rather depreciated when relying on one for something other than tabular data. In your case, your data is tabular. You have a column on the left specifying content types, and a column on the right specifying values. Thus, in this usage case, the use of tables is perfectly acceptable, and is actually what tables are designed for. Thus, it would actually make less sense to use tabs, spaces, or padding here, because there is already an HTML structure designed for this exact purpose. A: Use a definition list: <dl> <dt>Phone</dt> <dd>Some number</dd> <dt>Cell</dt> <dd>Some mobile number</dd> <dt>Fax</dt> <dd>Seriously, a fax?</dd> <dt>Email</dt> <dd>An email address</dd> </dl> CSS: dl { width: 80%; margin: 0 auto; } dt,dd { display: inline-block; /* or you could use: float: left; */ } dt { width: 30%; } dd { width: 65%; } JS Fiddle demo, using display: inline-block;. JS Fiddle demo, using float: left;.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding to strip menu at run time OK I have a list of strings (file names in fact), that i want to create a file menu dynamical form. So taking my list of file names, first code strips of the directory string and file sufix (for bonus question how can I wrap the two remove lines up in to one ?) List<string> test_ = populate.Directorylist(); foreach (var file_ in test_) { int len_ = file_.Length; string filename_ = file_.Remove(0, 8); filename_ = filename_.Remove(filename_.Length - 4).Trim(); ToolStripItem subItem = new ToolStripMenuItem(filename_); subItem.Click += new EventHandler(populate.openconfig(file_)); //this is my problem line templatesToolStripMenuItem.DropDownItems.Add(subItem); So simply cycle through the list and add an item to the "templatesToolStripMenuItem" each time. but I need to add an event that when the user clicks the item, it sends the file_ varible to the populate.openconfig method. so adding the items works fine, just how do i add the event handling? I suppose i could send it to a default method that searches for the full file name in the original array and follow it through that way. But surely I can do this as I add the items to the menu bar. Thank you Aaron So yes in the end i added subItem.tag = File_ .... then have the event handle to void subItem_Click (object sender, EventArgs e) //open files from menu { ToolStripMenuItem toolstripItem = (ToolStripMenuItem)sender; string filename_ = toolstripItem.Tag.ToString(); //use the tag field populate.openconfig(filename_); populate.Split(_arrayLists); //pass read varible dictonary to populate class to further splitting in to sections. Populatetitle();//Next we need to populate the Titles fields and datagrid view that users will enter in the Values } and just seen how i can tidy that up a bit more :) Cheers for the help guys, just love how many way you can skin a cat :) A: If I have understood this correctly, you presumably have this openconfig method which you want to be able to respond to whatever the text is. The method you pass as the event handler must be of the form void MethodName (object sender, EventArgs e) so you cannot pass it the string directly. However, once your are in your event handle message you can call the relevant message. Eg. subItem.Click += new EventHandler(subItem_Click) ... void subItem_Click (object sender, EventArgs e) { ToolStripMenuItem toolstripItem = (ToolStripMenuItem)sender; yourObject.openconfig(toolstripItem.Text) } If your object is not avaliable in that scope, you can put your event handler in your object and do the same thing. A: List<string> test_ = populate.Directorylist(); foreach (var file_ in test_) { int len_ = file_.Length; string FullFilename_ = file_.Remove(0, 8); string filename_ = FullFilename_.Remove(filename_.Length - 4).Trim(); ToolStripItem subItem = new ToolStripMenuItem(filename_); subItem.Tag = FullFilename; subItem.Click += new EventHandler(populate.openconfig(file_)); //this is my problem line templatesToolStripMenuItem.DropDownItems.Add(subItem); Then you can access the Tag property from the event handler. void subItem_Click (object sender, EventArgs e) { ToolStripMenuItem toolstripItem = sender as ToolStripMenuItem; if (toolstripItem != null && toolstripItem.Tag != null) { yourObject.openconfig(toolstripItem.Tag.ToString)) } } One more thing, you could use the Path class for file-path manipulations. There are bunch of methods to GetFileName, GetFileNameWithoutExtension etc.. string filePath = "C:\diectory\name.txt"; string fileNameWithoutExt = Path.GetFileNameWithoutExtension(filePath);
{ "language": "en", "url": "https://stackoverflow.com/questions/7590395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PreLoading in asp.net i really want to how preloading works in asp.net? for example when click on a button , an animated gif appears and after some seconds a panel or div appears! (like in many places in facebook) how can i do that in asp.net? (is jquery necessary for doing this job? if yes, which plugins?) A: First is during page about to load protected override void OnInit(EventArgs e) { base.OnInit(e); pnlLoading.Visible = true; } Second when I have update panel I use Update Progress to automatically handle it. Third is for ajax calls using jQuery. When I'm about to make an ajax call I use this $('#<%=updProgress.ClientID %>').css("display", "block"); and when the ajax call is finish, I use this $('#<%=updProgress.ClientID %>').css("display", "none"); Here are my loading indicator in the markup. These two are placed right after the body tag. <asp:Panel ID="pnlLoading" runat="server" Visible="true"> <div class="progressBackgroundFilter"> </div> <div class="processMessage"> <img src="/_layouts/Img/ajax-loader.gif" alt="Loading" /> </div> </asp:Panel> <asp:UpdateProgress ID="updProgress" runat="server"> <ProgressTemplate> <div class="progressBackgroundFilter"> </div> <div class="processMessage"> <img src="/_layouts/Img/ajax-loader.gif" alt="Loading" /> </div> </ProgressTemplate> </asp:UpdateProgress> And when the page are loaded I use this $(document).ready(function () { var objdiv = $('#<%=pnlLoading.ClientID%>'); if (objdiv) { objdiv.css('visibility', 'hidden'); } $('#<%=updProgress.ClientID%>').css("display", "none"); }); Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7590399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CakePHP combining Recursive and Group I have recursive set to Two on my find query, this is great and returns all the results i want, but i need to group by Day on the results that are Teo levels deep in the recursive query. This is what i have: Project->Track->Lapse. But i need to group by Day on the Track results, how can i do this? $project = $this->Project->find('all', array( 'conditions' => array( 'Project.id' => $id, 'Project.user_id' => $this->Auth->user('id') ), 'recursive' => 2 ) ); A: IMHO, Cake's ORM tend to be very disappointing for anything beyond the trivial. Here's is what I would do to find a solution: * *First of all, enable debug level 2 and take a look at the queries Cake is generating. That will depend on the types of the associations you have in place. If it's generating a single query for your find(), you're lucky! Just add a 'group' key to the find options array, and it's done. *Since Cake is probably generating more than one query, there are two possible solutions: a) Try Containable. If you are able to manipulate its options to force Cake to build a single query with the proper JOINs, you are ready to just add the 'group' options to the find. However, I have often been frustrated trying that, and resorted to the following option. b) Manually inform Cake about the JOINs it will have to use in order to be able to group the results. You can do that by first unbinding all associated models (this might be useful), then using the 'joins' option to force the joins. Then you can add the 'group' option to the find. I actually use option 2b quite frequently, not only when I have to group results, but also to filter by associated models.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get image URL from avatar I need to get an image url from the following page: http://social.msdn.microsoft.com/Forums/en-US/windowsdeveloperpreviewgeneral/thread/428510f3-ce59-4c97-9981-75fdc3291d97 Image source is base64 string (bytes of images) Is it possible to get it from code like this: <img src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAsACIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD9XdL0Wx+xWRWxtWBtrUsfs8XB8pP9j3714X8ZP2nf2avgBH/xdT4k+BfCt1h8aVd31hNrPyglydKt/NvkAyCN8C78nbnBqj+13+0DY/s1fs7eIfiCXiTWm0yHSvDcchBxqt1ZO32sx53SCwt45LpUAw80cUbYEmR/EJ8SfBvjP9o288bfFXUtS8Q6zrf25ZGH2e+1Bbi6v3hYRC5WOVLeKJpt8k05ghXeryPlt5/L8LQWIrzVSpCnhqclCVdyTbqSjF06cYt6ylzRbe0YNS2aZ+y5li5YSg40aLr4mVNyhStKK9nFuM6kpJaRTi4pK7lNcqu1Z/20fBn9rv8AZV/aH1KXRvg98V/A/jHXorU3s2gWjraa1HaqdryrpuoW9rczrG2fMNvHKI02u+FINfRc+m2JX/j2tRjOSLeHtg4JC+/65r/O1sPg98ZPhBbaB8RrKfxD4auNU8QnRvCWuaNd3lhPqNxaTpBqP9l39lJDcA29xLEsUkL+VcoWkhdljfH9Zv8AwSY/aa+JnxU8KfED4M/G3xLL4n8f/C2bTL3StY1O4E2vap4S1RZIkXUJ3bzb99Ku0hhF9KGuHt723S4dpIgz9mKwFPDqNSliI1YtOXLb3rbN3jeNle7b2Wj1PHwmYV8TJUcZg3hZztaV3y6pShbnSleaWlr36Xtr+kV/p9r9uvf9Htv+Pu5/5Yw/89n9qK1L9ohfXvzH/j7uex/57P8A7NFYJRsvRdX5efp+Hkd3sl3f3R8v7vl+XY/Jj/gth4hli+A/w3tv38lnPqV2k6IWCFp10O2j3EEJ5gSWXZv6DdhgCQaP7HEXhHwj4H8I+D9KtNO0nRNe0TR5PFOo+IPDdzqMF3MdIQ6tNqDpcBWs2ig+yW73NuYpcDcI0cOfqz/goX8GtI+Mn7Merw6lPPZXHhiLTtVsriGCO4ZTNJaWcwZZCoRF82O43jkPbrn5S1eCeFP+EY+HnwLj8SeInF3Dp+iW+n6XDBB9pvbuWe3S0sokVQzSzOFXyy2xI8eY7YRs+G8fhaKlQr0XiJVMW6soqUqbjCNKnTpQUkrKSUIqUlf3m5bM+2yvJcRmNSviMLi44WawEKVKq4Rk4z9s6tdLnTjJy55TgraKy3NrxF4Q+BvxC1a91XxX4R8NzHwH4f1Y+GtS0vTze21nfwWU13pI02yeP7LZQXc5YxPJFHJCZvLa5DIWPwV+xLqc3gX/AIKUvsa70iD4ofC/xLBcaXcRobW4OlS2t3ZfZTGwMduU0YzxFl3giRZDlga+p/hZ498N6r4w1HRtX0W+0G51bwhZPo/noJLO9ayX7RfW9y0TzgSoGJTzABOo3IUK4HY/sz/A7QdZ/aS8V/G7UTK+teA/D7+FNFtRCgsQPE001xJeIxLOs9rbW0sUUSgIYb4lhlVz2YfHUfcw8MNCEp4atCtXVWpJznJ+0glGS0UIrkfm3K+l3PE+S1o8uNhifbQeNw8qUKlONOdOMYwjUm42WluZpPXfR6J/pFf6on269+b/AJe7j+If89n9qK5O+J+23nJ/4+rjuf8Ans9FdUdl6L8j5d0ld/vFv2fdf3PX+kry+PtVf4geF73wJoWkjU9C1jQpLfxJ4huoZjp8GnNaHzbbRYx5Umqau4RngmiP2CzkRZJJZ5ALd/z+8O215baRD4elstSk0i1v3OjXGq28cT3WkRzstiNRgcbYpzbyFCGCBmwP3ZJx+uumXcSaVatHp2nRmO1t0AjgkVSphhjwyibBARioGAMcEGvlrxKlnB4m1fTE03T/ALDCd0Vu9uXRElhikaEbnLeSrSMUUklQQNxwK/MctzSpmeOqqcbOHJKnF25W+ePPztXa92/K4rfRpLU++4fmp1J0acp00qUZ042ThGcWnzO0k3okrbNX2PkfXtKfTNR06TT9IsLeO2S6knvBbw6cIoHgIEDFlDzs+47UU4OFTJJOfcv2Wrq5i0bxvdXOlTQyXniwtNL5ZWc26afZ29iwTH72FEDBwv7xJXbhw2Rv+IdP0ax0h7u20PTFuI7m3SKSRbucxK7HPlrPdyopwcDC/KOmK+hPhhFaWvgXRmhsbNXuov7SuJPLbfLc3V/5Mu8hwGTywAoI3JgYbgV6mMzOthHCtRhBONRU3Ft2blG7vo9LN287XRrxLGqsPCriKvtZ1MRFQUIKnGLVNpuSTs00nZJKza3OEvr20+23n73H+lXHB3Aj96/BBTgjuKK9Mu3g+13X+g2X/HxP/wAsW/56N/00orRcVVrJfVqey6y/u+fn/Wlvg2oXfuvfv/h/z/q2v//Z" alt=""> I have found usercard.js file that has following line of code: ...img src="data:image/jpg;base64,${AvatarData}"... but I cannot find where AvatarData is retrieved. A: There is no URL. That base64 data is the actual contents of the image file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to mimic UINavigation animation behavior when transitioning between two UITableViews I have a UIViewController that houses two UITableViews and swaps between the two. I'm wondering how can I implement the exact same animation behavior that a UINavigationController does when transitioning between these two UITableViews? (ie one tableView gets pushed off the screen left to right or right to left by the other tableView). A: // Set table 2 up offscreen as starting state CGRect rect = tableView2.frame; rect.origin.x = rect.size.width; tableView2.frame = rect; // fill in any details you need for the animation [UIView beginAnimation:... // move 1 left offscreen rect = tableView1.frame; rect.origin.x = -rect.size.width; tableView1.frame = rect; // bring 2 right onscreen rect = tableView2.frame; rect.origin.x = 0; tableView2.frame = rect; [UIView commitAnimation]; A: Any reason you cant use two UIViewController:s? If not you should be able to do it by animating the bounds property of both table views. You could probaby also do it by using a paged scroll view and just switch beteween pages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selecting a single row for each distinct combination in Oracle Please consider this table: firstName | lastName | hobby ----------------------------- Mike | Stone | music Sarah | James | cooking Mike | Stone | jogging Greg | Jones | reading Sarah | James | music Mike | Stone | painting ----------------------------- How do I select a single hobby (doesn't matter which), for each distinct firstName, lastName combination? (In Oracle) An example of the desired result is: firstName | lastName | hobby ----------------------------- Mike | Stone | music Sarah | James | cooking Greg | Jones | reading ----------------------------- Thank you for any assistance.. Sam A: You could do something like select firstname, lastname, max(hobby) as hobby from names group by firstname, lastname You could use other functions for max to give you different answers, for example, min.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SVN Batch Rename Whitespace Issue I'm trying to batch rename some files in svn. I have an issue where some files have a space in them. when I try to run I get this error: svn: Cannot copy path '00009.png' into its own child '00009.png' my code is: import subprocess.call call("svn rename " + "test 00009.png" + " test1 00009.png") looks like it's splitting at the whitespace. any ideas? A: Backslash escape your whitespace. So: import subprocess.call call("svn rename " + r"test\ 00009.png" + r" test1\ 00009.png") The r'' syntax means that python should treat the \s literally, not as escapes in themselves. It passes them through svn where they are treated as escapes. A: This should work: call("svn rename " + "\"test 00009.png\"" + " \"test1 00009.png\"") Basically surrounding all the paths with quotes, which you can easily do with say something like "\"%s\"" % file
{ "language": "en", "url": "https://stackoverflow.com/questions/7590416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Realtime Streaming per User via some Comet Server I need to design a Streaming API where each connected user might have different data per category. Lets say two users are interested in sport(category) rss feeds from the streaming api but each user has its own filtering mechanism on the server which results in different push data sets... By using juggernaut , you can stream data through categories(channels) but i couldn't find a way to filter some part of the data per category on the server side depending on user filter settings. A: Channels are usually used for filtering data i.e. one for /SPORT/FOOTBALL/PREMIERLEAGUE/MANU, another /SPORT/FOOTBALL/CHAMPIONSHIP/WESTHAM and /SPORT/GOLF/USMASTERS. I only know of one realtime Comet server which offers additional filtering though subscriptions to the channels and that is Caplin System's Liberator. For example (pseudocode): var subscriber = new Subscriber(); var filter = "headline~transfer"; // where '~' means contains subscriber.subscribe("/SPORT/FOOTBALL/PREMIERLEAGUE/MANU", filter, function(update) { // handle update }); The above code would subscribe to the channel but only send updates whenever and update came in where the headline field contained the text transfer. Another solution that appears to offer this querying functionality is pubsub.io. From their site: // connect from node var pubsub = require('pubsub.io').connect('hub.pubsub.io/238258'); // or the browser var pubsub = pubsubio.connect('hub.pubsub.io/238258'); pubsub.subscribe({ hello:{$any:['world','mundo','verden']} }, function(doc) { console.log(doc); }); pubsub.publish({hello:'world'}); This sort of channel querying may well be something we start to see more of.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Orbeon Form Builder - Referring to a control within a Section Template I have a number of forms that all reference a 'Header' Section Template. I would like to reference a control in this section template from another control in the form. (Using the method shown here: Write constraint to validate a field based on the value entered in another field in Orbeon Form Builder) I get the following error when I try to reference a control named 'section' in the section template: Undeclared variable in a standalone expression: $section Here is the XPath Expression I am using: if($section = 'PKP' or $section = '') then true() else false() There is a control named 'section' in the Section Template, but it appears that it is not accessible from the rest of the form. Does anyone know if it is possible to reference a control that is in a 'Section Template' in Orbeon form builder? A: As you noticed, you can't access the value for a field of a section template outside of that section using named $gaga, assuming that the field name is gaga. This is because you could have multiple "instances" of the same section template in your form. Imagine you have an "address" section template, and you insert it twice in the form for the "Billing address" and "Shipping address". Then if using $city outside of those section templates, you wouldn't know if it refers to the City field in the billing or shipping address. Instead, when adding the section template to the form, you'll want to assign a name to those sections (say billing-address) and use an XPath expression such as /form/billing-address/city to reference the value of the city field in the billing address. A: I dont use Form builder for developing forms, but based on the error, see if there is code for variable declaration for $section. Anything that starts with $ is meant as variable, hence a variable declaration is required. If a variable is declared the corresponding line might look this <xxforms:variable name="section" select="<some_xpath_expression_here>" /> If you dont want to use a variable then try referring with nodeset. You can write the nodeset like this assuming that 'section' is in 'my-instance' model instance. if(instance('my-instance')/section = 'PKP' or instance('my-instance')/section = '') then true() else false()
{ "language": "en", "url": "https://stackoverflow.com/questions/7590420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: BarCode reader component for Silverlight/.net, resources, recommendations, animal crossing? oh my I'm looking for a barcode reader component. Hoping to use it in a Silverlight Out of browser Application. Eventually be ported for usage in windows 8. Hoping to supliment physical bar code readers. Possibly reading other types the physical device may not be able to decode. http://blog.lemqi.com/?cat=3 a posting from 2008 has a round up comparing different components. A few look promising but it's a bit dated. General recommendations, or general products to stay away from would be greatly appreciated. Open source projects are welcome, I briefly looked at a Silverlight port of Zebra Crossing(zxing) but the documentation looked scarce. Looking for something that will work world wide, and detects the barcode types. A: Ended up going with http://imagetools.codeplex.com/ Nice little added wrapper for Zebra Crossing for Silverlight. Had some other features I was considering using. If anyone is interested, grab the source code, there are examples. Basic run down incase anyone is interested. Add Dependencies App.xaml.cs Decoders.AddDecoder<PngDecoder>(); //or whatever format your barcode is in. Load Image FileInfo fileInfo = path; var extendedImage = new ExtendedImage(); extendedImage.SetSource(fileInfo.OpenRead()); Image.Source=extendedImage; //Image is of type AnimatedImage and found in the xaml. Scan Image IBarcodeReader barcodeReader = new ZxingBarcodeReader(true, BinarizerMode.Hybrid) BarcodeResult result = barcodeReader.ReadBarcode(Image.Source); // Set some values in the xaml for results Barcode.Text = result.Text BarcodeFormat.Text = result.Format.ToString(); This is more or less the example. I just trimmed it down so people could understand it at a glance. A: Based on your requirements, the ClearImage Barcode Recognition SDK from Inlite Research should work well for you. It's designed for Windows with COM and .Net APIs so should have no issues with Silverlight or Windows 8. It handles all popular 1D and 2D barcodes types and reliably handles all types of damaged barcodes (which happen more often than you may think). Note: I have done some work for Inlite A: Siverlight provides access to the Webcam, but I haven't done that yet. I would be a little wary, as you probably are, of a vendor-based review/comparison that you linked to. I have heard good things about http://www.atalasoft.com/ but I haven't used it. http://accusoft.com/ worked well in Silverlight for me, but I didn't use the AccuSoft barcode module. If the user will provide 90 degree-ish alignment with the camera, you'll probably be good with any open source bar code library or writing your own.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: QCheckBox Indicator, SVG Image Is it possible to prevent a QCheckBox indicator within a QGraphicsView from becoming pixelated when scaling the graphics view? I have tried using a SVG image by setting the CheckBox's style sheet but that hasn't resolved the issue. A: I'm assuming you're using a QGraphicsWidget. I believe the problem you are having is that Qt asks the widget to paint itself, and then scales whatever it painted - so I don't think that you're going to be able to use a QCheckBox and get the clean scaling that you're looking for. There are a couple of options I can think of: * *Subclass QGraphicsSvgItem - This would give you the ability to use your SVG image, but you would have to essentially re-implement all of the QCheckBox functionality yourself in your new subclass. *Subclass QGraphicsItem and create your own QGraphicsView-capable checkbox from scratch. This would give you the ability to paint your checkbox however you'd like using the paint() function, but once again you'd still have to re-implement the QCheckBox functionality.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: time data with irregular intervals in HighChart I have a time data with irregular intervals like the following : data: [ [Date.UTC(1970, 10, 27), 12 ], [Date.UTC(1970, 10, 29), 8 ] ] in this example the time different is shown as complete to the flow, what i really want is to have the difference as zero, So the data between 27 and 29 will be filed with 0 and the Date will be 28, i did it manually but i wonder if there is something available in highchart to do something like this ? A: Looks like it's not possible yet. See the links below - Discussion on forum Request on user voice Doing it manually is the only way to go and that you have done already. I had the similar problem, in my case I took care of it on the server-side. I am using Java so used HashMap with date as the key.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: StateMachine in WF4 First a disclaimer - I am new to WF and I've beel playing with WF4 only for 3 days - so apologies on any benign or lame questions I may have... I am trying to implement WF4 State Machine in my project. Here is some background info: * *I have WinForm UI as a main app that can generate different commands to a networking stack *I have Interface layer as a DLL that receives events from a network stack *The state machine should implement a softphone state machine somewhere in the intermediate layer parallel to interface layer. The phone state change based on the networking events and on the user actions. Some user actions just cause networking commands and some may directly affect the state machine. *My interface layer implements an object Phone so I made this object as a host of the state machine. I am passing my main interface object WinSipItf to the phone object, and do the following (WinSipItf object lives in another namespace WinSipNetLib): Code: public void Initialize(WinSipNetLib.WinSipItf winSipItf, string hostname, string user, string password) { try { WinSipItf = winSipItf; var Itf = WinSipItf; var input = new Dictionary<string, object> { {"winSipItf", Itf} }; this.WorkFlowHostApp = new WorkflowApplication(new Activity1(), input) { Idle = this.OnWorkflowIdle, Completed = this.OnWorkflowCompleted }; // Setup the Tracking to output in the debug window WorkFlowHostApp.Extensions.Add(new Tracker()); this.WorkFlowHostApp.Extensions.Add(this); this.workflowBusy.Reset(); Console.WriteLine("Starting Workflow"); this.WorkFlowHostApp.Run(); } catch (Exception ex) { Console.Write(ex); } } Phone initial state is Initial and it has automatic/null trigger with a target state PhoneIdle. OnEntrace to Initial state I need to execute couple of Phone registrations with networking stack - register a callback (sync operation) and register with network stack manager (async). All this functionality lives at the lower level unmanaged code that I access through constructed APIs in my Interface layer. Upon successful registration I get a callback in the Interface layer and fire an event. Therefore my Registration Acitivity looks like that: public sealed class Register : NativeActivity<Int32> { // Define an activity input argument of type string [RequiredArgument] public InArgument<WinSipNetLib.WinSipItf> winSipItf { get; set; } #region Constants and Fields private readonly Variable<NoPersistHandle> _noPersistHandle = new Variable<NoPersistHandle>(); internal const string BookmarkName = "WaitingForAccountStatusEvent"; /// <summary> /// The transition callback. /// </summary> private BookmarkCallback registrationCallback; #endregion #region Properties ///// <summary> ///// Gets or sets PhoneTransition. ///// </summary> //public PhoneTransition PhoneTransition { get; set; } /// <summary> /// Gets a value indicating whether CanInduceIdle. /// </summary> protected override bool CanInduceIdle { get { return true; } } /// <summary> /// Gets TransitionCallback. /// </summary> private BookmarkCallback RegistrationCallback { get { return this.registrationCallback ?? (this.registrationCallback = new BookmarkCallback(this.OnRegistrationCallback)); } } #endregion #region Methods /// <summary> /// The cache metadata. /// </summary> /// <param name="metadata"> /// The metadata. /// </param> protected override void CacheMetadata(NativeActivityMetadata metadata) { metadata.RequireExtension(typeof(Tracker)); metadata.RequireExtension(typeof(Phone)); metadata.RequireExtension(typeof(WaitForRegistrationExt)); // !!! and one more for GUI // Provide a Func<T> to create the extension if it does not already exist metadata.AddDefaultExtensionProvider(() => new WaitForRegistrationExt()); metadata.AddArgument(new RuntimeArgument("winSipItf", typeof(WinSipNetLib.WinSipItf), ArgumentDirection.In, true)); metadata.AddArgument(new RuntimeArgument("Result", typeof(int), ArgumentDirection.Out, false)); metadata.AddImplementationVariable(_noPersistHandle); } protected override void Execute(NativeActivityContext context) { // Enter a no persist zone to pin this activity to memory since we are setting up a delegate to receive a callback var handle = _noPersistHandle.Get(context); handle.Enter(context); // Get Phone extension needed to call the functions in WinSipItf Phone phone = (Phone)context.GetExtension<Phone>(); // Get (which may create) the extension WaitForRegistrationExt regExt = context.GetExtension<WaitForRegistrationExt>(); // Add the callback regExt.AddRegistrationCallback(winSipItf.Get(context)); bool bRet = phone.WinSipItf.RegisterDBusCallback("WinSipPhone"); // Obtain the runtime value of the Text input argument if (bRet == false) { this.Result.Set(context, bRet.ToString()); return; } string hostname = "demo2.demo.com"; string username = "406"; string password = "123123"; string id = username + "@" + hostname; String regUri = hostname; if (phone.WinSipItf.DoSipRegister(id, regUri, username, password) == 0) { this.Result.Set(context, bRet.ToString()); return; } // Set a bookmark - the extension will resume when the Gizmo is fired context.CreateBookmark(BookmarkName, RegistrationCallback); //context.CreateBookmark(this.PhoneTransition.ToString(), this.RegistrationCallback); //// Obtain the runtime value of the Text input argument //string text = context.GetValue(this.Text); //Result.Set(context, string.Format("The text is {0}", text)); } /// <summary> /// The on transition callback. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="bookmark"> /// The bookmark. /// </param> /// <param name="value"> /// The value. /// </param> /// <exception cref="InvalidOperationException"> /// </exception> private void OnRegistrationCallback(NativeActivityContext context, Bookmark bookmark, object value) { if (value is WinSipItf.MSGDATA) { } ////if (value is StateTransitionResult) //{ // this.Result.Set(context, value as StateTransitionResult); //} //else if (value != null) //{ // // Resumed with something else // throw new InvalidOperationException( // "You must resume PhoneTransition bookmarks with a result of type StateTransitionResult"); //} // Exit the no persist zone var handle = _noPersistHandle.Get(context); handle.Exit(context); } #endregion } As you can see from the code I make cals like: phone.WinSipItf.DoSipRegister Is it valid? I think all state machine is executing on a different thread from the one that the WinSipItf object is constructed... Redundant to say that I dont get anywhere with this... I cant even break in Execute or CacheMetadata. Not sure what to do at this point. Worth to mention that my xaml diagram is quite built but I was trying to implement only the Initial state and its transition to Idle state by constructing this custom activity... Maybe I shouold have started from a simple question: I am getting "Value for a required activity argument 'winSipItf' was not supplied" warning when I drop my Register activity on the Entry of Initial state. I checked all the code and I dont see why. WHat am I missing? A: First since you are new to Workflow you might want to do the Introduction to State Machine Hands On Lab. Second - I have a sample application that demonstrates how to support callbacks (yes the workflow is executing on a different thread) Windows Workflow Foundation (WF4) - Activity Callbacks and Event Handlers. A: You didn't add the workflow definition but the error "Value for a required activity argument 'winSipItf' was not supplied" seems to be the result of the winSipItf argument on the Register activity not being set. It is marked as required so it needs to be set using a VB expression in the workflow. You are providing an argument with the name winSipItf to the workflow but that is tied to a worklfow argument and doesn't propagate to contained activities with the same argument name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Temporarily saving textarea value I am trying to create a comment form like a page I know has. You fill in a comment, select a network to log into, you go to the login page, and when it redirects you back, your textarea value is still filled in what you had. Everything is done, except for storing the value, because I can’t figure that out. Can someone point me in the direction of what to do? I tried the jQuery.data() function, but when I get redirected back, it’s empty. A: .data() only stores data for the duration that page exists; when the browser navigates away, it's lost, like all other JS state information. Your solutions here are to either store the value in a cookie with this cookie plugin, or store it in a session variable server-side. I'd recommend you store it in a cookie in this case, which is easy enough with the plugin. A: $('#yourTextareaElement').html() That will return the value of it, and from there, you can save it as a cookie with PHP or Javascript, whichever you prefer. A: those values are stored periodically on the server session. you just need a to make an ajax request every2 mins or so that copies the value from your textfield to the server... A: I would either use a session variable or a cookie. You can simply import those three functions I've linked on quirksmode. A: My first thoughts are to send you to the .post() function. You could send the text (textarea.getVal()) through as a variable in the function and it's easy enough to use the PHP $_POST variable to access it from the page you send it to, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Set File Permissions in C# I wanna set the permissions on a file to "can not be deleted" in C#, only readable. But I don't know how to do this. Can you help me ? A: Take a look at File.SetAttributes(). There are lots of examples online about how to use it. Taken from that MSDN page: FileAttributes attributes = File.GetAttributes(path); if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { // Show the file. attributes = RemoveAttribute(attributes, FileAttributes.Hidden); File.SetAttributes(path, attributes); Console.WriteLine("The {0} file is no longer hidden.", path); } else { // Hide the file. File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden); Console.WriteLine("The {0} file is now hidden.", path); } A: You forgot to copy in the RemoveAttribute method, which is: private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove) { return attributes & ~attributesToRemove; } A: Is this about attributes (see jb.'s answer) or permissions, i.e. read/write access, etc.? In the latter case see File.SetAccessControl. From the MSDN: // Get a FileSecurity object that represents the // current security settings. FileSecurity fSecurity = File.GetAccessControl(fileName); // Add the FileSystemAccessRule to the security settings. fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType)); // Set the new access settings. File.SetAccessControl(fileName, fSecurity); See How to grant full permission to a file created by my application for ALL users? for a more concrete example. In the original question it sounds like you want to disallow the FileSystemRights.Delete right.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: accepts_nested_attributes_for undefined method error I'm trying to use accepts_nested_attributes to create a complex form. Based on the Nested Attributes documentation, examples, etc., I've set up the models like so: User model: require 'digest' class User < ActiveRecord::Base attr_accessor :password attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :ducks_attributes has_many :ducks, :class_name => 'Duck' accepts_nested_attributes_for :ducks . . . end Duck model: class Duck < ActiveRecord::Base belongs_to :user accepts_nested_attributes_for :user end But when I try to access the nested attributes in the console, I get ruby-1.9.2-p290 :003 > User.first.ducks_attributes NoMethodError: undefined method `ducks_attributes' for #<User:0x007ffc63e996e0> from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activemodel-3.0.9/lib/active_model/attribute_methods.rb:392:in `method_missing' from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activerecord-3.0.9/lib/active_record/attribute_methods.rb:46:in `method_missing' from (irb):3 from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in `start' from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/commands/console.rb:8:in `start' from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/commands.rb:23:in `<top (required)>' from script/rails:6:in `require' from script/rails:6:in `<main>' What am I doing wrong? Many thanks in advance. A: Only the attribute writer is defined. class User < ActiveRecord::Base has_many :ducks accepts_nested_attributes_for :ducks end class Duck < ActiveRecord::Base belongs_to :user end # This works: User.first.ducks_attributes = [ { :name => "Donald" } ] # This is more common (attributes posted from a form): User.create :ducks_attributes => [ { :name => "Donald" }, { :name => "Dewey" } ]
{ "language": "en", "url": "https://stackoverflow.com/questions/7590458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Working on dotted line span and I can't figure out how to make it same line dl { width: 480px; } dt { float: left; clear: right; width: 100%; background: url(http://galeon.sourceforge.net/twiki/pub/TWiki/TWikiDocGraphics/dot_lr.gif) repeat-x 0 180%; } dt span { background: #fff; } dd { float: right; width: auto; } <dl> <dt><span>Phone</span></dt> <dd>123-4567</dd> <dt><span>Email</span></dt> <dd>info@email.com</dd> </dl> I am trying to make it so i can have a dotted line span through the middle of my text but i am having trouble with the width of the dots, for some reason the text keeps going to the next line after the dots. You can see what i mean here http://jsfiddle.net/MUqYn/16/ A: Maybe something like this: http://jsfiddle.net/dwCmg/1 Not exactly what you hoped for (different markup), but it seems to work well on all major browsers. The idea is basically to use tables: HTML: <div class='definition'> <span class='name'>Phone</span> <span class='dots'></span> <span class='value'>123-4567</span> </div> CSS: .definition {display:table; width:480px;} .definition > span {display:table-cell; white-space:nowrap;} .definition > span.dots {width:100%; background: url(http://galeon.sourceforge.net/twiki/pub/TWiki/TWikiDocGraphics/dot_lr.gif) repeat-x 0 180%;} A: Here is one way to approach the problem using a negative margin-top on the dd elements. http://jsfiddle.net/newspark/KvpCM/1/ A: As was said, you are pushing the dd to the next line by making the dt have 100% width... If you let the left-floated dt have its normal width and just make the dd have the 100% width and background instead, it should work fine: http://jsfiddle.net/aneves_sw/meKhe/ You just need to get a new image, 1px per 2px, with a dot and a white-space to its right, so that you don't need to juggle with background-position.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: AppWidget in Accounts & Sync not getting updated I've successfully gotten an AppWidget working on the home screen, which properly updates in response to pushes from a running background service. I'm thinking this proves my overall logic and creation of AppWidgets. I also have my sync adapter working correctly and have a sync settings profile built which properly functions with application preferences. I would like to embed the running AppWidget within my specific account settings page in the "Accounts & Sync" tab from the OS. Here's the XML for the account preference screen: <PreferenceScreen android:key="general_description" android:summary="@string/preferences_general_description" > </PreferenceScreen> <PreferenceCategory android:title="General Settings" /> <PreferenceScreen android:key="account_information" android:title="@string/preferences_account_information_title"> <intent android:targetPackage="@string/package_name" android:targetClass="com.dashwire.android.app.AccountInformationSettingsActivity"/> </PreferenceScreen> <PreferenceScreen android:key="sync_settings" android:title="@string/preferences_syncsettings_title" android:summary="@string/preferences_syncsettings_summary"> <intent android:targetPackage="@string/package_name" android:targetClass="com.dashwire.android.app.SyncSettingsActivity"/> </PreferenceScreen> <PreferenceScreen android:key="sync_notifications" android:title="@string/preferences_syncsettings_notifications"> <intent android:targetPackage="@string/package_name" android:targetClass="com.dashwire.android.app.ApplicationsActivity"/> </PreferenceScreen> <Preference android:key="squarepants" android:widgetLayout="@layout/appwidget_layout"/> The AppWidget shows up, it's just not being updated like the working "Home Screen" is... How can I do this? A: You can only embed app widgets in App Widget hosts. As far as I can tell the basic Preferences screen is not a working app widget hosts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Relationship between view and model in Backbone.js In Backbone.js, how does a view know what model it represents? Is it necessary for the view to be named Model_NameView? Because I can't find any other View property or function for setting the model (like collection has the model property, to define what models this collection is of) A: As you can see at http://documentcloud.github.com/backbone/#View, there is a model property for each view. In other words, you do not have to name the view and model anything in particular.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I Encrypt/Decrypt using GnuPG/GPG4Win from a website? I am attempting to encrypt/decrypt user names to pass between two different websites using gpg4win 2.1.0. I can get my code to work on my development machine, but not in production. I'm developing the application with VS 2008. I have run the GPG4Win install package, chose gnupg & kleopatra. I've attempted to use the code found at "http://www.codeproject.com/KB/security/gnupgdotnet.aspx". I keep getting Error Code 255 Unknown error. The following code sample is how the GPG application is being run. The BuildOptions() function returns the string: --homedir "C:\Path\gnupg" --no-auto-check-trustdb --always-trust --no-default-keyring --secret-keyring "C:\Path\gnupg\secring.gpg" --keyring "C:\Path\gnupg\pubring.gpg" --yes --batch --encrypt --armor --recipient recipient@email.ca --passphrase-fd 0 --no-verbose public void ExecuteCommand(string inputText, out string outputText) { outputText = ""; string gpgOptions = BuildOptions(); string gpgExecutable = GetGpgPath(); binddirectory = GetGPGInstallLocation(); // TODO check existence of _bindirectory and gpgExecutable // Create startinfo object ProcessStartInfo pInfo = new ProcessStartInfo(gpgExecutable, gpgOptions); pInfo.WorkingDirectory = _bindirectory; pInfo.CreateNoWindow = true; pInfo.UseShellExecute = false; // Redirect everything: // stdin to send the passphrase, stdout to get encrypted message, stderr in case of errors... pInfo.RedirectStandardInput = true; pInfo.RedirectStandardOutput = true; pInfo.RedirectStandardError = true; _processObject = Process.Start(pInfo); // Send pass phrase, if any if (!string.IsNullOrEmpty(_passphrase)) { _processObject.StandardInput.WriteLine(_passphrase); _processObject.StandardInput.Flush(); } // Send input text _processObject.StandardInput.Write(inputText); _processObject.StandardInput.Flush(); _processObject.StandardInput.Close(); _outputString = ""; _errorString = ""; // Create two threads to read both output/error streams without creating a deadlock ThreadStart outputEntry = new ThreadStart(StandardOutputReader); Thread outputThread = new Thread(outputEntry); outputThread.Start(); ThreadStart errorEntry = new ThreadStart(StandardErrorReader); Thread errorThread = new Thread(errorEntry); errorThread.Start(); if (_processObject.WaitForExit(ProcessTimeOutMilliseconds)) { // Process exited before timeout... // Wait for the threads to complete reading output/error (but use a timeout!) if (!outputThread.Join(ProcessTimeOutMilliseconds/2)) outputThread.Abort(); if (!errorThread.Join(ProcessTimeOutMilliseconds/2)) errorThread.Abort(); } else { // Process timeout: PGP hung somewhere... kill it (as well as the threads!) _outputString = ""; _errorString = "Timed out after " + ProcessTimeOutMilliseconds.ToString() + " milliseconds"; _processObject.Kill(); if (outputThread.IsAlive) outputThread.Abort(); if (errorThread.IsAlive) errorThread.Abort(); } // Check results and prepare output _exitcode = _processObject.ExitCode; if (_exitcode == 0) outputText = _outputString; else { if (_errorString == "") { _errorString = "GPGNET: [" + _processObject.ExitCode.ToString() + "]: Unknown error"; } throw new GnuPGException(_errorString); } } A: I was able to resolve my issue by creating a user for the app pool identity to run as and set the necessary permissions to access the keyring/gpg program.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PostgreSQL regexp with case-insensitive parts Using PostgreSQL v.8.2.14, I'm trying to build a regexp with several branches, some of which are case-insensitive, the others not. Consider the following perl one-liner: % echo 'foo Foo bar Bar' | perl -pe 's/(foo|(?i:bar))/_\1/g' _foo Foo _bar _Bar I thought I would get there with: select regexp_replace('foo Foo bar Bar','(foo|((?i)bar)',E'_\\1','g'); But I get: ERROR: invalid regular expression: quantifier operand invalid. Note that the regex_flavor is advanced, and BTW when I put the (?i) at the very beginning of the regexp, then there is no error: select regexp_replace('foo Foo bar Bar','(?i)(foo|bar)',E'_\\1','g'); _foo _Foo _bar _Bar Any help gladly appreciated. A: The (?i) (and related options) are only valid at the beginning of the expression. From the fine manual: An ARE may begin with embedded options: a sequence (?xyz) (where xyz is one or more alphabetic characters) [...] Emphasis mine. The (?xyz) options are like the trailing /.../xyz options in the regexes of other languages. Also note that the 9.0 manual uses the same language so you can't just upgrade your way around this. Looks like you need two regexp_replace calls: > select regexp_replace(regexp_replace('foo Foo bar Bar', 'foo', E'_\\&', 'g'), 'bar', E'_\\&', 'ig'); regexp_replace -------------------- _foo Foo _bar _Bar Or do the case-insensitive matching the hard way (i.e. character classes): > select regexp_replace('foo Foo bar Bar', '(foo|[Bb][Aa][Rr])', E'_\\1', 'g'); regexp_replace -------------------- _foo Foo _bar _Bar
{ "language": "en", "url": "https://stackoverflow.com/questions/7590469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Confused about salting (Cryptography)? I'm a newb at this so this question is prob really easy. I just don't quite understand salting. Without salting and with sha1 you can hash a password to be sha1('password') and to verify a user you just compare sha1_stored ==? sha1(user_input). With salting and sha1 you hash the password to be sha1('password' + salt), but i'm not sure how to verify it. Based on what I've read the salt is always random. So if you sha1('password' + random_salt1), do you have to store the random_salt somewhere because when you verify sha1('password' + random_salt1) ==? sha1(user_input + random_salt2), you can't guarantee that random_salt1 == random_salt2. Or is salt like a site_key(a random salt, but only one is stored for the whole site) ? I get how salt would increase security, but I'm not sure how to implement it correctly such that I can verify what I stored(don't know about this either). So can someone explain this to me and possibly give me an example of salting and verifying a string? A: Yes, you have to store the random salt somewhere. No, you shouldn't have it be the same for the whole site, as it completely defeats the purpose of salting. The purpose of salting is to increase security on an entire list of passwords. If you do not salt, and your database is breached, an attacker gets all your accounts and passwords. If they're not salted, the attacker just sha1's a bunch of words and compares all of them to all of the sha1 passwords. Some of them will match some of the passwords, and wha-la some accounts are compromised. With salting, the attacker has to operate on each password independently, starting with an entire dictionary of words, salting them, hashing them, and then comparing them each to the salted, hashed, password. You can see that this would be much less efficient, as the attacker must change the salt each time. In this way it is much harder to get passwords from a compromised database. One common method of storing the salt is to just append or prepend it to the hash and store it in the database. Since the salt and hash are of known length, it's pretty easy to pull them out independently. A: The salt is randomly chosen and different for each string, but it is not secret. So you store the salt along with the hash: salt + hash. To verify check that hash(salt + password) equals the stored hash. The main purpose of using a salt is to ensure that two equal passwords don't hash to the same thing, and also to make an attack on the hashed password more difficult. Without salt, you'd just have to break a given hash once and for all to identify all passwords that hash to it. With salt, you'd essentially have to attack each hash anew. Note that in these modern days of cheap parallel computing hardware (GPUs and cloud), a single salted hash is not all that secure anymore, as it can possibly be discovered by brute force in feasible amounts of time. The current recommendation is therefore to hash a password many times (like 1000 rounds or so) to make the computation expensive. When presented with the correct password, the extra time won't matter, but if you try to brute-force, then an increase by a factor 1000 is a significant deterrent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Having a dependency on a specific nuget package We have a bunch of internal packages that we create for other teams to consume, and many of these have dependencies on open sources packages. I would like to add a dependency to a specific version of a nuget package to my nuspec, such that when the end user installs my package the dependent packages get installed too. My <dependencies> section of my nuspec looks like this: <dependencies> <dependency id="MassTransit" version="2.0.0.4" /> <dependency id="MassTransit.RabbitMQ" version="2.0.0.4" /> </dependencies> Which I was hoping would bring down only version 2.0.0.4 of MassTransit, however it brings down 2.0.0.5, which my application currently doesn't work with. I've tried the following formats, but none of them seem to work: version="[2.0.0.4, 2.0.0.5)" version="[2.0.0.4]" version="2.0.0.5)" Infact, I can't seem to get anything in the documentation about version ranges to work properly. I do have one thought, which is that masstransit is using a 4 digit version number, while all the examples are 3 digits a-la semver. Is this what could be causing my problem? Edit: It turns out the version of nuget on the build server was out of date and didn't support the ranges I wanted to use. Upgrading it fixed everything! A: No, doing something like [version] should get you the exact version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Why does increasing timer resolution via timeBeginPeriod impact power consumption? I am currently writing an application in C# where I need to fire a timer approx. every 5 milliseconds. From some research it appears the best way to do this involves p/invoking timeBeginPeriod(...) to change the resolution of the system timer. It works well enough in my sample code. I found an interesting warning about using this function on Larry Osterman's MSDN Blog in this entry: Adam: calling timeBeginPeriod increases the accuracy of GetTickCount as well. using timeBeginPeriod is a hideously bad idea in general - we've been actively removing all of the uses of it in Windows because of the power consumption consequences associated with using it. There are better ways of ensuring that your thread runs in a timely fashion. Does anyone know exactly why this occurs, or what those "better ways" (which are unspecified in the thread) might be? How much extra power draw are we talking about? A: Changing the system timer resolution does impact on power usage, mainly because lots of developers do not understand windows timers. You see lots of code with sleep or timer values less than 15ms. It also changes the behaviour of system tasks which can result in more power usage. Changing the system timer to 1ms suddenly all this code that was only waking up every 15ms starts to wake up much more often, and the CPU usage goes up. However from the users perspective the programs that have misused the timers can become more responsive, even the OS in the case of WinXP, so there is a trade off. I have a small program that changes the system timer so you can experiment and test the power usage for yourself. There are also a number of links and some more background at http://www.lucashale.com/timer-resolution/ A: Because it causes more CPU usage. A good explanation is at Timers, Timer Resolution, and Development of Efficient Code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: ASP.NET Authentication Issues on IIS7 - User.Identity.Name is empty for Windows authentication We have an ASP.NET application on ASP.NET 4.0 using MVC 3 which uses Windows authentication. When run from Visual Studio 2010 everything works as expected but when rolled out to IIS7 the Windows logged in user never gets populated (checking User.Identity.Name). No dialog prompt for user credentials comes up either. The web.config setting: <authentication mode="Windows" /> In IIS I can see that Windows authentication is enabled, as is Anonymous (disabling Anonymous results in a 403 Forbidden and no content being shown). I've tried both enabling and disabling "Kernel-mode authentication" (useKernelMode="true"), but this doesn't seem to make any difference. Though I do remember that we had to disable this setting on another site on a different server to get the authentication to work properly (might point to a potential issue further down the stack?). In case it's useful, from IIS's applicationHost.config: <security> <authentication> <anonymousAuthentication enabled="true" /> <digestAuthentication enabled="false" /> <basicAuthentication enabled="false" /> <windowsAuthentication enabled="true" useKernelMode="false"> <providers> <clear /> <add value="NTLM" /> </providers> </windowsAuthentication> </authentication> </security> Any ideas what the issue could be? Thanks in advance for any suggestions. Update 1 I managed to find another IIS7 server to test on and I found if I disabled Anonymous access everything worked as desired. However I still have issues on the original IIS7 server even when I disable Anonymous access as well (I'm keeping Anonymous disabled now). So there must be some issue further down the stack I guess. Any ideas? Something I need to fix as it's going to keep popping up and biting us I imagine. Update 2 If I enable Digest Authentication on the problem IIS7 box then I am challenged with the login prompt dialog and everything works as expected if I provide suitable credentials. But being an internal web app with users already logged in to the domain we don't really want to challenge them this way. Credentials should be passed through transparently as it works on the second IIS7 box. Update 3 Some progress... I've found that if the web app is in the root and not a sub site then directly editing the applicationHost.config file for IIS7 to give the following authentication settings allows the site to work as expected: <authentication> <anonymousAuthentication enabled="false" /> <windowsAuthentication enabled="true"> <providers> <clear /> <add value="NTLM" /> </providers> </windowsAuthentication> <digestAuthentication enabled="false" /> </authentication> Using IIS7's UI to configure the authentication doesn't give quite the right results. authentication items are either missing after wards (as I guess IIS7 assumes they are being inherited) or they have the wrong settings (windowsAuthentication seems to need the providers configuration above present to work correctly). Unfortunatly the web application in question is actually a sub application as there's an internal version (using windows authentication > www.site.com/internal) and an external version (using forms authentication > www.site.com/external). I still can't get the authentication to work as a sub application yet. I just get a "Error Code: 403 Forbidden". A: In this case it was a Microsoft ISA Server issue. Seems the request was being routed internally through ISA for the Windows Authenticated site, once ISA was removed the problem disappeared. I don't know a lot about ISA and how it routes requests but I assume it must have been stripping out some important information from the request because of some rule someone will have configured. As a side note in case it helps diagnose similar setups: I was told by the network admin staff that internal traffic was not routed through ISA, but pinging the website internally showed that ISA was actually in play. A: You mentioned that disabling anonymous access worked on another server, but on your main server you are experiencing 403 errors. Therefore, I would check the file based permissions on the folder where your site is running from. In the past I have needed to grant the \Network Serivce account full control to the site folder and all subfolders or I would experience 403 errors. Check the file permissions on the server that is working and see if there are differences with the server that is not working. Also, if this is not the issue, I would recommend comparing all of the other IIS settings between the two servers, since you know it works on one and not the other. Find the difference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: how to load specific attributes from two table to another? I am trying to load attributes from two tables to one table. I have a Location table: Id City State Country =============================== 1 New York New York USA 2 Portland Oregon USA 3 Tokyo Honshu Japan And a User table: Id First_Name Last_Name Hometown_City Hometown_State Hometown_Country =========================================================================== 1 Brett Burr New York New York USA 2 Bucky Beaver Portland Oregon USA 3 Ranma Saotome Tokyo Honshu Japan I'm creating a new table for users, which instead of containing the separate Hometown fields, has a Hometown_Id foreign key. Something like: Id First_Name Last_Name Hometown_Id ======================================== 1 Brett Burr 1 2 Bucky Beaver 2 3 Ranma Saotome 3 However, I'm having a problem with the syntax when inserting the data into the new Users table. I can insert the non-location based fields easily with a command like: INSERT INTO newusers (Id, First_Name, Last_Name) SELECT DISTINCT Id, First_Name, Last_Name FROM users However, I'm not sure of the correct syntax to then add the values from the location table A: Assuming that you have the appropriate constraints, and that the Location table contains unique entries, the following should work: INSERT INTO newusers (Id, First_Name, Last_Name, Hometown_Id) SELECT users.Id, users.First_Name, users.Last_Name, locations.Id FROM users INNER JOIN locations ON locations.City = users.Hometown_City AND locations.State = users.Hometown_State AND locations.Country = users.Hometown_Country If you have more than one location needed (such as a 'current residence' entry), alias and join to the locations table (from users) a second time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with Warble JAR not running correctly on Tomcat 6, runs fine on Webrick I am somewhat new to Jruby - up to this point I have had no problem using warble and building a war for my Jruby. Now when I try to deploy the created war I see this error in the logs and I am not sure 100% how to fix. Please help. Error in logs below: load error: sqlite3/sqlite3_native -- java.lang.UnsatisfiedLinkError: failed to load shim library, error: dlopen(/tomcat6-1/bin/file:/tomcat6-1/webapps/ROOT/WEB-INF/lib/jruby-stdlib-1.6.3.jar!/META-INF/jruby.home/META-INF/jruby.homeDarw in/libjruby-cext.jnilib, 10): image not found --- System jruby 1.6.3 (ruby-1.8.7-p330) (2011-07-07 965162f) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_26) [darwin-x86_64-java] Time: Wed Sep 28 16:26:29 -0600 2011 Server: Apache Tomcat/6.0.32 jruby.home: file:/tomcat6-1/webapps/ROOT/WEB-INF/lib/jruby-stdlib-1.6.3.jar!/META-INF/jruby.home --- Context Init Parameters: public.root = / rails.env = production --- Backtrace LoadError: load error: sqlite3/sqlite3_native -- java.lang.UnsatisfiedLinkError: failed to load shim library, error: dlopen(/tomcat6-1/bin/file:/tomcat6-1/webapps/ROOT/WEB-INF/lib/jruby-stdlib-1.6.3.jar!/META-INF/jruby.home/META-INF/jru by.homeDarwin/libjruby-cext.jnilib, 10): image not found require at org/jruby/RubyKernel.java:1038 require at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:239 load_dependency at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:225 new_constants_in at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:596 new_constants_in at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:595 load_dependency at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:225 require at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:239 (root) at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/sqlite3-1.3.4/lib/sqlite3.rb:6 require at org/jruby/RubyKernel.java:1038 require at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/sqlite3-1.3.4/lib/sqlite3.rb:68 each at org/jruby/RubyArray.java:1603 require at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/bundler-1.0.15/lib/bundler/runtime.rb:66 each at org/jruby/RubyArray.java:1603 require at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/bundler-1.0.15/lib/bundler/runtime.rb:55 require at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/bundler-1.0.15/lib/bundler.rb:120 (root) at /tomcat6-1/webapps/ROOT/WEB-INF/config/application.rb:7 require at org/jruby/RubyKernel.java:1038 require at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:239 load_dependency at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:225 new_constants_in at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:596 new_constants_in at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:595 load_dependency at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:225 require at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:239 (root) at /tomcat6-1/webapps/ROOT/WEB-INF/config/application.rb:2 require at org/jruby/RubyKernel.java:1038 require at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:239 load_dependency at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:225 new_constants_in at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:596 new_constants_in at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:595 load_dependency at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:225 require at /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/activesupport-3.0.9/lib/active_support/dependencies.rb:239 load_environment at /tomcat6-1/webapps/ROOT/WEB-INF/config/environment.rb:169 to_app at file:/tomcat6-1/webapps/ROOT/WEB-INF/lib/jruby-rack-1.0.9.jar!/jruby/rack/rails.rb:173 new at file:/tomcat6-1/webapps/ROOT/WEB-INF/lib/jruby-rack-1.0.9.jar!/jruby/rack/rails.rb:193 (root) at <web.xml>:1 instance_eval at org/jruby/RubyKernel.java:2061 initialize at file:/tomcat6-1/webapps/ROOT/WEB-INF/lib/jruby-rack-1.0.9.jar!/vendor/rack-1.2.2/rack/builder.rb:46 (root) at <web.xml>:1 --- RubyGems Gem.dir: /tomcat6-1/webapps/ROOT/WEB-INF/gems Gem.path: /tomcat6-1/webapps/ROOT/WEB-INF/gems Activated gems: bundler-1.0.15 rake-0.9.2 abstract-1.0.0 activesupport-3.0.9 builder-2.1.2 i18n-0.5.0 activemodel-3.0.9 erubis-2.6.6 rack-1.2.3 rack-mount-0.6.14 rack-test-0.5.7 tzinfo-0.3.29 actionpack-3.0.9 mime-types-1.16 polyglot-0.3.2 treetop-1.4.10 mail-2.2.19 actionmailer-3.0.9 arel-2.0.10 activerecord-3.0.9 activeresource-3.0.9 rdoc-3.9.1 thor-0.14.6 railties-3.0.9 rails-3.0.9 sqlite3-1.3.4 --- Bundler Bundler.bundle_path: /tomcat6-1/webapps/ROOT/WEB-INF/gems Bundler.root: /tomcat6-1/webapps/ROOT/WEB-INF Gemfile: Gemfile Settings: without = development:test gemfile = Gemfile bin_path = /tomcat6-1/webapps/ROOT/WEB-INF/gems/gems/bundler-1.0.15/bin/bundle --- JRuby-Rack Config background_spooling = false compat_version = filter_adds_html = true filter_verifies_resource = false ignore_environment = false initial_runtimes = jms_connection_factory = jms_jndi_properties = logger = org.jruby.rack.logging.ServletContextLogger@19af2a9c logger_class_name = servlet_context logger_name = jruby.rack maximum_runtimes = memory_buffer_size = 65536 num_initializer_threads = rackup = rackup_path = rewindable = true runtime_timeout_seconds = serial_initialization = false servlet_context = org.apache.catalina.core.ApplicationContextFacade@1181a6d Please let me know if there is anything else I can provide. Thank you for your help! Daniel A: I figured this out shortly after posting - seems an issue was getting confused and the issue I posted here revolved around trying to run in Jruby a ruby native extension. Issue resolved, after switching out with Gems were needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dividing selected elements of array on Matlab I have the following array a = [ 1 10 3 4 68 2 34 8 10 ] And I need to divide each number (/2) if this number is higher than 9. This means that 1 has not to be divided, and 10 has to be divided (/2) The resulting array should be: a = [ 1 5 3 4 34 2 17 8 5 ] I have to do it without using a FOR function. So I tried with this: a = a./2; This divides every number of the array, and I as told you before, I want to divide only the ones higher than 9. Can anyone tell me how can I do it? Add a 'if whatever>5' in that statement or something? Thanks in advance A: Use logical indexing for both dividing only the numbers that meets your criterion and for assigning the result to those specific indices. a = [ 1 10 3 4 68 2 34 8 10 ]; a(a>9) = a(a>9) ./ 2
{ "language": "en", "url": "https://stackoverflow.com/questions/7590490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java arrays and foreach iteration implementation Is there some interface that will allow for iteraction of arrays and java.util.Lists? Seeing as how the for-each loop can iterate both it seems to me there must be some sort of base 'iterable' that is being traversed in both cases. So, can i setup a method parameter that accepts either Foo[], or List? We have lots of old code (which we won't be updating), that calls a few low level methods (which i'd like to update) that are expecting arrays. Our new code is converting from Lists (specifically ArrayLists most of the time) to arrays using List's toArray method, and i'd like to be able to skip this step. I've seen this post which shows the implementation, but I'm not sure how it might help. Can this be done? A: No, the language specification explicitly calls out arrays separately. Arrays don't implement Iterable<T>, which is the "normal" interface used by the enhanced for loop other than for arrays. From section 14.14.2 of the JLS: The enhanced for statement has the form: EnhancedForStatement: for ( VariableModifiers Type Identifier: Expression) Statement The Expression must either have type Iterable or else it must be of an array type (§10.1), or a compile-time error occurs. The two cases are then handled separately. Converting from arrays to lists is easy of course - but it sounds like you need to do this the other way round. There's really no "pleasant" way of doing this - and creating the array requires copying everything, of course. How much work would it be to convert at least the most heavily used bits of the API to use lists? You can write method overloads of course, e.g. public void foo(String[] array) { foo(Arrays.asList(array)); } public void foo(List<String> list) { // Use the list } ... but doing that for your old code will still involve work, as the real implementation is in terms of the list, not the array. A: Java could have made Foo[] a subtype of Iterable<Foo>; unfortunately that won't work on primitive arrays because Java doesn't support primitive type arguments, so we don't have this nicety. A: I think arrays are just special cased in the for loop's implementation. One thing you can do is overload your methods: public void foo(MyClass[] stuff) { foo(Arrays.asList(stuff)); } public void foo(Collection<MyClass> stuff) { // stuff } Or the other way around: public void foo(MyClass[] stuff) { // stuff } public void foo(Collection<MyClass> stuff) { foo(stuff.toArray(new MyClass[stuff.size()])); } A: There is not such a common interface, an Array does not implement Iterable. What you can do is to overload you method: public void mymethod(String ... strings) { mymethod(Arrays.asList(strings)); } public void mymethod(List<String> strings) { // do what you need }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Method to dump classes on the classpath from inside JVM? My code is failing with a ClassNotFoundException. I can see that the jar file containing the class is definitely on the classpath from the command prompt execution. Is there a way to dump the list of classes on the classpath from the JVM? (Ideally some Java code). (I don't want to see the classes in a directory, I want to see a list of what is loaded into the JVM). A: ..? (Ideally some Java code) If you were looking only to resolve a Class-Not-Found bug, then adding a dump code within the app can add complexity to turn it off later. Perhaps it would be better to use -verbose:class JVM argument which would output all classes loaded at runtime. Its easy to turn off and output of the console can be easily redirected to a log. A: That's actually not what you want to see if you're getting a CNFE, since it's not found. Plus not all available classes will be loaded at any given time. Start by going through this list. But in general, if it's not found, it's actually not found. A: You can programatically display the classpath by looking at the classloaders and dumping the URLs they are loading from. Something like this: import java.net.URLClassLoader; import java.util.Arrays; public class ClasspathDumper { public static void main(String... args) { dumpClasspath(ClasspathDumper.class.getClassLoader()); } public static void dumpClasspath(ClassLoader loader) { System.out.println("Classloader " + loader + ":"); if (loader instanceof URLClassLoader) { URLClassLoader ucl = (URLClassLoader)loader; System.out.println("\t" + Arrays.toString(ucl.getURLs())); } else System.out.println("\t(cannot display components as not a URLClassLoader)"); if (loader.getParent() != null) dumpClasspath(loader.getParent()); } } it would produce output similar to: Classloader sun.misc.Launcher$AppClassLoader@2a340e: [file:/C:/Java/workspaces/myproject/bin/] Classloader sun.misc.Launcher$ExtClassLoader@bfbdb0: [file:/C:/Java/jdk/jdk1.7.0/jre/lib/ext/dnsns.jar, file:/C:/Java/jdk/jdk1.7.0/jre/lib/ext/localedata.jar, file:/C:/Java/jdk/jdk1.7.0/jre/lib/ext/sunec.jar, file:/C:/Java/jdk/jdk1.7.0/jre/lib/ext/sunjce_provider.jar, ...] A: Well, you could create a memory dump (e.g. via jmap) and view it (e.g. via jhat). Alternatively, IIRC jconsole can show the loaded classes, so you could just view them. I'm not entirely sure though and I don't have a running jconsole right now. A third alternative (for Java 5+) would be VisualVM which is part of the Java6+ distribution. However, most certainly your jar file is not on the classpath or you are using some custom classloaders. Could you elaborate on how you put that jar on the classpath?
{ "language": "en", "url": "https://stackoverflow.com/questions/7590495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why is the Facebook API returning an empty array for albums? I'm fairly new to the Facebook API, but I've tried to do my due diligence to figure this out, but I can't seem to. I'm simply trying to get a list of the logged-in user's albums, using various techniques, to no avail. I'm using the JavaScript SDK, and I have the following code: <script src="http://connect.facebook.net/en_US/all.js"></script> <script> FB.init({ appId:'{MY_APP_ID}', cookie: true, status: true, xfbml: true, oauth : true }); FB.login(function(response) { if(response.status === 'connected') { FB.api('/me/albums', function(response) { console.log(response); }); } }, { scope : 'user_photos' }); </script> Note that {MY_APP_ID} is actually my application ID. So, when this executes, the popup will request access to the users photos, and that works fine. Now, in code, response returns a data array that contains no elements. In addition to trying the above, I've tried initiating a JSON request to the following URL as well as directly visiting it in the browser: https://graph.facebook.com/me/albums?access_token=" + response.authResponse.accessToken And this returns an empty data array as well. The access token that I'm using is coming either from the FB.login method or FB.getLoginStatus. Any help would be greatly appreciated. Thanks in advance. A: So, I figured it out, so I will answer my own question. All the other answers on SO was related to permissions, but this wasn't it. It turns out that if I looked at my account settings (I'm the 'user'), and looked at apps, for this application, for some reason, it showed it only was requesting the email address. I knew this wasn't correct, because I was clearly asking for user_photos as well. So, after deleting the application from my profile, and reinitiating the connect, it looks like I'm able to access the albums fine. I'm not sure if Facebook intended to do this by design, but it seems like a potential bug to me. A: This can also happen if you're using the JS SDK, as that authentication process and auth dialog are apparently complete separate from what you set up in the developer app. You need to ALSO include the permissions you desire when you call FB.login() using the optional scope parameter, eg... FB.login(function(response) { if (response.authResponse) { M.FB.setIsAuthorised(true); // On success. } else { // On failure. } }, { scope: 'email,friends_birthday,user_photos,friends_photos,publish_actions' }); A: I had a similar issue. Several solutions on stackoverflow mostly attributed the issue to the lack of required permissions. Check the permissions you need by using the Graph API explorer or documentation (The tables have a column called permissions for each field). Jonathan's solution actually gave me a clue about where I went wrong. I had a different issue where I had double-checked all the permissions set for my app dashboard that were correct, but while logging in, I had specified a scope with a set of permissions which seemed to override the app settings. :( I found this strange, but I rectified it by including the other permissions in the scope too and my problem was resolved. An effective way to see if the right permissions are being set through the code is to use the following code: FB.api({ method: 'fql.query', query: 'SELECT user_status,friends_status,user_photos,friends_photos,user_location,friends_location FROM permissions WHERE uid=me()' }, function(resp) { for(var key in resp[0]) { if(resp[0][key] === "1") console.log(key+' is granted'); else console.log(key+' is not granted'); } }); P.S: Also make sure that if you changed the permissions in the app dashboard, you log out of your application and login again before testing. I wasted over 3 hours trying to fix this issue and facebook documentation did not help me a bit, so hope this helps someone!
{ "language": "en", "url": "https://stackoverflow.com/questions/7590501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make contributions to JUNIT open source How can one make contributions to JUnit or any other open source java framework in general? I am a entry level programmer and any suggestions are welcome. A: JUnit is hosted at github, like many other projects. So you can clone the source, make a change, commit it, push it to your own fork on github, and then issue a pull request to ask them to merge your changes into the official repo. See the list of issues for ideas of what types of changes to make. A: Generally speaking, the method depends on the project. Many have a page detailing how you can get involved. Keep in mind that a level of trust needs to be built up -- don't expect your first submissions to make it in right away, if at all. Don't let that discourage you, though. Getting involved with an open source project is an excellent way to build your own knowledge experience, and helps others at the same time. A: Go to www.junit.org and join its mailing list. To see what JUnit project is going on, what new features people expect, which is bugfixes...you could create a topic to discuss in the mailing list. Hope it will help you!
{ "language": "en", "url": "https://stackoverflow.com/questions/7590502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to force particular registers in inline assembly code? I have the following assembly code: __asm__ __volatile__ ( "1: subi %0, 1" "\n\t" "brne 1b" : "=d" (__count) : "M" (__count)); which results in the following compiler ouptut ce: 81 50 subi r24, 0x01 ; 1 d0: f1 f7 brne .-4 ; 0xce <main> d2: 80 e0 ldi r24, 0x00 ; 0 d4: 90 e0 ldi r25, 0x00 ; 0 How can i achieve the following: ce: 81 50 subi r16, 0x01 ; 1 d0: f1 f7 brne .-4 ; 0xce <main> d2: 80 e0 ldi r16, 0x00 ; 0 Is it even possible to tell the compiler to use r16 instead of r24:r25? That way i can reduce the cycle count by 1 which is used by the ldi r25,0x00 line. Thanks Jack A: This question is old and you most certainly already solved it, but for archiving purposes, let me answer it: yes, you can. Declare __count like this: register <type> __count __asm__ ("r16"); And voilá! Using the GNU extension explicit register variables, you've declared that the C variable __count should always be placed in r16 wherever it is used - including outside of an ASM call. Note that this declaration should have local scope, otherwise the compiler will avoid using this register in other functions. A: Check out this: http://www.nongnu.org/avr-libc/user-manual/inline_asm.html#io_ops It seems you can't force it to use a specific register. However, if you use "=a" instead of "=d" you would restrict it to registers r16..r23 which should be what you want (because you just don't want it to use the 'paired' registers r24/r25)
{ "language": "en", "url": "https://stackoverflow.com/questions/7590505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Grails controller, Command Object explotion In Grails controller actions, for validations, We use command objects. The problem is the number of CommandObject classes have exploded. def publish = { PublishCommand command -> if (command.hasErrors()) { return redirect(action: 'errors',params:params) } //rest of the code } ...... Class PublishCommand { long personId String name static constraints = { personId(nullable: false, blank: false) name(nullable: false, blank: false) } } PublishCommand Class exists only for this databinding & validation purpose. Number of such classes have exploded, 1 created for each of the action of the application. Question is, Is there a way I can have this PublishCommand as innerClass? Or other ways where I don't have to create so many classes? A: It's a pretty common practice to place the command object classes within the same .groovy file as the controller (after the controller class). This will help cut down on the number of files you have to manage. Otherwise, you are following best practices (from what you have described).
{ "language": "en", "url": "https://stackoverflow.com/questions/7590506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: value in form dependent on URL schema.yml: Shop: title: { type: string(50) } number: { type: integer(2) } i can set default value for number in ShopForm.class or method save. but how can i make it with address URL? http://www.myaddress.com/shop/new in action.class.php (Shop.class.php) public function executeNew(sfWebRequest $request) { $this->form = new ShopForm(); } for example if i open address: http://www.myaddress.com/shop/new/number/2 then automatically set number = 2 for this form. thanks for help! A: you can catch the parameter in the New Action doing this: $this->number = $request->getParameter('number'); Doing that you can access to the $number variable in your template (where you build your form). Then in the form field where you specify the number value, just put something like this: <input type="whatever" name="number" value="<?php echo $number?>"> hope this helped you! good luck
{ "language": "en", "url": "https://stackoverflow.com/questions/7590507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to use facebook connect in local host Each developer is running IIS on his own machine. We all sit in separate physical location. One developer develops the code using: http://localhost:8054/connectToFacebook.aspx another developer develops the code using: http://localhost:80/virtualDirectory/connectToFacebook.aspx etc. I'd like the Facebook Connect authentication to work for all the developers. Generally, the connect mechanism (login button with ajax dialog) does not work from localhost, as it requires a domain name. Is it possible to make the Connect mechanism work - when watching the webpage from localhost? (or must I run the webpage be a publicly accessible domain name like dyndns?) A: the easiest way is to make every dev on the team use the same url. if u r using fb c# sdk, u can continue to use differnt url by implementing your own IFacebookApplication and depending on the request url change the appid and appsecret. A: this tutorial shows you how to use the c# sdk w/ localhost. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find all subfolders of the Inbox folder using EWS I have the following Inbox folder structure: Inbox --ABC ----ABC 2 ----ABC 3 --XYZ ----XYZ 2 --123 ----123 A ----123 B ----123 C I am using Exchange Web Services and the following code to find the child folders of the Inbox folder: ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010); service.AutodiscoverUrl("MyName@MyDomain.com"); Mailbox mb = new Mailbox("MyName@MyDomain.com"); FindFoldersResults findResults = service.FindFolders( WellKnownFolderName.Inbox, new FolderView(int.MaxValue)); foreach (Folder folder in findResults.Folders) { Console.WriteLine(folder.DisplayName); } This partly works because it returns the ABC, XYZ, and 123 folders; unfortunately, it does not return the folders inside each of those folders (ABC 2, ABC 3, XYZ 2, 123 A, 123 B, 123 C). Also, it is possible that a folder could have more than one level of subfolders inside it. How can I write this code so that it will return all subfolders regardless of how deeply nested they may be? A: You can page your requests and get the entire folder hierarchy from the server in just a few calls. The key is the FolderView.Traversal property, as Jacob indicates. For example, for an Exchange mailbox with ~1,300 folders the code below only makes 2 requests. You can set your page size to whatever you like, as long as you stay at or below the server limit. FYI: Exchange Online (Office365) caps at a maximum of 1,000 items in a response. I haven't tested, so I can't speak for any similar limits when querying an on-premises Exchange Server. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security; using Exchange = Microsoft.Exchange.WebServices.Data; // from nuget package "Microsoft.Exchange.WebServices" namespace FolderViewTraversal { class Program { public static void Main() { Exchange.ExchangeService oService; Dictionary<string, User> oUsers; oUsers = new Dictionary<string, User> { { "User1", new User("write.to.me1@my.address.com", "Some-Fancy-Password1") }, { "User2", new User("write.to.me2@my.address.com", "Some-Fancy-Password2") } }; foreach (KeyValuePair<string, User> Credential in oUsers) { File.Delete(String.Format(LOG_FILE_PATH, Credential.Key)); } foreach (KeyValuePair<string, User> Credential in oUsers) { LogFileName = Credential.Key; Console.WriteLine("Getting message counts for mailbox [{0}]...", LogFileName); Console.WriteLine(); oService = Service.ConnectToService(Credential.Value); GetAllFolders(oService, String.Format(LOG_FILE_PATH, Credential.Key)); Console.Clear(); }; Console.WriteLine(); Console.Write("Press any key to exit..."); Console.ReadKey(); } private static void GetAllFolders(Exchange.ExchangeService Service, string LogFilePath) { Exchange.ExtendedPropertyDefinition oIsHidden = default; List<Exchange.Folder> oFolders = default; Exchange.FindFoldersResults oResults = default; bool lHasMore = false; Exchange.Folder oChild = default; Exchange.FolderView oView = default; short nPageSize = 0; short nOffSet = 0; List<string> oPaths = default; List<string> oPath = default; oIsHidden = new Exchange.ExtendedPropertyDefinition(0x10f4, Exchange.MapiPropertyType.Boolean); nPageSize = 1000; oFolders = new List<Exchange.Folder>(); lHasMore = true; nOffSet = 0; while (lHasMore) { oView = new Exchange.FolderView(nPageSize, nOffSet, Exchange.OffsetBasePoint.Beginning) { PropertySet = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly) }; oView.PropertySet.Add(oIsHidden); oView.PropertySet.Add(Exchange.FolderSchema.ParentFolderId); oView.PropertySet.Add(Exchange.FolderSchema.DisplayName); oView.PropertySet.Add(Exchange.FolderSchema.FolderClass); oView.PropertySet.Add(Exchange.FolderSchema.TotalCount); oView.Traversal = Exchange.FolderTraversal.Deep; oResults = Service.FindFolders(Exchange.WellKnownFolderName.MsgFolderRoot, oView); oFolders.AddRange(oResults.Folders); lHasMore = oResults.MoreAvailable; if (lHasMore) { nOffSet += nPageSize; } } oFolders.RemoveAll(Folder => (bool)Folder.ExtendedProperties[0].Value == true); oFolders.RemoveAll(Folder => Folder.FolderClass != "IPF.Note"); oPaths = new List<string>(); oFolders.ForEach(Folder => { oChild = Folder; oPath = new List<string>(); do { oPath.Add(oChild.DisplayName); oChild = oFolders.SingleOrDefault(Parent => Parent.Id.UniqueId == oChild.ParentFolderId.UniqueId); } while (oChild != null); oPath.Reverse(); oPaths.Add(String.Format("{0}{1}{2}", String.Join(DELIMITER, oPath), '\t', Folder.TotalCount)); }); oPaths.RemoveAll(Path => Path.StartsWith("Sync Issues")); File.WriteAllText(LogFilePath, String.Join(Environment.NewLine, oPaths)); } private static string LogFileName; private const string LOG_FILE_PATH = "D:\\Emails\\Remote{0}.txt"; private const string DELIMITER = "\\"; } internal class Service { public static Exchange.ExchangeService ConnectToService(User User) { return Service.ConnectToService(User, null); } public static Exchange.ExchangeService ConnectToService(User User, Exchange.ITraceListener Listener) { Exchange.ExchangeService oService = default; oService = new Exchange.ExchangeService(Exchange.ExchangeVersion.Exchange2013_SP1) { Credentials = new NetworkCredential(User.EmailAddress, User.Password) }; oService.AutodiscoverUrl(User.EmailAddress, RedirectionUrlValidationCallback); if (Listener != null) { oService.TraceListener = Listener; oService.TraceEnabled = true; oService.TraceFlags = Exchange.TraceFlags.All; } return oService; } private static bool RedirectionUrlValidationCallback(string RedirectionUrl) { var _with1 = new Uri(RedirectionUrl); return _with1.Scheme.ToLower() == "https"; } } internal class User { public string EmailAddress { get; } public SecureString Password { get; } public User(string EmailAddress) { this.EmailAddress = EmailAddress; this.Password = new SecureString(); } public User(string EmailAddress, string Password) { this.EmailAddress = EmailAddress; this.Password = new SecureString(); foreach(char Chr in Password) { this.Password.AppendChar(Chr); }; this.Password.MakeReadOnly(); } public static User GetUser() { Console.Write("Enter email address: "); string sEmailAddress = Console.ReadLine(); Console.Write("Enter password: "); User functionReturnValue = new User(sEmailAddress); while (true) { ConsoleKeyInfo oUserInput = Console.ReadKey(true); if (oUserInput.Key == ConsoleKey.Enter) { break; // TODO: might not be correct. Was : Exit While } else if (oUserInput.Key == ConsoleKey.Escape) { functionReturnValue.Password.Clear(); } else if (oUserInput.Key == ConsoleKey.Backspace) { if (functionReturnValue.Password.Length != 0) { functionReturnValue.Password.RemoveAt(functionReturnValue.Password.Length - 1); } } else { functionReturnValue.Password.AppendChar(oUserInput.KeyChar); Console.Write("*"); } } if (functionReturnValue.Password.Length == 0) { functionReturnValue = null; } else { functionReturnValue.Password.MakeReadOnly(); Console.WriteLine(); } return functionReturnValue; } } internal class TraceListener : Exchange.ITraceListener { public void Trace(string TraceType, string TraceMessage) { File.AppendAllText(String.Format("{0}.txt", Path.Combine("D:\\Emails\\TraceOutput", Guid.NewGuid().ToString("D"))), TraceMessage); } } } A: You can tell EWS to do a deep traversal when searching the folders. You can do this using the FolderView.Traversal property. Your code would then be changed to something similar to the following: FindFoldersResults findResults = service.FindFolders( WellKnownFolderName.Inbox, new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep });
{ "language": "en", "url": "https://stackoverflow.com/questions/7590510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: PHP Fatal error: Using $this when not in object context for script I've got problem: I have a script that I'm working with and just upgraded to PHP 5.3. In my kit_parser.php I'm getting the following fatal error: Fatal error: Using $this when not in object context in /home/sitename/public_html/secure/includes/hooks/kits/kit_parser.php on line 71 This is the section of code it's referencing: LINE 71---> $this->kit__log_add(array("<b>PHP Warning</b> [$errno] $errstr on line $errline in file $errfile")); function kit_error($errno, $errstr, $errfile, $errline, $die = false) { if (1==1){//$this->displayErrors ) { switch ($errno) { /* Custom Errors */ case E_USER_ERROR: break; case E_USER_WARNING: break; case E_USER_NOTICE: break; case E_ERROR: $this->kit__log_add(array("<b>PHP Error</b> [$errno] $errstr on line $errline in file $errfile")); die(); break; case E_WARNING: $this->kit__log_add(array("<b>PHP Warning</b> [$errno] $errstr on line $errline in file $errfile")); break; } return true; } return false; } Why is the error coming? Nothing found, never seen before in my other scripts. Can anyone help me please? A: This error usually means that you're using $this in a static class method. Make sure that the method this code is in is not static. If it is, you should probably be using this syntax instead: YourClassNameGoesHere::kit__log_add(array("<b>PHP Warning</b> [$errno] $errstr on line $errline in file $errfile"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7590513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tools for automatic deployment of JavaScript, CSS and HTML? I am looking for a solution to automate my project workflow a bit. Let's say I have the following folder structure: project ---- less -------- project.less ---- css -------- project.min.css ---- js -------- project.js -------- project.min.js ---- index.html Are there any tools (Mac) out there so I can manage this project so that: * *project.js is used while building the project but only project.min.js gets deployed *again, project.less is used while building the project but only project.min.css gets deployed Or do I manually need to change paths and minify files? A: You could probably write something using Capistrano, which while Rails focussed can be used to deploy anything. I have used it for PHP projects, for example. Another option would be to base your project off the HTML5 boiler plate (which uses ant) as this will build/concatenate stuff for you and could be extended to deploy just what you need. I think I would use some local scripts and Capistrano.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Xpath/XSLT : check if following sibling is a particular node I have seen questions where following-sibling has been applied based on a node's value but my issue is related to the actual node itself. This is the type of XML I have have: <Employee> <Summary> <A> <B> </Summary> <Elections> </Elections> <Employee> I need to write a Xpath condition as follows: if (NOT(the following sibling(first sibling) of /Employee/Summary is Elections)), then do something. Currently I have: <xsl:if test="(not(following-sibling::Employee/Summary[1]='Earnings')) <xsl:call-template name="EmployeeRecord"/> </xsl:if> Please note that I am not checking a node value but the node itself(i.e the node name). Any help in the right direction will be much appreciated. A: You are on the right track. The following-sibling axis evaluates from the context node in the previous step. * *if you are looking for the first element that is the following-sibling of /Employee/Summary, you would use: /Employee/Summary/following-sibling::*[1]. *In order to evaluate whether that first following-sibling is an Elections element, you can use an additional predicate filter [self::Elections]. *Testing for the negation of that, wrap the whole thing in not() Putting it all together, adjusting your example: <xsl:if test="not(/Employee/Summary/following-sibling::*[1][self::Elections])"> <xsl:call-template name="EmployeeRecord"/> </xsl:if> A: I need to write a Xpath condition as follows: if (NOT(the following sibling(first sibling) of /Employee/Summary is Elections)), then do something. Use: not(/Employee/Summary/following-sibling::*[1][self::Elections]) The XPath expression that is specified as argument to the not() function selects any Elections element that is the first following-sibling element of any Summary element that is a child of the top element Employee. If this doesn't select any node, then the XPath expression above evaluates to true().
{ "language": "en", "url": "https://stackoverflow.com/questions/7590520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: PHP Pipe into a background process I'm trying to use popen to run a php script in the background. However, I need to pass a (fairly large) serialized object. $cmd = "php background_test.php >log/output.log &"; $fh = popen($cmd, 'w'); fwrite($fh, $data); fclose($fh); //pclose($fh); Without the ampersand this code executes fine but the parent script will wait until the child is finished running. With the ampersand STDIN gets no data. Any ideas? A: You can try forking letting child process to write data and main script continue as normal. Something like this // Fork a child process $pid = pcntl_fork(); // Unable to fork if ($pid == -1) { die('error'); } // We are the parent elseif ($pid) { // do nothing } // We are the child else { $cmd = "php background_test.php >log/output.log"; $fh = popen($cmd, 'w'); fwrite($fh, $data); fclose($fh); exit(); } // parent will continue here // child will exit above Read more about it here: https://sites.google.com/a/van-steenbeek.net/archive/php_pcntl_fork Also check function pcntl_waitpid() (zombies be gone) in php documentation. A: As far as I know there is no way in php to send a process in background and continue to feed its STDIN (but maybe I'm wrong). You have two other choices here: * *Refactor your background_test.php to get its input from command line and transform your command line in php background_test.php arg1 arg2 ... >log/output.log & *If your input is pretty long, write it to a temporary file and then feed the background_test.php script with that file as in the following code Example for point 2: <? $tmp_file = tempnam(); file_put_content($tmp_file, $data); $cmd = "php background_test.php < $tmp_name > log/output.log &"; exec($cmd); A: Make a background processes listen to a socket file. Then open socket file from PHP and send your serialized data there. When your background daemon receives connection through the socket, make it fork, read data then process. You would need to do some reading, but I think that's the best way to achieve this. By socket i mean unix socket file, but you can also use this over the network. http://gearman.org/ is also a good alternative as mentioned by @Joshua
{ "language": "en", "url": "https://stackoverflow.com/questions/7590521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: one complex business XML to Object deserialize in Silverlight to rule them all I have been now searching for some time tutorials and posts how to deserialize a complex XML Document to objects and use it in an silverlight application. I have seen a lot of tutorials and posts from 2008, 2009 and many which clearly do not work.. It is kinda easy to work with Hello World or a class "Person" but i can not find any good stuff about some complex xml files and objectaction on the data. The 3 lines of parsingcode are not the problem, but what does the c # code look like? How do i create all those classes? How to work with those objects? Lets imagine you get from a Web Service a stream or you have a string in your logic like this. You have namespaces, attributes and 6 childnodes. <?xml version="1.0" encoding="UTF-8"?> <om:root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:om="http://www.opengis.net/om/1.0"> <a name="a1"> <b> <c id="1" name="C1"> <d id="1" name="D1">My name is D1</d> <d id="2" name ="D2">My name is D2</d> <e> <f>this is f1</f> </e> </c> <c id="2" name="C2"> <d id="3" name="D3">My name is D3</d> <e> <f>this is f2</f> </e> </c> </b> <b> <c id="3" name="C3"> <d id="4" name="D5">My name is D4</d> <d id="5" name="D5">My name is D5</d> <d id="6" name="D6">My name is D6</d> <d id="7" name="D7">My name is D7</d> <e> <f>this is f3</f> </e> </c> </b> </a> </om:root> 1) Is there any website, which can create the classes and c# code to be able to work/store the data within a xml? You post your xml file and u get the sourcecode for your c # classes. Something like www.json2csharp.com 2) How would my classes, properties, etc look like? I would like to see one standard modern state of the art way how to deal with Properties, Attributes, Lists, etc. The complete code with "using xxx"! Please lets use standard serializer class which will work with Silverlight! 3)Some object action. Like * *give me all nom:c in a list *give me the value from f in nom:c id="2" *put all b into a list *give me all atributevalues from name="" FROM all test:d nodes just some serius practical queries and not those easymode get.me.person.name or book.name edit: Ok, maybe this is to difficult. Can anyone post some Links where there is at least a kind of tutorial or a blog with some examples? A: For generating c# classes from xml you can use Microsoft tool xsd.exe. A: I am a begginer myself but if I were you I would definitely look into System.Xml.Linq class. When you already figure out your class it should be pretty simple to deserialize your document. Underneath I m pasting a snippet from my code which does exactly what you want. It`s for WP7 but apart from IsolatedStorage part everything should be the same. ItemTemplate item = new ItemTemplate(); using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("/Items.xml", FileMode.Open)) { XElement doc = XElement.Load(stream); IEnumerable<XElement> itemTest = from el in doc.Elements("item") where (string)el.Element("id") == itemId select el; foreach (XElement el in itemTest) { item.ItemContent = el.Element("content").Value; item.Status = Convert.ToBoolean(el.Element("status").Value); item.Notes = el.Element("notes").Value; item.Location = el.Element("location").Value; item.Deadline = Convert.ToDateTime(el.Element("deadline").Value); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IE ignores styles for dynamically loaded content I've seen a couple similar questions here with no real answers. Hopefully someone notices this... IE 8 and below are refusing to apply styles from the css stylesheet defined in the header when they are loaded in a document.ready jquery call. Paranoid client wants NOBODY to see code or the dev site so I'll have to give a short example. The client wants the site to render only the relevant portion of HTML on a nearly exclusively "ajaxed" site. So, the site is like a grid. If you load the homepage you get this: <div id="content"> <section id="home"> <h1>Title</h1> <p>Hi There!</p> </section> </div> Then onload I use jquery to render the surrounding pages... $(document).ready(function(){ $('#content').append('<section id="about"><h1>About Us</h1></section>'); }); IE can handle this much, but when it comes to respecting my carefully plotted css, it just ignores the styles and laughs at me. The site is entirely positioned with absolute positioning, tons of z-indexing and a horrendous amount of jquery animation. The kind of thing you do not want to have recreate in some extra stupid way for some inferior yet dominantly used browser. Dear god please tell me someone has figured out some way to get IE to respect defined styles on elements created after load. Have ye any ideas? * *I know chunks of real code are preferred but this is succinct and tells you enough without having a full blown audit. Even if the only defined style is #about{ display:none; } it is ignored. The about section is written as requested but it is display block by default. *I also know this is not technically ajaxing, but I'm using technical jargon to attempt to clarify the order of page loading in as much as it is not standard loaded html. THE SOLUTION $('#content').append($('<section>').attr('id', 'about').html('<h1>About Us</h1><p>some text</p>')); Properly applies the element as well as the css for this and all children. Not sure why nested elements are read properly by IE without having to be declared the same way, but I am definitely grateful. Thanks jfriend00 and everyone else who helped. A: The problem is that this line of code does not generate the desired set of HTML objects in IE7/IE8: $('#content').append('<section id="about"><h1>About Us</h1></section>'); If you look in the IE DOM inspector, you don't see the desired tags nested appropriately so the DOM is messed up and thus the style rules don't work appropriately. The issue is how things are getting inserted into the DOM by jQuery. I think it's a jQuery interaction problem with IE more than anything else. Without stepping through the code in detail on IE, I can't say whether it's actually a jQuery issue or an IE issue or just one of those weired combo bugs. Obviously, IE has earned the right of first blame for it's previous transgressions, but it's probably better to just avoid this bug by using some more straightforward code. Breaking down the code a bit, this code works for me in IE7: Here, we create a single tag, add some innerHTML to it and then insert that root tag using append() rather than give HTML to append. $(document).ready(function() { var section = $("<section>"); section.attr("id", "about"); section.html('<h1>About Us</h1>'); $('#content').append(section); }); You can see the revised code work here: http://jsfiddle.net/jfriend00/vEST8/ I don't know why IE has a problem with appending an whole HTML string directly via jQuery, but I have seen this problem before. A: To be safe, use jQuery to apply said classes after the append: $('#content').append('<section id="about"><h1>About Us</h1></section>'); $("#about").addClass("foo");
{ "language": "en", "url": "https://stackoverflow.com/questions/7590537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Rookie mysql join question I have: * *a coupons table with a column called owner_id and id *and an owners table with a column called id and website_url. I'd like to get owners.website_url using only coupons.id (which is provided in a php variable $coupon_id. Here's my best shot: SELECT owners.website_url FROM owners o LEFT JOIN coupons c ON o.id = c.owner_id WHERE c.id='$coupon_id' LIMIT 1 Is this correct? I put LIMIT 1 beacause there are many coupons per owner. A: It looks correct, but it's pointless to use a LEFT JOIN there since you are filtering away the failed joins in your WHERE clause. Just use JOIN. You also shouldn't need the LIMIT clause since all coupons should have unique ids (assuming that id is a primary key) and each coupon has only one owner. A: SELECT o.website_url FROM coupons c INNER JOIN owners o ON o.id = c.owner_id WHERE c.id='$coupon_id'
{ "language": "en", "url": "https://stackoverflow.com/questions/7590540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to deploy flex app using different web service urls? Is there some sort of configuration settings in FlashBuilder 4.5 where you can easily switch between webservice urls? Right now I have to delete and recreate the web service every time I switch from local to production and vice versa. A: The need/requirement is this – Since I work in a startup, we keep changing servers, and their IP addresses. And being a service oriented application – I need to be able to edit the webservice endpoints in my Flex application in a easy manner every time this happens. My Solution for this - Assumption is that my webservice endpoint looks like this - http:////ListAllServices/ 1) Create a file config.xml in a folder named “settings” that sits in the root folder of your Flex application – outside the “src” folder. And the config.xml will be a simple xml file of the following format - localhostTestFlexApp At the end of this exercise the directory structure of your flex source code will look like this - flex_src(root of the source code) -com(some source folder) –testapp —view — -images -settings –config.xml -appName.mxml 2) Now in your application code, setup a HTTPService object either in mxml or action script. Set the url of that object to this value- “settings/config.xml” – And the above xml fiel containing the current settings will be loaded into memory . Now you can store these values in a singleton object and construct your Webservice call at runtime. And whenever you want to move this to a new server in production, edit the tag of your config.xml and you should be good to go. And this can be automated as well via the EnvGen ant task. This is not the best way but yes it is very helpful while switching among servers. A: Alrighty... The way I was doing it before in fact worked. The problem was browser caching. For the benefit of others I modified the subsclass for the generated service and replace the wsdl variable with whatever endpoint I need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: removing space from cell in an html table I have an html table as <table width="600" cellspacing="0" cellpadding="0"> <tr> <td><img src="image.jpg" width="600" height="170" style="padding:0; margin:0;"></td> </tr> <tr> <td> <p style="padding:0; margin:0;">Text</p> </td> </tr> </table> Inspite of specifying the padding, margin as 0. I can see some white space between the image and the Text in Outlook 2003, 2002 email clients. How do I get rid of it? A: You're most likely seeing line-height of the <td>. Use the following CSS to remove it, along with any whitespace: /* Gets rid of table cell whitespace */ table td { line-height: 0; font-size: 0; } /* Sets the font and line height correctly for the paragraph of text */ table td p { line-height: 14px; font-size: 14px; } You can see it in action here. A: the answer above did not help me. for outlook 2003 try the following. there is no css required. just add vspace="0" hspace="0" on the image tag to remove the whitespace. <img src="........" vspace="0" hspace="0" /> if your image has a link on it you can then take off the border with css by having border:none on the img tag and text-decoration with none on the a tag. <a href="#" style="text-decoration:none;"> <img src="imagename.jpg" vspace="0" hspace="0" style="border:none;" /> </a> take off padding on the td by adding padding of 0 <td style="padding: 0;"> <a href="#" style="text-decoration:none;"> <img src="imagename.jpg" vspace="0" hspace="0" style="border:none;" /> </a> </td>
{ "language": "en", "url": "https://stackoverflow.com/questions/7590551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Magic: The Gathering database design I would like to create a database for MTG cards I own. What would the design be? I would like to store the following information about each card: 1. Name of card. 2. Set the card belongs to. 3. Condition of card. 4. Price it sold for. 5. Price I bought it for. Here is a little info about MTG cards in general: 1. Every card has a name. 2. Every card belongs to a set. 3. A card may have a foil version of itself. 4. Card name, set it belongs to, and whether it's foil or not makes it unique. 5. A card may be in multiple sets. 6. A set has multiple cards. The gimmick is that in my collection I may have several copies of the same card but with different conditions, or purchased price, or sold price may be different. I will have another collection of mtg cards that have been sold on eBay. This collection will have the price/condition/date/whether it was a "Buy It Now" or Bid, etc. The idea is to find out what price I should sell my cards based on the eBay collection. A: It's not a programming question, it's a modeling question. Anyone who is programming but not modeling, is a coder, not a programmer. That's just a step above data entry. Modeling is a fundamental aspect of programming as it deals directly with abstraction, and abstraction is the real genius of computer programming. Normalization and database design is an excellent way for someone to become better at programming in general as normalization is also an abstraction process. Abstraction is arguably the most difficult aspect of computer programming, particularly since computer programming requires a person to both be especially pedantic and literal (in order to properly work with the steadfast stubbornness and idiocy that is a computer) as well as handle and work in a very high level and abstract space. For example, the arguments in design meetings are not over language syntax. So, that said. I have updated the schema in minor ways to address the changes. create table card ( card_key numeric not null primary key, name varchar(256) not null, foil varchar(1) not null); -- "Y" if it's foil, "N" if it is not. create table set ( set_key numeric not null primary key, name varchar(256) not null); create table cardset ( card_key numeric not null references card(card_key), set_key numeric not null references set(set_key)); create table condition ( condition_key numeric not null primary key, alias varchar(64), description varchar(256)); create table saletype ( saletype_key numeric not null primary key, alias varchar(64), description varchar(256)); create table singlecard ( singlecard_key numeric not null primary key, card_key numeric not null references card(card_key), condition_key numeric not null references condition(condition_key), purchase_date date, purchase_price numeric, saletype_key numeric references saletype(saletype_key), sell_date date, sell_price numeric, notes varchar(4000)); A more detailed explanation. The card table is the concept of the card vs an actual card. You can have a card row without having any actual cards in hand. It models any details of the card that are common to all cards. Obviously MTG cards have very many details (color text as some one mentioned), but these are likely not important to this kind of model, since this is to track actual cards for the sake of collecting and sale. But if there was any desire to add any other attributes, like card rarity, the 'card' table would be the place to put them. The set table is for the sets. I don't know what a set is, only what is posited here (there is also casual reference to a series, I don't know if they are related or not). Sets have a name, and are used to group cards. So, we have a 'set' table. The cardset table is the many-to-many joiner table. Since a set can have several cards, and a card can belong to several sets, the model needs something to represent that relationship. This is a very common pattern in relational databases, but it is also non-obvious to novices. There are two simple lookup tables, the condition and saletype table. These two tables are here for normalization purposes and let the user standardize their terms for these two categories of data. They each have an 'alias' and a 'description'. The alias is the short english version: 'Good', 'Poor', 'Auction', 'Buy it now', while the description is the longer english text 'Poor cards show sign of wear, bending, and rub marks'. Obviously someone doing this for their own purpose likely do not need the description, but it's there as a habit. Finally, the meat of the system is the singlecard table. The singlecard table represents an actual, in your hand card. It models all of the characteristic that make each actual card different from each other. An individual card is not a member of a set (at least not from the description), rather that's a higher level concept (such as how it was published -- all "Hero: Bartek the Axe Wielder" cards are part of the "Dark Mysteries" and "Clowns of Death" sets, or whatever). So, the single card needs only reference its parent card table, with the actual common card characteristics. This single card has the references to the card's condition and how it was sold via the foreign keys to the appropriate tables. It also has the other data, such as the dates and prices that were necessary. Based on what was given, this should meet the basic need. It would be a good exercise to remodel this yourself. Start with the your most basic needs, and the best model that you understand to make. Then contrast it to what I've written here, and then use that book to perhaps try and understand how whatever your simple design may have been becomes this design. Note that there is no way to actually enforce that a card is a member of ANY set, or that a set has any cards. That will be an application logic problem. This is the one of this issues with many-to-many joiner tables. It can model the relationship, but it can not enforce it. A: Ok, this isn't really a programming question as such; it's very high-level and you haven't indicated what database you'll be using and what you've tried. However, just to give you a few points, the first list (in your question) almost certainly represents most of the information that you'll need to store in your database. What you need to figure out is which combination of those fields can be used to mark a card uniquely from another. If as you say, the Date of Purchase and the Cost can vary then in the database you choose, you would need to make an index based upon those fields; this will give you the ability to store more than one instance of the same card. I would read up on 'Relational databases'. If you're really lost, I suggest picking up a copy of 'SQL for dummies', SQL is the language that most database providers use and it has step by step instructions and tutorials for building your own databases'. A: I suggest you look at data file from www.mtgjson.com By merely seeing what field types they selected and reading comments and documentation you will be likely to avoid many caveats. For instance you will see how they handle duplicate names, cards that are related to each other like one is flipped or rotated or meld together version of another and many many more little nuances.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Android : AsyncTask, how can update ProgressDialog increment I want to parse a webpage and visual a progressdialog style horizontal and increment it byte to byte, it's possibile ? A: Try something like this, Create a ProgressDialog. ProgressDialog mProgressDialog = new ProgressDialog(Your_Activity.this); mProgressDialog.setMessage("Here you can set a message"); mProgressDialog.setIndeterminate(false); mProgressDialog.setMax(100); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.show(); MyAsyncTask obj = new MyAsyncTask (); obj.execute("url"); Your AsyncTask Class. private class MyAsyncTask extends AsyncTask<String, Integer, String>{ @Override protected String doInBackground(String... url) { int count; try { URL url = new URL(url[0]); URLConnection connection = url.openConnection(); connection.connect(); // this will be useful so that you can show a tipical 0-100% progress bar int length = connection.getContentLength(); // downlod the file InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream("/sdcard/file_name.txt"); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; // publishing the progress.... publishProgress((int)(total*100/length)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (Exception e) {} return null; } @Override public void onProgressUpdate(String... args){ mProgressDialog.setProgress(args[0]); } } } You have to give these Permission's in the AndroidManifest file. <uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7590555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Simple, hassle-free, zero-boilerplate serialization in Scala/Java similar to Python's Pickle? Is there a simple, hassle-free approach to serialization in Scala/Java that's similar to Python's pickle? Pickle is a dead-simple solution that's reasonably efficient in space and time (i.e. not abysmal) but doesn't care about cross-language accessibility, versioning, etc. and allows for optional customization. What I'm aware of: * *Java's built-in serialization is infamously slow ([1], [2]), bloated, and fragile. Also have to mark classes as Serializable---annoying when there are things that are clearly serializable but which don't have that annotation (e.g. not many Point2D authors mark these Serializable). *Scala's BytePickle requires a bunch of boilerplate for every type you want to pickle, and even then it doesn't work with (cyclic) object graphs. *jserial: Unmaintained and doesn't seem to be that much faster/smaller than the default Java serialization. *kryo: Cannot (de-)serialize objects with no 0-arg ctors, which is a severe limitation. (Also you have to register every class you plan to serialize, or else you get significant slowdowns/bloat, but even so it's still faster than pickle.) *protostuff: AFAICT, you have to register every class you intend to serialize in advance in a "schema." Kryo and protostuff are the closest solutions I've found, but I'm wondering if there's anything else out there (or if there's some way to use these that I should be aware of). Please include usage examples! Ideally also include benchmarks. A: Edit 2020-02-19: please note, as mentioned by @federico below, this answer is no longer valid as the repository has been archived by the owner. Scala now has Scala-pickling which performs as good or better than Kyro depending on scenario - See slides 34-39 in this presentation. A: Twitter's chill library is just awesome. It uses Kryo for serialization but is ultra simple to use. Also nice: provides a MeatLocker[X] type which makes any X a Serializable. A: I would recommend SBinary. It uses implicits which are resolved at compile time, so it's very effective and typesafe. It comes with built-in support for many common Scala datatypes. You have to manually write the serialization code for your (case) classes, but it's easy to do. A usage example for a simple ADT A: I actually think you'd be best off with kryo (I'm not aware of alternatives that offer less schema defining other than non-binary protocols). You mention that pickle is not susceptible to the slowdowns and bloat that kryo gets without registering classes, but kryo is still faster and less bloated than pickle even without registering classes. See the following micro-benchmark (obviously take it with a grain of salt, but this is what I could do easily): Python pickle import pickle import time class Person: def __init__(self, name, age): self.name = name self.age = age people = [Person("Alex", 20), Person("Barbara", 25), Person("Charles", 30), Person("David", 35), Person("Emily", 40)] for i in xrange(10000): output = pickle.dumps(people, -1) if i == 0: print len(output) start_time = time.time() for i in xrange(10000): output = pickle.dumps(people, -1) print time.time() - start_time Outputs 174 bytes and 1.18-1.23 seconds for me (Python 2.7.1 on 64-bit Linux) Scala kryo import com.esotericsoftware.kryo._ import java.io._ class Person(val name: String, val age: Int) object MyApp extends App { val people = Array(new Person("Alex", 20), new Person("Barbara", 25), new Person("Charles", 30), new Person("David", 35), new Person("Emily", 40)) val kryo = new Kryo kryo.setRegistrationOptional(true) val buffer = new ObjectBuffer(kryo) for (i <- 0 until 10000) { val output = new ByteArrayOutputStream buffer.writeObject(output, people) if (i == 0) println(output.size) } val startTime = System.nanoTime for (i <- 0 until 10000) { val output = new ByteArrayOutputStream buffer.writeObject(output, people) } println((System.nanoTime - startTime) / 1e9) } Outputs 68 bytes for me and 30-40ms (Kryo 1.04, Scala 2.9.1, Java 1.6.0.26 hotspot JVM on 64-bit Linux). For comparison, it outputs 51 bytes and 18-25ms if I register the classes. Comparison Kryo uses about 40% of the space and 3% of the time as Python pickle when not registering classes, and about 30% of the space and 2% of the time when registering classes. And you can always write a custom serializer when you want more control. A: Another good option is the recent (2016) **netvl/picopickle**: * *Small and almost dependency-less (the core library depends only on shapeless). *Extensibility: you can define your own serializators for your types and you can create custom backends, that is, you can use the same library for the different serialization formats (collections, JSON, BSON, etc.); other parts of the serialization behavior like nulls handling can also be customized. *Flexibility and convenience: the default serialization format is fine for most uses, but it can be customized almost arbitrarily with support from a convenient converters DSL. *Static serialization without reflection: shapeless Generic macros are used to provide serializers for arbitrary types, which means that no reflection is used. For example: Jawn-based pickler also provides additional functions, readString()/writeString() and readAst()/writeAst(), which [de]serialize objects to strings and JSON AST to strings, respectively: import io.github.netvl.picopickle.backends.jawn.JsonPickler._ case class A(x: Int, y: String) writeString(A(10, "hi")) shouldEqual """{"x":10,"y":"hi"}""" readString[A]("""{"x":10,"y":"hi"}""") shouldEqual A(10, "hi")
{ "language": "en", "url": "https://stackoverflow.com/questions/7590557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Is it possible to call an undefined variable without getting an "undefined variable" message? I'm trying to make a simple little templating system where I don't want to define every variable that's available in the template. For example. Every page would have <?php displayHTML($variable); ?> but only some pages would actually have $variable defined. $variable = "something"; In included functions.php I have tried function displayHTML($variable){ if(isset($variable)){ echo $variable; }else{ echo ''; } } But the error seems to be coming from the fact that $variable isn't defined rather than not being set with a value. This error only shows with E_ALL enabled and I know I can shut it with @ or simply defining $variable across the board. Any function or best practice to avoid having to do this? I know this seems weird but I would like to option to not define every variable if its not gonna be used on a page. A: Define each variable before you use it. If your templates are trying to use variables that don't exist, then that is a logical fault with your design, and you should fix that. Give them some "default" or empty value if that's the visualisation that you wish to assign to those values. Leaving them undefined is simply error-prone and, forgive me for saying so, lazy. Some people would tell you to use the @ error-suppressant. This is a fast, cheap, hacky workaround to an underlying fault... and my advice would be to steer well clear of it. A: The problem is that the code where displayHTML() is being called is trying to reference $variable. Checking if it's set within the function itself won't work. You would need to check if it's set where the function is being called: <?php displayHTML(isset($variable) ? $variable : ''); ?> A: Your displayHTML function will not omit notices if you change it to: function displayHTML(&$variable){ ... } This will have the side effect of defining the variable if it is undefined, but will do what you want. As to what you are trying to do, you are probably better off making sure every variable in your template is defined, or just using plain ol' isset() before using a potentially undefined variable. A: You can either use http://php.net/manual/en/function.error-reporting.php to turn off error reporting or make manual error handler which is more intelligent about error display http://php.net/manual/en/function.set-error-handler.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7590560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: handling a callback with ctypes I'm attempting to map libpcap using ctypes to python3.2 and I'm having a problem using callbacks with pcap_loop... here is the code .. class c_int_hack: def from_param(self, *args): return ctypes.c_void_p #void got_packet(u_char *args, const struct pcap_pkthdr *header, # const u_char *packet) CALLBACK=ctypes.CFUNCTYPE(ctypes.c_void_p,c_int_hack,ctypes.pointer(pkthdr),ctypes.POINTER(ctypes.c_ubyte)) #int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user) def process(user,pkthdr,packet): print("In callback:") print("pkthdr[0:7]:",pkthdr.contents.len) print("packet6:%2x",packet[6]) print("packet7:%2x",packet[7]) print("packet8:%2x",packet[8]) print("packet9:%2x",packet[9]) print("packet10:%2x",packet[10]) print("packet11:%2x",packet[11]) got_packet=CALLBACK(process) if(pcap_loop(handle,ctypes.c_int(10), got_packet,"what") == -1): err = pcap_geterr(handle) print("pcap_loop error: {0}".format(err)) it seems to have a problem with the 2nd parameter which is the "c_int_hack" Got Required netmask Pcap open live worked! Filter Compiled! Filter installed! Traceback (most recent call last): File "./libpcap.py", line 72, in <module> CALLBACK=ctypes.CFUNCTYPE(ctypes.c_void_p,c_int_hack,ctypes.pointer(pkthdr),ctypes.POINTER(ctypes.c_ubyte)) File "/usr/lib/python3.2/ctypes/__init__.py", line 99, in CFUNCTYPE return _c_functype_cache[(restype, argtypes, flags)] TypeError: unhashable type THis is my first time doing work with ctypes so I'm rather confused at this point. ...... EDIT.......... So the prototype is trying to accept a pointer to a list of arguments. so I tried doing a pointer to a instance that can take a list but now I'm getting a new error.. class ListPOINTER(object): '''Just like a POINTER but accept a list of ctype as an argument''' def __init__(self, etype): self.etype = etype def from_param(self, param): if isinstance(param, (list,tuple)): return (self.etype * len(param))(*param) #void got_packet(u_char *args, const struct pcap_pkthdr *header, # const u_char *packet) args=ListPOINTER() CALLBACK = ctypes.CFUNCTYPE(ctypes.c_void_p,args(ctypes.c_char_p),ctypes.pointer(pkthdr),ctypes.POINTER(ctypes.c_ubyte)) and this is the error Got Required netmask Pcap open live worked! Filter Compiled! Filter installed! Traceback (most recent call last): File "./libpcap.py", line 81, in <module> args=ListPOINTER() TypeError: __init__() takes exactly 2 arguments (1 given) A: The callback takes an int, so declare the callback prototype with ctypes.c_int and pass one. Note you can pass a plain Python integer and ctypes will take care of marshaling it correctly to the C function. It doesn't have to be a c_int instance. Your c_int_hack is unnecessary. Update Here's an excerpt of what I got to work: # struct pcap_pkthdr class Header(Structure): _fields_ = [ ('ts',c_uint), ('caplen',c_uint), ('len',c_uint)] # Something for user data class User(Structure): _fields_ = [ ('one',c_uint), ('two',c_uint), ('three',c_char_p)] # callback type # To Python, a pointer is a pointer...so I lie and tell it the actual type # instead of the byte pointers in the original function definition, indicating # the user structure and the data buffer size. PKTHANDLER = CFUNCTYPE(None,POINTER(User),POINTER(Header),POINTER(c_ubyte*65536)) def packet_handler(param,header,data): print(param.contents.three) print(header.contents.ts,header.contents.caplen,header.contents.len) print(data.contents[:10]) print() ph = PKTHANDLER(packet_handler) user = User(1,2,b"hello") wpcap.pcap_loop(h,0,ph,byref(user))
{ "language": "en", "url": "https://stackoverflow.com/questions/7590561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: authorisation with Spring Security Grails plugin Background I'm using the Spring Security Grails plugin. Because my User and Role classes are not GORM objects, I I've replaced the UserDetailsService provided by the plugin with my own implementation: class CustomUserDetailsService implements UserDetailsService { static transactional = false private static final log = LogFactory.getLog(this) @Autowired private UserManager userManager @Autowired private RoleManager roleManager UserDetails loadUserByUsername(String username) { User user = userManager.getUserByEmail(username) UserDetails userDetails = new UserAdapter(user, roleManager) log.debug "user '$username' has roles: ${userDetails.authorities?.authority}" userDetails } } Problem When I login, I see the following message is logged from CustomUserDetailsService.loadUserByUsername() user 'a5511120@nepwk.com' has roles: [USER] So it seems that the user has been assigned the USER role. However, when I then try and access an action of this controller: @Secured(['ROLE_USER', 'ROLE_ADMINISTRATOR']) class MyProfileController { def someAction = { // impl omitted } } I get bounced to the access denied page. I'm pretty sure that the user is logged in, because the access denied page contains markup such as <sec:ifLoggedIn> protected content </sec:ifLoggedIn> and the protected content is displayed. So it seems that somehow the USER role is not associated with the current user, when the controller authorisation is performed. The log message suggests that the UserDetailsService is OK. A: Solution The solution is to make sure that the role names in the domain class/database begin with "ROLE_", as per the annotation parameters. Acknowledgements All credit for this answer goes to @BurtBeckwith and @tim_yates, who provided the solution in comments. I'm converting their comments to an answer, as future readers may easily miss their comments.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CMFCPropertyGridCtrl last item not drawn? I have a CMFCPropertyGridCtrl that I'm using in an options dialog box. I have a method in my options dialog class called InitPropertyGrid(). This method clears any properties and populates the CMFCPropertyGrid objects (using a custom Settings object for the property values) and appends them to the grid. When I open my dialog box the first time all the properties show correctly. However, if I then close my dialog box and reopen it, the very last property is not drawn on the screen. All other properties are drawn normally: First time: All subsequent times: As you can see, the plus/minus icon is showing minus in both cases to indicated the section is expanded. When the last item is not showing, clicking on the +/- icon once to contract and once to expand causes the last item to be correctly shown. Note when I close the dialog box, I do not destroy it but just reshow it. However immediately before calling ShowWindow on the dialog I call the InitPropertyGrid() (called by UpdateToCurrentSettings) method. if(optionsDialog_ == NULL) { optionsDialog_ = new OptionsDialog(settings_, this); optionsDialog_->Create(OptionsDialog::IDD, this); } optionsDialog_->UpdateToCurrentSettings(); optionsDialog_->ShowWindow(SW_SHOW); A: I found I can eliminate this problem simply by calling myPropertyGrid.ExpandAll(TRUE) at the end of the code where I initialize the property grid (InitPropertyGrid() for me). This seems to force all the properties to expand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check that a string exists within another string with regular expression I've got a regular expression that I am using to strip an extension from another string The extensions in this example are BK|BZ|113 If the string does not contain any of the extensions, then I need it to leave the string as is. The regular expression I'm using is base_value = base_string[/(.*?[^-])-?(?:BK|BZ|113)/,1] However, if the base_value does not contain the string, I want to return the base_value. I thought I could use base_value = base_string base_value = base_string[/(.*?[^-])-?(?:BK|BZ|113)/,1] unless (base_value !~ /(.*?[^-])-?(?:BK|BZ|113)) == false but that isn't working. What is the best way to return the base_string if the extensions are not found? A: If I understand well, you want to strip the regexp from a string, if it matches, right? So.. do it: string.sub(/(?:BK|BZ|113)$/, "") A: Perhaps you can use sub like this: base_string1 = "test1BK" base_string2 = "test2" p base_string1.sub(/(.*?[^-])-?(?:BK|BZ|113)/,'\1') p base_string2.sub(/(.*?[^-])-?(?:BK|BZ|113)/,'\1') When the pattern is not found nothing is replaced, otherwise it returns the string without the extension. A: If /(.*?[^-])-?(?:BK|BZ|113)/ doesn't match then base_string[/(.*?[^-])-?(?:BK|BZ|113)/,1] will be nil. So this should work: base_value = base_string[/(.*?[^-])-?(?:BK|BZ|113)/,1] || base_string
{ "language": "en", "url": "https://stackoverflow.com/questions/7590568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC 3 custom DataAnnotation: associate error message with particular property I've defined a custom DataAnnotation attribute similar to this one that goes on the class but ensures that at least one property is populated. It works correctly and adds an error message to the model's ValidationSummary. However, I want to be able to associate the error message with a particular property (or any string, really) so that I can display it in a particular place on my view. Thus, if my custom attribute is used like this: [RequireAtLeastOne(GroupId = 0, ErrorMessage = "You must specify at least one owner phone number.")] public class UserViewModel: User { ... } then I want to be able to say something like: [RequireAtLeastOne(GroupId = 0, ErrorMessage = "You must specify at least one owner phone number.", ValidationErrorKey = "my_key")] public class UserViewModel: User { ... } ...and use it in a view like this: @Html.ValidationMessage("my_key") It would also be fine if I had to associate the error message with a particular property on my model instead of an arbitrary string. How can I accomplish this? A: Using ryudice's answer and this question as the starting point, I was able to solve this problem using IValidatableObject. For anyone interested, here is the full code I ended up with: 1. Define a custom validation attribute, RequireAtLeastOneAttribute This attribute goes on the class to indicate that validation should check for property groups and ensure that at least one property from each group is populated. This attribute also defines the error message and an ErrorMessageKey, which will be used to keep track of the error messages and display them in the view instead of using the general-purpose ValidationSummary collection. [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class RequireAtLeastOneAttribute: ValidationAttribute { /// <summary> /// This identifier is used to group properties together. /// Pick a number and assign it to each of the properties /// among which you wish to require one. /// </summary> public int GroupId { get; set; } /// <summary> /// This defines the message key any errors will be associated /// with, so that they can be accessed via the front end using /// @Html.ValidationMessage(errorMessageKey). /// </summary> public string ErrorMessageKey { get; set; } public override bool IsValid(object value) { // Find all properties on the class having a "PropertyGroupAttribute" // with GroupId matching the one on this attribute var typeInfo = value.GetType(); var propInfo = typeInfo.GetProperties(); foreach (var prop in propInfo) { foreach (PropertyGroupAttribute attr in prop.GetCustomAttributes(typeof(PropertyGroupAttribute), false)) { if (attr.GroupId == this.GroupId && !string.IsNullOrWhiteSpace(prop.GetValue(value, null).GetString())) { return true; } } } return false; } } 2. Define a custom attribute PropertyGroupAttribute This will be used to define which property groups need to have at least one value filled in. [AttributeUsage(AttributeTargets.Property)] public class PropertyGroupAttribute : Attribute { public PropertyGroupAttribute(int groupId) { this.GroupId = groupId; } public int GroupId { get; set; } } 3. Attach the attributes to the model and properties Group properties together using the "GroupId" integer (which can be anything, as long as it's the same for all properties among which at least one must be filled in). [RequireAtLeastOne(GroupId = 0, ErrorMessage = "You must specify at least one owner phone number.", ErrorMessageKey = "OwnerPhone")] [RequireAtLeastOne(GroupId = 1, ErrorMessage = "You must specify at least one authorized producer phone number.", ErrorMessageKey = "AgentPhone")] public class User: IValidatableObject { #region Owner phone numbers // At least one is required [PropertyGroup(0)] public string OwnerBusinessPhone { get; set; } [PropertyGroup(0)] public string OwnerHomePhone { get; set; } [PropertyGroup(0)] public string OwnerMobilePhone { get; set; } #endregion #region Agent phone numbers // At least one is required [PropertyGroup(1)] public string AgentBusinessPhone { get; set; } [PropertyGroup(1)] public string AgentHomePhone { get; set; } [PropertyGroup(1)] public string AgentMobilePhone { get; set; } #endregion } 4. Implement IValidatableObject on the model public class User: IValidatableObject { ... #region IValidatableObject Members public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { var results = new List<ValidationResult>(); // This keeps track of whether each "RequireAtLeastOne" group has been satisfied var groupStatus = new Dictionary<int, bool>(); // This stores the error messages for each group as defined // by the RequireAtLeastOneAttributes on the model var errorMessages = new Dictionary<int, ValidationResult>(); // Find all "RequireAtLeastOne" property validators foreach (RequireAtLeastOneAttribute attr in Attribute.GetCustomAttributes(this.GetType(), typeof(RequireAtLeastOneAttribute), true)) { groupStatus.Add(attr.GroupId, false); errorMessages[attr.GroupId] = new ValidationResult(attr.ErrorMessage, new string[] { attr.ErrorMessageKey }); } // For each property on this class, check to see whether // it's got a PropertyGroup attribute, and if so, see if // it's been populated, and if so, mark that group as "satisfied". var propInfo = this.GetType().GetProperties(); bool status; foreach (var prop in propInfo) { foreach (PropertyGroupAttribute attr in prop.GetCustomAttributes(typeof(PropertyGroupAttribute), false)) { if (groupStatus.TryGetValue(attr.GroupId, out status) && !status && !string.IsNullOrWhiteSpace(prop.GetValue(this, null).GetString())) { groupStatus[attr.GroupId] = true; } } } // If any groups did not have at least one property // populated, add their error messages to the // validation result. foreach (var kv in groupStatus) { if (!kv.Value) { results.Add(errorMessages[kv.Key]); } } return results; } #endregion } 5. Use the validation messages in the view The validation messages will be saved as whatever ErrorMessageKey you specified in the RequireAtLeastOne attribute definition - in this example, OwnerPhone and AgentPhone. @Html.ValidationMessage("OwnerPhone") Caveats The built-in validation also adds an error message to the ValidationSummary collection, but only for the first attribute defined on the model. So in this example, only the message for OwnerPhone would show up in ValidationSummary, since it was defined first on the model. I haven't looked for a way around this because in my case it didn't matter. A: You can implement IValidatableObject on your model and do the custom logic there, it will let you add the message using whichever key you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Group By Day Given this array: array(1) { [0]=> array(2) { ["Project"]=> array(5) { ["id"]=> string(1) "2" ["user_id"]=> string(2) "21" ["customer_id"]=> string(1) "4" ["name"]=> string(15) "WordPress Theme" ["created"]=> string(19) "2011-09-26 21:30:38" } ["Track"]=> array(1) { [0]=> array(8) { ["id"]=> string(1) "7" ["user_id"]=> string(2) "21" ["project"]=> string(1) "2" ["customer"]=> string(1) "4" ["title"]=> string(7) "Backend" ["notes"]=> string(0) "" ["created"]=> string(19) "2011-09-28 22:21:22" ["Lapse"]=> array(2) { [0]=> array(5) { ["id"]=> string(1) "4" ["track_id"]=> string(1) "7" ["start"]=> string(19) "2011-09-28 22:22:21" ["stop"]=> string(19) "2011-09-28 22:22:30" ["created"]=> string(19) "2011-09-28 22:22:21" } [1]=> array(5) { ["id"]=> string(1) "3" ["track_id"]=> string(1) "7" ["start"]=> string(19) "2011-09-28 22:22:07" ["stop"]=> string(19) "2011-09-28 22:22:12" ["created"]=> string(19) "2011-09-28 22:22:07" } } } } } } How would i group by Day in the Lapse Array with PHP? This may have been easier to do directly with MySQL but i'm using CakePHP's recursive function and i cant figure out how to use Group By with that! A: $list = array(); function extractByDates($arr) { foreach ($arr as $key => $v) if (is_array($v)) function extractByDates($v); else if ($key == 'created') $list[$v] = $v; } extractByDates($yourGivenArray); I not tested!
{ "language": "en", "url": "https://stackoverflow.com/questions/7590571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use a relative image source in WPF using IronPython I'm creating a WPF project using Python Tools for Visual Studio (in VS 2010). I add an Image control to the form. I click the "..." in the Image's Source property, and find an image. This adds an "Images" folder to the project (both in the filesystem and in the solution), and copies the image to that folder (again both in the filesystem and in the solution). The image does not show up in the "Add" dialog. The Source attribute is set to "Images/foo.png". In the XAML the source is blue-underlined because the "Build Action" is not set to "Resource". The only build actions available are "Content", "Compile", and "None". I presume "Resource" isn't available in a dynamic language like IronPython (certainly an embedded resource would be complex). I don't know whether this is the problem or whether this can be ignored. The image does not show in the live editing window, and it doesn't show when the program runs. I've tried "/Images/foo.png" (as suggested here), "pack://application:,,,/foo.png", "pack://application:,,,/Images/foo.png", "pack://siteoforigin:,,,/foo.png", and "pack://siteoforigin:,,,/Images/foo.png". (The siteoforigin doesn't work because the 'origin' is ipy.exe. If I move the Images folder to the folder where IronPython is installed, then this does work. Obviously not a great solution!). I've tried moving the Images folder in the filesystem to the same folder as the solution (i.e. one level up in the hierarchy), and having the image in the same folder as the .py file rather than in an Images subfolder. If I change the source (directly in the XAML) to an absolute path, then it works perfectly. Obviously this isn't a great solution either! How can I use a relative path for the Image? A: It is possible. Apparently all you need to do is specify the source as a BitmapImage and relative URI will use the current directory as the base. Ignore the warnings about the file not being a resource, it doesn't really matter. It will show when you run your program. <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MyWpfApplication" Height="300" Width="300"> <Grid> <Image> <Image.Source> <BitmapImage UriSource="../Relative/Path/To/Image.png" /> </Image.Source> </Image> </Grid> </Window> I think it is all due to the default value converters for images. If you bypass using them, it all seems to just work out. A: The best way I found to deal with image paths is to just completely bypass that ponderous pack:// URI nonsense and simply use a Binding that binds directly to a BitmapImage. <Image Source="{Binding imgWarningYellow}" Height="50" HorizontalAlignment="Center" VerticalAlignment="Center" /> This way, I can use a simple GetFullPath filesystem call in code to locate the damn thing and load it up as a BitmapImage: yellowbitmap = System.Windows.Media.Imaging.BitmapImage() yellowbitmap.BeginInit() yellowbitmap.UriSource = System.Uri(System.IO.Path.GetFullPath("Images\warning-yellow50.png")) yellowbitmap.DecodePixelHeight = 50 try: yellowbitmap.EndInit() except System.IO.FileNotFoundException as e: print e.Message else: self.imgWarningYellow = yellowbitmap
{ "language": "en", "url": "https://stackoverflow.com/questions/7590586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Suggestions for lazy loading images plugin for jQuery I'm in search of most popular and working lazy loading images plugin for jQuery which would normally sustain large amounts of images per page. I have tried following plugins: - http://www.appelsiini.net/projects/lazyload - http://code.google.com/p/jquery-appear/ - http://developer.yahoo.com/yui/imageloader/ Non of them suites my needs. First didn't work as it should, second overloads server with requests, third couldn't get running. I know, that last one isn't jQuery, but I was desperate. Would be really appreciated if anyone could suggest anything. UPD: Okei, my mistake. First plugin works as it is described, but it still works to slow with needed amount of images. A: I have tried the plugin Andrew mentions (JAIL a.k.a. JqueryAsynchImageLoader) and it works well, and is very easy to use. By default you have to use the data-href attribute to store your actual image. Afterwards you simply call $("#yourdiv").asynchImageLoader() to enable asynchronous image loading. That's all. A: this plugin might suit. It appears to be in active development, but I have not tried it out yet. it does require you to make changes to the HTML IMG tags. http://www.sebastianoarmelibattana.com/projects/jail
{ "language": "en", "url": "https://stackoverflow.com/questions/7590588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: iPhone client not registering for push? I "think" my app is not registering for push notifications. It should be as simple as adding the code to didFinishLaunchingWithOptions and then the when tested the app alert for push notifications should (but does not in my case) pop up. my code: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)]; return YES; } This is an iPad app. It is running without push on my real device so I assume the provisioning is correct. Any ideas? I do not get the push Don't allow/ok pop up. A: Do u have this code in your delegate? - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken]; NSLog(str); } You should get the device token generated and put it in your server where you want to push your notification.. If let say you have everything right on the iphone part, the problem may lies on your server code where you push your notification.. Take a look at this tutorial about push notification : http://mobiforge.com/developing/story/programming-apple-push-notification-services A: You need to implement the delegate methods and set up the certificates on your server. Here is some code for the objc side: - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken { NSString *token = [[devToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]; [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"]; [[NSUserDefaults standardUserDefaults] synchronize]; } - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithString:@""] forKey:@"token"]; [[NSUserDefaults standardUserDefaults] synchronize]; } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"] message:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; [alert show]; } * *A good tutorial about setting up the server and Dev Center certs - How to renew your Apple Push Notification Push SSL Certificate *How to build an Apple Push Notification provider server (tutorial) A: Yes I have the other part of the code also. I was under the impression that the pop up would happen weather the server stuff was done yet or not? I got it working. I had to get a new provisioning file. Delete the old one. The go into the app folder. View contents of the project file. Open with text editor the file with the provisioning key in it and swap the key (two spots) out with the new key code. Now it works. Thanks for the help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ajax and linked resources There must be something I don't understand about ajax. I want to display part of page (page B) on another page (Page A) using ajax. But linked page (page B) depends on some linked resources (page C) and these resources don't display on the original page (Page A). Is there anyway around this? Here's the script (from Page B) I want to display on the original page (page A) using ajax: echo "<p>To comment, please first prove that you are human being</p>"; echo "<form method='post' action='../recapatcha_verify.php'>"; require_once('../../phpfunctions/recaptchalib.php'); $publickey = "key"; // you got this from the signup page echo recaptcha_get_html($publickey); echo "<input type='submit' />"; echo "</form>" When this page is called through ajax -- the <p> element shows up as well as the form and submit button. But the recapatcha widget accessed through linked resource (page C) does not show up. I know script works however, because if I load the page itself (page B) everything is fine. Any thoughts? suggestions? thanks A: Your recaptcha is likely injected into the page by running a script. <script>s do not get automatically evaluated when you inject them into a page (Page A). You can, for example, use jquery's $.ajax() method to do this though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to determine candidate keys from record schema and functional dependencies? If I have a schema say R={A,B,C,D} and functional dependencies say {B->C, D->A} will my set of candidate keys be {B,D} or {BD}? A: If B were a candidate key, you'd have to be able to derive these functional dependencies from the ones given in the problem. * *{B->A} *{B->C} *{B->D} Can you do that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7590599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Create directory by mkdir I want to create a folder named by the user name in /tmp/vnc/, I can create that folder in command line with perl -e 'mkdir("$ENV{USER}")', but for the following code cannot work. chdir ("/tmp/vnc") or die -1; mkdir ("$ENV{USER}", 0777) or die -1; If I use mkdir -p /tmp/vnc/$ENV{USER} in command line to make folder, nothing happens and no error reports. A: It works for me. Maybe the /tmp/vnc directory does not exist, and the chdir fails. Or maybe the $USER environment variable is not defined, because you are running it from a init.d script, for example... Or maybe you do not have write permissions in the /tmp/vnc directory. Have you tried executing mkdir /tmp/vnc/$USER from the shell? Impossible to know more without details. A: * *Please check special variable $! for text error message *Please check that variable $ENV{USER} doesn't contain extra quotes. I had similar problem in Windows OS for Activer Perl. My problem was in extra quotes A: Perhaps something is resetting your environment when you are running the script? Can you print the contents of $ENV{USER} and make sure it contains what you think it should? A: if $ENV{USR} is an absolute path (with the leading slash), then the chdir is useless since you are not using a relative path
{ "language": "en", "url": "https://stackoverflow.com/questions/7590601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: prevent command line from opening on _popen I'm opening a process in C++ like so FILE* pipe = _popen(ss.str().c_str(), "r"); This create a cmd window which goes to the forefront of the desktop. I want to prevent the cmd window from opening, and if I can't, a way to keep it minimized. Tried solutions: HWND hWnd = GetConsoleWindow(); ShowWindow(hWnd, SW_HIDE); But that only works if you are calling that function in the process that holds the cmd window. A: Instead of using _popen, use CreateProcess and the CREATE_NO_WINDOW flag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding New Admins to Active Admin I am using devise for my users. I recently installed the rails Active Admin gem, everything is working beautifully. However I can't figure out how to add a new admin users. I can see that active admin created an admin_user table in the db with a user admin@example.com, which I use to log in to the interface. I tried adding admin_user as a resource so that I can just click the Add Admin User button within the active admin interface to add a new user, however that does not seem to work. A: What brian said works perfectly http://net.tutsplus.com/tutorials/ruby/create-beautiful-administration-interfaces-with-active-admin/ AdminUser.create!(:email => 'admin@example.com', :password => 'password', :password_confirmation => 'password') A: What Brian said works, but if you want to set the password in the interface rather than have it send a reset email try this: Leave the admin_user model at its original generated default, then in app/admin/admin_users.rb: ActiveAdmin.register AdminUser do index do column :email column :current_sign_in_at column :last_sign_in_at column :sign_in_count default_actions end form do |f| f.inputs "Admin Details" do f.input :email f.input :password f.input :password_confirmation end f.buttons end end A: * *login: admin@example.com password: password => login *go to http://localhost:3000/admin/admin_users If you want create users (devise users, table "users") in admin panel: * *$ rails generate active_admin:resource user *app/admin/user.rb: ActiveAdmin.register User do permit_params :email, :name, :password, :password_confirmation index do column :name column :email actions end form do |f| f.inputs 'User' do f.input :name f.input :email f.input :password f.input :password_confirmation end f.actions end end A: this is the new syntax AdminUser.create!(email: "youremail@domain.com", password: "password123", password_confirmation: "password123")
{ "language": "en", "url": "https://stackoverflow.com/questions/7590609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "47" }
Q: Very basic question about argument with signature void *data This is very likely an extremely basic question - sorry about that. I have written an interface in C++ which is powered by a C engine. One of the C-engine functions has the following signature: static int f(double t, double *y, double *ydot, void *data) The *data thingy is to pass user data to an ODE solver. Now, in C I would simply create an struct, initialize it with my data, and pass it around. In C++ I want to create a class containing the user data, and pass it as I previously passed the struct. This can be done, as structs are classes. However, when I try to do it, the following happens: int.cpp:25: error: no matching function for call to ‘UserData::UserData()’ int.cpp:13: note: candidates are: UserData::UserData(double) int.cpp:5: note: UserData::UserData(const UserData&) int.cpp:28: error: ‘void*’ is not a pointer-to-object type int.cpp:29: error: ‘void*’ is not a pointer-to-object type My questions are the following: * *What does the void *data notation mean? *Why is it complaining that I don't have a constructor with the appropriate signature? Obviously I am very much a rookie, so I'm sorry if this is very obvious, but I don't even know what terms to use to google the problem (in addition to googling the error itself). Thanks! Edit: I apologize for the vagueness of the previous question. Also, I solved the problem and it was a very stupid mistake. I had a class containing parameters: class Data{ // an interface to get parameters }; and I needed to call a C function with the signature static int f(double t, ...., void *user_data) I mistakenly did this: static int f(double t, ...., void *user_data){ Data *data = (Data*) data; /* this is the stupid mistake */ } When I meant to do this (now it works): static int f(double t, ...., void *user_data){ Data *data = (Data*) user_data; /* this is the correction */ } Thank you all - and I appreciate indicating the correct meaning of void *data. A: void *data means a pointer to any address. It is a non-typesafe way of passing data of arbitrary type. It is a common pattern in C to implement what would be done with a function object in C++. The data parameter is probably not actually used by your ODE solver, but by a callback that you are providing. You and the callback need to know the what data points to, the ODE solver doesn't. The solver just passes the address to the callback function. As simple example, suppose the library had a function to find the root of a function in a single variable typedef double (*valuation_function) (double x, void * params); double find_root(valuation_function fn, double lower, double upper, void* params); The params function gives you the ability to write a parameterized function. Suppose you wanted to find the root of a line. struct Line { double slope; double intercept; public: Line(double s, double i) : slope(s), intercept(i) {} }; double a_line(double x, void *params) { Line* line = (Line *)params; return line->slope * x + line->intercept; } You could then call the function find_root for any line. Line fortyFive(1.0, 0.0); find_root(a_line, fortyFive); You can look at the gsl library for more examples.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Send UIPanGesture translation to all views in array I'm trying to move all views in my array at the same time. But it doesn't work. Only the first view I touch is moveable then. I don't want the other views to move to the same exact spot, I just want all views in the array to move the same amount of distance and speed as the view being panned. How can I achieve this? A: Add all your views to a common superview (if not already) and add the UIGestureRecognizer to this common superview ;) This will make it easier to manage for you (only one UIGestureRecognizer) and will move all the subviews alltogether.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to rewrite this php more efficiently I need to display manual/automatic transmission vehicle information, and the best I can come up with is the following code. I think its wrong and inefficient, but I can't quite put my finger on it. <?php if ($obj->AutoTrans == 'S'): echo "Automatic"; if ($obj->ManualTrans == 'O'): echo " (Manual Optional)"; endif; elseif($obj->ManualTrans == 'S'): echo "Manual"; if ($obj->AutoTrans == 'O'): echo " (Automatic Optional)"; endif; endif; ?> A: There's nothing inefficient about this method. You could write it cleaner (in my opinion) by using curly braces instead of using block syntax, though. A: if ($obj->AutoTrans == 'S') echo "Automatic".($this->ManualTrans=='O'?' (Manual Optional)':''); if ($obj->ManualTrans == 'S') echo "Manual".($this->AutoTrans=='O'?' (Automatic Optional)':'');
{ "language": "en", "url": "https://stackoverflow.com/questions/7590627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Should I Use the jQuery-UI-Map Plugin? I'm thinking about using jquery-ui-map, which is a google map plugin. Are there any disadvantages to using this plugin? Will I have access to all of the methods, events, etc. that are in the regular Google Maps API? Any reasons not to use it? A: All of the methods are accessible, however not through the plugin, e.g. the distance matrix is not a method in the plugin. All events in the Google API can be bound to any Google Maps object with the plugin. Performance wise it will always be better to use the API instead of a plugin. If you are using http://code.google.com/p/jquery-ui-map/ then the overhead would be ~4kb and between 0 - 50 milliseconds if you compare adding 10000 markers with the plugin and 10000 markers with Google API. 4kB extra is not that much especially when compared to jQuery ~31KB, jQM ~20KB + ~7KB CSS, Google Maps js files (~85KB) (plus atleast ~80KB in images).
{ "language": "en", "url": "https://stackoverflow.com/questions/7590630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Formatting ScrollView to occupy the parent container I am trying to format the scroll view to completely occupy the parent container, but it looks like I'm missing something. Any suggestions would be great. XAML: <Border Grid.Row="0" BorderBrush="#1B5468" BorderThickness="3,3,3,3" CornerRadius="7,7,7,7" Margin="5,0,5,5"> <StackPanel Height="Auto" Width="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"> <StackPanel HorizontalAlignment="Center" Width="350" Height="30"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <Image Source="../Images/Blue.png" Stretch="Fill" Margin="7,0,5,-27" Height="52" /> <TextBlock HorizontalAlignment="Center" Height="Auto" Margin="36,3,-2,4" Name="lblHeader" Text="Comments" VerticalAlignment="Center" Width="Auto" Foreground="Silver" FontWeight="Bold" FontSize="12" /> </Grid> </StackPanel> <ScrollViewer Height="Auto" HorizontalAlignment="Stretch" Name="dComments_Scroll" VerticalAlignment="Stretch" Width="Auto" HorizontalContentAlignment="Left" VerticalContentAlignment="Top"> <StackPanel Height="Auto" Name="dStack_Comments" Width="Auto" HorizontalAlignment="Left" VerticalAlignment="Top" UseLayoutRounding="False"> </StackPanel> </ScrollViewer> </StackPanel> </Border> A: By putting your ScrollViewer in a StackPanel, you're saying "make this ScrollViewer just tall enough to hold its content". That's what StackPanel is designed to do -- to make each child exactly as tall as it needs to be to show all its content, and then stack the next child right underneath. If that's not the layout you want, don't use a StackPanel. Edit: Instead of a StackPanel inside your Border, you probably want a Grid. (I originally wrote DockPanel, forgetting that Silverlight doesn't ship with a DockPanel.) Grid is flexible enough to let you have some controls autosized, and other controls filling (or sharing) the remainder of the available space. <Border ...> <Grid ...> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <StackPanel Grid.Row="0" ...> ... </StackPanel> <ScrollViewer Grid.Row="1" ...> ... </ScrollViewer> </Grid> </Border> Also, once you get it working, I'd strongly suggest that you see if you can simplify your XAML. You're setting a lot of properties to their default values (e.g. HorizontalAlignment="Stretch", Height="Auto"), which just makes your XAML harder to read and maintain. If you can start to learn which attributes you can remove and still keep the same behavior, you'll have a much better handle on XAML development.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Executing JS for iframe Possible Duplicate: Invoking javascript in iframe from parent page what Im trying to do is - load a html page with iframe'd website, and then remove an element of that website, lets call it '#test' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head profile="http://gmpg.org/xfn/11"> </head> <body> <iframe src="http://www.google.com"></iframe> </body> </html> Anyone got any ideas how I would go about this? Can't seem to do it in normal .remove() fashion... Thanks! A: if you are in same domain you can use window.parent inside your iframe to load an script and your desired elements and using evaling that script remove the iframe itself code for inner window aka the iframe: var myscript = document.createElement('script'); myscript.innerHTML = "var removeIframe = function(){document.body.removeChild(document.body.querySelector('iframe'));}" window.parent.document.body.appendChild(myscript); window.parent.eval(removeIframe); A: Use .contents(). $('iframe').contents().find('#test').remove();
{ "language": "en", "url": "https://stackoverflow.com/questions/7590642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JavaCV: cvLoadImage returns null no matter what I pass it I'm on OS X 10.7.1. I've downloaded the latest JavaCV binaries, and built OpenCV from a current subversion checkout. The cvLoadImage() function returns null, no matter what I pass it. I have verified that I am passing it a valid path to a valid jpg image. Other JavaCV functions seem to return reasonable values, but since I can't load images, I can't really check. I think I may have an error somewhere, but I'm not familiar with how JavaCV reports errors, so I can't check. EDIT: I can verify that the overall JavaCV installation is valid and functioning, in that if I use Java's ImageIO to load an image, it works and I can subsequently operate on the loaded image, and save an image out (again, through ImageIO). SSCE follows: import static com.googlecode.javacv.cpp.opencv_core.*; import static com.googlecode.javacv.cpp.opencv_imgproc.*; import static com.googlecode.javacv.cpp.opencv_objdetect.*; import static com.googlecode.javacv.cpp.opencv_highgui.*; import java.io.IOException; import javax.imageio.ImageIO; import java.io.File; import java.awt.image.BufferedImage; import com.googlecode.javacv.cpp.*; import com.googlecode.javacpp.Loader; class ImgLoadTest { public static void main(String[] args) { //comment out EITHER the BufferedImage bit OR the cvLoadImage portion. //works BufferedImage img = ImageIO.read(new File(args[0])); IplImage origImg = IplImage.createFrom(img); //returns null //IplImage origImg = cvLoadImage(args[0]); System.out.println("origImg is" + origImg); } } Since I can make it work via ImageIO, I'm not overly concerned about this bug anymore, but solving it may be of use to others working with JavaCV. A: OpenCV only works well with ASCII filenames. If you have i18n characters in the path, it may very well choke. Also, at the moment, JavaCV maps all String objects to UTF-8, and it does not seem like Mac OS X uses UTF-8 by default. So, if i18n is important to your application, keep on using ImageIO...
{ "language": "en", "url": "https://stackoverflow.com/questions/7590643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ACTION_HEADSET_PLUG not documented extra strange "state"? I'm doing some test with Intent.ACTION_HEADSET_PLUG. Giving the fact that the following code should be the one who give the responses (From com.android.server.HeadsetObserver class 2.2.1 r1): private final void sendIntent(int headset, int headsetState, int prevHeadsetState, String headsetName) { if ((headsetState & headset) != (prevHeadsetState & headset)) { // Pack up the values and broadcast them to everyone Intent intent = new Intent(Intent.ACTION_HEADSET_PLUG); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); int state = 0; int microphone = 0; if ((headset & HEADSETS_WITH_MIC) != 0) { microphone = 1; } if ((headsetState & headset) != 0) { state = 1; } intent.putExtra("state", state); intent.putExtra("name", headsetName); intent.putExtra("microphone", microphone); if (LOG) Slog.v(TAG, "Intent.ACTION_HEADSET_PLUG: state: "+state+" name: "+headsetName+" mic: "+microphone); // TODO: Should we require a permission? ActivityManagerNative.broadcastStickyIntent(intent, null); } } And in the documentation they say: state - 0 for unplugged, 1 for plugged. I strangely get two different state by plugging two different headsets: 0 = unplugged 1 = Headset with microphone 2 = Headset without microphone The question is: where the State 2 (two) come from? Can someone enlighten me? Thanks A: I am using that extra state myself in one of my applications. One of your headsets has a mic the other doesn't. Also make sure you a plugging it in all the way, but don't break anything :) 0 - unplugged as in no headset attached to the device 1 - headset with microphone as in wired headset that had a mic so you can talk and the device uses it as a input as you talk 2 - a headset with no microphone as in your regular old stereo headset that you would normally hook up to your stereo system to listen to music with This is extremely good info to verify that what was just connected is a wired headset that you expect to be able to talk in to and be heard correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenGL object creation Right now, I'm modelling some sort of little OpenGL library to fool around with graphic programming etc. Therefore, I'm using classes to wrap around specific OpenGL function calls like texture creation, shader creation and so on, so far, so good. My Problem: All OpenGL calls must be done by the thread which owns the created OpenGL Context (at least under Windows, every other thread will do nothing and create an OpenGL error). So, in order to get an OpenGL context, I firstly create an instance of a window class (just another wrapper around the Win API calls) and finally create an OpenGL context for that window. That sounded quiet logical to me. (If there's already a flaw in my design that makes you scream, let me know...) If I want to create a texture, or any other object that needs OpenGL calls for creation, I basically do this (the called constructor of an OpenGL object, example): opengl_object() { //do necessary stuff for object initialisation //pass object to the OpenGL thread for final contruction //wait until object is constructed by the OpenGL thread } So, in words, I create an object like any other object using opengl_object obj; Which then, in its contructor, puts itself into a queue of OpenGL objects to be created by the OpenGL context thread. The OpenGL context thread then calls a virtual function which is implemented in all OpenGL objects and contains the necessary OpenGL calls to finally create the object. I really thought, this way of handling that problem, would be nice. However, right now, I think I'm awfully wrong. The case is, even though the above way works perfectly fine so far, I'm having troubles as soon as the class hierarchy goes deeper. For example (which is not perfectly, but it shows my problem): Let's say, I have a class called sprite, representing a Sprite, obviously. It has its own create function for the OpenGL thread in which the vertices and texture coordinates are loaded into the graphic cards memory and so on. That's no problem so far. Let's further say, I want to have 2 ways of rendering sprites. One Instanced and one through another way. So, I would end up with 2 classes, sprite_instanced and sprite_not_instanced. Both are derived from the sprite class, as they both are sprite which are only rendered differently. However, sprite_instanced and sprite_not_instanced need further OpenGL calls in their create function. My Solution so far (and I feel really awful about it!) I have some kind of understanding how object generation in c++ works and how it affects virtual functions. So I decided to use the virtual create function of the class sprite only to load the vertex data and so on into the the graphics memory. The virtual create method of sprite_instanced will then do the preparation to render that sprite instanced. So, if I want write sprite_instanced s; Firstly, the sprite constructor is called and after some initialisation, the constructing thread passes the object to the OpenGL thread. At this point, the passed object is merely a normal sprite, so sprite::create will be called and the OpenGL thread will create a normal sprite. After that, the constructing thread will call the constructor of sprite_instanced, again do some initialisation and pass the object to the OpenGL thread. This time however, it's a sprite_instanced and therefore sprite_instanced::create will be called. So, if I'm right with the above assumption, everything happens exactly as it should, in my case at least. I spend the last hour reading about calling virtual functions from constructors and how the v-table is build etc. I've ran some test to check my assumption, but that might be compiler-specific so I don't rely on them 100%. In addition, it just feels awful and like a terrible hack. Another Solution Another possibility would be implementing factory method in the OpenGL thread class to take care of that. So I can do all the OpenGL calls inside the constructor of those objects. However, in that case, I would need a lot of functions (or one template-based approach) and it feels like a possible loss of potential rendering time when the OpenGL thread has more to do than it needs to... My Question Is it ok to handle it the way I described it above? Or should I rather throw that stuff away and do something else? A: You were already given some good advice. So I'll just spice it up a bit: One important thing to understand about OpenGL is, that it is a state machine, which doesn't need some elaborate "initialization". You just use it, and that's about it. Buffer Objects (Textures, Vertex Buffer Objects, Pixel Buffer Objects) may make it look different, and most tutorials and real world applications indeed fill Buffer Objects at application start. However it is perfectly fine to create them during regular program execution. In my 3D engine I use the free CPU time during the double buffer swap for asynchronous uploads into Buffer Objects (for(b in buffers){glMapBuffer(b.target, GL_WRITE_ONLY);} start_buffer_filling_thread(); SwapBuffers(); wait_for_buffer_filling_thread(); for(b in buffers){glUnmapBuffer(b.target);}). It's also important to understand that for simple things like sprites should not given its own VBO for each sprite. One normally groups large groups of sprites in a single VBO. You don't have to draw them all together, since you can offset into the VBO and make partial drawing calls. But this common pattern of OpenGL (geometrical objects sharing a buffer object) completely goes against that principle of your classes. So you's need some buffer object manager, that hands out slices of address space to consumers. Using a class hierachy with OpenGL in itself is not a bad idea, but then it should be some levels higher than OpenGL. If you just map OpenGL 1:1 to classes you gain nothing but complexity and bloat. If I call OpenGL functions directly or by class, I'll still have to do all the grunt work. So a texture class should not just map the concept of a texture object, but it should also take care of interacting with Pixel Buffer Objects (if used). If you actually want to wrap OpenGL in classes I strongly recommend not using virtual functions but static (means on the compilation unit level) inline classes, so that they become syntactic sugar the compiler will not bloat up too much. A: The question is simplified by the fact a single context is assumed to be current on a single thread; actually there can be multiple OpenGL contexts, also on different threads (and while we're at, we consider context name spaces sharing). First all, I think you should separate the OpenGL calls from the object constructor. Doing this allow you to setup an object without carrying about OpenGL context currency; successively the object could be enqueued for creation in the main rendering thread. An example. Suppose we have 2 queues: one which holds Texture objects for loading texture data from filesystem, one which hold Texture objects for uploading texture data on GPU memory (after having loaded data, of course). Thread 1: The texture loader { for (;;) { while (textureLoadQueue.Size() > 0) { Texture obj = textureLoadQueue.Dequeue(); obj.Load(); textureUploadQueue.Enqueue(obj); } } } Thread 2: The texture uploader code section, essentially the main rendering thread { while (textureUploadQueue.Size() > 0) { Texture obj = textureUploadQueue.Dequeue(); obj.Upload(ctx); } } The Texture object constructor should looks like: Texture::Texture(const char *path) { mImagePath = path; textureLoadQueue.Enqueue(this); } This is only an example. Of course each object has different requirements, but this solution is the most scalable. My solution is essentially described by the interface IRenderObject (the documentation is far different from the current implementation, since I'm refactoring alot at this moment and the development is at a very alpha level). This solution is applied to C# languages, which introduce additional complexity due the garbage collection management, but the concept are perfectly adaptable to C++ language. Essentially, the interface IRenderObject define a base OpenGL object: * *It has a name (those returned by Gen routines) *It can be created using a current OpenGL context *It can be deleted using a current OpenGL context *It can be released asynchronously using an "OpenGL garbage collector" The creation/deletion operations are very intuitive. The take a RenderContext abstracting the current context; using this object, it is possible to execute checks that can be useful to find bug in object creation/deletion: * *The Create method check whether the context is current, if the context can create an object of that type, and so on... *The Delete method check whether the context is current, and more important, check whether the context passed as parameter is sharing the same object name space of the context that has created the underlying IRenderObject Here is an example on the Delete method. Here the code works, but it doesn't work as expected: RenderContext ctx1 = new RenderContext(), ctx2 = new RenderContext(); Texture tex1, tex2; ctx1.MakeCurrent(true); tex1 = new Texture2D(); tex1.Load("example.bmp"); tex1.Create(ctx1); // In this case, we have texture object name = 1 ctx2.MakeCurrent(true); tex2 = new Texture2D(); tex2.Load("example.bmp"); tex2.Create(ctx2); // In this case, we have texture object name = 1, the same has before since the two contexts are not sharing the object name space // Somewhere in the code ctx1.MakeCurrent(true); tex2.Delete(ctx1); // Works, but it actually delete the texture represented by tex1!!! The asynchronous release operation aim to delete the object, but not having a current context ( infact the method doesn't take any RenderContext parameter). It could happen that the object is disposed in a separate thread, which doesn't have a current context; but also, I cannot rely on the gargage colllector (C++ doesn't have one), since it is executed in a thread with I have no control. Furthermore, it is desiderable to implement the IDisposable interface, so application code can control the OpenGL object lifetime. The OpenGL GarbageCollector, is executed on the thread having the right context current. A: * *It is always bad form to call any virtual function in a constructor. The virtual call will not be completed as normal. *Your data structures are very confused. You should investigate the concept of Factory objects. These are objects that you use to construct other objects. You should have a SpriteFactory, which gets pushed into some kind of queue or whatever. That SpriteFactory should be what creates the Sprite object itself. That way, you don't have this notion of a partially constructed object, where creating it pushes itself into a queue and so forth. Indeed, anytime you start to write, "Objectname::Create", stop and think, "I really should be using a Factory object." A: OpenGL was designed for C, not C++. What I've learned works best is to write functions rather than classes to wrap around OpenGL functions, as OpenGL manages its own objects internally. Use classes for loading your data, then pass it to C-style functions which deal with OpenGL. You should be very careful generating/freeing OpenGL buffers in constructors/destructors! A: I would avoid having your objects insert themselves into the GL thread's queue on construction. That should be an explicit step, e.g. gfxObj_t thing(arg) // read a file or something in constructor mWindow.addGfxObj(thing) // put the thing in mWindow's queue This lets you do things like constructing a set of objects and then putting them all in the queue at once, and guarantees that the constructor ends before any virtual functions are called. Note that putting the enqueue at the end of the constructor does not guarantee this, because constructors are always called from top-most class down. This means that if you queue an object to have a virtual function called on it, derived classes will be enqueued before their own constructors begin acting. This means you have a race condition which can cause action on an uninitialized object! A nightmare to debug if you don't realize what you've done. A: I think the problem here isn't RAII, or the fact that OpenGL is a c-style interface. It's that you're assuming sprite and sprite_instanced should both derive from a common base. These problems occur all the time with class hierarchies and one of the first lessons I learned about object orientation, mostly through many errors, is that it's almost always better to encapsulate than to derive. EXCEPT that if you're going to derive, do it through an abstract interface. In other words, don't be fooled by the fact that both of these classes have the name "sprite" in them. They are otherwise totally different in behaviour. For any common functionality they share, implement an abstract base that encapsulates that functionality.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Centering a .jpg image in PDF using Imagemagick? I'm using convert version ImageMagick 6.6.2-6 2011-03-16, and I'd like to use it to generate an A4 pdf from an image, where the image will be non-scaled and centered. I'm running the following (as a modification of Overlaying Images with ImageMagick): # generate a 100x100 JPG with just red color convert -size 100x100 xc:red red.jpg # generate PDF from JPG convert -page A4 xc:white red.jpg -gravity center -composite -format pdf out.pdf ... but, basically nothing shows? Same thing happens for a png image... Note that * *Just 'convert -page A4 red.jpg out.pdf' works - but the image is not centered; (-gravity center causes image not to show) *If the image is png, 'convert -page A4 -gravity center red.png out.pdf' does indeed work fine ... however, I'd like convert to embed the contents of the JPEG stream directly - hence, I wouldn't like to convert the JPG to PNG first. So, would it be possible to use convert to center a JPG image in an A4 PDF page directly? Many thanks in advance for any answers, Cheers!   EDIT2: @John Keyes answer works for the example above; where the image is "smaller" than the PDF size -- however if the image is bigger, e.g.: $ convert -size 1228x1706 -background \#f44 -rotate 45 gradient:\#f00-\#fff red.jpg $ identify red.jpg red.jpg JPEG 2075x2075 2075x2075+0+0 8-bit DirectClass 120KB 0.000u 0:00.000 ... then it will fail. However, it turns out: "if you change -extent to 50x50, then play with -gravity, you'll see changes" - except, the question is: which extent do you change, that of the image - or that of the final PDF? Well, it turns out - it is the extent of the final PDF... To find that size as convert sees it, check the page: Magick::Geometry - however, note that the "Postscript page size specifications" like "A4+43+43>" unfortunately, cause convert to crash in this context... But at least the respective numbers for the size (595x842) can be copied from the page; and finally this works: convert -page A4 -gravity center -resize 595x842 -extent 595x842 red.jpg out.pdf ... and actually, the -extent part is not really needed - the -resize part is the important one to have the large image show.. However, the problem here is that the image included seems to be resampled - however, I'd just like to show it scaled so it fits the page, but would otherwise like the original JPG stream to be inserted in the file.. So I guess the question is still partially open :) EDIT: Related: * *ImageMagick Gravity parameter - Stack Overflow *ImageMagick and Geometry Issue - resizing with > - Stack Overflow *command line - Resizing and croping images to an aspect ratio of 6x4 with width of 1024 pixels - Unix and Linux - Stack Exchange *conversion - using imagemagick or ghostscript (or something) to scale PDF to fit page? - Stack Overflow A: The following works perfectly for me: convert -page A4 red.jpg -gravity center -format pdf out.pdf and if you change the order of the "files" it works too: convert -page A4 red.jpg xc:white -gravity center -composite -format pdf out.pdf I think the red.jpg is centered but the white is drawn on top of it. A: Well, this is outside of imagemagick, but here is a solution in Latex, using tikz package (using How to define a figure size so that it consumes the rest of a page? #14514), which seems to reliably place images on page, and preserve them fully: % note: need to run pdflatex twice!! First time generates blank pages! % convert -size 1228x1706 -background \#f44 -rotate 45 gradient:\#f00-\#fff red.jpg % convert -size 595x1400 xc:red redlong.jpg \documentclass[a4paper]{letter} \usepackage{graphicx} \usepackage[hmargin=0.5cm,vmargin=0.5cm]{geometry} % sets page margins \usepackage{tikz} \usetikzlibrary{calc} \newcommand{\imagepage}[1]{ \tikz[overlay,remember picture]\coordinate (image-start); \par \vfill \null\hfill \begin{tikzpicture}[overlay,remember picture] \path let \p0 = (0,0), \p1 = (image-start) in node [inner sep=0pt,outer sep=0pt,anchor=center] at (current page.center) {% \pgfmathsetmacro\imgheight{\y1-\y0}% \includegraphics[height=\imgheight pt,width=\textwidth,keepaspectratio]{#1}% }; \end{tikzpicture}% } \begin{document} % there must be a \n\n after {letter!} \begin{letter} \imagepage{red.jpg} \end{letter} \begin{letter} \imagepage{redlong.jpg} \end{letter} % see also \resizebox{\textwidth}{!}{\includegraphics{red.jpg}} \end{document} Note, the letter documentclass is used to allow that each image is split on separate page..
{ "language": "en", "url": "https://stackoverflow.com/questions/7590649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Adding To A Map I'm trying to add the file size to this map. It looks like I'm making a mess of things. Any help is appreciated. Thank you. int GetFileList(const wchar_t *searchkey, std::map<std::wstring, std::wstring> &map) { WIN32_FIND_DATA fd; HANDLE h = FindFirstFile(searchkey,&fd); if(h == INVALID_HANDLE_VALUE) { return 0; // no files found } while(1) { wchar_t buf[128]; FILETIME ft = fd.ftLastWriteTime; SYSTEMTIME sysTime; FileTimeToSystemTime(&ft, &sysTime); wsprintf(buf, L"%d-%02d-%02d",sysTime.wYear, sysTime.wMonth, sysTime.wDay); map[fd.cFileName] = buf; map[fd.nFileSizeHigh] = buf; map[fd.nFileSizeLow] = buf; if(FindNextFile(h, &fd) == FALSE) break; } return map.size(); } void main() { std::map<std::wstring, std::wstring> map; int count = GetFileList(L"C:\\Users\\DS\\Downloads\\*.zip", map) && GetFileList(L"C:\\Users\\DS\\Downloads\\*.txt", map); for(std::map<std::wstring, std::wstring>::const_iterator it = map.begin(); it != map.end(); ++it) { //MessageBoxW(NULL,it->first.c_str(),L"File Name",MB_OK); //MessageBoxW(NULL,it->second.c_str(),L"File Date",MB_OK); } } A: Well, you need to decide what you're mapping from, and what you're mapping to. Probably you want to map from file-name to struct {file-size, file-time}. Keeping it similar to your code: struct file_data { wstring sLastAccessTime; __int64 nFileSize ; }; int GetFileList(const wchar_t *searchkey, std::map<std::wstring, file_data> &map) { WIN32_FIND_DATA fd; HANDLE h = FindFirstFile(searchkey,&fd); if(h == INVALID_HANDLE_VALUE) { return 0; // no files found } while(1) { wchar_t buf[128]; FILETIME ft = fd.ftLastWriteTime; SYSTEMTIME sysTime; FileTimeToSystemTime(&ft, &sysTime); wsprintf(buf, L"%d-%02d-%02d",sysTime.wYear, sysTime.wMonth, sysTime.wDay); file_data filedata; filedata.sLastAccessTime= buf; filedata.nFileSize = (((__int64)fd.nFileSizeHigh) << 32) + fd.nFileSizeLow; map[fd.cFileName]= filedata; if (FindNextFile(h, &fd) == FALSE) break; } return map.size(); } int main() { std::map<std::wstring, file_data> map; GetFileList(L"C:\\Users\\DS\\Downloads\\*.zip", map); GetFileList(L"C:\\Users\\DS\\Downloads\\*.txt", map); for(std::map<std::wstring, file_data>::const_iterator it = map.begin(); it != map.end(); ++it) { MessageBoxW(NULL,it->first.c_str(),L"File Name",MB_OK); MessageBoxW(NULL,it->second.sLastAccessTime.c_str(),L"File Date",MB_OK); } return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can you have a win32 program that consists solely of a tray (notification) icon? I have a program that literally consists of a tray icon. No GUI is needed. However, when writing the win32 code, is it necessary to still initialize a hWnd object to be associated with the tray icon? For instance, it is normal to have a the NOTIFYICONDATA hWnd field point to the window's handle. Like nid.hWnd = hwnd; Essentially, will my icon be able to still receive messages if i set nid.hwnd = NULL; A: How would you receive messages without a window? Yes you need a window associated with the tray icon. A: You could create a message-only window by specifying HWND_MESSAGE creating the window. However, message-only windows do not receive broadcast messages and you would miss out on the TaskbarCreated message. This message tells your application that explorer.exe has restarted and that your application needs to re-add its notification icons. Rather important. So create a window that never becomes visible: never call ShowWindow().
{ "language": "en", "url": "https://stackoverflow.com/questions/7590652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Walk array recursively and print the path of the walk Can someone help me with some code or instructions on how to walk recursively an array and when reaching the last element print the full path to it? A simple echo will work because I will adapt the code to some other function I'm developing. The function doesn't need to figure the array dimension because this param will be passed: Example: $depth = 8; $array[1][3][5][6][9][5][8][9]; When function reachs the 8th element it print all the path to it: //print path '1 -> 3 -> 5 -> 6 -> 9 -> 5 -> 8 -> 9' * *As I said, only printing in this format will work cause I will implement the code into some other function. *array keys can have the same value. Obviously not the same value in the same sequence for the entire arary. Updated: Walk recursively function: $someArray[1][2][3] = 'end'; $someArray[1][2][6] = 'end'; $someArray[1][3][6] = 'end'; $someArray[4][3][7] = 'end'; function listArrayRecursive(&$array_name, $ident = 0){ if (is_array($array_name)){ foreach ($array_name as $k => &$v){ if (is_array($v)){ for ($i=0; $i < $ident * 10; $i++){ echo "&nbsp;"; } echo $k . " : " . "<br>"; listArrayRecursive($v, $ident + 1); }else{ for ($i=0; $i < $ident * 10; $i++){ echo "&nbsp;"; } echo $k . " : " . $v . "<br>"; } } }else{ echo "Variable = " . $array_name; } } listArrayRecursive($someArray); Will print: 1 : 2 : 3 : end 6 : end 3 : 6 : end 4 : 3 : 7 : end Now, how can I also print the path of the array everytime it reaches the end? For example: 1 : 2 : 3 : end : path -> 1,2,3 6 : end : path -> 1,2,6 3 : 6 : end : path -> 1,3,6 4 : 3 : 7 : end : path -> 4,3,7 EDITED CODE ADDING A THIRD PARAM TO RECORD THE PATH: $someArray[1][2][3] = 'end'; $someArray[1][2][6] = 'end'; $someArray[1][3][6] = 'end'; $someArray[4][3][7] = 'end'; $someArray[3][2] = 'end'; function listArrayRecursive(&$array_name, $ident = 0, $path = null){ foreach ($array_name as $k => &$v){ if (is_array($v)){ for ($i=0; $i < $ident * 10; $i++){ echo "&nbsp;"; } echo $k . " : " . "<br>"; $path .= $k . ', '; listArrayRecursive($v, $ident + 1, $path); }else{ for ($i=0; $i < $ident * 10; $i++){ echo "&nbsp;"; } echo $k . " : " . $v . ' - path -> ' . $path . "<br>"; } } } listArrayRecursive($someArray); Will print: 1 : 2 : 3 : end - path -> 1, 2, 6 : end - path -> 1, 2, 3 : 6 : end - path -> 1, 2, 3, 4 : 3 : 7 : end - path -> 1, 4, 3, 3 : 2 : end - path -> 1, 4, 3, A: You could employ a RecursiveIteratorIterator (docs) to take the hard work out of recursing through the arrays. function listArrayRecursive($someArray) { $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($someArray), RecursiveIteratorIterator::SELF_FIRST); foreach ($iterator as $k => $v) { $indent = str_repeat('&nbsp;', 10 * $iterator->getDepth()); // Not at end: show key only if ($iterator->hasChildren()) { echo "$indent$k :<br>"; // At end: show key, value and path } else { for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) { $p[] = $iterator->getSubIterator($i)->key(); } $path = implode(',', $p); echo "$indent$k : $v : path -> $path<br>"; } } } A: This example is to give you idea, not to solve the actual task. function recursiveSearch($array,$search){ foreach($array as $key=>$val){ if($val==$search)return $key; $x=recursiveSearch($array[$key],$search); if($x)return $key.' -> '.$x; } } echo recursiveSearch($array,'search'); If no match is found, null is returned. A: $a= array(1,2,3,4,5,6); $val = end($a); print_array($a,$val); function print_array(&$arr, $val) { if ($val === false) return; $curr = prev($arr); print_array($arr,$curr); echo $val; } A: I just wrote a function that makes recursive looping a bit easier: Similar to array_walk_recursive but with some extra functionality public static function walk($array, $callback, $custom = null, $recursive = false, $info = []) { $r = $recursive; if (gettype($r) === 'integer') { $r--; } $info['depth'] = empty($info)?1:$info['depth'] + 1; $info['count'] = count($array); $info['i'] = 1; foreach($array as $k => $v) { if (is_array($v) && $r > 0) { $array[$k] = static::walk($v, $callback, $custom, $r, $info); } else { $array[$k] = $callback($v, $k, $custom, $info); } $info['i'] ++; } return $array; } public static function walkable($v, $k, $custom, $info) { if (is_string($v)) { return $v." [ custom: {$custom['key']} ] [ level: ".$info['depth'].' | No '.$info['i'].' of '.$info['count']." ]"; } return $v; } Called like so: $result = Namespace\ClassName::walk($array, ['Namespace\ClassName', 'walkable'], ['key'=>'value'], true); Setting recursive to false will only evaluate the first level. Setting recursive to true will cause it to traverse the entire array. Setting recursive to an integer will cause it to only traverse to that depth. Walkable functions can be referenced or passed to callback as anonymous function. (expects: value, key, custom, info) The returned value replace the current value. Custom data can be passed and some additional info is provided for you. You can expand on the walk function if you need additional info. A: I had similar problem. Here is a Depth-First Search-ish solution(no path depth included, it reaches until the very end of the array). Comment the 'if' statement if u don't want to include the value: $output = array(); retrievePath($someArray, $output); function retrievePath($someArray, array &$pathKeeper) { if(!is_array($someArray)){ // $someArray == "end" $element = array_pop($pathKeeper) ?? '';// if the array is empty pop returns null, we don't want that array_push($pathKeeper, $element . '->'. $someArray); } else{ end($someArray);//we want to get the last element from the array so we move the internal pointer to it's end $endElKey = key($someArray);//take the key where the pointer is reset($someArray); foreach($someArray as $key=>$value){ $element = array_pop($pathKeeper); array_push($pathKeeper, $element === null ? $key : $element . '->' . $key);// we don't want '->' at the beginning retrievePath($value, $pathKeeper); if($key != $endElKey) //we check whether this is not the last loop array_push($pathKeeper, $element); } } } A: <?php function printListRecursive($a, $var='', $i = 0) { if (!is_array($a)) { $var .= $a; return $var; } $string = ""; foreach ($a as $k => $value) { $string .= str_repeat("&nbsp;&nbsp;", $i) .' - '. $k . ':'; if (!is_array($value)) { $string .= $value . '<br />'; } else { $string .= '<br />'; $string .= printListRecursive($value, $var, $i + 1); } } return $string; } $test_array = [ 'America' => [ 'Argentina' => 'Buenos Aires', 'Peru' => 'Lima' ], 'Europe' => [ 'Ireland' => 'Dublin', 'France' => 'Paris', 'Italy' => 'Rome' ] ]; $result = printListRecursive($test_array); echo $result; ?> Check code here A: I came up with the following function based on @salathe's one. It returns an array where each element is an array containing the leaf at index 0 and the array of the path keys at index 1: function loosenMultiDimensionalArrayPathForEachVal($array) { $iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array), \RecursiveIteratorIterator::SELF_FIRST); $iterator->rewind(); $res = []; foreach ($iterator as $v) { $depth = $iterator->getDepth(); for ($path = array(), $i = 0, $z = $depth; $i <= $z; $i++) { $path[] = $iterator->getSubIterator($i)->key(); } $leaf = $array; foreach ($path as $pathKey) { $leaf = $leaf[$pathKey]; } if (!is_array($leaf)) { $res[] = [ $v, $path ]; } } return $res; } The main reason I implemented this one is that $iterator->hasChildren() returns true if the current iterated leaf is an object. Therefore, I wouldn't be able to get the path of it that way. A: I found this solution, which also keeps into account if elements of the structure are arrays: $file_contents=file_get_contents("data.json"); $json_dump=json_decode($file_contents); printPath($json_dump, '', "" ,""); function printPath($the_array, $path, $prevType) { // Parse all elements of a structure // and print full PHP path to each one. foreach($the_array as $key => $value) { if(is_array($value)) { // Array element cannot be directly printed: process its items as objects: printPath($value, $path . $key , "array"); } else { if (!is_object($value)) { // If the element is not an object, it can be printed (it's a leaf) if(is_string($value)) { $finalValue = '"' . $value . '"'; } else { $finalValue = $value; } if($prevType == "array") { // If array element, add index in square brackets echo($path . "[" . $key . "] = " . $finalValue . "<br>"); } else { echo($path . $key . " = " . $finalValue . "<br>"); } } else { // else store partial path and iterate: if($prevType == "array") { // Path of array element must contain element index: printPath($value, $path . "[" . $key . "]->" , "dummy"); } else { printPath($value, $path . $key . "->", "dummy"); } } } } } Example output: status->connections->DSS-25->band = "X" status->connections->DSS-25->endAt = "2019-11-20T20:40:00.000Z" status->connections->DSS-25->startAt = "2019-11-20T12:40:00.000Z" geometry[0]->obs[0]->name = "UDSC64" geometry[0]->obs[0]->hayabusa2->azm = 90.34 geometry[0]->obs[0]->hayabusa2->alt = -20.51 In case anybody is interested, here it is the port to Javascript: function iterate(obj, stack, prevType) { for (var property in obj) { if ( Array.isArray(obj[property]) ) { //console.log(property , "(L=" + obj[property].length + ") is an array with parent ", prevType, stack); iterate(obj[property], stack + property , "array"); } else { if ((typeof obj[property] != "string") && (typeof obj[property] != "number")) { if(prevType == "array") { //console.log(stack + "[" + property + "] is an object, item of " , prevType, stack); iterate(obj[property], stack + "[" +property + "]." , "object"); } else { //console.log(stack + property , "is " , typeof obj[property] , " with parent ", prevType, stack ); iterate(obj[property], stack + property + ".", "object"); } } else { if(prevType == "array") { console.log(stack + "[" + property + "] = "+ obj[property]); } else { console.log(stack + property , " = " , obj[property] ); } } } } } iterate(object, '', "File") A: You can add a third parameter which holds the actual path as String. At the end you can output it then.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to design libraries written in ANSI C? I want to develop a library with ANSI C. I have a string struct: struct libme_string { char* buffer; int length; }; I want to write a function, libme_create_string(), that creates and initializes a string (like constructors in C++). Which of these methods is better for designing libme_create_string()? Method #1 Allocate memory for string object in libme_create_string() and return it: struct libme_string* libme_create_string(int length) { // Check arguments... // Allocate memory for object. struct libme_string* str = malloc(sizeof(struct libme_string)); // Handle memory allocation errors... str->buffer = malloc(length); str->length = length; // Handle memory allocation errors... return str; } void libme_delete_string(struct libme_string* str) { // Check arguments... free(str->buffer); free(str); } Use struct libme_string* str; str = libme_create_string(1024); // ... libme_delete_string(str); str = NULL; Method #2 Do not allocate memory for string object in libme_create_string() function, accept it as an argument: struct void libme_create_string(libme_string* str, int length) { // Check arguments... // Just allocate memory for members. str->buffer = malloc(length); str->length = length; // Handle memory allocation errors... } void libme_delete_string(struct libme_string* str) { // Check arguments... free(str->buffer); } Use struct libme_string str; // << different, not a pointer! libme_create_string(&str, 1024); // ... libme_delete_string(&str); Notes * *string just a sample. *Method #2 is faster, isn't it? Lastly, are there any good design guidelines for designing libraries written in C? A: Personally, I would view the second version as less intuitive and more error prone. If you're trying your hardest to encapsulate instantiation (which you should be doing anyway), then the first really is the only way to go — one step, done. The second version means that in order to have a fully initialized variable, you need to not only instantiate it, but you need to call a helper function on it immediately. That extra step is a bug waiting to happen. A: Personally I prefer the first method. Agreed: it's a bit C++ like, but ... thing_t *thing_new(...); void thing_delete(thing_t *ptr); I do think that all "size" or "count" members should be unsigned, preferably size_t. Also: you last snippet tries to free() an automatic variable. That is a good reason not to use it. EDIT: There is (at least) a third way: return the entire object as a value. I don't particularly like the method, but it at least avoids the double allocation. It goes like this: typedef struct { StrLen length; StrType type; /* type is not stored in the brainfile **but recomputed on loading */ char *word; } STRING; STATIC STRING new_string(char *str, size_t len) { STRING this; if (str) { if (!len) len = strlen(str); if (len) { this.word = malloc(len); memcpy(this.word, str, len); } else { this.word = malloc(1); memset(this.word, 0, 1); } this.length = len; this.type = word_classify(this); } else { this.word = NULL; this.length = 0; this.type = 0; } return this; } Typical usage goes like this: if (*np == WORD_NIL) { STRING this; *np = dict->size++; this = new_string(word.word, word.length); dict->entry[*np].string = this; dict->entry[*np].hash = hash_word(this); } (code inherited from megahal, reused in wakkerbot) As I said, I don't like this method, but the struct assignment definitely has its advantages. A: Why not factor the process into two functions, so you can use whichever you need: struct libme_string * create_string(); void destroy_string(struct libme_string *); struct libme_string * init_string(struct libme_string * str, unsigned int length); struct limbe_string * deinit_string(struct libme_string * str); Usage #1, all dynamic allocations: struct libme_string * str = init_string(create_string(), 10); destroy_string(deinit_string(str)); Usage #2, automatic outer struct: struct libme_string str; init_string(&str); deinit_string(&str); Make sure that the init functions return the pointer, so that you can compose the calls like I did. If deinit() also sets the pointer to zero, then you could make destroy() call deinit() if the pointer is non-zero, though that breaks the symmetry a bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: php socket daemon, 2nd window tab not being processed until broadcast is sent out So I have written a daemon in php and it worked great until I opened two tabs in the same browser and then this error started happening. The 2 tabs were treated as the same socket because when a message is sent the first tab gets the message but the 2nd doesnt until another message is sent. So if 3 tabs are open it alternates between the 3. Is there any way to solve this? Links to Daemon and Client: Daemon Client Command Line: php z.daemon.php Just 2 tabbed windows: client.php?action=listen Then run: client.php?action=broadcast&broadcast=test -- Edit -- Also, the 2nd tab window which is listen does not even show its connected as a client in the commandline output. -- Edit -- Basically is there a way to send unique ids to socket_select to help it figure out if its a new or not? A: Genreate an random id on page load and use that to identify the individual clients with the query string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to properly dereference multidimensional arrays without []-operator So, I've figured out how to dereference a multidimensional array like this: #include <tchar.h> #include <iostream> wchar_t g_pppwcSymbol[2][3][4]; int main(int argc, TCHAR **argv) { (* (*( (*(g_pppwcSymbol+1) )+2 )+3 ) ) = L'K'; std::wcout<<g_pppwcSymbol[1][2][3]; std::wcin.get(); return 0; } Output: K However, I've also heard that the compiler transforms this into a 1-dimensional array, is that correct? This would mean that all the wchar_t elements follow up each other in the memory. So there must be a way to do something like this: ***(g_pppwcSymbol + x) = value; However I'm not sure how this works exactly. Could someone elaborate? EDIT: this seems to work so far: int main(int argc, TCHAR **argv) { /*(* (*( (*(g_pppwcSymbol+1) )+2 ) + 3)) = L'K';*/ /*std::wcout<<g_pppwcSymbol[1][2][3];*/ ***(g_pppwcSymbol + 1) = L'K'; std::wcout<<g_pppwcSymbol[1][0][0]; std::wcin.get(); return 0; } output: K NEXT EDIT: Working model: static const int X = 2; static const int Y = 3; static const int Z = 4; wchar_t g_pppwcSymbol[X][Y][Z]; int main(int argc, TCHAR **argv) { int iAccess = ((Y*Z) * 1) + ((Z) * 2) + 3; *( (**g_pppwcSymbol) + iAccess) = L'K'; std::wcout<<g_pppwcSymbol[1][2][3]; std::wcin.get(); return 0; } Output: K A: The compiler actually transforms the [] operator into just those mathematical calculations, so you are going about this the hard way... But it's an interesting exercise so I'll play along. g_pppwcSymbol[2][3][4] is actually a 2 elements large array of 3 elements large array of 4 elements large. Thus, g_pppwcSymbol + ((3 * 4) /* size of first level array element */ * 1) + (4 /* size of second level array element */ * 2) + 1 /* size of third level array element */ * 3; should give you the position of the last item of the last array of the last array. As long as each element is 1 byte large. The array simply is a memory area the size of "element_count * element_size and the [] operator takes the array location as a pointer and adds element_size * index. It may contain other arrays since it can compute their sizes the same way as other memory structures. BTW, I'm sure you'll find plenty of documentation about this in details all over the internet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access self from decorator In setUp() method of unittest I've setup some self variables, which are later referenced in actual tests. I've also created a decorator to do some logging. Is there a way in which I can access those self variables from decorator? For the sake of simplicity, I'm posting this code: def decorator(func): def _decorator(*args, **kwargs): # access a from TestSample func(*args, **kwargs) return _decorator class TestSample(unittest.TestCase): def setUp(self): self.a = 10 def tearDown(self): # tear down code @decorator def test_a(self): # testing code goes here What would be the best way of accessing a (set in setUp()) from decorator? A: Since you're decorating a method, and self is a method argument, your decorator has access to self at runtime. Obviously not at parsetime, because there are no objects yet, just a class. So you change your decorator to: def decorator(func): def _decorator(self, *args, **kwargs): # access a from TestSample print 'self is %s' % self return func(self, *args, **kwargs) return _decorator
{ "language": "en", "url": "https://stackoverflow.com/questions/7590682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "95" }
Q: Installing Ruby w/RBENV: I get "ruby-build command not found" I put 'rbenv install 1.9.2-p290' in the terminal and I get back 'rbenv-install: line 31: ruby-build: command not found' I have ruby-build as well. Did I not install ruby-build correctly? I see this on the github site: "You can install to a different prefix by setting the PREFIX environment variable." I'm not exactly sure what PREFIX is but does that mean I can install to another directory? Do I need to put ruby-build in a specific place? Thanks, Jae A: From a fresh terminal run which ruby-build. This will return the path to ruby-build provided it is in your path. If it is not in your path, it will return nothing. You need to edit your PATH variable such that ruby-build is found. find where ruby-build is installed with find / -name "ruby-build". If you're sure it's in /usr/local you can use /usr/local instead of /.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django: get unique object list from QuerySet I have the following (simplified) models in my Django app: class Color(models.Model): name = models.CharField(max_length=10) class Item(models.Model): name = models.CharField(max_length=200) color = models.ForeignKey(Color, blank=True, null=True) class Favorite(models.Model): user = models.ForeignKey(User) item = models.ForeignKey(Item) I'm currently getting all the items I need using the following query: favorites = Favorite.objects.filter(user=request.user) How can I get all the distinct colors for the items in that QuerySet? I need the a list of the actual color objects, not just the color ids, which I can get using favorites.values_list('item__color').distinct A: Can you do: Color.objects.filter(item__favorite__user = request.user).distinct() You might have to set some related_names on your foreign keys if these aren't the defaults (I can never remember the defaults). A: Can you do: favorites = Favorite.objects.filter(user=request.user).distinct('item__color') A: If I understand you correctly, the following should do the trick: favorites = Favorite.objects.filter(user=request.user) color_ids = favorites.values_list('item__color', flat=True).distinct() colors = Color.objects.filter(id__in=color_ids) There has to be a cleaner way than that though. Edit: A much cleaner solution: colors = Color.objects.filter(item__favorite__user=request.user).distinct() A: The is values_list(*fields, flat=False, named=False) method, so run it on your objects, for example: user.groups.values_list('name', flat=True)
{ "language": "en", "url": "https://stackoverflow.com/questions/7590692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: C# log in app with SQL Hi I'm trying to get data from a local sql service database to take the input from a user register form. but when i push the button its not recorded onto the serviceable database. do i need to use execute non query? how would i fix this code up? thanks using System.Data.Sql; using System.Data.SqlClient; namespace Paddle_Power { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 form2 = new Form2(); form2.Show(); string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PaddlePower.mdf;Integrated Security=True;User Instance=True"; SqlConnection cn = new SqlConnection(connection); try { cn.Open(); MessageBox.Show("open"); } catch (Exception) { MessageBox.Show("Did not connect"); } string username = textBox1.Text; string password = textBox2.Text; string sqlquery = ("SELECT * FROM User WHERE Username = '" + textBox1.Text + "'"); sqlquery = "INSERT INTO [User] (Username, Password) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "')"; SqlCommand command = new SqlCommand(sqlquery, cn); command.Parameters.AddWithValue("Username", username); command.Parameters.AddWithValue("Password", password); command.Parameters.Clear(); } } } A: Something along the lines of the following should hopefully do it. There's some room for improvement, but I at least hope it solves the problem you're having. string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PaddlePower.mdf;Integrated Security=True;User Instance=True"; object queryResult = null; using (SqlConnection cn = new SqlConnection(connection)) { cn.Open(); // Open connection // SELECT using (SqlCommand cmd = new SqlCommand("SELECT * FROM User WHERE Username = @Username AND Password = @Password", cn)) { cmd.Parameters.AddWithValue("@Username", textBox1.Text); cmd.Parameters.AddWithValue("@Password", textBox2.Text); queryResult = cmd.ExecuteScalar(); } // INSERT using (SqlCommand cmd = new SqlCommand("INSERT INTO [User] (Username, Password) VALUES (@Username, @Password)", cn)) { cmd.Parameters.AddWithValue("@Username", textBox1.Text); cmd.Parameters.AddWithValue("@Password", textBox2.Text); cmd.ExecuteNonQuery(); // or int affected = cmd.ExecuteNonQuery() } } You can requse the first SqlCommand object or create a new one. There's very little difference with either way you choose to do it. queryResult is just there for storing the result of cmd.ExecuteScalar(). You can map it to an object if you want (when selecting multiple columns) or cast it to a new type (if you're selecting a single column). A: The direct answer is yes, you need to execute a non query. You see, you've prepared the command but you have not issued it. jstnasn's example should be very helpful. Take note of the using statements -- these will implicitly close the command when you exit the using statement, thus ensuring that the command is always closed when done. The same occurs for the SqlConnection -- the using helps make sure that the connection is disposed of properly. However, if your database connection string allows connection pooling, then I believe the using statement will merely kill your object, without actually killing the connection to the database. This is advantageous because you will have lower I/O overhead the next time you need to open a database connection -- you'll just be connecting to an existing TCP/IP socket rather than opening a new on. A: You have no parameters, nor do you ever actually send the query to the database // parameter placeholders defined with @parameter_name sqlquery = "INSERT INTO [User] (Username, Password) VALUES (@username, @Password); SqlCommand command = new SqlCommand(sqlquery, cn); command.Parameters.AddWithValue("@Username", username); command.Parameters.AddWithValue("@Password", password); // This will make the query happen on the database. // It will handle sending the parameters and all that good stuff // http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx command.ExecuteNonQuery();
{ "language": "en", "url": "https://stackoverflow.com/questions/7590694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Help with ScalaCheck I'd like to use ScalaTest's Checkers trait to use ScalaCheck from ScalaTest cases. A simple case I'm playing with is: test("can create local date UTC from millis") { check(localDate.toTimestampUTC.toLocalDateUTC == localDate) } I need to create a arbitrary LocalDate, so I tried this: object ArbitraryValues { implicit def abc(): Arbitrary[LocalDate] = Arbitrary(Gen.choose(new LocalDate(0L), new LocalDate(Long.MaxValue))) } It doesn't compile, saying, error: could not find implicit value for parameter c: org.scalacheck.Choose[org.joda.time.LocalDate] implicit val abc: Arbitrary[LocalDate] = Arbitrary(Gen.choose(new LocalDate(0L), new LocalDate(Long.MaxValue))) and error: not found: value localDate check(localDate.toTimestampUTC.toLocalDateUTC == localDate) A: Ok figured it out through trial and error. My working code looks like this: object ArbitraryValues { implicit val abc: Arbitrary[LocalDate] = Arbitrary(Gen.choose(0L, Long.MaxValue).map(new LocalDate(_))) } test("can create local date UTC from millis -and- vice versa") { check((localDate: LocalDate) => localDate.toTimestampUTC.toLocalDateUTC == localDate) } I had to change the way I was creating the Arbitrary[LocalDate], and then update my syntax for the check.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Device orientation at launch I've read ALL of the posts on this topic, but still can't figure this one out. I add a VC to the window in applicationDidFinishLaunching. The VC contains a UIImageView. I want to set the image of the UIImageView based on the device orientation, but statusBarOrientation, deviceOrientation, interfaceOrientation, everything I check returns portrait. There's gotta be something simple I'm missing. Your help is appreciated. A: Have you enabled the other orientations in your Info.plist? There's a graphical editor for this in Xcode 4's project editor. A: Sometimes (not sure if this is in every case, or just the simulator), the app will launch in one orientation and then immediately rotate to another orientation to match the device orientation. I would suggest implementing -[UIViewController willRotateToInterfaceOrientation:duration:] to set your image, which should be called immediately after. A: Well.. it seems there were several issues. 1) The simulator doesn't consistently generate orientation (or change in orientation) data as expected. Also, 2) immediately at start up, the device may (or may not) send statusBarOrientation info in time to read that. So, I did this right in the didFinishLaunching method in the app delegate. // add the splash IV to the window per the current orientation, then animate it away [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; if([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait){ self.theSplashIV.image = [UIImage imageNamed:@"Default-Portrait~ipad.png"]; self.theSplashIV.frame = CGRectMake(0, 20, 768, 1004); } else if([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown){ self.theSplashIV.image = [UIImage imageNamed:@"Default-Portrait~ipad.png"]; self.theSplashIV.transform = CGAffineTransformMakeRotation(M_PI); self.theSplashIV.frame = CGRectMake(0, 0, 768, 1004); } else if([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft){ self.theSplashIV.image = [UIImage imageNamed:@"Default-Landscape~ipad.png"]; self.theSplashIV.transform = CGAffineTransformMakeRotation(M_PI / 2); self.theSplashIV.frame = CGRectMake(0, 0, 748, 1024); } else if([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight){ self.theSplashIV.image = [UIImage imageNamed:@"Default-Landscape~ipad.png"]; self.theSplashIV.transform = CGAffineTransformMakeRotation(M_PI / -2); self.theSplashIV.frame = CGRectMake(20, 0, 748, 1024); } [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications]; And then I animate away the splash IV with a delay. Not very elegant, but it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Phone 7 map control: panning the map while keeping the pushpin constant I'm working on a WP7 (mango) app which has a Bing Maps control with one pushpins on the screen. I need to be able to drag/pan the map so that the map view changes while the pushpin remains in a constant position relative on the screen. How can I achieve this? The pin always seems to be attached to the map and moves with the map. (This is basically an alternative to dragging the pushpin around the map i.e. dragging the map around the pushpin). A: Don't add a Location to the Pushpin. Instead just set it's Margin to the values you want. The margins are calculated from the absolute center of the Map control That way it'll be in a fixed position. Alternatively, you can add the map on a Canvas, and just draw any element on top of the Canvas. But why you want to do this, I really cannot imagine. Normally a Pushpin is fixed according to a GeoLocation (a GPS coordinate), and stays at that fixed point, when you pan/drag/zoom the map. That's what the Pushpin.Location property/attribute is for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding a clickable button or text to rich:suggestionbox suggestions I'd like to add a button to the suggestions presented in a rich:suggestionbox (an 'x' so suggestions can be removed). Is there a way to keep from being selected? What I've tried so far: <rich:suggestionbox id="suggestionBox" for="inputText" suggestionAction="#{myBean.getSugestions}" var="result" fetchValue="#{result}" usingSuggestObjects="true"> <h:column> <h:outputText value="#{result}" /> </h:column> <h:column> <a4j:outputPanel onclick="removeCommand('#{result}');Event.stop(event);"> <h:outputText value="X" /> </a4j:outputPanel> </h:column> </rich:suggestionbox> <a4j:jsFunction name="removeCommand" action="#{myBean.removeSuggestion}" ajaxSingle="true" reRender="commandInputBox"> <a4j:actionparam name="removedCommand" /> </a4j:jsFunction> The Event.stop(event) was inspired by a similar technique used by Ilya Shaikovsky I'm open to suggestions (hehe) that use completely other techniques too. A: The technique works just fine! I had a typo that was causing a client side error that halted the onclick processing. See the edit for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error when using URL conenction with thread in MapActivity in android I am using a URL connection to connect Google maps web service and get the result in KML format and parse it and display it on MapView. I put this operations in a thread, but I get this error that I don't know what does it mean ?! please help me in finding out what is this error and what is the solution ? 09-28 23:00:45.026: ERROR/ActivityManager(67): ANR in com.android.uis (com.android.uis/.RoutingMapActivity) 09-28 23:00:45.026: ERROR/ActivityManager(67): Reason: keyDispatchingTimedOut 09-28 23:00:45.026: ERROR/ActivityManager(67): Load: 0.49 / 0.21 / 0.15 09-28 23:00:45.026: ERROR/ActivityManager(67): CPU usage from 22714ms to 0ms ago: 09-28 23:00:45.026: ERROR/ActivityManager(67): 99% 1049/com.android.uis: 98% user + 0.4% kernel / faults: 159 minor 09-28 23:00:45.026: ERROR/ActivityManager(67): 0.4% 199/com.google.process.gapps: 0.2% user + 0.1% kernel / faults: 52 minor 09-28 23:00:45.026: ERROR/ActivityManager(67): 0.1% 67/system_server: 0% user + 0% kernel 09-28 23:00:45.026: ERROR/ActivityManager(67): 0% 40/adbd: 0% user + 0% kernel 09-28 23:00:45.026: ERROR/ActivityManager(67): 0% 131/com.android.systemui: 0% user + 0% kernel / faults: 1 minor 09-28 23:00:45.026: ERROR/ActivityManager(67): 100% TOTAL: 99% user + 0.7% kernel 09-28 23:00:45.026: ERROR/ActivityManager(67): CPU usage from 996ms to 1566ms later: 09-28 23:00:45.026: ERROR/ActivityManager(67): 91% 1049/com.android.uis: 91% user + 0% kernel / faults: 2 minor 09-28 23:00:45.026: ERROR/ActivityManager(67): 89% 1049/com.android.uis: 89% user + 0% kernel 09-28 23:00:45.026: ERROR/ActivityManager(67): 10% 67/system_server: 5.2% user + 5.2% kernel / faults: 6 minor 09-28 23:00:45.026: ERROR/ActivityManager(67): 8.7% 97/InputDispatcher: 3.5% user + 5.2% kernel 09-28 23:00:45.026: ERROR/ActivityManager(67): 1.7% 68/HeapWorker: 0% user + 1.7% kernel 09-28 23:00:45.026: ERROR/ActivityManager(67): 100% TOTAL: 94% user + 5.2% kernel MapActivity class package com.android.uis; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.List; import android.content.Context; import android.graphics.drawable.Drawable; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import com.android.geo.Road; import com.android.geo.RoadProvider; import com.android.maps.MyItemizedOverlay; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.OverlayItem; public class RoutingMapActivity extends MapActivity implements LocationListener { // Key : 0ObBrVVNjsIA__m7D1lmsednIXg6pcDRBG-Qvfg MapView mapView; List<Overlay> mapOverlays; Drawable drawable; Drawable drawable2; MyItemizedOverlay itemizedOverlay; MyItemizedOverlay itemizedOverlay2; LocationManager locationManager; private String provider; private Road mRoad; private Handler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map_layout); initMap(); //initMyLocation(); } private void initMap(){ mapView = (MapView) findViewById(R.id.google_maps); mapView.setBuiltInZoomControls(true); mapOverlays = mapView.getOverlays(); new Thread(){ @Override public void run(){ double fromLat = 49.85, fromLon= 24.016667, toLat = 50.45, toLon = 30.523333; String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon); InputStream is = getConnection(url); mRoad = RoadProvider.getRoute(is); mHandler.sendEmptyMessage(0); } }.start(); mHandler = new Handler(){ public void handleMessage(Message msg){ //drawable2 = getResources().getDrawable(R.drawable.marker2); drawable = getResources().getDrawable(R.drawable.marker); itemizedOverlay2 = new MyItemizedOverlay(drawable, mapView,mRoad); mapOverlays.clear(); for(int i=0; i<mRoad.mRoute.length;i++){ addPoint("","",new GeoPoint((int)(mRoad.mRoute[i][1]*1E6),(int)(mRoad.mRoute[i][0]*1E6)),itemizedOverlay2); } //addPoint("Point 2.","Point 2.",(int)(51.515259*1E6),(int)(-0.086623*1E6),itemizedOverlay2); mapOverlays.add(itemizedOverlay2); mapView.invalidate(); }; }; } private InputStream getConnection(String url){ InputStream is = null; try { URLConnection urlConn= new URL(url).openConnection(); is= urlConn.getInputStream(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return is; } private void addPoint(String name,String description,GeoPoint point, MyItemizedOverlay myItemizedOverlay){ OverlayItem overlayItem = new OverlayItem(point,name,description); myItemizedOverlay.addOverlay(overlayItem); } private void initMyLocation(){ locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE); Criteria criteria=new Criteria(); provider = locationManager.getBestProvider(criteria, false); Location location = locationManager.getLastKnownLocation(provider); } @Override protected boolean isRouteDisplayed() { return false; } @Override public void onLocationChanged(Location arg0) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String arg0) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String arg0) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { // TODO Auto-generated method stub } } Edit I have changed the code to the following .. but still have the same error private void initMap(){ new DrawRoad().execute(""); } private class DrawRoad extends AsyncTask<String, Void, Road> { protected Road doInBackground(String... unused) { mapOverlays = mapView.getOverlays(); double fromLat = 49.85, fromLon= 24.016667, toLat = 50.45, toLon = 30.523333; String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon); InputStream is = getConnection(url); mRoad = RoadProvider.getRoute(is); return mRoad; } protected void onPostExecute(Road road) { drawable = getResources().getDrawable(R.drawable.marker); itemizedOverlay2 = new MyItemizedOverlay(drawable, mapView,road); mapOverlays.clear(); for(int i=0; i<mRoad.mRoute.length;i++){ addPoint("","",new GeoPoint((int)(road.mRoute[i][1]*1E6),(int)(road.mRoute[i][0]*1E6)),itemizedOverlay2); } //addPoint("Point 2.","Point 2.",(int)(51.515259*1E6),(int)(-0.086623*1E6),itemizedOverlay2); mapOverlays.add(itemizedOverlay2); mapView.invalidate(); } } A: You could try using an async task which is simpler, something like: private class GetKMLTask extends AsyncTask<String, Integer, String> { protected String doInBackground(String... unused) { double fromLat = 49.85, fromLon= 24.016667, toLat = 50.45, toLon = 30.523333; String url = ""; InputStream is = getConnection(url); //.... get the road here return result; } protected void onPostExecute(String jsonResult) { try { drawable = getResources().getDrawable(R.drawable.marker); itemizedOverlay2 = new MyItemizedOverlay(drawable, mapView,mRoad); mapOverlays.clear(); for(int i=0; i<mRoad.mRoute.length;i++){ addPoint("","",new GeoPoint((int)(mRoad.mRoute[i][1]*1E6),(int)(mRoad.mRoute[i][0]*1E6)),itemizedOverlay2); } //addPoint("Point 2.","Point 2.",(int)(51.515259*1E6),(int)(-0.086623*1E6),itemizedOverlay2); mapOverlays.add(itemizedOverlay2); mapView.invalidate(); } catch (Exception e) { onFail(""); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Only add child to current frame Is it possible to add a child to the current frame only? I know you can just remove/hide them, and generate/show them again. But isn't there an easier way? A: Old school way: If you have a timeline you can add a MovieClip as a holder only on that frame. The holder clip only exists on that frame. Once you reach that frame you add the real clip to the holder display list using code: holder.addChild(new special_clip()) That way it will be removed when you change to another frame. It will however need to be re-created the next time you get to the frame. A: package { import flash.display.MovieClip; public class MyChild extends MovieClip { // Values private var _containingFrame:int = 1; /** * ... * @param e Event.ENTER_FRAME */ private function _check(e:Event):void { if(parent) { if(parent.currentFrame != containingFrame) { removeEventListener(Event.ENTER_FRAME, _check); parent.removeChild(this); } } } /** * Getters & Setters */ public function get containingFrame():int{ return _containingFrame; } public function set containingFrame(n:int):void { _containingFrame = n; addEventListener(Event.ENTER_FRAME, _check); } } } Just make this the base class of your children. Now when you add children (either via ActionScript or dragging onto the stage and assigning an instance name) you can just go: myChild.containingFrame = currentFrame; I'm not confident that there's a simpler way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: toggleClass not working I have a series of links that change content of a span element. I'm trying to toggle the classes on them so that users know which section of a profile they are on. It does not seem to be changing the class though. <div class="profilemenu" style="background: #e2ecfd; width: 100%"> <a style="color: #0b439f;" class="profilemenubutton" id="profile" href="#">Profile</a>&nbsp;&nbsp; <a class="profilemenubutton" id="clanactivity" href="#">Clan Activity</a>&nbsp;&nbsp; <a class="profilemenubutton" id="recentsessions" href="#">Recent Sessions</a>&nbsp;&nbsp; <a class="profilemenubutton" id="progress" href="#">Progress</a> </div> Jquery script. $(\'a#profile\').click (function () { $.ajax({ type: "GET", url: "includes/profile.php?username='.$username.'", success: function(msg) { $(\'span#info\').html(msg); $(\'.active\').toggleClass("profilemenubutton"); $(this).toggleClass("active"); } }); }); A: A collective of the information above. echo "$('#profile').click (function () { $.ajax({ type: 'GET', url: 'includes/profile.php?username=".$username."', success: function(msg) { $('#info').html(msg); $('.active').toggleClass'profilemenubutton'); $(this).toggleClass('active'); } }); });";
{ "language": "en", "url": "https://stackoverflow.com/questions/7590721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }