text
stringlengths
8
267k
meta
dict
Q: How to get applications associated with a application pool in IIS7 I have a virtual directory name. For this virtual directory i have to find out the application pool associated. Once i get the application pool i have to find out all the virtual directories on this application pool.. I am using this code to find out the application pool associated with virtual directory string AppPoolName = string.Empty; ServerManager manager = new ServerManager(); foreach (Site site in manager.Sites) { foreach (Application app in site.Applications) { string path = app.Path; path = path.Replace("/", " "); path = path.Trim(); if (path.ToLower() == VDName.ToLower()) { AppPoolName = app.ApplicationPoolName; break; } } } A: using (var serverManager = new ServerManager()) { var apps = (from site in serverManager.Sites from app in site.Applications where app.ApplicationPoolName.Equals("DefaultAppPool") select app); } A: I think we have to rerun the function for application pool to get the name for applications associated. ServerManager manager = new ServerManager(); foreach (Site site in manager.Sites) { foreach (Application app in site.Applications) { if (app.ApplicationPoolName.ToString() == AppPoolName) { string appname = app.Path; } } } A: Or a new line no looping approach: Environment.GetEnvironmentVariable("APP_POOL_ID", EnvironmentVariableTarget.Process);
{ "language": "en", "url": "https://stackoverflow.com/questions/7607175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Redirect xsl:message to log4j I am using SaxonJ to perform XSLT transformation from Java. My XSLT files have to output any debug/info as output since my transformation logic is complex. Is there a way in which I can redirect to log4j so that I can store have the transformation information in a log file? My system already uses log4j to log output to file. I want to append the transformation debug messages as well. Any ideas? A: I am pretty sure that you have already found out how to perform this. But I hope that my answer will be useful for other people. All you need to do is implementing MessageListener interface: http://www.saxonica.com/documentation/javadoc/net/sf/saxon/s9api/MessageListener.html public class MessageListenerImpl implements MessageListener { private static Logger logger = Logger.getLogger(MessageListenerImpl.class); public void message(XdmNode content, boolean terminate, SourceLocator locator) { if (terminate) { logger.error(content.getStringValue()); System.exit(1); } else { logger.warn(content.getStringValue()); } } } A: You can configure your own Message emitter. There are various interfaces to do this, see for example http://www.saxonica.com/documentation/javadoc/net/sf/saxon/lib/FeatureKeys.html#MESSAGE_EMITTER_CLASS or there's a simpler interface in the s9api XsltTransformer class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Building LLVM on Linux Well not that anyones probably going to see this but I A) figured out that LLVM wasn't what I needed it was LLVM-gcc which you can get from sauriks repo. B) realized that the toolchain I torrented already worked minus a la libstdc++ not in /usr/local/lib/gcc/arm-apple-darwin/4.0.1/ so to get libstdc++ I believe I got it from either the filesystem that comes with the torrent or my actual Ipod via SFTP. I can Proudly say that C++ can be compiled on IOS(although it was a pain in the ass :D). not sure if linking torrents is alright on SO but for anyone that wants a link email me or pm me if you can do that on SO(i'm not sure?) the only thing I haven't tested yet is objc which I can't find any non xcode tutorials. this is what stumped me last time was finding tutorials that didn't rely on templates so heavy. I was never one for templates :D Why keep downvoting it only hurts other users who are looking for the same answers i was? A: it look alot like the usual subjects cstdio, cstdlib, cstring are not included. I would start by trying including them :-) A: which svn revision of LLVM are you building ? from the page you linked: Currently, due to Issue 70, we are limited to revision 42498. A: Read the my original Post I got it working just ported my previous PC(ie linux,win,mac) only patcher(game save) to ios :D finally :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7607178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Magento: easy way to remove "paypal/express/review" step When ordering using paypal in magento, it takes you to paypal, paypal already displays a confirmation, you confirm, you get redirected to another confirmation page (/paypal/express/review), it is an extra step that is unnecessary for user experience, I would like to remove it and make the order automatically placed when user confirm on paypal page, once leave paypal if order successful the customer should see the success page. is there any easy solution to this I might have overlooked or at least if you can point me to the right direction to remove that step. A: don't use paypal express and use paypal standard if you don't need this feature. paypal express is a checkout method and not a payment method edit: this is now configurable in 1.9, still retarded but doable. A: So the right deal there, that works perfectly (for me ) is a sum up from the above : 1. Go to: \app\code\core\Mage\Paypal\Controller\Express\Abstract.php and search in returnAction() for: $this->_redirect('*/*/review'); There you have to change: $this->_redirect('*/*/review'); to: $this->_redirect('*/*/placeOrder'); 2. Go to: \app\code\core\Mage\Paypal\Model\Config.php and change the: public function getExpressCheckoutStartUrl($token) { return $this->getPaypalUrl(array( 'cmd' => '_express-checkout', 'token' => $token, )); } to: public function getExpressCheckoutStartUrl($token) { return $this->getPaypalUrl(array( 'cmd' => '_express-checkout', 'useraction' => 'commit', 'token' => $token, )); } With the 2 changes above, i figure out how to Skip Review Page in Magento Paypal Express Checkout. A: Andrew Angel's answer really doesn't avoid the comfirmation page, it just changes button value to "Pay" rather to "Confirm", or something like that. Anyway the correct way to do that is going to \app\code\core\Mage\Paypal\Model\Config.php, to getExpressCheckoutEditUrl($token) method and change 'useraction' => 'continue', to 'useraction' => 'commit’. To aviod confirmation user page in Paypal Express you only need to change one line in on controller action. Go to Mage/Paypal/Controller/Express/Abstract.php and search for $this->_redirect('*/*/review'); in returnAction(). There you have to change $this->_redirect('\*/\*/review'); to $this->_redirect('\*/\*/placeOrder'); That way when paypal returns to return action you avoid to show entire review page and payment was automatically confirmed. So, Paypal redirects again to success pages the same way like PayPal Standard method. A: @Toni The redirect url part works excellent, thanks! However changing the 'continue' to 'commit' did not change the buttons on PayPal's website. However, I was able to fix it by doing the following: Right above the getExpressCheckoutEditUrl function where Toni instructed to change the continue to commit, there is the funciton getExpressCheckoutStartUrl. If you add the useraction variable there, it will work. Original function: public function getExpressCheckoutStartUrl($token) { 'return $this->getPaypalUrl(array( 'cmd' => '_express-checkout', 'token' => $token, )); } New function: public function getExpressCheckoutStartUrl($token) { 'return $this->getPaypalUrl(array( 'cmd' => '_express-checkout', 'useraction' => 'commit', 'token' => $token, )); } Notice the 'useraction' => 'commit', was added at the new function. This should work! A: THere was one step missing let me summarize the entire process again. 1. Go to: \app\code\core\Mage\Paypal\Controller\Express\Abstract.php and search in returnAction() for: $this->_redirect('*/*/review'); There you have to change: $this->_redirect('*/*/review'); to: $this->_redirect('*/*/placeOrder'); 2. Go to: \app\code\core\Mage\Paypal\Model\Config.php and change the: public function getExpressCheckoutStartUrl($token) { return $this->getPaypalUrl(array( 'cmd' => '_express-checkout', 'token' => $token, )); } to: public function getExpressCheckoutStartUrl($token) { return $this->getPaypalUrl(array( 'cmd' => '_express-checkout', 'useraction' => 'commit', 'token' => $token, )); } 3. With the above two changes you will still be taken to the review page and have to agree to the terms and conditions, to avoid this go to: /app/code/core/Mage/Paypal/Controller/Express/Abstract.php Search for : public function placeOrderAction() { try { $requiredAgreements = Mage::helper(‘checkout’)->getRequiredAgreementIds(); if ($requiredAgreements) { $postedAgreements = array_keys($this->getRequest()->getPost(‘agreement’, array())); if (array_diff($requiredAgreements, $postedAgreements)) { Mage::throwException(Mage::helper(‘paypal’)->__(‘Please agree to all the terms and conditions before placing the order.’)); } } Comment out the following lines with a simple // at the beginning : //if (array_diff($requiredAgreements, $postedAgreements)) { // Mage::throwException(Mage::helper(‘paypal’)->__(‘Please agree to all the terms and conditions before placing the order.’)); // } The only time you will every be take to the review page is if the customers paypal returns a declined error. A: Magento 1.9 has built-in support for this, the Skip Order Review Step option, but it has a subtle caveat. The feature doesn't work with the 'Shortcut' buttons you can display on the product detail and cart pages. My suggestion, disable the shortcut buttons and enable the Skip Order Review Step option. For extra credit you can rearrange the Onepage Checkout flow so that customers won't have to enter billing information twice (once on Magento and again on PayPal). More details available in this blog post. A: Actually, Express Checkout can handle this no problem, and I would personally recommend sticking with it. After the SetExpressCheckout request you redirect the user over to PayPal. You can append useraction=commit to this URL in order to trigger the confirmation from PayPal pages. This causes the "Continue" button on PayPal to switch to a "Pay" button and informs the user that this is their final confirmation...clicking Pay will submit the payment. You still have to call DoExpressCheckoutPayment on your server to complete the process, but GetExpressCheckoutDetails is optional at this point. When using useraction=commit you'll get the PayerID back as a URL parameter in your ReturnURL so you don't have to call GECD if you don't want/need to. You can take this all a setup farther and use the callback API (also known as instant update API) to feed shipping and sales tax information to the PayPal review page. This allows you to populate the drop down values on PayPal's review page with your own shipping data based on the user's shipping address selected on the PayPal review page. The introduction of those features was to do exactly what you specified...eliminate the additional review process. All of that said, if the Magento module for Express Checkout doesn't provide options for all of this you'll need to extend it and build them in yourself. I'm pretty it does, though. A: Actually all the solutions mentioned here required to edit the Magento core. This is known as bad practise and does not keep your shop updateable. What you need to do for a clean solution: * *Create a module (in my exampe: Avoe_Paypal) to include the changes *Rewrite Paypal Config *Redirect on paypal express review step which is http://yourdomain.com/paypal/express/review/ 1) Create your module Avoe/Paypal/etc/config.xml <?xml version="1.0" encoding="UTF-8"?> <config> <modules> <Avoe_Paypal> <version>0.1.0</version> </Avoe_Paypal> </modules> <global> <models> <Avoe_Paypal> <class>Avoe_Paypal_Model</class> </Avoe_Paypal> <paypal> <rewrite> <config>Avoe_Paypal_Model_Config</config> </rewrite> </paypal> </models> <events> <controller_action_predispatch_paypal_express_review> <observers> <avoe_paypal_predispatch> <type>singleton</type> <class>Avoe_Paypal_Model_Observer</class> <method>paypalExpressReturnPredispatch</method> </avoe_paypal_predispatch> </observers> </controller_action_predispatch_paypal_express_review> </events> </global> </config> app/etc/Avoe_Paypal.xml <?xml version="1.0" encoding="UTF-8"?> <config> <modules> <Avoe_Paypal> <active>true</active> <codePool>local</codePool> <depends> <Mage_Paypal /> </depends> </Avoe_Paypal> </modules> </config> 2) Rewrite config, add useraction 'commit': <?php class Avoe_Paypal_Model_Config extends Mage_Paypal_Model_Config { /** * Get url for dispatching customer to express checkout start * Added useraction 'commit' to remove PayPal Express Checkout review page * * @param string $token * @return string */ public function getExpressCheckoutStartUrl($token) { return $this->getPaypalUrl(array( 'cmd' => '_express-checkout', 'useraction' => 'commit', 'token' => $token, )); } } 3) Create observer to redirect: <?php class Avoe_Paypal_Model_Observer { function paypalExpressReturnPredispatch($observer) { Mage::app()->getResponse()->setRedirect(Mage::getUrl('*/*/placeOrder')); } } There is also a small Magento extension which was just released yesterday, to remove the review step: https://github.com/tim-bezhashvyly/Sandfox_RemovePaypalExpressReviewStep
{ "language": "en", "url": "https://stackoverflow.com/questions/7607180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Imitating ViewState into WinForm's If it's possible it would be a great thing. So is there a way how to achieve somehow a ViewState behavior into a WinForm's Application. Like if i have a Bunch of TextBoxes ,than uses types text into them ,TextBoxes should store Their Text ,Location ,Size etc. and on Next Application Startup they should Load their Content Text ,Location ,Size etc. Further...every Control into every Form ,should store Their State somehow ,and on Load ,they should Load their Content and Other Properties like they where last time Application was running. PS : If there is not any Library or already made Solution ,than please don't try to spend time writing Code ,because it's not Fear to ask you guy's for Code ,i need just Direction's and Ideas because i plan to achieve it by my-self.Down-Voter's please consider that!!! A: Using my google-fu I found this on code project. The guy's written some code that effectively serializes a form out to XML so you can load it back in again. Don't know if it would cope with forms with dynamic controls that perhaps aren't on the form when you load it back in again - but I'm sure you can tweak the code to do what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Servlet/ How to write the logs(log.debug and log.error entries) written in the server console to a separate txt file? This is my first java servlet so I would be glad if you can help me and tell me what to do in details :) I can see my program's logs in server console but I need to copy all logs including log.debug and log.error entries to a txt file and later send the txt file via email. I have to define the directory/file for the logs. I have managed this for a regular java program by adding log4j.xml under src folder so I could set the directory in it, it worked, it is writing logs to a txt file created. But I do not know how to do it for the servlet version of my program. How can I set the directory for logs in the servlet and write logs to a specific txt file? A: Use log4j and have a FileAppender configured A: You could use log4j too with servlets. You just have to add your log4j.xml in the folder YOURWEBAPP/WEB-INF/classes
{ "language": "en", "url": "https://stackoverflow.com/questions/7607185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: nHibernate big queries timeout We are developing a new system for a customer and we have a member table with about 23600 members. And when we are trying to get them all it times out. I have used sql profiler to get the question and run it separatly and it took about 3 secs. using (ISession s = SessionFactory.OpenSession()) { return CreateCriteria(typeof(Member)).List<Member>(); } It looks like the problem is that the mapping of the result of 23600 objects takes too long. When limiting the results to for an example 300 (.SetMaxResults(300)) it works fine. I dont know right now if we ever would need to actually get all members in the final system, but i know when the time comes we would like to get most members to generate the their accounts in the membership provider of our site. Member mapping (fluent nHibernate): Id(x => x.ID).Default("NEWID()"); Map(x => x.LegacyID).ReadOnly(); Map(x => x.Username).Length(32); Map(x => x.Password).Length(32); Map(x => x.MemberID).Length(10); Map(x => x.FirstName).Length(50); Map(x => x.LastName).Length(50); Map(x => x.Gender).CustomType<int>(); Map(x => x.BirthDate); Component(c => c.Home); Map(x => x.Email).Length(80); Map(x => x.SendInformation).CustomType<int>(); Map(x => x.SendInvoice).CustomType<int>(); Map(x => x.Comment); Map(x => x.PublicProfile); Map(x => x.EntryDate); Map(x => x.ResignationDate); References<ProfileItem>(x => x.MemberStatus, "StatusID"); References<ProfileItem>(x => x.MemberType, "TypeID"); References<ProfileItem>(x => x.NationalAssociation); References<ProfileItem>(x => x.Position, "PositionID"); References<ProfileItem>(x => x.SpecialSkills, "SpecialSkillsID"); References<ProfileItem>(x => x.CompanyType, "CompanyTypeID"); References<ProfileItem>(x => x.JobType, "JobTypeID"); References<ProfileItem>(x => x.GraduateCity, "GraduateCityID"); HasManyToMany<ProfileItem>(x => x.Interessts).Table("MemberInterests") .ParentKeyColumn("UserID").ChildKeyColumn("ProfileItemID").Cascade.AllDeleteOrphan().Not.LazyLoad(); HasManyToMany<ProfileItem>(x => x.Properties).Table("MemberProperties") .ParentKeyColumn("UserID").ChildKeyColumn("ProfileItemID").Cascade.AllDeleteOrphan().Not.LazyLoad(); Component(c => c.Company).ColumnPrefix("Work"); Component(c => c.Invoice).ColumnPrefix("Invoice"); Map(x => x.Created); Map(x => x.CreatedBy).Length(32); Map(x => x.LatestChange); Map(x => x.LatestChangeBy).Length(32); Map(x => x.ElementarySchool); Map(x => x.University); Map(x => x.GraduateYear); Map(x => x.Title).Length(50); Map(x => x.LibraryAccess); Anyone know anything about this problem or how to fix it ? A: Fetching so big dataset is not a good idea. Think about memory consumption. If you need process this data, consider processing in batches (up to 1000 items). If you need present data to user, consider paging. If cannot reduce fetched dataset, you can increase timeout, but it is not recommended practice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does my Google App Engine Mail API calls still result in a DeadlineExceededError despite putting them in a task queue? I have a Python function that adds a task queue for each email address in my mailing list (thousands each time I mail them). The problem is that, even though each mail was to be sent via execution in a task queue, I still get this dreaded error: DeadlineExceededError: The API call mail.Send() took too long to respond and was cancelled. Any solutions? A: The deadline happens during communication between your GAE instance and the RPC server that handles the mail.Send call. This, in turn, might indicate internal problems of GAE or (more likely) failure to communicate with SMTP server in timely manner. The latter is conceptually very similar to deadline on URLFetch call. It is possible, however, to set a custom deadline for URLFetch which largely alleviates that problem. Unfortunately, there is no documented analogy for Mail API. There is workaround, though, that involves providing your own make_sync_call method - which allow for more lenient deadline - as parameter of EmailMessage.send(). To produce such a method, you need to delve into the internals of Python's interface used to make GAE RPC calls. The solution I find working looks as follows: from google.appengine.api import apiproxy_stub_map from google.appengine.api.apiproxy_stub_map import APIProxyStubMap class TimeoutAPIStub( object ): def __init__( self, service, deadline = 25 ): self.service = service self.deadline = deadline def CreateRPC( self ): rpc = apiproxy_stub_map.CreateRPC( self.service ) rpc.deadline = self.deadline return rpc def create_MakeSyncCall( service, deadline = 25 ): apsm = APIProxyStubMap() apsm.RegisterStub( service, TimeoutAPIStub( service, deadline ) ) return apsm.MakeSyncCall You can then use it to supply your custom deadline which will be honored by the resulting make_sync_call method: msg = EmailMessage() # ... prepare your email ... msg.send(make_sync_call = create_MakeSyncCall('mail', deadline = 300)) If you want to know more about what happens under the curtains of GAE RPC calls, I suggest reading Nick Johnson's blog post about it. This is good starting point if you'd ever want to go through the Python's GAE RPC bindings in order to solve similar issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: mysql insert into not work I want insert 4 datas into 4 fields and checked if 2 of them have not exists. (the data match `pid = '1' and sid '123') Here is my code, I checked several times, my mysql connect is well, my database is right, these four fields in my table. but I just can not insert. there has no warning return page. require ("connect.php");// this one I always test on my localhost, no proble, even require on other page, all works well mysql_select_db("test",$database_link); mysql_query("SET NAMES utf8"); mysql_query("INSERT INTO user_data (uid, pid, sid, wid) SELECT '123456', '1', '123', '2' FROM dual WHERE not exists (SELECT pid,sid FROM user_data WHERE user_data.pid = '1' AND user_data.sid = '123')"); for see clearlly: INSERT INTO user_data (uid, pid, sid, wid) SELECT '123456', '1', '123', '2' FROM dual WHERE NOT EXISTS ( SELECT pid, sid FROM user_data WHERE user_data.pid = '1' AND user_data.sid = '123' ) Error message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'pid, sid, wid) SELECT '123456', '1', '123', '2' FROM dual WHERE not exists (SE' at line 1 A: Query works fine on MySQL 5.1.54. From docs: The target table of the INSERT statement may appear in the FROM clause of the SELECT part of the query. (This was not possible in some older versions of MySQL.) However, you cannot insert into a table and select from the same table in a subquery. When selecting from and inserting into a table at the same time, MySQL creates a temporary table to hold the rows from the SELECT and then inserts those rows into the target table. However, it remains true that you cannot use INSERT INTO t ... SELECT ... FROM t when t is a TEMPORARY table, because TEMPORARY tables cannot be referred to twice in the same statement (see Section C.5.7.2, “TEMPORARY Table Problems”). Could this be the reason? A: It could be a duplicate name problem on the tables, try to use alias : INSERT INTO user_data (uid, pid, sid, wid) SELECT '123456', '1', '123', '2' FROM dual WHERE NOT EXISTS ( SELECT NULL -- don't need to select fields in a NOT EXISTS clause FROM user_data u2 WHERE u2.pid = '1' AND u2.sid = '123' )
{ "language": "en", "url": "https://stackoverflow.com/questions/7607190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF InstanceContextMode and serviceThrottling In WCF, if I specify the InstanceContextMode to be 'Single' and configure the serviceThrottling in config to be like, <serviceThrottling maxConcurrentCalls="100" maxConcurrentInstances="100" maxConcurrentSessions="100" /> Will these two settings conflict..? Thanks A: No maxConcurrentInstances and maxConcurrentSessions will be ignored since they are not applicable in your case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get the value at runtime Can anybody tell me how i can do this? declare @test varchar(20) set @test ='DatabaseName' select b.* from @test.dbo.Table_Name Here i am taking database from variable and using it in query. Shall do this? A: Make use of Exec command or Sp_executesql because you are building dynamic query. sp_executesql (Transact-SQL) A: declare @test varchar(20) set @test ='DatabaseName' declare @SQL nvarchar(max) set @SQL = 'select b.* from '+quotename(@test)+'.dbo.Table_Name as b' exec (@SQL)
{ "language": "en", "url": "https://stackoverflow.com/questions/7607195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I create a basic submission form in rails and write to a database? I'm trying to build a micro-app where a user pastes a link, clicks submit, the link is added to the database and is also shown (called from the database) in a list below the submission form. I've created a Rails app and in the index.html.erb file I have this: <%= form_tag("/search", :method => "get") do %> <%= label_tag(:q, "Please Paste your Link here") %> <br /> <br /> <%= text_field_tag(:q) %> <%= submit_tag("Submit") %> <% end %> That code has been repurposed from a tutorial site so the /search destination in the first line doesn't point to anywhere real in my app. I'm trying to simply get this submission to go into my database that I created running bundle exec rake db:create Not sure what to do next to get the link I paste to enter be logged in the database. A: There's a little bit of a learning curve that you'll need to achieve before you can complete what you're trying to do. Your application will require a controller, model and some routes at least in order to get that form working correctly. I'd suggest taking a look at some introduction videos that should be able to cover most/all of what you require. There are some videos available here for free: http://rubyonrails.org/screencasts Rails for zombies is also a great way to learn rails interactively http://railsforzombies.org/ If you're not a video person then there are plenty of books available which cover all the info you need. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Can't merge models with two different entities I try to modify my model file, but when I build and run it, the console outputs the error as mentioned in the title, "Can't merge models with two different entities", I try to delete the original model file and create a new one, the error is still there. I have checked this post, but the question is I cannot find the .momd directory or previous versions of the model file in the main bundle, any idea? A: I've received the same message after changing an entity. This worked for me: * *Opened the resources folder in a shell (something like /Users/[name]/Library/Application Support/iPhone Simulator/[number]/Applications/[alphanumerical]/[appname].app/). *Moved all directories with the .momd suffix to another folder outside of the project. *Opened the Documents folder and deleted the stored data (I named it "store.data", it is set when you create a persistent store). WARNING: This means you will loose all db entries of course! Without issue 3 the application may not be able to open the database because something in the db model has changed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add the unit testing functionality in existing ASP.NET MVC project? How to add the unit testing functionality (in Visual Studio 2010 Ultimate Edition) for an already existing ASP.NET MVC project? I have added Test Project to achieve TDD but it looks entirely different. Thanks in advance. A: I think the easiest way is to create empty project with unit test project and then add existing project to the current solution. Fix namespaces, type names (if needed) and that's it. But you need to understand that you will have only couple sample tests and you will need to write your own to cover all code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OCT 1st deadline and fbs_xxx cookie I have a lil confusion regarding the changes for OCT 1st deadline. I am using FB Connect on my site and obtaining the accesstoken from the cookie $_COOKIE['fbs_xxxxx']. Do I need to change this? because according to my understanding signed_request is only available to canvas apps. A: You have to migrate to oauth 2.0, this means use oauth:true in javascript SDK: https://developers.facebook.com/blog/post/525/ which is responsible for the cookie, new cookie name will be fbsr_APP_ID instead of fbs_APP_ID. You have to support it on a website as well as on canvas apps. In addition canvas apps have to support SSL, websites don't have to. hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7607223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How Do you reset a bit value in a string? In the recent interview I got a question like this : Given a string value, find out its 127th bit and reset it, do this in C language Reset means if that particular bit is 0 change to 1 and vice versa I didn't find out any algorithm for this, but I want to know about how one could solve this in C language. Edit: After getting the answer from few, I tried this : #include<stdio.h> void main() { char *str="anto"; str[15] ^= 0x80; printf("%s",str); } I get the output as : anto. Now I got strike in my head that changing a bit doesn't change the output? A: Assuming char is 8 bits and the endian is little-endian: char *str = ...; str[15] ^= 0x80; This will flip the 127th bit. EDIT: If the bit-endian is big-endian, then use 0x01 instead. The answer also depends on how the bits are numbered. If we start numbering from 0, the use 0x80. If we index from 1, then we use 0x40. (0x01 and 0x02 for big-endian) EDIT 2 : Here's the general case: (with the same assumptions) char *str = ...; int bit = 127; int index = bit / 8; // Get the index int chbit = bit % 8; // Get which bit in the char int mask = 1 << chbit; // Build the mask str[index] ^= mask; // XOR to flip the bit. A: To toggle any bit in a string: #include <limits.h> void flip_bit(char *x, int bit_no) { (x + bit_no/CHAR_BIT) ^= 1 << bit_no%CHAR_BIT; } Explanation: Finding the bit_no:th bit is done in two steps: First as many whole bytes as required (integer division): (x + bit_no/CHAR_BIT) Then as many bits that are left over. This is done by shifting a 1 by bit_no%CHAR_BIT bits (the remainder). Finally toggle the bit using the xor operator (^). A: 1st is you are asking is says as toggle not reset okey To toggle a bit The XOR operator (^) can be used to toggle a bit. number ^= 1 << x; That will toggle bit x. for more info of such think read this Now as you know string is number of character & size of 1 charachter is 1 byte so now which ever bit you want to toggle that put instead of X in and string in place of number. A: You have to create a bitmask, for the n-th bit, the bitmask will be: char *bitmask = 2^(n-1); and to flip the bit xor the string and the bitmask: string ^= bitmask;
{ "language": "en", "url": "https://stackoverflow.com/questions/7607224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to configure django environment for pycharm on windows? I am new to django development (I was working with MS and Oracle/Java stack). I now how important it is to prepare your dev environment right. I have web server with some small django project I am going to expand, pycharm IDE (checked possibilities and chosen this one) on windows. Project is not in any version control but I am going to put it into git later. My question is - how to configure environment and import my project into it? Is it possible to put my devproject into virtual machine and edit it in pycharm from windows (tried but didnt know how to do it) or do I have to install django on windows? I am a little reluctant to install all this staff on my workstation but it may be necessary. Is it possible to install django modules only for this project and not pollute my global python environment? This may be obvious for regular django devs but I am little lost. A: Since I wrote this answer, PyCharm has greatly expanded their support for virtual environments; and now you can create virtual environments when starting projects. For more information, see PyCharm online documentation. I use PyCharm on Windows at work, and this process works for me (since PyCharm doesn't support virtual env in the project creation stage). You have to put the django libraries on your development machine for the code hinting and method signatures to work. To do this, you need to first install setuptools and then install pip in your system python. For New Projects * *First create your virtual environment, this will avoid polluting your base python install. D:\>virtualenv --no-site-packages myenv New python executable in myenv\Scripts\python.exe Installing setuptools................done. Installing pip...................done. *Next, switch into this env: D:\>myenv\Scripts\activate (myenv)D:\> *Install django into this environment: pip install django, and any other libs you might need for this project. *Run PyCharm and File > New Project *Give your project a name and select Django project from the Project type drop down *On the next screen, click the button to the right of the python interpreter, and browse to your virtual environment, and select the directory with the python.exe file. Now your project is setup to only use the virtualenv python. Once you are done developing, you can freeze your install and replicate it on your testing environment. Once you are done, you can simply delete the directory myenv to remove the project-specific libs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OpenGraph - Setting expiry? So, on facebook, the ticker shows recent stories from views to my site, now, what would i need to do to make the ticker display the fact that someone is 'viewing' a post. Anything i try just ends up saying 'viewed' a post. Is there a way to make it say 'is viewing' through opengraph? A: You should set the Start Time (in the past) and the End Time (in the future). Expires In can be used instead of End Time if you prefer that. While the user is still on your web page (viewing a post) you can regularly update the action to keep it from expiring. If you for example assume that it takes at least 2 minutes for a user to read a post, you can do this: When the user first opens the web page: * *Create the action with start_time=now and expires_in=120 *Save the action ID for future updates Every minute the user is still on the web page: * *Update the action with expires_in=120
{ "language": "en", "url": "https://stackoverflow.com/questions/7607227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: C# MVC - Get UserId from Session array I need to get the current logged in user identity through the Session array declared as below: if (user != null) { string[] UserProfile = new string[4]; UserProfile[0] = Convert.ToString(user.UserID); UserProfile[1] = user.FirstName; UserProfile[2] = user.LastName; UserProfile[3] = Convert.ToString(user.UserType); Session["UserProfile"] = UserProfile; I cant get the syntax to retrieve UserId from the Session in another controller. Appreciate any help... thanks... A: string[] userProfile = Session["UserProfile"] as string[]; string id = userProfile[0];
{ "language": "en", "url": "https://stackoverflow.com/questions/7607232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swipe Pages in Android I have a question that I want to Swipe Screens with touch in Horizontal Manner with Many Pages. Means the background of all these pages are same but Pages over that are different. Same as the WallPaper Screen of any Android Phone which is horizontal Scrollable and Pages are different. How to implement this in our project? PLease suggest me for right result. A: What do you want is a ViewFlipper that android has it since day one. 1) the doc is right here: ViewFlipper Doc 2) Someone asked similar question before here:ViewFlipper Stackoverflow A: You should do a Gallery or an HorizontalListView (which is not a component from android framework). You can always set a background and the component deals with the swiping behaviour for you ! A: I think you need ViewPager. You can use it after install android compatible packages. you can get detail infomation from here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reflection of sky on car in Opengl es 2 in iphone/ ipad Started working on car racing game with Opengl-es 2.0 ... Wandering how to show reflection of sky, trees ,etc on a car while its moving ... i have seen many games doing so... please guide me where to start from ? Thanks A: This is called "environment mapping". See this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FQL requesting error String fqlurl="https://api.facebook.com/method/fql.query?query=SELECT name FROM user WHERE uid = me()"; Does anyone could tell me what's wrong with this url? I have illegalArgumentException error. A: You'll need to URLEncode the query. So, your query becomes : SELECT+name+FROM+user+WHERE+uid+%3D+me%28%29 from SELECT name FROM user WHERE uid = me()
{ "language": "en", "url": "https://stackoverflow.com/questions/7607241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Processing X509 certificate, java converts postalCode present in Subject line to its OID value When converting an uploaded security certificate to X509 format and later obtaining the subject line through following code. eg cert = (X509Certificate) cf.generateCertificate(inStream); String subject =cert.getSubjectX500Principal().toString().toUpperCase(); I find that the java X500Principal() converts postalCode to its OID value OID.2.5.4.17. Is there any way that the object name 'postalCode' can be retained or OID can be converted back to its user friendly format.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java regular expression optimization tips I am new to Java Regular expression. We are using a pattern for matching a string. We are using this for validating a text field and it meets our requirements. But there is a performance issue in the matching. Pattern : ([a-zA-Z0-9]+[ ]?(([_\-][a-zA-Z0-9 ])*)?[_\-]?)+ * *Input text should start with a-zA-Z0-9. *Space(single) is allowed between words *"_" and "-" are allowed but cannot be consecutive. Our problem is, for certain input strings the CPU time goes high and causes hanging the threads. Also we get exceptions. Can anyone please help me to optimize the Pattern or suggest a new pattern to solve my issue. Exception details ============================================ Hung thread details, all the same: [9/28/11 11:40:07:320 CDT] 00000003 ThreadMonitor W WSVR0605W: Thread "WebContainer : 26" (0000004f) has been active for 709755 mi lliseconds and may be hung. There is/are 1 thread(s) in total in the server that may be hung. at java.util.regex.Pattern$GroupCurly.match(Pattern.java:3938) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3801) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$BranchConn.match(Pattern.java:4090) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$GroupCurly.match0(Pattern.java:4006) at java.util.regex.Pattern$GroupCurly.match(Pattern.java:3928) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$BranchConn.match(Pattern.java:4090) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$GroupCurly.match0(Pattern.java:4006) at java.util.regex.Pattern$GroupCurly.match(Pattern.java:3928) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$BranchConn.match(Pattern.java:4090) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$GroupCurly.match0(Pattern.java:4006) at java.util.regex.Pattern$GroupCurly.match(Pattern.java:3928) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3801) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$BranchConn.match(Pattern.java:4090) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$GroupCurly.match0(Pattern.java:4006) at java.util.regex.Pattern$GroupCurly.match(Pattern.java:3928) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$BranchConn.match(Pattern.java:4090) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$GroupCurly.match0(Pattern.java:4006) at java.util.regex.Pattern$GroupCurly.match(Pattern.java:3928) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$BranchConn.match(Pattern.java:4090) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$GroupCurly.match0(Pattern.java:4006) at java.util.regex.Pattern$GroupCurly.match(Pattern.java:3928) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.match(Pattern.java:4307) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$BranchConn.match(Pattern.java:4090) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4239) at java.util.regex.Pattern$GroupCurly.match0(Pattern.java:4006) at java.util.regex.Pattern$GroupCurly.match(Pattern.java:3928) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Branch.match(Pattern.java:4124) at java.util.regex.Pattern$Ques.match(Pattern.java:3703) at java.util.regex.Pattern$Curly.match0(Pattern.java:3794) at java.util.regex.Pattern$Curly.match(Pattern.java:3756) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4180) at java.util.regex.Pattern$Loop.matchInit(Pattern.java:4323) at java.util.regex.Pattern$Prolog.match(Pattern.java:4263) at java.util.regex.Matcher.match(Matcher.java:1139) at java.util.regex.Matcher.matches(Matcher.java:514) A: Your regex allows for a phenomenon known as Catastrophic Backtracking. Follow the link for a complete description, but briefly you have a combination of optional matching that means the evaluation must keep going back through every combination of preceding characters, leading to n! operations (I pretty sure about n!), which will quickly blow your stack. Try this regex instead: ^(?!.*(__|--| ))[a-zA-Z0-9][\w -]*(?<! )$ Explanation: * *^(?!.*(__|--| )) means the entire input must not contain 2 adjacent _ or - or space (a better way of expressing "at most one space between words" - forget about words - check the spaces) *[a-zA-Z0-9][\w -]* means must have letter or number at start, the rest can be any combo of letters, numbers, underscores (\w = [a-zA-Z0-9_]), spaces and dashes (given the above two proviso) *[^ ]$ means doesn't end in a space (not stated, but seems reasonable - add other chars to the character class like - as you like - but dash if used must be first or last) This regex won't cause catastrophic backtracking. A: I think this will be a lot easier to understand if you start with a smaller problem. The simplest way to match several words separated by spaces is this: ^\w+(?:[ ]\w+)*$ To enforce the rule about no consecutive hyphens or underscores, all you have to do is add them to the existing character class: (?i)^[A-Z0-9]+(?:[ _-][A-Z0-9]+)*$ However, your regex explicitly allowed for them at the end of the string too, and mine doesn't. I'll assume that's okay and deal with it the same way you did: (?i)^[A-Z0-9]+(?:[ _-][A-Z0-9]+)*[_-]?$ Try that last regex and see if it works for you. EDIT: The anchors, ^ and $, aren't really necessary if you use the matches() method, but they don't hurt either, and they do help communicate your intent. A: digit pattern ^(([\\@|\\-|\\_]*([0-9]+))+)*(([\\@|\\-|\\_])+)*$ char pattern (([\\@|\\-|\\_]*([a-zA-Z]+))+)*(([\\@|\\-|\\_])+)*$ input field is compered with above two for below conditions * must have atleast one digit and char * can have only @,_,- as special chars not others A: I wanted to post this as a comment to Tim Pietzcker's answer but figured there won't be enough space there. While the regex given by Tim avoids catastrophic backtracking to some extent, it still has nested quantifiers which can cause a problem with a specific input text and cause StackOverflowException as shown below. I want to repeat that this answer is just a demonstration of the weird StackOverflowException and it is not supposed to be a rant on anyone's answer. public class CatastrophicBacktrackingRegexRemedy { public static void main(String[] args) { regexWithNoStackOverflow(); regexCausingStackOverflow(); } /** * Stackoverflow is caused on a specific input, * In this case "A " repeated about 1000 times. * This is because of the nested quantifier (?:[\\ ][\\w-]+)* */ private static void regexCausingStackOverflow() { StringBuilder subjectStringBuilder = new StringBuilder(); String subjectString = "A "; for (int i = 0; i < 1000; i++) { subjectStringBuilder.append(subjectString); } subjectStringBuilder.append("A"); //2001 character input System.out.println("Input length :" + subjectStringBuilder.length()); //This causes stackoverflow exception on a string with 2001 characters //on my JVM boolean foundMatch = subjectStringBuilder.toString().matches( "(?ix) # Case-insensitive, multiline regex:\n" + "^ # Start of string\n" + "(?! # Assert that it's impossible to match\n" + " .* # any number of characters\n" + " (?:--|__) # followed by -- or __\n" + ") # End of lookahead assertion\n" + "[A-Z0-9]+ # Match A-Z, a-z or 0-9\n" + "(?: # Match the following:\n" + " [\\ ] # a single space\n" + " [\\w-]+ # followed by one or more alnums or -\n" + ")* # any number of times\n" + "$ # End of string"); //This will not be printed because of exception in the matches method System.out.println("Is match found? " + foundMatch); } /** * Stackoverflow can be avoided by modifying the negative lookahead * and removing the nested quantifiers as show below. */ private static void regexWithNoStackOverflow(){ StringBuilder subjectStringBuilder = new StringBuilder(); String subjectString = "A "; for (int i = 0; i < 1000000; i++) { subjectStringBuilder.append(subjectString); } //returns match = true subjectStringBuilder.append("A"); //uncomment following and it will give match = false (space in the end) //subjectStringBuilder.append("A A "); //uncomment following and it will give match = false (multiple spaces) //subjectStringBuilder.append("A A"); //2000001 character input System.out.println("Input length :" + subjectStringBuilder.length()); boolean foundMatch = subjectStringBuilder.toString().matches( "(?ix) # Case-insensitive, multiline regex:\n" + "^ # Start of string\n" + "(?! # Assert that it's impossible to match\n" + " .* # any number of characters\n" + " (?:--|__|\\s{2,}|\\s+$) # followed by -- or __ or more than a " + " # single space or a space in the end\n" + ") # End of lookahead assertion\n" + "[A-Z0-9]+ # Match A-Z, a-z or 0-9\n" + "(?: # Match the following:\n" + " [\\s\\w-] # followed by a space or alnum or -\n" + ")* # any number of times\n" + "$ # End of string"); System.out.println("Is match found? " + foundMatch); } } A: Your problem is catastrophic backtracking which you're getting because you have nested quantifiers. This starts becoming a problem when the text doesn't match the requirements because of the exponentially increasing number of permutations the regex engine has to go through to declare failure. ([a-zA-Z0-9]+[ ]?(([_\-][a-zA-Z0-9 ])*)?[_\-]?)+ ^ ^ | repetition repetition Reconstruct your regex like this: (?i)^(?!.*(?:--|__))[A-Z0-9][\w-]*(?: [\w-]+)*$ Java, with explanation: boolean foundMatch = subjectString.matches( "(?ix) # Case-insensitive, multiline regex:\n" + "^ # Start of string\n" + "(?! # Assert that it's impossible to match\n" + " .* # any number of characters\n" + " (?:--|__) # followed by -- or __\n" + ") # End of lookahead assertion\n" + "[A-Z0-9] # Match A-Z, a-z or 0-9\n" + "[\\w-]* # Match 0 or more alnums/dash\n" + "(?: # Match the following:\n" + " [\\ ] # a single space\n" + " [\\w-]+ # followed by one or more alnums or -\n" + ")* # any number of times\n" + "$ # End of string"); Note that the string must not end in a space as per your requirements. In case you're wondering, \w is a shorthand for [A-Za-z0-9_]. A: You haven't posted any code but I can see that you run it in a web application. I guess optimization of the pattern won't help you much. Remember that the Matcher class is not thread safe. Instances of this class are not safe for use by multiple concurrent threads Try to compile your pattern in synchronized block and use reset() method of the Matcher class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Why is a class' size affected when it contains only a virtual function? class classWithNoVirtualFunction { public: int a; void x () { char c; c = 'a'; } }; class classWithOneVirtualFunction { public: int a; virtual void x () {} }; class classWithTwoVirtualFunctions { public: int a; virtual void x () {} virtual void y () {} }; int main() { cout << "\nclassWithNoVirtualFunction's size: " << sizeof (classWithNoVirtualFunction); cout << "\nclassWithOneVirtualFunction's size: " << sizeof (classWithOneVirtualFunction); cout << "\nclassWithTwoVirtualFunctions's size: " << sizeof (classWithTwoVirtualFunctions); cout << "\nvoid*'s size : " << sizeof (void*); } W.R.T the above code, Thinking in C++ says: This example required at least one data member. If there had been no data members, the C++ compiler would have forced the objects to be a nonzero size because each object must have a distinct address. If you imagine indexing into an array of zero-sized objects, you’ll understand. A “dummy” member is inserted into objects that would otherwise be zero-sized. My question: Now, I am not able to understand what && how EXACTLY happens if we have a class with zero members and a virtual function. Please explain with some programming examples. A: Whenever a class contains at least one virtual function, the compiler needs to add RunTime Type Information to each of the objects. The implementation will usually add a single pointer to each object that refers to a structure, defined by the compiler and hidden from users, with a pointer to the type_info object and the vtable used for dynamic dispatch of functions. In the case of a class with no non-static data members and at least one virtual function, the size of each object is the size of the per-object RTTI information (one pointer), and because that is non-zero, the compiler will not add extra space. What the quote is saying is that sizeof(T) != 0 for any and all types T, and a type with a dynamic function trivially fits that requirement. Only with types that would have zero size, the compiler is forced to make the object 1 char big. A: The C++ standard does not define the complete layout of a class. This is up to the compiler vendor. But the C++ standard does make some guarantees. For example, the size of a complete object is always greater than zero. The reason for this rule is hinted at by the text you quoted from Thinking in C++. Virtual functions of a simple class are usually implemented in terms of an additional hidden pointer member that identifies the object's dynamic type so that it's possible to invoke the correct function of the object's dynamic type. Since this additional hidden member adds to the size of the class, the compiler doesn't need to put any padding in there to make the class have a non-zero size. But these are mostly implementation details you should not worry about too much. As long as you only rely on the guarantees the C++ standard makes, you should be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check non-numeric characters in string I want to check whether the String contains only numeric characters or it contains alpha-numeric characters too. I have to implement this check in database transaction where about a hundred-thousand records are going to be fetched and passed through this check, so I need optimized performance answer. Currently, I have implemented this through a try-catch block: I parsed the string in Integer in try block and checked for the NumberFormatException in the catch block. Please suggest if I'm wrong. A: Just Googling, I found out this link public boolean containsOnlyNumbers(String str) { //It can't contain only numbers if it's null or empty... if (str == null || str.length() == 0) return false; for (int i = 0; i < str.length(); i++) { //If we find a non-digit character we return false. if (!Character.isDigit(str.charAt(i))) return false; } return true; } Edit: A RegExp to check numeric should be : return yourNumber.matches("-?\\d+(.\\d+)?"); A: You can check this with a regex. Suppose that (numeric values only): String a = "493284835"; a.matches("^[0-9]+$"); // returns true Suppose that (alphanumeric values only): String a = "dfdf4932fef84835fea"; a.matches("^([A-Za-z]|[0-9])+$"); // returns true As Pangea said in the comments area : If the performance are critical, it's preferrable to compile the regex. See below for an example : String a = "dfdf4932fef84835fea"; Pattern pattern = Pattern.compile("^([A-Za-z]|[0-9])+$"); Matcher matcher = pattern.matcher(a); if (matcher.find()) { // it's ok }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to upload document with metadata to SharePoint doc. library using Client Object Model? I'm developing VSTO Outlook Add-In, so I'm using SharePoint Client Object Model. Can I upload a document to SharePoint doc. library and add metadata with one action? Using Google I have found many samples where metadata is added after uploading. Also I found out that it is possible to add metadata using full API(File.Add() method and a hashtable). Help? A: You could use code like this: ClientContext context = new ClientContext("SITEURL"); Site site = context.Site; Web web = context.Web; context.Load(site); context.Load(web); context.ExecuteQuery(); List list = listCollection.GetByTitle("Reports"); context.Load(list); context.ExecuteQuery(); context.Load(list.RootFolder); context.Load(list.RootFolder.Folders); context.ExecuteQuery(); foreach (Folder folder in list.RootFolder.Folders) { if (folder.Name == "Folder-To-Upload") { FileCreationInformation fci = new FileCreationInformation(); byte[] array = System.IO.File.ReadAllBytes("SlmReportPeriods.xml"); // File which you want to upload fci.Content = array; fci.Overwrite = true; fci.Url = "Sample"; File file = folder.Files.Add(fci); ListItem item = file.ListItemAllFields; item["Field1"] = "Example1"; item["Field2"] = "ETC."; item.Update(); folder.Files.Add(fci); context.ExecuteQuery(); } } The essence of this sample is to use FileCreationInformation and File objects and get ListItemAllFields of item. A: Redzio's answer worked for me. Following code was derived from blog post Upload Large Files to SharePoint Online (by Piyush K Singh): public File UploadLargeFileWithMetadata(ClientContext ctx, List docs, string fileName) { int blockSize = 8000000; // 8 MB string uniqueFileName = String.Empty; long fileSize; Microsoft.SharePoint.Client.File uploadFile = null; Guid uploadId = Guid.NewGuid(); ctx.Load(docs.RootFolder, p = >p.ServerRelativeUrl); // Use large file upload approach ClientResult < long > bytesUploaded = null; FileStream fs = null; try { fs = System.IO.File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); fileSize = fs.Length; uniqueFileName = System.IO.Path.GetFileName(fs.Name); using(BinaryReader br = new BinaryReader(fs)) { byte[] buffer = new byte[blockSize]; byte[] lastBuffer = null; long fileoffset = 0; long totalBytesRead = 0; int bytesRead; bool first = true; bool last = false; // Read data from filesystem in blocks while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0) { totalBytesRead = totalBytesRead + bytesRead; // We've reached the end of the file if (totalBytesRead <= fileSize) { last = true; // Copy to a new buffer that has the correct size lastBuffer = new byte[bytesRead]; Array.Copy(buffer, 0, lastBuffer, 0, bytesRead); } if (first) { using(MemoryStream contentStream = new MemoryStream()) { // Add an empty file. FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.ContentStream = contentStream; fileInfo.Url = uniqueFileName; fileInfo.Overwrite = true; uploadFile = docs.RootFolder.Files.Add(fileInfo); // Start upload by uploading the first slice. using(MemoryStream s = new MemoryStream(buffer)) { // Call the start upload method on the first slice bytesUploaded = uploadFile.StartUpload(uploadId, s); ctx.ExecuteQuery(); // fileoffset is the pointer where the next slice will be added fileoffset = bytesUploaded.Value; } ListItem Subs = uploadFile.ListItemAllFields; Subs["Title"] = Convert.ToString(CompanyName.Value); Subs["Address"] = Convert.ToString(Address.Value); Subs["City"] = Convert.ToString(City.Value); Subs["State"] = Convert.ToString(State.Value); Subs["Zip"] = Convert.ToString(Zip.Value); Subs["Country"] = Convert.ToString(Country.Value); Subs["Website"] = Convert.ToString(WebSite.Value); Subs.Update(); // we can only start the upload once first = false; } } else { // Get a reference to our file uploadFile = ctx.Web.GetFileByServerRelativeUrl(docs.RootFolder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + uniqueFileName); if (last) { // Is this the last slice of data? using(MemoryStream s = new MemoryStream(lastBuffer)) { // End sliced upload by calling FinishUpload uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s); ctx.ExecuteQuery(); // return the file object for the uploaded file return uploadFile; } } else { using(MemoryStream s = new MemoryStream(buffer)) { // Continue sliced upload bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s); ctx.ExecuteQuery(); // update fileoffset for the next slice fileoffset = bytesUploaded.Value; } } } } } } catch(Exception ex) { this.Ex.Text = ex.ToString(); } finally { if (fs != null) { fs.Dispose(); } } return uploadFile; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: presentModalViewController fullscreenmode issue I'm trying to present this modalViewController in my app and it needs to be fullscreen. This is how I call up the ModalViewController. myViewController = [[MyViewController alloc] init]; //self.myViewController.SomeView = [[UIView alloc] init]; //self.myViewController.SomeView.frame = self.ThisView.frame; //self.myViewController.backButtonEnabled = NO; //self.myViewController.dismissDelegate = self; //[self.myViewController doLoadShizzle]; //do this to load view and stuffs as well //all commented to try to make the edit construction work UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.myViewController]; navController.modalPresentationStyle = UIModalPresentationFullScreen; [self presentModalViewController:navController animated:YES]; [self.myViewController release]; [navController release]; The navController.modalPresentationStyle works for everything besides the full screen mode. I've logged the self.view of the modalview in the ViewDidLoad and it has the right dimensions (including the adjustments to the statusbar) NSLog (modalviewcontroller.view) => < UIView: 0x7d173a0; frame = (20 0; 748 1024); autoresize = W+H; layer = > NSLog (modalviewcontroller.SomeView => < UIView: 0x7d154a0; frame = (0 0; 1024 660); layer = > Im doing something wrong here (obviously), but I can't seem to figure out what it is. I've been searching for stuff as workaround but none of the options have been the answer thus far. If anyone has a clue of what the issue is here, I would very much like to know. Thanks in advance. //---EDIT---// Ok, now I build this prototype and I confirmed that this code is working as I want it to. Yet I can't seem to implement the very same thing in my larger architecture. --------.h (mainVC) #import <UIKit/UIKit.h> #import "ModalFullScreenShizzle.h" @interface ModalViewControllerFullScreenTry2ViewController : UIViewController <ModalViewDelegate> { ModalFullScreenShizzle *fullscreenShizzle; } @property (nonatomic,retain) ModalFullScreenShizzle *fullscreenShizzle; -(void)gotoFullscreenModal; @end -----------.m (mainVC) @implementation ModalViewControllerFullScreenTry2ViewController @synthesize fullscreenShizzle; - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor yellowColor]; UIButton *fullscreenActivate = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 200, 200)]; fullscreenActivate.backgroundColor = [UIColor greenColor]; [fullscreenActivate addTarget:self action:@selector(gotoFullscreenModal) forControlEvents:UIControlEventTouchUpInside]; [fullscreenActivate setTitle:@"Full Screen ACTIVATE!!!!!!1111one" forState:UIControlStateNormal]; [self.view addSubview:fullscreenActivate]; } -(void)gotoFullscreenModal { self.fullscreenShizzle = [[ModalFullScreenShizzle alloc] init]; self.fullscreenShizzle.theScreen.frame = self.view.frame; // self.fullscreenShizzle.dismissDelegate = self; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.fullscreenShizzle]; navController.modalPresentationStyle = UIModalPresentationFullScreen; [self presentModalViewController:navController animated:YES]; // [self.fullscreenShizzle release]; // [navController release]; } -(void)didDismissModalView { [self dismissModalViewControllerAnimated:YES]; } -----------.h (modalVC) #import <UIKit/UIKit.h> @protocol ModalViewDelegate <NSObject> - (void)didDismissModalView; @end @interface ModalFullScreenShizzle : UIViewController { UIView *theScreen; id<ModalViewDelegate> dismissDelegate; } @property (nonatomic, retain) UIView *theScreen; @property (nonatomic, assign) id<ModalViewDelegate> dismissDelegate; @end --------------.m (modalVC) #import "ModalFullScreenShizzle.h" @implementation ModalFullScreenShizzle @synthesize theScreen; - (void)loadView { [super loadView]; self.view.frame = theScreen.frame; self.view.backgroundColor = [UIColor blueColor]; } //---EDIT 2---// I've done the code above this and tried to add it to main mainVC window. It works but it's not conforming to the autoresizing. Yet even if the autoresizing works properly this is (kinda) a dirty fix and not a proper solution that I'd like to use. Also it's not the the order of which windows show themselves. In the meantime I'm using one of the other (working) presentation styles. But I would still like to know the solution.. ..if anyone knows that is. A: Maybe the problem is : self.myViewController.SomeView = [[UIView alloc] init]; self.myViewController.SomeView.frame = self.ThisView.frame; Try to do this inside the viewDidLoad or loadView of the MyViewController. -- EDIT After look your edit code, I am still think that the problem is that you are setting the Frame when the view is not loaded yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: incorrect display lineWidth=1 at html5 canvas I have example: https://developer.mozilla.org/samples/canvas-tutorial/4_5_canvas_linewidth.html But first line is not equals 1 pixel: How can i fix this? (browser Google Chrome) A: To make life easier you can move the whole canvas by 0.5px: var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.translate(0.5, 0.5); // Move the canvas by 0.5px to fix blurring It prevents anti-aliasing on all graphics, except images, so you'll have to use +0.5px only for images. A: Always add 0.5 pixel to the position of your line to prevent the anti-aliasing. https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors#A_lineWidth_example
{ "language": "en", "url": "https://stackoverflow.com/questions/7607272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Xcode: Creating A Popup UIViewController I would like to create a UIVewController and have it popup similar to what is shown in this image: http://i.stack.imgur.com/WzMKk.png When the user taps outside the popup window, the window (view controller) goes away. Can someone please provide some example code as far as what goes in the .h files, and .m file, and any extra steps I may need to follow in the interface builder? A: Use UIPopoverController - http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIPopoverController_class/Reference/Reference.html#//apple_ref/occ/cl/UIPopoverController A: It's just a UIViewController presented modally with the popup's view controller modalPresentationStyle set to UIModalPresentationFormSheet. MyPopupViewController *popup = ... popup.modalPresentationStyle = UIModalPresentationFormSheet; [self presentModalViewController:popup animated:YES]; From the docs regarding UIModalPresentationFormSheet presentation style... The width and height of the presented view are smaller than those of the screen and the view is centered on the screen. If the device is in a landscape orientation and the keyboard is visible, the position of the view is adjusted upward so that the view remains visible. All uncovered areas are dimmed to prevent the user from interacting with them. You'll need to detect touches on the darkened area to allow the form to be dismissed that way. This answer has some details on implemented that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: 'out' keyword in C++ Is there an equivalent to the C# 'out' keyword for out parameters but in C++? I'd like to have a constructor also set a couple of references to variables where it is called. A: C#'s out means that initialization of some value is done within a function. C++ does not have an equivalent. Initialization of non-member variables is always done at the point of declaration, and for member variables it is done in the constructor, before the constructor body's opening brace. Luckily, modern C++ compilers exercise RVO (Return Value Optimization), so const correctness usually comes at no performance penalty: const Foo foo = create_a_foo(); A good compiler will emit something like the following p-code: BYTE foo_store [sizeof (Foo)]; create_a_foo (foo_store); const ALIAS Foo foo = foo_store; Where ALIAS would just be another (typed) name for foo_store, without any runtime cost. The memory allocation for foo_store is usually free, too, as it is basically nothing else like a stack frame increment. Even if you pass a reference to a pointer, void create_a_foo (Foo* &) {...} then it is not an equivalent. It is still against const-correct code, and you really are assigning to a pointer, which is not the same as initializing a Foo. Foo *p; // initialization of pointer is HERE, and nowhere else create_a_foo(p); // creates a Foo and _assigns_ it to po. References-to-pointer are at best a hack if you intend an exact C# out clone, as if e.g. reference-to-boost::optional. A: You don't need the out keyword. You use pointers. int x = 47; f(&x); //x is 5 void f(int* p) { *p = 5; } See what I did there? You pass the reference of x to the function so the function actually writes a new value to x. A: No direct equivalent. In C++ you choose between passing by value, passing a pointer value, or passing a reference parameter. The latter two can be used to get data back from function. VOID foo(int* pnA, int& nB) { *pnA = 1; nB = 2; } int nA, nB; foo(&nA, nB); // nA == 1, nB == 2;
{ "language": "en", "url": "https://stackoverflow.com/questions/7607276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Not able to run doxygen script through my xcode? I have installed doxygen.dmg. I have used this link for reference: duckrowing I have followed each and every step from that. Now I am able to create html docset using that doxygen tool. But for the next steps, while generating a documentation using XCode itself using some script phase. I have tried that also but it throws me error while building that application. Here is the error: .build/Debug-iphonesimulator/.build/loadDocSet.scpt:23:157: execution error: Xcode got an error: No documentation set present at specified path. (6) Please help me for that. I want to generate my documentation on build phase only. So that it can be automatically changed if i change my code. Thanks in advance. Mrunal A: It probably means that Xcode's working directory isn't your source trees directory. Trace the working directory with a pwd in the script to prove this. Use pushd \foo\bar\myproject\ and popd to bracket your call to doxygen. As in pushd \Users\mrunal\projects\fooproject\ doxygen -switch -blah popd You might even get away with a simple cd \foo\bar\myproject\ at the start but don't be surprised if this borks the rest of the build. or use one of the doxygen command switches to explicitly define the working directory. I don't have it installed at the moment but most likely -d or -w There is also an environment variable to dynamically define the source directory. so you could do cd $PROJECT_DIR See Xcode variables for lots more environ vars
{ "language": "en", "url": "https://stackoverflow.com/questions/7607282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OpenCV CvSeq recursive element access fails for large images? My development enviroment is Mingw32 bit CMake on Windows 7.(this same code works fine on Linux) I use cvFindContours() to detect contours using OpenCV. I use recursive method to traveser the resultant CvSeq to access the contours by level as follows: void helperParseCurves(CvSeq* contour, int level) { //Travel same level contours if(contour->h_next != NULL) { helperParseCurves(contour->h_next, level); } if(contour->v_next != NULL) { helperParseCurves(contour->v_next, level+1); } //Travel child levels for(int i=0; i<contour->total; i++){ //Try to access Point data -- Crash here when threshold level 114 ? //Works when uncommented CvPoint* p = CV_GET_SEQ_ELEM(CvPoint, contour, i); } } But the application crashes at the line CvPoint* p = CV_GET_SEQ_ELEM(CvPoint, contour, i); This happens to some specific large images and works fine in Linux. I have uploaded an sample program to demonstrate the scenario at http://dl.dropbox.com/u/17399055/opencv-test.zip *download and compile using CMake *run the code using the sample image - "OCvTest.exe test-img.tif" *change the slider value around 114 , application crashes. *if the line #27 is commented works fine. Any tips on this ? Could this be a OpenCV bug ? thanks in advance. A: I realized that this happens due to the recursive function.Once I made it an iterative one ,everything worked fine. Now I know why recursive functions are bad...didnt really "practically" understood that before..
{ "language": "en", "url": "https://stackoverflow.com/questions/7607287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding custom attribute to a system class I want to add classes from System.Activites.Presentation my custom attribute. I tried to do it with emit(TypeBuilder, ModuleBuilder, AssemblyBuilder). Is it possible to change an existing type by adding an attribute to it? Or how to tell TypeBuilder, so that it uses an existing data type? Or inherit from a given type? Thank you. A: You can't add attributes to System classes but, if they are not marked as Sealed you can create your custom class deriving from original and adding custom attribute. All your code must call derived class, that is identical to the original except on the attribute added. [MyAttribute(DisplayName="Name shown")] public class MyActivity: System.Activities.Activity { } /// <summary> /// Custom attribute definition /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class MyAttribute : System.Attribute { /// <summary> /// Defines the attribute /// </summary> public string DisplayName { get; set; } /// <summary> /// Allow access to the attribute /// </summary> /// <param name="prop"></param> /// <returns></returns> public static string GetDisplayName(System.Reflection.MemberInfo prop) { string field = null; object[] attr = prop.GetCustomAttributes(false); foreach (object a in attr) { MyAttribute additional = a as MyAttribute; if (additional != null) { field = additional.DisplayName; } } return field; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to replace to html code with a php function I want to replace a image with html code, that must be the output of a php function. whenever a image tag is found in an html document, it should be passed to a php function and replaced with a html strings. my expectation is like below. index.htm file contains hello <img src="image.jpg" /> sentence continuation. this image.jpg is passed to php function like convert_pic('image.jpg'); so the output of index.htm is hello <div>....</div> sentence continuation. where <div>....</div> is the out put of php function convert_pic('image.jpg'); so <img src="image.jpg" /> is to be replace by <?php convert_pic('image.jpg'); how it can be done, or any other possibility to attain this? A: With the DOM extension you can use XPath to find all img tags and then replace them see also: * *http://docs.php.net/domdocument.loadhtml *http://docs.php.net/class.domxpath *http://docs.php.net/domnode.replacechild e.g <?php // closure/lambda, php 5.3+ only $convert = function($src) { return '---'.$src.'---'; }; $doc = new DOMDocument; $doc->loadhtml(getHTML()); echo "before: ", $doc->savehtml(), "\n\n"; foo($doc, $convert); echo "after: ", $doc->savehtml(), "\n\n"; function foo(DOMDocument $doc, $fn) { $xpath = new DOMXPath($doc); $imgs = array(); foreach( $xpath->query('/html/body//img') as $n ) { $imgs[] = $n; } foreach($imgs as $n) { $txt = $fn($n->getAttribute('src')); $div = $doc->createElement('div', $txt); $n->parentNode->replaceChild($div, $n); } } function getHTML() { return '<html><head><title>...</title></head><body> <p>lorem ipsum <img src="a.jpg" alt="img#1"/></p> <p>dolor sit amet<img src="b.jpg" alt="img#2"/></p> <div><div><div><img src="c.jpg" alt="img#3" /></div></div></div> </body></html>'; } prints before: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><head><title>...</title></head><body> <p>lorem ipsum <img src="a.jpg" alt="img#1"></p> <p>dolor sit amet<img src="b.jpg" alt="img#2"></p> <div><div><div><img src="c.jpg" alt="img#3"></div></div></div> </body></html> after: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><head><title>...</title></head><body> <p>lorem ipsum <div>---a.jpg---</div></p> <p>dolor sit amet<div>---b.jpg---</div></p> <div><div><div><div>---c.jpg---</div></div></div></div> </body></html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7607293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I structure the file and directory Rake tasks within a regular task? I want to generate the file my.db in the db/ directory. I'm unfamiliar with how to structure the file and directory tasks within a regular task. Help! task :create, [:name, :type] do |t, args| args.with_defaults(:name => "mydb", :type => "mysql") directory "db" file "db/my.db" => "db" do sh "echo 'Hello db' > db/my.db" end puts "Create a '#{args.type}' database called '#{args.name}'" end A: The following code will create the db and file unless the already exist... You can use this if you wish to have the commands in a single rake task Dir.mkdir("db") unless Dir.exists?("db") unless File.exists?("db/my.db") File.open("db/my.db", 'w') do |f| f.write("Hello db") end end If you wish to use the file task provided by rake you would need to do this... # Rakefile directory "db" file "db/my.db" => 'db' do sh "echo 'Hello db' > db/my.db" end task :create => "db/my.db" do end In this example your actually telling rake to create tasks called "db" and "db/my.db" which have the side effect of creating the directory or file. Hope this helps, sorry for the initial confusion :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7607295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to know what actually is those blue blocks in Instruments? I am using Instruments to find memory leaks in my app. When a object alloc, a blue block(line) display in Instrument, like this: Screenshot of Instruments's timeline, showing the Allocations graph http://naituw.com/temp/instruments.png When the object have been release, the blue line will disappear. But when I make some operation in my application, some blue block left there, doesn't disappear, How can I know what those block actually is in the memory? Thanks! A: In leaks instrument these shows the memory allocations that took place at the particular time. A: Select the instrument and look in the list in the lower half of the window. It will show a table or outline (depending on the instrument) listing what the instrument recorded. For the Allocations instrument, it lists things your application has allocated. Depending on the view settings, they may be objects that are still alive or all objects, even those that you have freed. For the Leaks instrument, it lists things your application has allocated and leaked (i.e., no longer has any reference to). Note that you might still be wasting ever-increasing amounts of memory on things you will never use, not because you don't have a reference to it but because it's in a write-only cache (you stash it but never look it up) or similar situation. Bill Bumgarner calls this “abandoned memory”. With either instrument, you can click on ➲ buttons within the list to drill deeper down into it, to see the list of allocations of a given type (e.g., all NSImages) or everything that happened to a single object, from birth to death. The latter is extremely useful for hunting down both leaks and over-release crashes, and is the reason why Instruments's Zombies template is so much better than NSZombieEnabled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I delete a file when I am watching it with a FileSystemWatcher? We know that in .NET (C# to be specific), we can use a FileSystemWatcher to detect any type of modification. public void MessageFileWatcher(string Path, string FileName) { FileSystemWatcher Watcher = new FileSystemWatcher(); Watcher.Path = Path; Watcher.Filter = FileName; Watcher.NotifyFilter = NotifyFilters.LastWrite; Watcher.Changed += new FileSystemEventHandler(OnChanged); Watcher.EnableRaisingEvents = true; } but I want to keep a watch on a file and after some time also want to delete that file. To be precise. can FileSystemWatcher class always look for modifications... and if I want to delete that particular file, will it raise an exception? A: It won't raise an exception. A FileSystemWatcher doesn't watch files: it watches the file system. In this case you'll find that there will be at least the Deleted event raised when the file is removed. A: A FileSystemWatcher wathes a path with an optional filter, not a single file. Of course, if you set the filter to be the name of the file, the watcher will only watch one file, but that is more of a side-effect that its intended usage. That said, it's clear that yes, you can delete the file you are watching. However, the deletion should not raise the Changed event. To monitor the deletion you will need to use the Deleted event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 100% layout with min/max sizes which doesn't overflow I have two layout elements lets say one is 33%, the other 66%. They both use 100% of my screen size (So it is dependent on browser window). The smaller element also has a min-size property, so it cant fall below 250px; Now if the layout is at least 757px large (so the size where the min property doesn't apply) everything looks fine. If the layout falls below the 757px the second element starts to overflow since it still takes the 66%, so the sum of both layouts exceeds the 100%. I made some graphics to show the behavior: Layout 1000px not overflowing: Layout 500px overflowing Is there a solution to prevent the overflow (not overflow: hidden) so the second element takes only the remaining space when the first element reaches it's min width. Also JavaScript shouldn't be used excessive! Regards, Stefan A: Try using the following for the second widget: position: fixed; right: 0; A: Sure, this is actually pretty easy and requires a very minimal amount of code: HTML: <div class="sidebar"> ... </div> <div class="content"> ... </div> CSS: .sidebar{ float: left; width: 33%; } .content { overflow: hidden; /* Ensures that your content will not overlap the sidebar */ } You can view the live demo here: http://jsfiddle.net/7A4Tj/ Edit: If you're trying to achieve a site layout that has equal-height background images for the sidebar and content, all you need to do is wrap both those elements in a containing div and use the Faux Columns technique. A: Here´s my five cents min-width on both divs and a wrapper that also has min-width, plus both of the divs having percentage width JS fiddle code PS seems to be working fine in IE8 PPS Also do check out @media queries if you want to have conditional CSS rules on different window sizes, might be helpful. Will run on browsers supporting CSS3: CSS Media queries at CSS Tricks
{ "language": "en", "url": "https://stackoverflow.com/questions/7607300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Overwriting resources during maven war overlay As I've gathered, maven-war-plugin never overwrites files which already exist in the target of an overlay. For example, if I have a war A which has a dependency on a war B, both of which contain some resource located at src/main/resources/some.xml, the resulting A.war will contain the some.xml from the A project. How do I instruct the maven-war-plugin to favor the resources from the dependency (B) over the original ones (A)? A: See http://maven.apache.org/plugins/maven-war-plugin/overlays.html: "For instance if the index.jsp file of the overlay my-webapp must be set in the webapp but other files can be controlled the regular way, define two overlay configurations for my-webapp" <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <overlays> <overlay> <id>my-webapp-index.jsp</id> <groupId>com.example.projects</groupId> <artifactId>my-webapp</artifactId> <includes> <include>index.jsp</include> </includes> </overlay> <overlay> <!-- empty groupId/artifactId represents the current build --> </overlay> ... </overlays> </configuration> Guess that's not the final desicion, but a point to start at. A: You can use maven-resources plugin to copy a file to the desired location. Before or after a war has been built.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails 3.1 and dynamic jquery ui-theme switch To be brief: application.css /* *= require_self *= require_tree . *= require vendor */ application.js //= require jquery //= require jquery_ujs //= require jquery-ui //= require_tree . and vendor/assets$ tree . └── stylesheets ├── ui-themes │ ├── smoothness │ │ ├── images │ │ │ ├── ui-bg_flat_0_aaaaaa_40x100.png │ │ │ ├── ui-bg_flat_75_ffffff_40x100.png │ │ │ ├── ui-bg_glass_55_fbf9ee_1x400.png │ │ │ ├── ui-bg_glass_65_ffffff_1x400.png │ │ │ ├── ui-bg_glass_75_dadada_1x400.png │ │ │ ├── ui-bg_glass_75_e6e6e6_1x400.png │ │ │ ├── ui-bg_glass_95_fef1ec_1x400.png │ │ │ ├── ui-bg_highlight-soft_75_cccccc_1x100.png │ │ │ ├── ui-icons_222222_256x240.png │ │ │ ├── ui-icons_2e83ff_256x240.png │ │ │ ├── ui-icons_454545_256x240.png │ │ │ ├── ui-icons_888888_256x240.png │ │ │ └── ui-icons_cd0a0a_256x240.png │ │ └── jquery-ui-1.8.16.custom.css │ └── trontastic │ ├── images │ │ ├── ui-bg_diagonals-small_50_262626_40x40.png │ │ ├── ui-bg_flat_0_303030_40x100.png │ │ ├── ui-bg_flat_0_4c4c4c_40x100.png │ │ ├── ui-bg_glass_40_0a0a0a_1x400.png │ │ ├── ui-bg_glass_55_f1fbe5_1x400.png │ │ ├── ui-bg_glass_60_000000_1x400.png │ │ ├── ui-bg_gloss-wave_55_000000_500x100.png │ │ ├── ui-bg_gloss-wave_85_9fda58_500x100.png │ │ ├── ui-bg_gloss-wave_95_f6ecd5_500x100.png │ │ ├── ui-icons_000000_256x240.png │ │ ├── ui-icons_1f1f1f_256x240.png │ │ ├── ui-icons_9fda58_256x240.png │ │ ├── ui-icons_b8ec79_256x240.png │ │ ├── ui-icons_cd0a0a_256x240.png │ │ └── ui-icons_ffffff_256x240.png │ └── jquery-ui-1.8.16.custom.css └── vendor.css.erb Then my problem is how to dynamic load jquery theme css through params[:theme], i tried /* *= require "ui-themes/<%= params[:theme] %>/jquery-ui-1.8.16.custom" * */ in vendor.css.erb, but not lucky. thanks for any help. A: * *solution, include all possible themes in your css file, but scope them, i.e. nest all rules under a distinct body id (or class) e.g. #theme-1 ui-widget-... { .. } etc... then switch the id of your body tag dynamically *solution make an own css for every theme (each also including your other styles), add those files to config.assets.precompile in your config/environments/production.rb, disable the hash cache buster suffix (there is a question here at stack overflow how to do this) and then switch stylesheets on your server side (in your layout) by param
{ "language": "en", "url": "https://stackoverflow.com/questions/7607306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Listview Backcolor I am using vb 6.0 and i want to change the back color of the selected item. in Default by windows,the back color is blue, how can I customize the color. Thanks in advance A: Unless it is something you have a real need to do you may want to live with the default system color. There is no property for this so you'll need to dip into the API. If you still want to do it here is a site with a link to an application that will get you started. http://www.vb6.us/tutorials/indepth-vb6-listbox-tutorial
{ "language": "en", "url": "https://stackoverflow.com/questions/7607308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: No item is shown in ListView I have a ListView and a Arrayadapter filled with Strings. The data should be the StringArray myStrings My Code: public class Main extends Activity { private SQLiteDatabase myDB; final String MY_DB_NAME = "PizzaCounter"; final String MY_DB_TABLE = "Pizza"; private ListView lv; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.e("XXX", "Start"); lv = ((ListView)findViewById(R.id.list)); Log.e("XXX List View",lv.toString()); onCreateDBAndDBTabled(); Button bt = (Button)findViewById(R.id.bt_add); bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivityForResult(new Intent(Main.this, AddPizza.class), 1); } }); } private void onCreateDBAndDBTabled() { myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null); myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE + " (_id integer primary key autoincrement, name varchar(100), rate integer(1), eattime datetime)" +";"); List<String> list = new ArrayList<String>(); Cursor cursor = this.myDB.query(MY_DB_TABLE, new String[] { "name" },null,null,null,null,null,null); if (cursor.moveToFirst()) { do { Log.e("XXX", "Courser Enter: " + cursor.getString(0)); list.add(cursor.getString(0)); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } Log.e("XXX", "Coung:" + list.size()); Log.e("XXX", "Item[0] -->" + list.toArray()[0].toString()); String[] mStrings = new String[] { "Nyros", "Mobile", "Android" }; ArrayAdapter<String> aa = new ArrayAdapter<String>(Main.this, android.R.layout.simple_list_item_1, mStrings); Log.e("XXX", String.valueOf(aa.getCount())); lv.setAdapter(aa); } The problem is that no item is shown and the list count is 3. LogCat: 09-29 08:43:03.344: ERROR/XXX(461): Start 09-29 08:43:03.344: ERROR/XXX List View(461): android.widget.ListView@43d13918 09-29 08:43:03.384: ERROR/XXX(461): Courser Enter: EditText 09-29 08:43:03.394: ERROR/XXX(461): Count:1 09-29 08:43:03.394: ERROR/XXX(461): Item[0] -->EditText 09-29 08:43:03.394: ERROR/XXX(461): 3 Layout: <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:text="hinzufügen" android:id="@+id/bt_add" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button> <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent"></ListView> </LinearLayout> A: Your problem is in the layout - the linear layout defaults to a horizontal orientation which means the button (which is set to fill_parent) will fill the screen leaving no room for the listview. If you add the attribute: android:orientation="vertical" to your LinearLayout then you should see the list. Hope that works!
{ "language": "en", "url": "https://stackoverflow.com/questions/7607309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Joomla good PDF viewer I'm searching for a good PDF viewer for Joomla, the problem is when there is a module in an article all the PDF viewers I tried so far show: {loadposition myposition} in place of that module. Does anybody know a PDF viewer that will show the module. I would also like it to have a header and footer option. Thx. A: I suspect that your extensions 'might' not be the sole source of your troubles. Have you installed "Modules Anywhere" from nonumber.nl? I recommend you try that first before assuming that the problem lies in your extensions. Here is the appropriate link: http://www.nonumber.nl/extensions/modulesanywhere Install it, and make sure the editor plugin is also installed and enabled (Modules Anywhere may perform these steps upon installation), then open up the content item you wish to inject your module into and use the module selection tool provided to you by the editor plugin. After you perform this test, you can more reliably assume that your PDF related modules are the culprits. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7607313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WPF Application slowing down on i5 Processor machine One of the developed application in WPF is running very slow on i5 process Laptop. UI contains multiple user controls (200+) in nested Items control. Same application is running with good performance in one of the Desktop machine. Below is the detailed configuration of Laptop where its very slow (50 sec to render the UI) : Operating System: Windows XP Professional (5.1, Build 2600) Service Pack 3 (2600.xpsp_sp3_gdr.101209-1647) System Manufacturer: LENOVO System Model: 2537W2K BIOS: Ver 1.00PARTTBLx Processor: Intel(R) Core(TM) i5 CPU M 520 @ 2.40GHz (4 CPUs) Memory: 3060MB RAM Page File: 784MB used, 5172MB available Windows Dir: C:\WINDOWS DirectX Version: DirectX 9.0c (4.09.0000.0904) DX Setup Parameters: Not found DxDiag Version: 5.03.2600.5512 32bit Unicode Display Card name: NVIDIA NVS 3100M Manufacturer: NVIDIA Chip type: NVS 3100M DAC type: Integrated RAMDAC Device Key: Enum\PCI\VEN_10DE&DEV_0A6C&SUBSYS_214217AA&REV_A2 Display Memory: 256.0 MB Current Mode: 1680 x 1050 (32 bit) (60Hz) Monitor: ThinkPad Display 1440x900 Monitor Max Res: 1440,900 Below is the detailed configuration of Desktop where its fast (6 sec to render the same UI) : Operating System: Windows XP Professional (5.1, Build 2600) Service Pack 3 (2600.xpsp_sp3_gdr.101209-1647) System Manufacturer: Dell Inc. System Model: OptiPlex 755 BIOS: Phoenix ROM BIOS PLUS Version 1.10 A04 Processor: Intel(R) Core(TM)2 Duo CPU E6550 @ 2.33GHz (2 CPUs) Memory: 2004MB RAM Page File: 1544MB used, 2353MB available Windows Dir: C:\WINDOWS DirectX Version: DirectX 9.0c (4.09.0000.0904) DX Setup Parameters: Not found DxDiag Version: 5.03.2600.5512 32bit Unicode Display Card Card name: Intel(R) Q35 Express Chipset Family Manufacturer: Intel Corporation Chip type: Intel(R) GMA 3100 DAC type: Internal Device Key: Enum\PCI\VEN_8086&DEV_29B2&SUBSYS_02111028&REV_02 Display Memory: 384.0 MB Current Mode: 1280 x 960 (32 bit) (60Hz) Monitor: Plug and Play Monitor Monitor Max Res: 1600,1200 Driver Name: igxprd32.dll Driver Version: 6.14.0010.4837 (English) Please help me to understand the cause to slow down the rendering. <Grid x:Name="grid" Margin="3,0,0,15" HorizontalAlignment="Center" VerticalAlignment="Top" IsEnabled="{Binding IsEnableOrDisableControl}"> <Grid.ColumnDefinitions> <ColumnDefinition Width="70*" /> <ColumnDefinition Width="05" /> <ColumnDefinition Width="65" /> <ColumnDefinition Width="05" /> <ColumnDefinition Width="65" /> <ColumnDefinition Width="05" /> <ColumnDefinition Width="65" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="30" /> <RowDefinition Height="05" /> <RowDefinition Height="15" /> <RowDefinition Height="Auto" /> <RowDefinition /> </Grid.RowDefinitions> <AppUserControl:NumericUPDown Value="{Binding Total, Mode=TwoWay}" MinValue="2" MaxValue="{Binding MaxValue}" Grid.Column="0" Grid.Row="0" x:Name="NoOfFltr" /> <Button Background="Transparent" BorderBrush="Transparent" BorderThickness="0" Grid.Column="2" Grid.Row="0" ToolTip="Plot" HorizontalAlignment="Left" > <Button.Content> <Image Width="16" Height="16"> <Image.Source> <BitmapImage UriSource="..\Pictures\icon.png" DecodePixelWidth="16" /> </Image.Source> </Image> </Button.Content> <Button.InputBindings> <MouseBinding Gesture="CTRL+LeftClick" Command="{Binding OpenNewWindowCommand}" CommandParameter="0" /> <MouseBinding Gesture="LeftClick" Command="{Binding OpenCommand}" CommandParameter="1" /> </Button.InputBindings> </Button> <TextBlock Text="Text1" Height="20" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="2" Grid.Column="0" /> <TextBlock Text="Text2" Height="20" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="2" Grid.Column="2" /> <TextBlock Text="Text3" Height="20" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="2" Grid.Column="4" /> <TextBlock Text="Text4" Height="20" VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Row="2" Grid.Column="6" /> <Grid Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="7" HorizontalAlignment="Left" Height="{Binding DataParameterHeight}"> <ItemsControl Name="BiquadItem" ItemsSource="{Binding Parameters }"> <ItemsControl.ItemTemplate> <DataTemplate> <Grid Margin="3"> <Grid.ColumnDefinitions> <ColumnDefinition Width="70*" /> <ColumnDefinition Width="05" /> <ColumnDefinition Width="65" /> <ColumnDefinition Width="05" /> <ColumnDefinition Width="65" /> <ColumnDefinition Width="05" /> <ColumnDefinition Width="65" /> </Grid.ColumnDefinitions> <ComboBox Name="cmbType" Width="70" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding Source={StaticResource mdwType}}" Grid.Column="0" SelectedValue="{Binding bqType, Mode=TwoWay}" > </ComboBox> <AppUserControl:UnitUpDown Value="{Binding frq, Mode=TwoWay}" MinValue="0" MaxValue="24000" Grid.Column="2" IsEnabled="{Binding Status}" Increment="1" /> <AppUserControl:NumericUPDown Value="{Binding scale, Mode=TwoWay}" Grid.Column="4" IsEnabled="{Binding Status}" DecimalPoint="2" Increment="0.01" MinValue="{Binding ElementName=biquadGrid, Path=DataContext.MinVal}" MaxValue="{Binding ElementName=bqgrid, Path=DataContext.MaxVal}" /> <AppUserControl:NumericUPDown Value="{Binding qFactors, Mode=TwoWay}" MinValue="0.001" MaxValue="24" Grid.Column="6" IsEnabled="{Binding qStatus}" DecimalPoint="3" Increment="0.01" /> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> </Grid> A: You can use the WPF Performance Suite from Microsoft (my highlight): The WPF Performance Suite enables you to analyze the run-time behavior of your WPF applications and determine performance optimizations that you can apply. The WPF Performance Suite includes performance profiling tools called Perforator and Visual Profiler. Rendering 200+ complex UserControl's within an ItemsControl is a lot - at least for the user to interact with. The graphical muscle of the laptop may be the bottleneck. You could consider using a ListBox to display the UserControl's. ListBox uses a VirtualizingStackPanel to enable UI virtualization. Also, depending on the DirectX support on Windows XP on your hardware you may experience performance problems. You can even try to turn off hardware acceleration in the display properties of the Windows XP machine to see if that improves WPF performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VB.NET match whole word and replace I'm trying to replace a string with another but the problem is that the string is matching some other string partially. For e.g. - Dim x as String = "I am Soham" x = x.Replace("am","xx") After this replace I would only like the word am to replaced with xx but because my name also contains am its also getting replaced. The value of x is I xx Sohxx. How can I stop this. Please help. A: Use Regex.Replace and use the regular expression \bam\b. In a regular expression \b means "word boundary". A: You can write up like as follows also. X = X.Replace(" am"," xx")
{ "language": "en", "url": "https://stackoverflow.com/questions/7607320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Publishing very slow in fatwire CMS I was trying to publisg assets from one environment to another. It was almost very slow and not progressing further. Could any body suggest what can be the issue ? A: Try segmenting your assets and publishing in smaller goups A: Sometimes it boils down to finding the culprit asset which causes the entire batch to stall. This is why segmenting slow publishes can help narrow the issue. Also check if there are any assets checked out in your target destination. A: There are a few things to check You can set VERBOSE=TRUE on the publish destination config, to make the UI write a more detailed log. It's important to know exactly what is slow, whether its the movement of assets to target or the cache flush/potential rebuild on target. Check the futuretense.txt on source and target for any telltale error or curious messages, if nothing is appearing there then maybe the logging is suppressed. You should have INFO level for most loggers by default, and if still nothing is appearing then set com.fatwire.logging.cs=DEBUG and retry. Generally speaking if this is a production system, and its not a huge number of assets being published, then cache flush is where most time is spent. And, if it is configured to do so, cache regeneration. The verbose publish log will tell you how much is being flushed. If the cause of slowness can't be determined from inspecting the logs, then consider taking periodic thread dumps (source and target) during the publish, to see what is happening under the hood. Perhaps the system is slow waiting on a resource like shared disk (a common problem). Phil A: To understand better, you will need to find at what step the publishing process is stuck. As you know, the publishing is process is composed of 5 steps, first two (data gather and serialization) happens at source, the third (data transfer) happens between source & destination, and the last two (de-serialization & cache clear) happens at delivery. One weird situation that I have come across is the de-serialization step in which it was trying to update Locale tree in each real time publish. The then Fatwire support suggested us to add &PUBLISHLOCALETREE=false. This significantly improved the publish performance. Once again, this only applies if you're using locales/translations in your Site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ExtJs - Problems with grouping in grid a simple table contains - id, name, text. I need to bring these data in the grid with the grouping by the field name. In all the examples that I found (for example - paper) uses the variable already defined the data. And I need to get data from Store. ExtJs 3 The code: Ext.onReady(function() { var store = new Ext.data.JsonStore({ url : 'get_from_db.php', storeId : 'MyStore', totalProperty : 'totalCount', idProperty : 'id', remoteSort : true, fields : [ {name : 'id', type : 'int'}, {name : 'name', type : 'String'}, {name : 'text', type : 'String'} ] }); store.load(); var TestReader = new Ext.data.JsonReader({ idProperty : 'id', fields : [ {name : 'id', type : 'int'}, {name : 'name', type : 'String'}, {name : 'text', type : 'String'} ] }); var TestStore = new Ext.data.GroupingStore({ reader : TestReader, data : 'get_from_db.php', sortInfo : { field : 'id', direction : 'ASC' }, groupField : 'name' }); var TaskGrid = new Ext.grid.GridPanel({ store : TestStore, columns : [ {id : 'id', header : 'Id', dataIndex : 'id'}, {id : 'name', header : 'Name', dataIndex : 'name'}, {id : 'text', header : 'Text', dataIndex : 'text'} ], view : new Ext.grid.GroupingView({ forceFit : true, groupTextTpl : '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})' }), frame : true, width : 700, height : 450, collapsible : true, animCollapse : false, title : 'Grouping', renderTo : document.body }); }); As a result, output grid without a single error, the group is - but here's the column values - all zeros A: post the code of 'get_from_db.php', if you can, please. $connect = mysql_connect('localhost', 'root', ''); if ($connect) mysql_select_db('grid') or die('error with select table'); $select = mysql_query("select * from test"); while ($rec = mysql_fetch_array($select)) $rows[] = $rec; echo json_encode($rows); You made mistake in returning JSON. Instead $rows[] = $rec; you need $rows[] = array ("id"=>$rec['id'], "name"=>$rec['name'], "text"=>$rec['text']); A: decided. code: Ext.onReady(function() { var TestStore = new Ext.data.GroupingStore({ url : 'http://extjs/get_from_db.php', autoLoad : true, remoteGroup : true, groupField : 'name', sortInfo : { field : 'id', direction : 'ASC' }, reader : new Ext.data.JsonReader({ totalProperty : 'totalCount', root : 'items', idProperty : 'id', fields: [ {name : 'id', type : 'int'}, {name : 'name', type : 'String'}, {name : 'text' ,type : 'String'} ] }) }); var TaskGrid = new Ext.grid.GridPanel({ store : TestStore, colModel : new Ext.grid.ColumnModel({ columns : [ {id : 'id', header : 'Id', dataIndex : 'id'}, {header : 'Name', dataIndex : 'name'}, {header : 'Text', dataIndex : 'text'} ], defaults : { sortable : true, menuDisabled : false, width : 20 } }), view : new Ext.grid.GroupingView({ startCollapsed : true, forceFit : true, groupTextTpl : '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})' }), frame : true, width : 700, height : 450, collapsible : true, animCollapse : false, title : 'Grouping', renderTo : document.body }); }); More details in this note
{ "language": "en", "url": "https://stackoverflow.com/questions/7607324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to create a XML object from String in Java? I am trying to write a code that helps me to create a XML object. For example, I will give a string as input to a function and it will return me a XMLObject. XMLObject convertToXML(String s) {} When I was searching on the net, generally I saw examples about creating XML documents. So all the things I saw about creating an XML and write on to a file and create the file. But I have done something like that: Document document = new Document(); Element child = new Element("snmp"); child.addContent(new Element("snmpType").setText("snmpget")); child.addContent(new Element("IpAdress").setText("127.0.0.1")); child.addContent(new Element("OID").setText("1.3.6.1.2.1.1.3.0")); document.setContent(child); Do you think it is enough to create an XML object? and also can you please help me how to get data from XML? For example, how can I get the IpAdressfrom that XML? Thank you all a lot EDIT 1: Actually now I thought that maybe it would be much easier for me to have a file like base.xml, I will write all basic things into that for example: <snmp> <snmpType><snmpType> <OID></OID> </snmp> and then use this file to create a XML object. What do you think about that? A: If you can create a string xml you can easily transform it to the xml document object e.g. - String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xmlString))); } catch (Exception e) { e.printStackTrace(); } You can use the document object and xml parsing libraries or xpath to get back the ip address. A: try something like public static Document loadXML(String xml) throws Exception { DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance(); DocumentBuilder bldr = fctr.newDocumentBuilder(); InputSource insrc = new InputSource(new StringReader(xml)); return bldr.parse(insrc); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "45" }
Q: Sharepoint2010 hiding "Edit Item" button in ribbon for a specific Custom List I am using Share Point 2010, I have requirement where i create some Custom lists in feature activation by code and i have to hide "Edit Item" in ribbon for a specific Custom List There are so many solutions available but they hide "Edit Item " button for all lists in site , but its not required in my case. Thank i need your help .. pls Jay Bhagatwala A: Jay Create UserControl with the following codebehind and add to to a delegate control via Feature using module: SPRibbon ribbon = SPRibbon.GetCurrent(this.Page); if (!Request.Url.ToString().ToLower().Contains("ListNameWhereWeHideButtons")) return; // if it's not our list - do nothing if (ribbon != null) { ribbon.TrimById("Ribbon.ListItem.New"); //hide new button ribbon.TrimById("Ribbon.ListItem.Manage"); // hide edit button } } I've uploaded my test project on the following URL (I hope it's not prohibited by the rules): http://ge.tt/8TIqVX8
{ "language": "en", "url": "https://stackoverflow.com/questions/7607330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sql Server Index on Bit fields I am using Sql Server 2000 and want to know why we can not create index on bit fields? A: Just a limitation of the product. SQL Server 2005+ does allow this. Because of the Tipping Point a single column bit index is unlikely to be very useful unless the values are heavily skewed (a scenario for which filtered indexes in 2008 can help) Still - could be useful as part of a composite covering index though. A: I would guess this is by design. A bit field can only have 1 of 2 values, so it would not be selective enough for an index to be useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Dismissing keyboard? I do have Three TextField For Name Phone and Email. On selecting each textField keyboard will appears -(void)createdTextField{ phoneField = [[UITextField alloc]initWithFrame:CGRectMake(225, 306, 90, 31)]; [phoneField setPlaceholder:REQUIRED]; [phoneField setBorderStyle:UITextBorderStyleRoundedRect]; phoneField.delegate = self; phoneField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter; phoneField.keyboardType = UIKeyboardTypeNumberPad; [phoneField setTag:10]; [self.view addSubview:phoneField]; [self.view addSubview:phoneField]; nextPhoneField = [[UITextField alloc]initWithFrame:CGRectMake(325, 306, 142, 31)]; [nextPhoneField setBorderStyle:UITextBorderStyleRoundedRect]; nextPhoneField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter; nextPhoneField.delegate = self; nextPhoneField.keyboardType = UIKeyboardTypeNumberPad; [nextPhoneField setTag:11]; [self.view addSubview:nextPhoneField]; nameField = [[UITextField alloc] initWithFrame:CGRectMake(225, 265, 242, 31)]; [nameField setPlaceholder:REQUIRED]; [nameField setBorderStyle:UITextBorderStyleRoundedRect]; nameField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter; // [nameField setAutocorrectionType:UITextAutocorrectionTypeNo]; [nameField setTag:12]; [self.view addSubview:nameField]; eMailField = [[UITextField alloc]initWithFrame:CGRectMake(225, 347, 242, 31)]; [eMailField setPlaceholder:REQUIRED]; [eMailField setBorderStyle:UITextBorderStyleRoundedRect]; eMailField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter; eMailField.keyboardType = UIKeyboardTypeEmailAddress; [eMailField setAutocorrectionType:UITextAutocorrectionTypeNo]; [eMailField setTag:13]; [self.view addSubview:eMailField]; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return NO; } @When to dismiss keyboard when typing return button in all four textField I need to dismiss the keyboard. Its happen only for the phone no the remaining TextField. A: I saw the code you paste. There is no delegate of the last two textfields. I think this is the reason. A: Any time you want the keyboard hidden for a give field just do: [myField resignFirstResponder]; As apparently myField is the field currently active. A: How to Dismiss UITextField Keypad [textField resignFirstResponder]; If you want to dismiss when user touch 'return' button, use this (Needed to set delegate and protocol, ) - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } A: after creation of urEachTextField urEachTextField = [[UITextField alloc] initWithFrame:CGRectMake(225, 265, 242, 31)]; urEachTextField.delegate=self; head file .h @interface urViewController : UIViewController<UITextFieldDelegate>
{ "language": "en", "url": "https://stackoverflow.com/questions/7607333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recursing in a lambda function I have the following 2 functions that I wish to combine into one: (defun fib (n) (if (= n 0) 0 (fib-r n 0 1))) (defun fib-r (n a b) (if (= n 1) b (fib-r (- n 1) b (+ a b)))) I would like to have just one function, so I tried something like this: (defun fib (n) (let ((f0 (lambda (n) (if (= n 0) 0 (funcall f1 n 0 1)))) (f1 (lambda (a b n) (if (= n 1) b (funcall f1 (- n 1) b (+ a b)))))) (funcall f0 n))) however this is not working. The exact error is *** - IF: variable F1 has no value I'm a beginner as far as LISP goes, so I'd appreciate a clear answer to the following question: how do you write a recursive lambda function in lisp? Thanks. A: You can use Graham's alambda as an alternative to labels: (defun fib (n) (funcall (alambda (n a b) (cond ((= n 0) 0) ((= n 1) b) (t (self (- n 1) b (+ a b))))) n 0 1)) Or... you could look at the problem a bit differently: Use Norvig's defun-memo macro (automatic memoization), and a non-tail-recursive version of fib, to define a fib function that doesn't even need a helper function, more directly expresses the mathematical description of the fib sequence, and (I think) is at least as efficient as the tail recursive version, and after multiple calls, becomes even more efficient than the tail-recursive version. (defun-memo fib (n) (cond ((= n 0) 0) ((= n 1) 1) (t (+ (fib (- n 1)) (fib (- n 2)))))) A: You can try something like this as well (defun fib-r (n &optional (a 0) (b 1) ) (cond ((= n 0) 0) ((= n 1) b) (T (fib-r (- n 1) b (+ a b))))) Pros: You don't have to build a wrapper function. Cond constructt takes care of if-then-elseif scenarios. You call this on REPL as (fib-r 10) => 55 Cons: If user supplies values to a and b, and if these values are not 0 and 1, you wont get correct answer A: LET conceptually binds the variables at the same time, using the same enclosing environment to evaluate the expressions. Use LABELS instead, that also binds the symbols f0 and f1 in the function namespace: (defun fib (n) (labels ((f0 (n) (if (= n 0) 0 (f1 n 0 1))) (f1 (a b n) (if (= n 1) b (f1 (- n 1) b (+ a b))))) (f0 n)))
{ "language": "en", "url": "https://stackoverflow.com/questions/7607338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How to Delete Facebook Messages via Facebook API? Is there a way to retrieve all Facebook Message ids with the read mailbox permission and then delete them all one by one? Everyone is crying about how it's difficult to delete your chat/message history. I wondered if there was an easy way to write an app to do this. Facebook API - Message A: Normally you would issue an HTTP DELETE call to https://graph.facebook.com/messageID?access_token=... But it appears that this is an API call that either require special whitelisting from Facebook or isn't currently supported because it does not work right now and returns "Unsupported delete request." A: Install https://chrome.google.com/webstore/detail/jquerify/gbmifchmngifmadobkcpijhhldeeelkc Open the facebook using https://mbasic.facebook.com/messages/?_rdr Enable jQuery using jQueryify extension you installed. Then go to your chrome developer tools> sources > snippet and create a new snippet and paste the following code and run it. // Code snippet for facebook messages removing: var WHITELISTED_USERS_X = []; function removeElement(elementId) { // Removes an element from the document var element = document.getElementById(elementId); if (element) { element.parentNode.removeChild(element); } } function addElement(parentId, elementTag, elementId, html) { // Adds an element to the document // removeElement removeElement(elementId); var p = document.getElementById(parentId); var newElement = document.createElement(elementTag); newElement.setAttribute('id', elementId); newElement.innerHTML = html; if (p) { p.appendChild(newElement); } else { var body = document.getElementsByTagName("body")[0] body.appendChild(newElement); } } addElement("body", "div", "123x", "hello World23"); console.log(`getOlderMessagesLink()`); console.log(getOlderMessagesLink()); var aLinks = document.querySelectorAll('h3 a'), i; for (i = 0; i < aLinks.length; ++i) { let currentLink = aLinks[i]; currentLink.style.color = currentLink.style.color == "black" ? "red" : "green"; $.get( currentLink.href, function( data ) { getPayload1(currentLink.href).then(payLoad=>{ let abLink = currentLink.href; let deleteApiLink = abLink.split('?').pop().split('&'); deleteApiLink.splice(1 , 0, `tids=${deleteApiLink[0].split('=').pop()}`) deleteApiLink = deleteApiLink.join("&").split("#").shift(); const apiLink = `https://mbasic.facebook.com/messages/action_redirect?` + deleteApiLink; $.post(apiLink, payLoad ).done(function( data ) { let mydeletehref = findInParsed(data, "a:contains('Delete')"); const username = currentLink.innerText; const deleteLink = mydeletehref.href; if(WHITELISTED_USERS_X.indexOf(username) == -1){ // console.log(`${username}: ${deleteLink}`); insertDeleteLinkInUser(username, deleteLink); } }); }); }) } function getPayload1(link){ return new Promise(resp=>{ $.get(link, function( html1 ) { let fbDtsg = findInParsed(html1, "input[name='fb_dtsg']"); let jazoest = findInParsed(html1, "input[name='jazoest']"); resp ({ "fb_dtsg": fbDtsg.value, "jazoest": jazoest.value, "delete": "Delete" }) }); }) } function findInParsed(html, selector){ return $(selector, html).get(0) || $(html).filter(selector).get(0); } function getOlderMessagesLink(html = false){ if(html){ return $("#see_older_threads").find("a").get(0).href; } let selector = "#see_older_threads"; return $(selector, html).find("a").get(0).href || $(html).filter(selector).find("a").get(0).href; } function insertDeleteLinkInUser(username, link){ $("a:contains('" + username + "')").parent().parent().parent().prepend('<a href="' + link + '" style="color:red; padding:5px;" target="_blank">DELETE ME</a>'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Transform any ActionScript class in XML For a program i'm writing I need to marshal ActionScript classes to a format that is later to be read by Java (and back again). What solutions exists for such a need ? Is there a way (like when using Java through XMLEncoder/XMLDecoder) to generate that XML using standard flex libraries (that would be compatible with later decoding using XMLDecoder) ? Or is there a good existing library ? EDIT Yes, this question is a duplicate of Are there any tool mapping of JavaBeans to ActionScript Class through xml serialization and deserialization?, but I will accept correct answers and eventually start a bounty if no answer satisfies my needs. (in other words, i plan to make the previous - unanswered - question a duplicate of mine). EDIT 2 To be even more precise, I have an application divided in two parts : one Flex GUI and one Java core. They communicate over a non http layer which requires data to be sent in XML. In this context, I replicated my Java objects in Flex (using GAS3) and now want some of these objects to be sent from Flex to Java and back again. For that purpose, I have to serialize objects (on the Flex end) in XML and deserialize them in Java (and all that back again). A: We are using http://www.spicefactory.org/parsley/index.php which supports XML-to-object conversions back-and-forth. Their documentation is very decent: http://www.spicefactory.org/parsley/docs/2.4/manual/. A: See describeType function if you really want XML. But I seriously recommend considering the other serializations formats too. You can look into JSON. The classes needed for the actionscript serialization/deserialization are part of the as3corelib library. You might also want to take a look at BlazeDS. A: Solution used was to put XStream on the java side and FleXMLer (with some adaptations that can be found there : https://github.com/Riduidel/FleXMLer) on the Flex side. it works quite good (once FleXMLer is adapted to XStream architecture).
{ "language": "en", "url": "https://stackoverflow.com/questions/7607344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python Strategy for Large Scale Analysis (on-the-fly or deferred) To analyze a large number of websites or financial data and pull out parametric data, what are the optimal strategies? I'm classifying the following strategies as either "on-the-fly" or "deferred". Which is best? * *On-the-fly: Process data on-the-fly and store parametric data into a database *Deferred: Store all the source data as ASCII into a file system and post process later, or with a processing-data-daemon *Deferred: Store all pages as a BLOB in a database to post-process later, or with a processing-data-daemon Number 1 is simplest, especially if you only have a single server. Can #2 or #3 be more efficient with a single server, or do you only see the power with multiple servers? Are there any python projects that are already geared toward this kind of analysis? Edit: by best, I mean fastest execution to prevent user from waiting with ease of programming as secondary A: I'd use celery either on a single or on multiple machines, with the "on-the-fly" strategy. You can have an aggregation Task, that fetches data, and a process Task that analyzes them and stores them in a db. This is a highly scalable approach, and you can tune it according to your computing power. The "on-the-fly" strategy is more efficient in a sense that you process your data in a single pass. The other two involve an extra step, re-retrieve the data from where you saved them and process them after that. Of course, everything depends on the nature of your data and the way you process them. If the process phase is slower than the aggregation, the "on-the-fly" strategy will hang and wait until completion of the processing. But again, you can configure celery to be asynchronous, and continue to aggregate while there are data yet unprocessed. A: First: "fastest execution to prevent user from waiting" means some kind of deferred processing. Once you decide to defer the processing -- so the user doesn't see it -- the choice between flat-file and database is essentially irrelevant with respect to end-user-wait time. Second: databases are slow. Flat files are fast. Since you're going to use celery and avoid end-user-wait time, however, the distinction between flat file and database becomes irrelevant. Store all the source data as ASCII into a file system and post process later, or with a processing-data-daemon This is fastest. Celery to load flat files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add two array of objects from mysql result I have a query as follows : $q1 = " SELECT * FROM tbl_profile WHERE admin_selected = 'y' "; $res1 = mysql_query($q1); $r1 = mysql_fetch_object($res1); //print_r($r1); $q2 = " SELECT * FROM tbl_profile WHERE admin_selected = 'n' "; $res2 = mysql_query($q2); $r2 = mysql_fetch_object($res2); //print_r($r2); ?> Now I want to add the two results $r1 and $r2 into a single array of object say $r. How can I do that ? A: you can user following array_merge($r1,$r2) A: Why would you like to split it into 2 query statements? You can do it in just one statement. SELECT * FROM tbl_profile WHERE admin_selected = 'y' OR admin_selected = 'n' The fetch function will produce an array that holds values of both admin_selected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I create a Java method that accepts a variable number of arguments? For example, Java's own String.format() supports a variable number of arguments. String.format("Hello %s! ABC %d!", "World", 123); //=> Hello World! ABC 123! How can I make my own function that accepts a variable number of arguments? Follow-up question: I'm really trying to make a convenience shortcut for this: System.out.println( String.format("...", a, b, c) ); So that I can call it as something less verbose like this: print("...", a, b, c); How can I achieve this? A: Take a look at the Java guide on varargs. You can create a method as shown below. Simply call System.out.printf instead of System.out.println(String.format(.... public static void print(String format, Object... args) { System.out.printf(format, args); } Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method: import static java.lang.System.out; out.printf("Numer of apples: %d", 10); A: This is just an extension to above provided answers. * *There can be only one variable argument in the method. *Variable argument (varargs) must be the last argument. Clearly explained here and rules to follow to use Variable Argument. A: This is known as varargs see the link here for more details In past java releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message: Object[] arguments = { new Integer(7), new Date(), "a disturbance in the Force" }; String result = MessageFormat.format( "At {1,time} on {1,date}, there was {2} on planet " + "{0,number,integer}.", arguments); It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration: public static String format(String pattern, Object... arguments); A: The following will create a variable length set of arguments of the type of string: print(String arg1, String... arg2) You can then refer to arg2 as an array of Strings. This is a new feature in Java 5. A: You could write a convenience method: public PrintStream print(String format, Object... arguments) { return System.out.format(format, arguments); } But as you can see, you've simply just renamed format (or printf). Here's how you could use it: private void printScores(Player... players) { for (int i = 0; i < players.length; ++i) { Player player = players[i]; String name = player.getName(); int score = player.getScore(); // Print name and score followed by a newline System.out.format("%s: %d%n", name, score); } } // Print a single player, 3 players, and all players printScores(player1); System.out.println(); printScores(player2, player3, player4); System.out.println(); printScores(playersArray); // Output Abe: 11 Bob: 22 Cal: 33 Dan: 44 Abe: 11 Bob: 22 Cal: 33 Dan: 44 Note there's also the similar System.out.printf method that behaves the same way, but if you peek at the implementation, printf just calls format, so you might as well use format directly. * *Varargs *PrintStream#format(String format, Object... args) *PrintStream#printf(String format, Object... args) A: The variable arguments must be the last of the parameters specified in your function declaration. If you try to specify another parameter after the variable arguments, the compiler will complain since there is no way to determine how many of the parameters actually belong to the variable argument. void print(final String format, final String... arguments) { System.out.format( format, arguments ); } A: You can pass all similar type values in the function while calling it. In the function definition put a array so that all the passed values can be collected in that array. e.g. . static void demo (String ... stringArray) { your code goes here where read the array stringArray }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "73" }
Q: Why does element style override class that is set on element? Our problem is like this. We have piece of code like this. <div class="parent"> <div class="child"> <a href="#" class="child_item" onclick="return false;" onfocus="blur();">Item 1</a> </div> <div class="child"> <a href="#" class="child_item" onclick="return false;" onfocus="blur();">Item 2</a> </div> <div class="child"> <a href="#" class="child_item" onclick="return false;" onfocus="blur();">Item 3</a> </div> <div class="child"> <a href="#" class="child_item" onclick="return false;" onfocus="blur();">Item 4</a> </div> <div class="clear"> </div> </div> This is all in global container with class .content. CSS code: .content a { font-size: 11px; } .parent a { font-size: 16px; } For some reason, instead of applying .parent a, browsers are applying .content a. What is wrong and how come container CSS is applied instead of closer .parent a CSS? A: Both rules have the same specificity, so whichever rule comes last in the style declarations will win... Are you sure that the .parent a-rule is specified after the .content a-rule? Another way to solve it would be to increase the specificity slightly, i.e: .parent .child_item { font-size: 16px; } Edit: You can play around with your test case here: http://jsfiddle.net/gburw/ To prove my point, try switching the CSS-declarations and you will see that whichever rule is defined last will "win". Edit 2: You can read more about CSS specificity here. It's a pretty simple concept to grasp, the hard part is avoiding specificity wars with fellow developers =) So you should come up with a standard way you write CSS in your company. Following the guidelines of Pagespeed and YSlow is also always a good idea. A: Or if you really want .parent a to be applied. You can do this: .parent a{ font-size:16px !important; } that will give it more weight than .content a regardless of which was declared last. A: Sounds like an issue of CSS Specificity. Check to make sure that your CSS selectors are actually: .content a { font-size: 11px; } .parent a { font-size: 16px; } and not someting like #container .content a. You could also increase the specificity of .parent a to .parent .child a if that's not the case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Chrome OS in VMPlayer Trying to create a virtual machine using VMPlayer, I discovered that as the Chrome OS is now a Release Candidate, it is only available here: http://www.getchrome.eu/download.php However, there is no .vmdk download but "Live CD" and "USB Disk Image". I've downloaded the "Live CD", but the VMPlayer couldn't create a new machine. Ive tried several samples from the internet, using the following methods: * *Create it as Ubuntu. *Create it as a 2.6.x kernel. *Create a blank VM and point the HD to the .iso file. I keep getting" "Failed to mount RW root filesystem" and then there's a 120 seconds suspension before a reboot (which causes the same error). The screen shot of the log (Alt+F3): What am I missing? A: In the link you've shared there is no .vmdk (and I couldn't find it around the web). So if I were in your shoes I would go to: http://www.chromium.org/chromium-os/developer-guide#TOC-Building-Chromium-OS and try to built it with the spec (cpu, mem etc') that you have on the VMPlayer. Another option is to try and install a built that someone did: http://www.tomshardware.com/news/chrome-os-google-vmware-download,9124.html Good luck. A: You can try Chrome OS by deploying ready-to-use Chrome OS VMs by hexxeh.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt: Properly store image resource for custom widget I'm making a custom widget in Qt, and drawing an image as its background. The background image is to be exactly the same for all instances of widgets. I'd like to know if I'm doing it in an appropriate way. Here's how I'm doing it now: // QMyWidget.h class QMyWidget : public QWidget { /* some stuff.. and then: */ protected: static QImage *imgBackground; } // QMyWidget.cpp QImage *QMyWidget::imgDial = NULL; QMyWidget::QMyWidget(QWidget *parent) : QWidget(parent) { if(imgBackground== NULL) { imgBackground= new QImage(); imgBackground->load(":/Images/background.png"); } } void QMyWidget::paintEvent(QPaintEvent *e) { QPainter painter(this); painter.drawImage(QPoint(), *imgBackground); } The code works just fine, but is this considered a good way to do it? A: That's one way of doing it, and it's a reasonably good way if you're only dealing with a single image, but if you ever decide to scale and use a couple of custom resources then the Qt Resource System is the better way to do it. It'll save you time in code (don't need to repeatedly do QImage), and has a few other nice features like resource compression.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to Convert C# Desktop Application Project to website I Created an application in my desktop using c#. I want to use this application in my website. Is it Possible or there is any other way. A: It is impossible unless you rewrite the application for Web. They are totally different things.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: click the image and remove the active class Is there a way where it is possible to remove the active class on red btn when I click on my img and then make blue btn class active? HTML <div id="nav"> <ul> <li class="red btn"><a class="tildig" href="#din_app" data-transition="fade" > <p>TIL DIG</p> </a></li> <li class="blue btn"><a class="kontakt" href="#kontakt" data-transition="fade" > <p>KONTAKT</p> </a></li> </ul> </div> <div data-role="page" id="interesseret"> <div data-role="header" data-nobackbtn="true"> </div> <div data-role="content"> <p class="brod"> <a href="#kontakt" data-transition="fade"><img class="kontakt_link_480" src="image/link_img.png" width="480" height="100" alt="Tryk p&aring; kontakt og book et m&oslash;de" ></a></p> </div> <div data-role="footer"> </div> </div> Script <script type="application/x-javascript"> $(function() { $('li.btn').click(function(){ // Add "active" to the clicked element and // get all siblings and remove "active" from them $(this).addClass('active').siblings().removeClass('active'); }); }); CSS .red.btn { float:left; margin: 0 0 0 5px ; width: 40%; height:30px; background-image:url(../image/rod_bnt.png);} .red.btn.active { background-image:url(../image/red.jpg); height: 40px; background-position:center;} .blue.btn {float:right; margin:0 5px 0 0; height:30px; width: 40%; background-image:url(../image/blaa_bnt.png); } .blue.btn.active { background-image:url(../image/blue.jpg); height: 40px; background-position:center;} I tried this but it does not work <script type="application/x-javascript"> $(function() { $('a.img').click(function(){ // Add "active" to the clicked element and // get all siblings and remove "active" from them $(this).addClass('blue.btn.active').siblings().removeClass('red.btn.active'); }); }); </script> // thanks in advance Kasper. A: You could do: $('a img').click(function(){ // Add "active" to the blu li element and $('li.blue').addClass('active'); // remove "active" from the red element $('li.red').removeClass('active'); }); A: If you just want to add active to blue and remove from red: <script type="application/x-javascript"> $(function() { $('a.img').click(function(){ $('.blue.btn').addClass('active'); $('.red.btn').removeClass('active'); }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7607371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Evaluating formula in SQL I am trying to process salary details of employees depends upon some schedule using SQL Server 2005. Here some fields are evaluating from formula. like..eg. HRA=(BS+Earning1)*10/100 here formula is getting from Table, it'll vary for diff accounts(HRA, Medical Allavance etc). Value of formula operators (eg. BS, Earning1) are in table. I want to replace operator strings with its value and to get formula result. Thanks in advance. A: Depends on the table and data. This should help. SELECT account, (BS+Earning1)*10/100 as [SaleryFormula] FROM Table BS will be replaced with the value in BS column for that account. That assumes each account has a single record in the Table. Otherwise SELECT account, (SUM(BS)+SUM(Earning1))*10/100 as [SaleryFormula] FROM Table GROUP BY account
{ "language": "en", "url": "https://stackoverflow.com/questions/7607374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL - retrieve a value from another table if column is null Let's say I have a table setup with a few values, including a name, an ID, and a foreign key that references the ID of another table. The name can be null. When I select all the records from this table, I want to get the name if it is not null. If it is, I want to get the name of the record referenced by the foreign key. I am able to modify the database structure if necessary, or I can simply change the query. What are my options? A: Use IFNULL or COALESCE: SELECT T1.ID, IFNULL(T1.name, T2.name) AS name FROM firsttable T1 LEFT JOIN secondtable T2 ON T1.T2_id = T2.id A: Use ISNULL for sql SELECT T1.ID, ISNULL(T1.name, T2.name) AS name FROM firsttable T1 LEFT JOIN secondtable T2 ON T1.T2_id = T2.id
{ "language": "en", "url": "https://stackoverflow.com/questions/7607382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: vb.net Regex Improving Performance with compiling and shared variables I am writing some code that uses fixed regexs to search strings and pattern match. Its simple stuff, but I want to improve regex performance with compiling (its a high traffic website). I was thinking of compiling the regex and putting it in a Shared (static) variable inside a class. Something like this: Namespace Regexs Public Class UrlNickname Private Shared rgx As Regex = New Regex("^\/\w{4,20}$", RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant Or RegexOptions.Compiled) ''' <summary> ''' Returns a Nickname string if pattern found in Url, otherwise returns Empty string. ''' </summary> ''' <param name="url">The Url string to search.</param> ''' <returns></returns> ''' <remarks></remarks> Public Shared Function ContainsNickname(url As String) As String If rgx.IsMatch(url) Then Return url.Substring(1, url.Length - 1) End If Return String.Empty End Function End Class End Namespace Then you could use the function like this: Dim url As String = HttpContext.Current.Request.RawUrl Dim nickname As String = Regexs.UrlNickname.ContainsNickname(url) If Not String.IsNullOrEmpty(nickname) Then //nickname pattern match found: //do something like RedirectToRoutePermanent End If Basically , I store the regex in a Shared (static) variable so that is only compiled once. The function would then be called to check if a username pattern match was found on a 404 error page. Whould this be the best approach for improving regex performance? Note: I am not interested in a solution for 404 error page problems above, its just a simple example. Further advances could then use a Shared generic list of regexs , like so: Private Shared _rgxList As List(Of Regex) Public Sub New() //get list of regex expressions from database and populate: _rgxList.Add(New Regex("blah", RegexOptions.Compiled)) _rgxList.Add(New Regex("blah2", RegexOptions.Compiled)) Public Shared Function IsMatch(str) as Boolean With each reg in _rgxList return reg.IsMatch(str) New() would be called on Application.Start event. A: Looks fine. In addition, I'd make the Shared variable ReadOnly, to avoid accidental changes. Note, however, that compiling regular expressions increases performance by about 30% at runtime, but it also has its downsides, in particular, it requires more memory. A nice comparison can be found here: * *Coding Horror: To Compile or Not To Compile So, there's no general "A is better than B" answer here. It all depends on your exact requirements. You might have to do measurements to find out what performs better in your particular case. General advice on performance tuning: Make sure that something is really the performance bottleneck before improving it. It doesn't matter if your regex takes 0.01 or 0.02 seconds, if, for example, looking up the nickname in the databsae takes 2 seconds. Use built-in tools from the .net Framework (e.g. Stopwatch Class) or external tools (e.g. EQATEC Profiler) to find out where your bottlenecks are.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting return status AND program output I need to use Lua to run a binary program that may write something in its stdout and also returns a status code (also known as "exit status"). I searched the web and couldn't find something that does what I need. However I found out that in Lua: * *os.execute() returns the status code *io.popen() returns a file handler that can be used to read process output However I need both. Writing a wrapper function that runs both functions behind the scene is not an option because of process overhead and possibly changes in result on consecutive runs. I need to write a function like this: function run(binpath) ... return output,exitcode end Does anyone has an idea how this problem can be solved? PS. the target system rung Linux. A: I can't use Lua 5.2, I use this helper function. function execute_command(command) local tmpfile = '/tmp/lua_execute_tmp_file' local exit = os.execute(command .. ' > ' .. tmpfile .. ' 2> ' .. tmpfile .. '.err') local stdout_file = io.open(tmpfile) local stdout = stdout_file:read("*all") local stderr_file = io.open(tmpfile .. '.err') local stderr = stderr_file:read("*all") stdout_file:close() stderr_file:close() return exit, stdout, stderr end A: This is how I do it. local process = io.popen('command; echo $?') -- echo return code of last run command local lastline for line in process:lines() do lastline = line end print(lastline) -- the return code is the last line of output If the last line has fixed length you can read it directly using file:seek("end", -offset), offset should be the length of the last line in bytes. A: This functionality is provided in C by pclose. Upon successful return, pclose() shall return the termination status of the command language interpreter. The interpreter returns the termination status of its child. But Lua doesn't do this right (io.close always returns true). I haven't dug into these threads but some people are complaining about this brain damage. * *http://lua-users.org/lists/lua-l/2004-05/msg00005.html *http://lua-users.org/lists/lua-l/2011-02/msg00387.html A: With Lua 5.2 I can do the following and it works -- This will open the file local file = io.popen('dmesg') -- This will read all of the output, as always local output = file:read('*all') -- This will get a table with some return stuff -- rc[1] will be true, false or nil -- rc[3] will be the signal local rc = {file:close()} I hope this helps! A: If you're running this code on Win32 or in a POSIX environment, you could try this Lua extension: http://code.google.com/p/lua-ex-api/ Alternatively, you could write a small shell script (assuming bash or similar is available) that: * *executes the correct executable, capturing the exit code into a shell variable, *prints a newline and terminal character/string onto standard out *prints the shell variables value (the exit code) onto standard out Then, capture all the output of io.popen and parse backward. Full disclosure: I'm not a Lua developer. A: yes , your are right that os.execute() has returns and it's very simple if you understand how to run your command with and with out lua you also may want to know how many variables it returns , and it might take a while , but i think you can try local a, b, c, d, e=os.execute(-what ever your command is-) for my example a is an first returned argument , b is the second returned argument , and etc.. i think i answered your question right, based off of what you are asking.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: using push registry Alarm in j2me applicaiton I want to make the application where i want to set the alarm at particular time in the day.When the alarm rings the pop up message will came and the one .txt file from the application will move to the server. Does any one help me how to use set this alarm through push notification.Or is there any other way to do this task without using push notification. please help me Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/7607386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android.database.sqlite.SQLiteException: no such table: TableName I have a database [sqllite] in my assets folder and it have all the tables and fields which I have given in my query. But still while executing the app it shows some sqlite error like 09-30 13:09:53.656: ERROR/AndroidRuntime(334): Caused by: android.database.sqlite.SQLiteException: no such table: Table_name Query Happy Coding..! A: I solved the "no such table" exception by simple tricks. So first in the method createDatabse(), replace the "Error copying databse" with e.toString() so that you can see the real problem you are up against. Lets begin: first, the emulator will not check your database for any changes hence the many instances of same error no matter what you do. You need to trick it that the database it had stored nolonger exists then let it raise an error. If none of that works, try my dirty trick. You will need do clear the app settings on the emulator Settings->Apps->YOUR_APP->Clear Data. But don't stop there. You will then delete the database from the assets folder, right click app folder->Refresh, and copy into the folder the new database. Right click on the assets->Build Path->Use as Source Folder. I used a trick to inform the ide that I had no db, by commenting out this.getReadableDatabase(); then running the app so that it raises an error, then I un-commented and it worked well. I have done this twice now
{ "language": "en", "url": "https://stackoverflow.com/questions/7607390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to obtain information about downloads, total installation, and active installation from my published android applications programmatically? I have a few questions regarding android market(Google play). How can I list my published application by accessing from my google account? What I have done so far is using my application package name as a query string to search my application and display all information which I used android market api to do it. Is there another better way to display all my published or installed applications by accessing from my google accounts? My second question is about detecting number of downloading and installations of my published application. I have found only google analytics so far(for free) which I need to embedded some codes to monitoring my application. Is it possible for me to access those information from android market publish page . I have found that publish page contains information that I need. Edited: For second question, I would like to obtain statistical information without adding any new code to my application. Is it possible to provide only google account to grant the permission to get those information? My application is published. If I am using google analytics to monitoring my application do I need to start my counting from zero? Sorry for my English and my little knowledge about this. Thanks in advance.. Edited: .. I have found an application, called "analytics" that is what exactly I want to do. But I still cannot figure it out how it works.. A: The only place you will find this kind of information is on your Developer page. That said, if I were wanting to do what you are, I would put up an app on App Engine that either parsed my Dev page on request, or on a schedule. I mention App Engine as personal preference here, you could obviously use anywhere you can host scripts on. You can then do what you like with the data you have collected, and your app can request this from your site. Assuming you have no qualms with publicising these numbers, you wouldn't need to scare users by authenticating, and would just need a plain html request. Edit: In your language of choice, you would need to request your developer page (the one that lists apps and their install count) and would also need to authenticate as yourself to get it. It's for this reason I would use your own hosting if you can. I can't be more specific than this, as I don't know what language you're most likely to be using. It should be trivial to find out how to do an html request and step through the page in whatever language it is though. App Engine pages are written in Java or Python and deployed to the server, while other obvious options are PHP or Perl. On my own server I would most likely use Perl as it's ideal for ripping up html with regexps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change the class of a input field Sorry. Let me rephrase: I want js to change to class of a input field if it is left empty; Here is my code to detect a empty field: function validateForm() { var ctrl = document.forms["form1"]["username"]; var x=ctrl.value; if (x==null || x=="") { ////////////CHANGE INPUT CLASS///////////// } else { document.getElementById('username').style.backgroundColor="#FFFFFF"; } } i would have to css classes: .inputfield { background-color:white; } .inputfieldempty { background-color:red; } A: Have a look at this tutorial for the excellent jQuery Validation plugin, which does exactly what you need and you don't even have to fiddle with cross-browser concerns. If you don't want to use the plugin, I still recommend at least to use jQuery. Here's another tutorial that goes through all the necessary steps. A: To prevent submitting you need to call a function for the onsubmit event of the form (e.g. onsubmit="return checkFields()". In the function you will do the validations and return true or false depending on that. If the function will return false then the form will not be posted. As part of your validations when you determine that a field's value is empty you can do the desired css changes as well. I don't know if you use vanilla javascript or a library such as jQuery in order to give more specific details. A: This post should take care of adding your CSS classes: Change an element's class with JavaScript This post should take care of preventing forms to submit: https://developer.mozilla.org/en/DOM/event.preventDefault
{ "language": "en", "url": "https://stackoverflow.com/questions/7607396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Executing a thread inside AsyncTask's doInBackground() I have several AsyncTasks doing network operations. I was recently asked to add, after each of these operations, another network call that invokes a remote service sending some statistics. I'd like this statistics call not to delay 'main' network calls, and so I was thinking of executing them in a thread created and started inside the AsyncTask's doInBackground(). This thread would most probably end after the doInBackground() and possibly the whole AsyncTask has ended. I tried this and it works, but I was wondering if there are side effects, such as memory leaks or similar? Thanks ;) A: Try starting a second AsyncTask in the first AsyncTasks 'onPostExecute' Method. For me this worked without any issues. A: If you want to start thread in doInBackground method, you can start it in onProgressUpdate() method Example: protected class MyTask extends AsyncTask<Void,Integer,Void> { public static final int START_THREAD = -1; @Override protected void onProgressUpdate(Integer... values) { if(values[0] == START_THREAD){ startThread(); } } @Override protected Void doInBackground(Void... params) { publishProgress(START_THREAD); return null; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Calling a method of an object through a Vector This is a part of a larger program that I'm doing where the user can create a Flight object by entering data into JTextFields. The data is stored into a Vector, called flightList. On a second panel of my JApplet, the user can use a JComboBox - flightBox - to select one of the Flights that they have created. When the Flight is selected from the JComboBox, the getPrice() method needs to be called for the selected Flight object, and displayed in a JLabel below. private class ChoiceListener implements ActionListener { public void actionPerformed(ActionEvent event) { //needs to be completed if (flightBox.getSelectedIndex() == 0) { //flightBox.getSelectedItem(); // returns selected object outro.setText("The price for your flight is:"); int p = flightBox.getSelectedIndex(); Flight selectedFlight = flightList.get(p); String selectedPrice = money.format(selectedFlight.getPrice()) + ""; fPrice.setText(selectedPrice); } } I thought I was on the right track, and I've tried a lot of different variations but none seem to be working. Also, I know that the Flights are being added to flightList, because the JComboBox does display all added Flights. I've got all the labels set up correctly, I think. I just need to figure out how to actually get the selected Flight object from flightList using the flightBox, and pull that price value from it using the getPrice method. EDIT From the CreatePanel class (initializing variables and storing the Flight object into the flightList Vector from JTextFields). CityTime departure = new CityTime(); departure.setCity(dC); departure.setDate(dD); departure.setTime(dT); CityTime arrival = new CityTime(); arrival.setCity(aC); arrival.setDate(aD); arrival.setTime(aT); Flight newFlight = new Flight(); newFlight.setAirlines(air); newFlight.setFlightNum(iNum = Integer.parseInt(num)); newFlight.setPrice(dPrc = Double.parseDouble(prc)); newFlight.setDeparture(dC, dD, dT); newFlight.setArrival(aC, aD, aT); flightList.add(newFlight); From the Flight class: public class Flight { // Flight constructor and all other variables/accessors/mutators are added here as well. private double price; public double getPrice() { return price; } } EDIT Completed code: if (flightBox.getSelectedIndex() != -1) { //flightBox.getSelectedItem(); // returns selected object outro.setText("The price for your flight is:"); int p = flightBox.getSelectedIndex(); Flight selectedFlight = flightList.get(p); String selectedPrice = money.format(selectedFlight.getPrice()) + ""; fPrice.setText(selectedPrice); } All flightList Vectors have been updated with the element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finish activity after toast message disappears? Does anybody know, if there is a possibility to do something (in my case finish activity) on toast message will be closed? A: android.widget.Toast doesn't offer any listeners for informing when it is finished. You may call Toast.getDuration() to learn how long it will last, and make your own TimerTask to run at the time when Toast vanishes, and do your tasks there. A: Yes, but this is a trick way Android Toast doesn't have a way to set a callback after it finished. So what you can do is based on this fact private static final int LONG_DELAY = 3500; // 3.5 seconds private static final int SHORT_DELAY = 2000; // 2 seconds now you can do: * *Set up the toast *Set up a counter thread based on the LENGTH_LONG (3.5s) or LENGTH_SHORT(2s) to close the activity. *toast.show() and thread.start(); A: You do that simply by creating a Thread that lasts as long as the Toast is displayed and then you can finish your Activity. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // your other stuff Toast.makeText(this,"This is a Toast", Toast.LENGTH_LONG).show(); thread.start(); } Now create use a Handler that waits for (LENGTH_LONG = 3.5) or (LENGTH_SHORT = 2) seconds Handler().postDelayed({...},Toast.LENGTH_LONG * 1000); A: Here's how I do it... Note that this class includes a call to close down the activity that called it. You can take that out if needed. Also, note that the sleep times track the toast duration, but i've added an extra half second to give a little margin before the activity is ended. public class Toaster implements Runnable { Context theContext; CharSequence theMessage; int theDuration; Activity theActivity; public Toaster( Activity a, Context c, CharSequence s, int i ) { theActivity = a; theContext = c; theMessage = s; theDuration = i; } @Override public void run() { Toast toast = Toast.makeText(theContext, theMessage, theDuration ); toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL, 0, 0); toast.show(); Thread t = new Thread( new Runnable() { @Override public void run() { try { Thread.sleep(theDuration == Toast.LENGTH_SHORT ? 2500 : 4000); } catch (InterruptedException e) { e.printStackTrace(); } theActivity.finish(); } }); t.start(); } } In the activity, there's a chunk of code that looks like this, to call it: Context c = getApplicationContext(); CharSequence msg = "Form Data Submitted!"; int duration = Toast.LENGTH_SHORT; runOnUiThread( new Toaster(this, c, msg, duration) ); A: Actually there are no callbacks when a Toast is being finished, but if you need to know, when will it be closed, you can start a background thread that will sleep a number of milliseconds equal to the Toast duration, and then execute the needed operation. This is just one way of solving the issue, I'm sure there are more solutions. Hope this helps. A: It should first display Toast then after 2 seconds, it will finish your activity. Toast.makeText(YourActivity.this, "MESSAGE", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { YourActivity.this.finish(); } }, 2000); A: I'm not sure you can do this with Toasts, however, you could replace the toast by a simple dialog (and reuse the Toast design if you want), and then you could use methods such as onDetachedFromWindow to hook the closure of the activity to the window's. A: I'm not sure what your use case is, but do you really need to wait for the toast to close to finish your activity? In my case, I have an activity that is an entry point into the app from a url (allowing the app to be opened from a link in an email or on a web page). If the url doesn't pass a validation check, I show a toast and finish the activity: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... if (!validateUrl()) { Toast.makeText(this, R.string.invalid_url, Toast.LENGTH_LONG).show(); finish(); return; } ... } This shows the toast and I don't have to wait until it's no longer displayed before calling finish(). Initially, I thought this wasn't working, but then I discovered it was because I forgot to call show() on the toast! A: I've just make a simple library for that "issue" Download: https://github.com/mkiisoft/Toaster and use it this way: Toaster.getInstance().makeText(context, "your custom message", Toast.LENGTH_SHORT, new OnToasterFinish() { @Override public void finish() { // Your code over here after the Toast } }); A: Afaik the INotificationManager API (which is used under the hood of the toast class) does not have any support for notifying the caller when it closes the Toast. There's also no way to check if the Toast is showing or hidden without using reflection to pick out the inner class that represents the transient notification. A: You call the toast, thn finish using the Onstop(). Your toast now will appear. A: Extend the Toast-Class and use your own Callback. A: As of API level 30, there is an addCallback method for the Toast class. See here: addCallback documentation A: Since API 30 Toast.Callback is available: https://developer.android.com/reference/android/widget/Toast.Callback Example: val toast = Toast.makeText(requireContext(), "wow", Toast.LENGTH_LONG) toast.show() toast.addCallback(object : Toast.Callback() { override fun onToastShown() { super.onToastShown() Log.d("toast_log", "toast is showing") } override fun onToastHidden() { super.onToastHidden() Log.d("toast_log", "toast is hidden") } })
{ "language": "en", "url": "https://stackoverflow.com/questions/7607410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Any in-framework way to prevent Cross Site Request Forgery (CSRF) within ASP .NET 4.0 (not MVC)? Is there any in-framework way to prevent Cross Site Request Forgery (CSRF) within ASP .NET 4.0 Web forms based websites (not MVC)? I do see the framework generate __EVENTVALIDATION and __VIEWSTATE hidden form fields and I've encrypted them via machineKey and viewStateEncryptionMode="Always" in my web.config. However, it's not clear if they can actually prevent CSRF attacks. I tested a cross posting (via PostBackUrl in the form's asp:Button) form where I modified the __VIEWSTATE, __EVENTVALIDATION and __PREVIOUSPAGE (extra for cross posts) hidden, encrypted form fields and the other sensitive form fields still reached my code-behind processing block. I was expecting the framework to detect the modified encrypted fields and throw up an error. FYI, I saved the aspx as an .html, changed those hidden form fields and re-used the form (now in .html) to simulate an attacker. So I could still post to my sensitive form/fields because (start speculation) .html files don't go through the ASP.NET processing engine? (/end speculation) If no such in-framework mechanism exists, are there any code snippets for quick prototyping/usage? I can easily create a per-user unique identifier by hashing the user ID and even set a form hidden variable for that c# variable. But the ASP.NET 4.0 mechanics of * *Also setting that c# variable as a cookie and * *Checking if the cookie value == form value on subsequent requests (for validity) is unclear to me. A: I don't know how to do it in the framework, but you can do it yourself easier than your post suggests. You don't need to set the cookie value. Its just how the mvc framework does it as an optimization\ to allow the server to be stateless. All you need to do to pick some random ( to an attacker) value and add it as a hidden field in your form. When you get the data back, verify that that value is in the form. Don't just hash the userid, hash the userid and some secrete random value. That way the attacker can't compute the hidden value if she knows a user id. Because the same origin policy prevents attacker.com from reading the markup for your site, they can't read the hidden value. Thus the CSRF post they make, while having your cookie ( and hence the view state), won't have that value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to write rspec for private method in controller with params I have controller class ApplicationController < ActionController::Base def index end private def handle_login_sequence username = params[:userName] password = params[:password] cookies[:locale] = params[:locale] remember = params[:remember] username_locked = User.locked_username?(username) user = User.authenticate(username, password) if user && user.has_portal_access? case user.account_status when AccountStatus::Active flash[:error] = 'login' end end end end I want to write Rspec for this private method @controller = ApplicationController.new @controller.send(:handle_login_sequence) By the above code I can call handle_login_sequence method but I don't know how to pass the below: params[:userName], params[:password], params[:locale], params[:remember] A: You shouldn't test private methods of a controller directly. Instead, test the controller action that uses this method. Don't forget about black box metaphor with regards to your controllers. If you test private methods, you'll have to rewrite tests when you want to change the just the implementation and not the interface. Black box tests will help you to make sure that you haven't broken your controller functionality without directly testing the private methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Two Identical Code Segments, Different Results All I need to do is a simple read from a file in the same directory, but for some reason it refuses to work. It works perfectly fine in this quick test one I made after I had problems, and outputs the number of entries in the text file. #include <iostream> using std::cout; using std::cin; #include <cstdio> int main() { int a; int b = 0; freopen ("7.txt", "r", stdin); while (cin >> a) ++b; cin.clear(); fclose (stdin); freopen ("7.txt", "r", stdin); cout << b << '\n'; fclose (stdin); } EDIT: Wow I'm sorry to everyone who tried wrapping their heads around this. It was pretty late when I posted this, but I thought I finished. Apparently not. Now upon reopening my file to post the code in it, I realize that I moved everything into a folder before, but apparently when I tried to run the actual thing, it saved back outside of the folder, so it couldn't open "7.txt". Problem solved I guess, sad waste of space seeing as how it wasn't even complete O_o, sorry. EDIT2: Okay now I'm confused. I had a temp account on this computer, but when I logged into this account to ask a different question, this one as I meant to post it the other night showed up. I wasn't even on this computer while asking it. Not sure why it wasn't posted like that if it was all ready to be though. A: My best "guess" is that you are trying to re-read the same file. If this is the case then you could try this : std::ifstream file("7.txt"); std::string line = ""; while(std::getline(file, line)) { //do something } //reset file pointer file.clear(); file.seekg (0, std::ios::beg); //re-read file while(std::getline(file, line)) { //do something else } Please try and formulate better questions in the future. A: I have no idea what you're trying to do, but any interaction between freopen, fclose and cin is implementation defined at best (and most likely undefined behavior).
{ "language": "en", "url": "https://stackoverflow.com/questions/7607420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JAVA nontoop/apns certificate I have java application and I want to send push notification. I use nontoop/apns library. In this line of code which certificate should I use instead cert variable? ApnsService service = APNS.newService().withCert(cert, "atajerBritecs") .withSandboxDestination().build(); Thnaks in advance A: It looks like you are calling the ".withSandboxDestination()" so you will want to use the Development Push SSL Certificate. This can be configured in the "App Ids" section. Note to configure your App in the "App Ids" section you need to be Team Agent
{ "language": "en", "url": "https://stackoverflow.com/questions/7607426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run Flash in WPF i am trying to run a .swf file in my WPF application, i have created a html page and in that i have referenced my .swf file using object tag and then loading that html page in my Main Window my xaml looks like <Window x:Class="sirajflash.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <WebBrowser Name="myBrowser"></WebBrowser> <!--<Frame Name="myframe"/>--> //tried with frame also but no luck </Grid> </Window> assigning the source public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); myBrowser.Source = new Uri(CreateAbsolutePathTo("playflash.htm"), UriKind.Absolute); } private static string CreateAbsolutePathTo(string mediaFile) { return System.IO.Path.Combine(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName, mediaFile); } } The Problem: when i run the application the warning occurs that ActiveX content is trying to access etc etc and when i allow it nothing appears in my main window the warning keeps on occuring multiple times. if i run the flash movie in the browser directly it runs just fine. Regards. A: * *I have a flash based clock as a .swf file on my C:\Test\MyClock.swf *I have a htm file at C:\Test\MyHtml.htm <embed src=C:\Test\MyClock.swf width=200 height=200 wmode=transparent type=application/x-shockwave-flash> </embed> *I have web browser control as below... <Window x:Class="MyFlashApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <WebBrowser Source="C:\Test\MyHtml.htm"></WebBrowser> </Grid> </Window> *On running the app, I see the webbrowser control giving warning as "To help protect your security, Internet Explorer has restricted this file from showing active content that could access your computer. Click here for options." *I accept the warning by right click and the left click "Allow Blocked Content". A confirmation popup appears to which I say Yes. *I see the Flash based clock. A: WebBrowser control can support flash directly . If you don't need to present anything in HTML then you can directly provide the path to the flash file . myWebBrowser.Source = "C:\Test\MyClock.swf" However you will still get the IE warning message.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: c++ cross access to classes methods I'm not very experienced in cpp (used to work in python). I have the following problem: 1) I have a main class A (a window) and the methods m_A1 and m_A2 2) I have a little class B (a dialog) with a callback m_B1 3) the class B is instantiated and destroyed inside of m_A1 4) from the callback m_B1 I need to call m_A2 I tried to give to B reference to the instance of A (with 'this') but this solution that worked in python here doesn't. I tried to declare the class B inside of A to have the methods of A accessible inside of B but I can't understand how to write the code of the methods of B, writing for example the class constructor of B would be A::B::A::B() but gives syntax errors. Here's some code: class Centrino { public: Centrino(); virtual ~Centrino(); Gtk::Window *mp_window; protected: ... bool on_window_key_press(GdkEventKey *event); void io_process_incoming_command(char *in_str_complete); ... }; class DebugDialog : public Gtk::Dialog { public: DebugDialog(const char *title, Gtk::Window& parent, bool modal); virtual ~DebugDialog() {}; protected: void on_button_send_clicked(); ... }; void Centrino::io_process_incoming_command(char *in_str_complete) { ... } bool Centrino::on_window_key_press(GdkEventKey *event_key) { if(event_key->state & GDK_CONTROL_MASK) { if((event_key->keyval == GDK_KEY_d) || (event_key->keyval == GDK_KEY_D)) { DebugDialog dialog("Debug Dialog", *mp_window, true); int response = dialog.run(); } } ... } void DebugDialog::on_button_send_clicked() { Glib::ustring entry_content = m_entry.get_text(); io_process_incoming_command(entry_content.c_str()); } Centrino is the class that I called A, DebugDialog is the class that I called B. From DebugDialog:: on_button_send_clicked() I need to call Centrino:: io_process_incoming_command(). The scope of the class DebugDialog instance is inside of Centrino:: on_window_key_press(). Can anybody point me to an example? Thanks in advance. A: The scope of DebugDialog is global, and as written, DebugDialog has no knowledge of the context in which it was created. You need to pass and save this information explicitly: class DebugDialog : public Gtk::Dialog { Centrino* myOwner; public: DebugDialog( Centrino* owner, const char *title, Gtk::Window& parent, bool modal ); virtual ~DebugDialog() {}; protected: void on_button_send_clicked(); ... }; DebugDialog::DebugDialog( Centrino* owner... ) : myOwner( owner ) , ... void Centrino::io_process_incoming_command(char *in_str_complete) { ... } bool Centrino::on_window_key_press(GdkEventKey *event_key) { if(event_key->state & GDK_CONTROL_MASK) { if((event_key->keyval == GDK_KEY_d) || (event_key->keyval == GDK_KEY_D)) { DebugDialog dialog(this, "Debug Dialog", *mp_window, true); int response = dialog.run(); } } ... } void DebugDialog::on_button_send_clicked() { Glib::ustring entry_content = m_entry.get_text(); myOwner->io_process_incoming_command(entry_content.c_str()); } A: Add a Centrino reference in DebugDialog attributes and provide it in DebugDialog contructor. Declare Centrino::io_process_incoming_command() method public and invoke it from DebugDialog::on_button_send_clicked() method: class Centrino { public: Centrino(); virtual ~Centrino(); Gtk::Window *mp_window; void io_process_incoming_command(char *in_str_complete); protected: ... bool on_window_key_press(GdkEventKey *event); ... }; bool Centrino::on_window_key_press(GdkEventKey *event_key) { if(event_key->state & GDK_CONTROL_MASK) { if((event_key->keyval == GDK_KEY_d) || (event_key->keyval == GDK_KEY_D)) { DebugDialog dialog("Debug Dialog", *mp_window, true, *this); int response = dialog.run(); } } ... } class DebugDialog : public Gtk::Dialog { public: DebugDialog(const char *title, Gtk::Window& parent, bool modal, Centrino &centrino); virtual ~DebugDialog() {}; protected: void on_button_send_clicked(); ... Centrino &centrino_; }; DebugDialog::DebugDialog(const char *title, Gtk::Window& parent, bool modal, Centrino &centrino) : .... centrino_(centrino) { ... } void DebugDialog::on_button_send_clicked() { Glib::ustring entry_content = m_entry.get_text(); centrino_.io_process_incoming_command(entry_content.c_str()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Basic Authentication with Twitter and Facebook Is there a way to authenticate to Facebook / Twitter using basic authentication? the application I am working on requires posting to those two sites without the need to open the oAuth Dialog. A: Both twitter & facebook don't support basic auth. A: No, thank goodness. Basic authentication requires that you take the user's password, which is a secret between them and Twitter/Facebook. You shouldn't be asking for it. If your app is physically unable to display the dialog, OAuth 2.0 (not available on Twitter) offers a way (last I checked) for an independent web browser on another computer to perform the OAuth authorization process to your app running on some limited device.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sending mail with css is not applying in zend I am using zend.Following is my piece of code in my Action ....... // create view object $html = new Zend_View(); $html->setScriptPath(APPLICATION_PATH . '/layouts/scripts/'); // assign values $html->assign('OrderList', $this->view->OrderList); $html->assign('title', 'Package Slip'); $html->assign('current_date', date("F d, Y")); // render view $bodyText = $html->render('test.phtml'); $mail = new Zend_Mail('utf-8'); $mail->setBodyHtml($bodyText) ->setFrom('noreply@metalxplus.com', 'admin') ->addTo('dineshkumar.m@openwavecomp.in') ->setSubject('Test'); $mail->send(); ........ When I echo this $bodyText variable before sending mail, I got complete page with css. But when i send it to mail, css is not applying. What i have to do here? Kindly advice A: Many email clients utilise old version of html and therefore do not respect css. Gmail for instance will not respect any css you add to your message. To view output, I suggest using either litmus or email on acid which displays how your message will look across a range of email clients. A: First of all, view the source of the e-mail to see if the e-mail even contains the CSS you expect. If you're using relative paths; this might be the source of the issue. When you visit a page on, say, //example.com/hello, a path such as "/css/style.css" will be requested as "//example.com/css/style.css". An e-mail client has no such luxury; it doesn't have the domainname. You'll have to provide the full path to the CSS, ie "http://example.com/css/style.css". A: For this problem what I did is to apply in-line styles and it works fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: log4net / EventLogAppender is ignoring my LogName This configuration should make my log entries end up in a custom log, right? But it ends up in the Application log. My app is running as admin. After I run my app I can confirm that the Log and event source is created by using EventLog.Exists("MyLog") and EventLog.SourceExists("MyApplication"). <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" > <logName value="MyLog"/> <applicationName value="MyApp" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message %exception%newline" /> </layout> </appender> Edit: I found out what the problem was but I can't "self-answer" my question until 8h has passed. A: I was having the same problem where log4net created my new log, but messages kept getting logged in the Application log. Restarting the Event Viewer did not work, but as per this answer, simply restarting my computer fixed the problem and messages started getting logged to the new log as expected. A: I found out the problem. * *Refresh in Event View does not show new logs. I had to restart the Event Viewer to see my custom logs that I had managed to create. *Most of my log entries did end up in the Application log although I specified a log name. My conclusion is that I probably at some time early today wrote to the log using the same source name but without a log name so that it "stuck". Modifying the source name and starting over fixed the problem. A: Aaah, eventlogs, I so hate them... Is your app's event source registered within your log? Unless it is, everything you write with it will end up in the Application log. You have to register it during installation or manually, using System.Diagnostics.EventLog.CreateEventSource() (e.g. this one http://msdn.microsoft.com/en-us/library/2awhba7a.aspx) Beware of naming issues! A: Try to use <param name="LogName" value="MyLog" /> instead <logName value="MyLog"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7607441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Searching for information in files in several directories I need to check several files which are in different locations for a specific information. So, how to make a script which checks for the argument word through several directories? The directories are in different locations. For ex. /home/check1/ /opt/log/ /var/status/ A: Use the grep -R (recursive) option and give grep multiple directory arguments. A: At the very simplest, it boils down to find . -name '*.c' | xargs grep word to find a given word in all the .c files in the current directory and below. grep -R may also work for you, but it can be a problem if you don't want to search all files. A: You could also do (next to ´find´) do a for DIR in /home/check1 /opt/log /var/status ; do grep -R searchword $DIR; done A: Try find http://content.hccfl.edu/pollock/Unix/FindCmd.htm using your searchwords and the directories. A: The man page of grep should explain what you need. Anyway, if you need to search recursively you can use: grep -R --include=PATTERN "string_to_search" $directory You can also use: --exclude=PATTERN to skip some file --exclude-dir=PATTERN to skip some directories The other option is use find to get the files and pipe it to grep to search the strings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Booleans in Squeryl dynamic queries I'm trying to use Squeryl (0.9.4 for scala 2.8.1) dynamic queries (.? and inhibitWhen(...)). They are working fine while I'm using String/Int/whatever fields, but seem to interfere with squeryl's syntax sugar for boolean conditions. Assuming we have a is_trusted: Option[Boolean] defined somewhere, the following code where ( obj => obj.is_trusted === is_trusted.? ) does not compile, throwing the following error: ... type mismatch; [error] found : org.squeryl.dsl.ast.LogicalBoolean [error] required: org.squeryl.dsl.NonNumericalExpression[org.squeryl.PrimitiveTypeMode.BooleanType] [error] obj.is_trusted === is_trusted.? [error] ^ even this one does not work, failing on the first condition: where ( obj => obj.is_trusted.inhibitWhen(is_trusted == Some(true)) and not(obj.is_trusted).inhibitWhen(is_trusted == Some(false)) ) The only working version uses double not as a hint for the compiler: not(not(obj.is_trusted)).inhibitWhen(is_trusted != Some(true)) and not(obj.is_trusted).inhibitWhen(is_trusted != Some(false)) Is there a more sane way to do dynamic queries with booleans? A: Hmm... I think this is probably another bug caused by an implicit conversion from Boolean -> LogicalBoolean. That feature has been deprecated in 0.9.5 because of issues similar to this. What the .? should do is trigger an implicit conversion from Boolean -> BooleanExpression but since LogicalBoolean has a .? method as well there is a conflict and the latter appears to be have precedence. I know it's not terribly pretty, but try this: where ( obj => obj.is_trusted === is_trusted.~.? ) The .~ should force the conversion to BooleanExpression[Option[Boolean]] before .? is invoked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Zend Framework multiple checkbox I have a multiple check box in zend framework where I have to diaplay image in place of label. For example: <label for="elId-1222"> <input type="checkbox" name="elId[]" id="elId-1222" value="1222" checked="checked" class="inputtext"> <image src="images/yes.png"> </label><br /> So in multioptions I have prepared an array of key and value pair, but how will I be able to add an image in place of value so that above image get displayed in label. My code is as shown below: $multiCheckbox = new Zend_Form_Element_MultiCheckbox( 'elId', array ( 'disableLoadDefaultDecorators' =>true ) ); $multiCheckbox ->setName( 'elId' ) ->setLabel('elId') ->setRequired( false ) ->setAttrib('class', 'inputtext') ->setDecorators( array( 'ViewHelper' ) ) ->setMultiOptions( $options ); A: You can do this by using Decorator ViewScript For example, this is my case: $fanpages = $this->addElement('MultiCheckbox', 'fanpages', array( 'label' => 'Fanpages', 'id' => 'fanpages', )); //Don't check where value come from $this->getElement('fanpages')->setMultiOptions(array()) ->setRegisterInArrayValidator(false); $this->getElement('fanpages')->setDecorators(array(array('ViewScript', array( 'viewScript' => 'loadMyFanpages.phtml', 'class' => 'form_element' )))); views/script/loadMyFanpage.phtml <ul class="jp_listfan"> <?php foreach ($this->element->getMultiOptions() as $option => $value): ?> <li> <input name="fanpages[]" value="<?php echo trim($option); ?>" type="checkbox"/><img src="your/url/images.jpg"/><?php echo trim($value); ?> </li> <?php endforeach; ?> </ul> You can print all element with custom HTML based on your need ^_^ hope this help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery's fadeIn() similar functionality in Silverlight 4 I wish fadeIn() fadeOut() in Silverlight was as easy as jquery made it! I have a grid with 2 controls in it..one chart and another a textblock. At a time only one of them is visible. I wish to have a smooth transition on both of these controls whenever their visibility changes. Whats the simplest way to achieve this? A: For my game, I just set the opacity to increment on a short timer :) (www.aaronahearne.co.uk) if you would like to see an example using CompositionTarget.Rendering Maybe thats not the ideal solution, but thats how we were taught at university to animate in Silverlight A: There's a fade in fade out example on msdn SL animations may not be as easy as jquery but they are much richer. A: The best way to achieve this is to use Blend. Open your user control and add two states to the control using the states tab. Name your two states and then setup each state to have the desired visibility and then set the default transition. You can turn on transition preview and switch between the states to see what it looks like. To have your UI switch between the states add a DataStateBehavior or use a GotToStateAction to swtich them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to reference an embedded image from CSS? This is a NEW question and it is highly related to this topic: How to reference embedded images from CSS? For whatever reason I am forced to post a new thread here, so please see the original thread to understand what the issue is here. I want to create an asp.net server control which bringt an embedded .CSS field and a few embedded image files. From the css I want to use the background-image command to provide the output HTML using this class with the required images. I can't get any of the pointed approaches to work. I tried all variations...: [assembly: System.Web.UI.WebResource("MapBG.png", "image/png")] [assembly: System.Web.UI.WebResource("myWebControls.Resources.MapBG.png", "image/png")] background-image: url(<%=WebResource("myWebControls.Resources.MapBG.png")%>); background-image: url('<%= Page.ClientScript.GetWebResourceUrl(typeof(myWebControls.ElanStatusMap.ElanStatusMap), "MapBG.png") %>'); background-image: url('<%= Page.ClientScript.GetWebResourceUrl(typeof(myWebControls.ElanStatusMap.ElanStatusMap), "myWebControls.Resources.MapBG.png") %>'); Nothing works. Any more ideas on this? A: CSS pages are not rendered like aspx pages, so you can't put server blocks in them. Instead, you can include that CSS in your ASPX page in a <style> block and then you can use this mechanism.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iOS - Log in via Webservice In my app, I have a splitview containing data aquired via a WS call. To recieve this data, the user must be logged in. To log in, I modally present a login screen when the application loads. After entering the credentials, I print out the result from a isLoggedIn WS call. This all works fine and dandy. The problem is that while in the login screen, the isLoggedIn returns that the user is succesfully logged in (including session ID), but when I dismiss the login screen, every WS call fails because the user is not logged in. The session ID's match and the WS recieves the calls, but the iPad seems to remove the session upon dismissing the login screen. This results in the following logs: 2011-09-30 09:37:05.335 DSApp[366:707] url call: http://***/ipadwebservice.asmx/authenticateUser?username=user&password=pass 2011-09-30 09:37:05.508 DSApp[366:707] Call succesful. 2011-09-30 09:37:05.509 DSApp[366:707] Logged in successfully. 2011-09-30 09:37:05.511 DSApp[366:707] Dismissing LoginView. 2011-09-30 09:37:08.644 DSApp[366:7d0f] url call: http://***/ipadwebservice.asmx/getChildFoldersByFolderID?folderId=-1 2011-09-30 09:37:08.649 DSApp[366:7d0f] Call failed. (Reason: User not logged in!) 2011-09-30 09:37:09.493 DSApp[366:7d0f] url call: http://***/ipadwebservice.asmx/getDocumentsByFolderId?folderId=-1 2011-09-30 09:37:09.497 DSApp[366:7d0f] Call failed. (Reason: User not logged in!) Another weird thing is that when I hardcode the login details and call in the applicationDidFinishLaunching method, everything works perfectly and all WS calls are recieved succesfully. Bueno: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { # warning hardcode login [WebservicesController authenticateUserWithName:@"user" andPassword:@"pass"]; self.window.rootViewController = self.splitViewController; //login LoginViewController *loginView = [LoginViewController new]; loginView.modalTransitionStyle = UIModalTransitionStyleCoverVertical; [self.splitViewController presentModalViewController:loginView animated:YES]; [loginView release]; } No bueno: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { # warning hardcode login //[WebservicesController authenticateUserWithName:@"user" andPassword:@"pass"]; self.window.rootViewController = self.splitViewController; //login LoginViewController *loginView = [LoginViewController new]; loginView.modalTransitionStyle = UIModalTransitionStyleCoverVertical; [self.splitViewController presentModalViewController:loginView animated:YES]; [loginView release]; } A: Your code exemple is not really clear, but did you create your instance of WebservicesController in you login controller ? Cause if you release your login controller, your WebservicesController is probably release and so is the authentication... And that should explain why its working in the appDelegate A: The session ID's match and the WS recieves the calls, but the iPad seems to remove the session upon dismissing the login screen. Is there any piece of code which can "remove" the session? If so put a breakpoint there and see if it is being called. Otherwise, my guess is that after all, you are not sending the session ID correctly with the request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Submit Form without transferring to the target(Vaadin) I'm using an FormSender addon of Vaadin to send some data to my servlet via POST works like that: FormSender formSender = new FormSender(); formSender.setFormMethod(FormSender.Method.POST); formSender.setFormTarget("Servlet URL"); If(event.getSource() == Submit){ formSender.addValue("UserName", (String) UserName.getValue()); formSender.addValue("Password", (String) Password.getValue()); formSender.addValue("DataBase", (String) DatabaseName.getValue()); if(!UserName.getValue().equals("")&& !Password.getValue().equals("")&& !DatabaseName.getValue().equals("")){ formSender.submit(); } } now if I click on Submit button I get transferred away from my current page to the target ("Servlet URL"). is there a way to just notify the user when he clicks the button that the i've got the values without transferring him from the current page? Info: I'm working with eclipse(Helios) on a Liferay(6.0) Portal with the Vaadin(6.6.6) plugin in a Vaadin portlet A: Im not sure if you can accomplish this without getting transfered as long as you use the FormSender addon, however, you coudl let vaadin use a regular java urlconnection to send the data "manually" to the server. Here is a post on the vaadin forum to help you
{ "language": "en", "url": "https://stackoverflow.com/questions/7607462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Implement radial blur with OpenCV We would like to correct for field curvature introduced by a lens in a digital camera. We plan to use a digital unsharp mask Instead of applying a Gaussian blur we would like to try a radial blur, so the sharpening has more impact toward the edges of the image. What is simplest way to create a radial blur using OpenCV ? A: The answer above is close but missing a few key elements that took me a bit to figure out. I've changed the maps so that they are correctly calculating the zoom and shrink and added/subtracted them from the x and y at each position (otherwise you will just end up remapping your image to a tiny square. Also I changed the /blur to *blur otherwise your maps will contain very large numbers and just not come out right (extremely large multiples of each position). float center_x = width/2; //or whatever float center_y = height/2; float blur = 0.002; //blur radius per pixels from center. 2px blur at 1000px from center int iterations = 5; Mat growMapx, growMapy; Mat shrinkMapx, shrinkMapy; for(int x = 0; x < width; x++) { for(int y = 0; y < height; y++) { growMapx[x,y] = x+((x - center_x)*blur); growMapy[x,y] = y+((y - center_y)*blur); shrinkMapx[x,y] = x-((x - center_x)*blur); shrinkMapy[x,y] = y-((y - center_y)*blur); } } Mat tmp1, tmp2; for(int i = 0; i < iterations; i++) { remap(src, tmp1, growMapx, growMapy, CV_INTER_LINEAR); // enlarge remap(src, tmp2, shrinkMapx, shrinkMapy, CV_INTER_LINEAR); // shrink addWeighted(tmp1, 0.5, tmp2, 0.5, 0, src); // blend back to src } A: Python code: w, h = img.shape[:2] center_x = w / 2 center_y = h / 2 blur = 0.01 iterations = 5 growMapx = np.tile(np.arange(h) + ((np.arange(h) - center_x)*blur), (w, 1)).astype(np.float32) shrinkMapx = np.tile(np.arange(h) - ((np.arange(h) - center_x)*blur), (w, 1)).astype(np.float32) growMapy = np.tile(np.arange(w) + ((np.arange(w) - center_y)*blur), (h, 1)).transpose().astype(np.float32) shrinkMapy = np.tile(np.arange(w) - ((np.arange(w) - center_y)*blur), (h, 1)).transpose().astype(np.float32) for i in range(iterations): tmp1 = cv2.remap(img, growMapx, growMapy, cv2.INTER_LINEAR) tmp2 = cv2.remap(img, shrinkMapx, shrinkMapy, cv2.INTER_LINEAR) img = cv2.addWeighted(tmp1, 0.5, tmp2, 0.5, 0) A: I am interested in something similar to the Photoshop radial motion blur. If this is also what you are looking for, I think the best solution might be an iterative resize and blend (addWeighted). Can also be accomplished with remap. Pseudocode, more or less: float center_x = width/2; //or whatever float center_y = height/2; float blur = 0.02; //blur radius per pixels from center. 2px blur at 100px from center int iterations = 5; Mat mapx, mapy; for(int x = 0; x < width; x++) { for(int y = 0; y < height; y++) { mapx[x,y] = (x - center_x)/blur; mapy[x,y] = (y - center_y)/blur; } } Mat tmp1, tmp2; for(int i = 0; i < iterations; i++) { remap(src, tmp1, mapx, mapy, CV_INTER_LINEAR); // enlarge remap(src, tmp2, -mapx, -mapy, CV_INTER_LINEAR); // shrink addWeighted(tmp1, 0.5, tmp2, 0.5, 0, src); // blend back to src }
{ "language": "en", "url": "https://stackoverflow.com/questions/7607464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: jQuery: Scale entire div with its children? is it somehow possible to use jQuery or Javascript to scale an entire div down to 70%. E.g. I have a horizontal slider with images. On smaller screens the slider with all its images (and their captions) should be like 70% of it's original size. It's really difficult though do shrink everything manually with jquery and remember all the original sizes. Any idea how I could solve this? A: Maybe you can find inspiration from: http://css-tricks.com/examples/AnythingZoomer/ A zoomer that can zoom forth and back a generic html content, made in jQuery by a famous web designer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: bytearray:set_size(5) fails for Lua Wireshark In a Lua-based dissector, I would like to transform a tvb content to an other tvb. The code: local strbuf = buffer(offset, strlen * 2) -- range from tvb offset = offset + strlen * 2 local inbytes = strbuf:bytes() local outbytes = ByteArray.new() outbytes:set_size(strlen) -- fails; using a number instead strlen fails to The fail message is expected userdata, got number. Why would set_size expect userdata? Alternatively, how do I allocate a ByteArray of a given size? A: The following works, but is not too elegant: local s = "" for i = 0, strlen-1 do s = s .. "ff" end local outbytes = ByteArray.new(s) A: It seems that you found a bug in their implementation. According to their own API, creating an empty ByteArray isn't incompatible with using set_size. I could not find an issue tracker for it, but you could try sending the bug you found to their mailing list: https://www.wireshark.org/mailman/listinfo/wireshark-dev As an workaround, have you tried initializing the ByteArray with just an empty string? local outbytes = ByteArray.new("") -- notice the empty string here outbytes:set_size(strlen)
{ "language": "en", "url": "https://stackoverflow.com/questions/7607466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c# FileSystemWatcher and a Timer I have this strange, yet maybe very simple problem.. I have a timer1 in my program that should start when I for example click a button. which it does.. However when I use the FileSystemWatch it does not trigger timer1 for some reason I can't seem to figure out.. is there something special that prevents the timer from being triggered? Starting time works here: private void toolStripMenuItem2_Click(object sender, EventArgs e) { timer1.Start(); } but here it does not.. private void fsw_SS_Created(object sender, FileSystemEventArgs e) { fsw_SS.EnableRaisingEvents = false; timer1.Start(); } Intellisense of Visual Studio does not show any problems, neither can i seem to find a solution out there. timer settings are as followed: Interval of 5000ms, and a timer_tick event (setup properly). My problem is either 1) the timer doesn't start or 2) it doesn't tick.. What is wrong here, as I said before using a manual button or tool strip menue item it starts fine... A: Observe that the events are raised on a background thread, which means that you are accessing the timer from the wrong thread. (You never said what timer1 is, but I'm guessing it has thread affinity.) A: I don't think it's a good idea to use a WinForms timer in this particular scenario as @Raymond has pointed out you are dealing with different threads and may encounter unexpected behaviour. You should consider using System.Threading.Timer instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create new post with photo attached in WordPress using XMLRPC? Anyone knows how to create new post with photo attached in WordPress using XMLRPC? I am able to create new post and upload new picture separately, but looks like there is no way to attach the uploaded photo to the created post? Below is the codes I'm currently using. <?php DEFINE('WP_XMLRPC_URL', 'http://www.blog.com/xmlrpc.php'); DEFINE('WP_USERNAME', 'username'); DEFINE('WP_PASSWORD', 'password'); require_once("./IXR_Library.php"); $rpc = new IXR_Client(WP_XMLRPC_URL); $status = $rpc->query("system.listMethods"); // method name if(!$status){ print "Error (".$rpc->getErrorCode().") : "; print $rpc->getErrorMessage()."\n"; exit; } $content['post_type'] = 'post'; // post title $content['title'] = 'Post Title '.date("F j, Y, g:i a"); // post title $content['categories'] = array($response[1]['categoryName']); // psot categories $content['description'] = '<p>Hello World!</p>'; // post body $content['mt_keywords'] = 'tag keyword 1, tag keyword 2, tag keyword 3'; // post tags $content['mt_allow_comments'] = 1; // allow comments $content['mt_allow_pings'] = 1; // allow pings $content['custom_fields'] = array(array('key'=>'Key Name', 'value'=>'Value One')); // custom fields $publishBool = true; if(!$rpc->query('metaWeblog.newPost', '', WP_USERNAME, WP_PASSWORD, $content, $publishBool)){ die('An error occurred - '.$rpc->getErrorCode().":".$rpc->getErrorMessage()); } $postID = $rpc->getResponse(); echo 'POST ID: '.$postID.'<br/>'; if($postID){ // if post has successfully created $fs = filesize(dirname(__FILE__).'/image.jpg'); $file = fopen(dirname(__FILE__).'/image.jpg', 'rb'); $filedata = fread($file, $fs); fclose($file); $data = array( 'name' => 'image.jpg', 'type' => 'image/jpg', 'bits' => new IXR_Base64($filedata), false // overwrite ); $status = $rpc->query( 'metaWeblog.newMediaObject', $postID, WP_USERNAME, WP_PASSWORD, $data ); echo print_r($rpc->getResponse()); // Array ( [file] => image.jpg [url] => http://www.blog.com/wp-content/uploads/2011/09/image.jpg [type] => image/jpg ) } ?> A: I've been involved in WordPress sites (my current employer uses 3 of these) and posting stuff daily and by the bulk has forced me to use what I do best-- scripts! They're PHP-based and are quick and easy to use and deploy. And security? Just use .htaccess to secure it. As per research, XMLRPC when it comes to files is one thing wordpress really sucks at. Once you upload a file, you can't associate that attachment to a particular post! I know, it's annoying. So I decided to figure it out for myself. It took me a week to sort it out. You will need 100% control over your publishing client that is XMLRPC compliant or this won't mean anything to you! You will need, from your WordPress installation: * *class-IXR.php, located in /wp-admin/includes *class-wp-xmlrpc-server.php, located in /wp-includes class-IXR.php will be needed if you craft your own posting tool, like me. They have the correctly-working base64 encoder. Don't trust the one that comes with PHP. You also need to be somewhat experienced in programming to be able to relate to this. I will try to be clearer. * *Modify class-wp-xmlrpc-server.php * *Download this to your computer, through ftp. Backup a copy, just in case. *Open the file in a text editor. If it doesn't come formatted, (typically it should, else, it's unix-type carriage breaks they are using) open it elsewhere or use something like ultraedit. *Pay attention to the mw_newMediaObject function. This is our target. A little note here; WordPress borrows functionality from blogger and movabletype. Although WordPress also has a unique class sets for xmlrpc, they choose to keep functionality common so that they work no matter what platform is in use. *Look for the function mw_newMediaObject($args). Typically, this should be in line 2948. Pay attention to your text editor's status bar to find what line number you are in. If you can't find it still, look for it using the search/find function of your text editor. *Scroll down a little and you should have something that looks like this: $name = sanitize_file_name( $data['name'] ); $type = $data['type']; $bits = $data['bits']; *After the $name variable, we will add something. See below. $name = sanitize_file_name( $data['name'] ); $post = $data['post']; //the post ID to attach to. $type = $data['type']; $bits = $data['bits']; Note the new $post variable. This means whenever you will make a new file upload request, a 'post' argument will now be available for you to attach. How to find your post number depends on how you add posts with an xmlrpc-compliant client. Typically, you should obtain this as a result from posting. It is a numeric value. Once you've edited the above, it's time to move on to line 3000. // Construct the attachment array // attach to post_id 0 $post_id = 0; $attachment = array( 'post_title' => $name, 'post_content' => '', 'post_type' => 'attachment', 'post_parent' => $post_id, 'post_mime_type' => $type, 'guid' => $upload[ 'url' ] ); *So here's why no image is associated to any post! It is always defaulted to 0 for the post_parent argument! That's not gonna be the case anymore. // Construct the attachment array // attach to post_id 0 $post_id = $post; $attachment = array( 'post_title' => $name, 'post_content' => '', 'post_type' => 'attachment', 'post_parent' => $post_id, 'post_mime_type' => $type, 'guid' => $upload[ 'url' ] ); $post_id now takes up the value of $post, which comes from the xmlrpc request. Once this is committed to the attachment, it will be associated to whatever post you desire! This can be improved. A default value can be assigned so things don't get broken if no value is entered. Although in my side, I put the default value on my client, and no one else is accessing the XMLRPC interface but me. *With the changes done, save your file and re-upload it in the same path where you found it. Again, make sure to make backups. Be wary of WordPress updates that affects this module. If that happens, you need to reapply this edit again! *Include class-IXR.php in your PHP-type editor. If you're using something else, well, I can't help you there. :( Hope this helps some people. A: When you post, WordPress will scan at the post for IMG tags. If WP finds the image, it's loaded in it's media library. If there's an image in the body, it will automatically attached it to the post. Basically you have to: * *post the media (image) first *Grab its URL *include the URL of the image with a IMG tag in the body of your post. *then create the post Here is some sample code. It needs error handling, and some more documentation. $admin ="***"; $userid ="****"; $xmlrpc = 'http://localhost/web/blog/xmlrpc.php'; include '../blog/wp-includes/class-IXR.php'; $client = new IXR_Client($xmlrpc); $author = "test"; $title = "Test Posting"; $categories = "chess,coolbeans"; $body = "This is only a test disregard </br>"; $tempImagesfolder = "tempImages"; $img = "1338494719chessBoard.jpg"; $attachImage = uploadImage($tempImagesfolder,$img); $body .= "<img src='$attachImage' width='256' height='256' /></a>"; createPost($title,$body,$categories,$author); /* */ function createPost($title,$body,$categories,$author){ global $username, $password,$client; $authorID = findAuthor($author); //lookup id of author /*$categories is a list seperated by ,*/ $cats = preg_split('/,/', $categories, -1, PREG_SPLIT_NO_EMPTY); foreach ($cats as $key => $data){ createCategory($data,"",""); } //$time = time(); //$time += 86400; $data = array( 'title' => $title, 'description' => $body, 'dateCreated' => (new IXR_Date(time())), //'dateCreated' => (new IXR_Date($time)), //publish in the future 'mt_allow_comments' => 0, // 1 to allow comments 'mt_allow_pings' => 0,// 1 to allow trackbacks 'categories' => $cats, 'wp_author_id' => $authorID //id of the author if set ); $published = 0; // 0 - draft, 1 - published $res = $client->query('metaWeblog.newPost', '', $username, $password, $data, $published); } /* */ function uploadImage($tempImagesfolder,$img){ global $username, $password,$client; $filename = $tempImagesfolder ."/" . $img; $fs = filesize($filename); $file = fopen($filename, 'rb'); $filedata = fread($file, $fs); fclose($file); $data = array( 'name' => $img, 'type' => 'image/jpg', 'bits' => new IXR_Base64($filedata), false //overwrite ); $res = $client->query('wp.uploadFile',1,$username, $password,$data); $returnInfo = $client->getResponse(); return $returnInfo['url']; //return the url of the posted Image } /* */ function findAuthor($author){ global $username, $password,$client; $client->query('wp.getAuthors ', 0, $username, $password); $authors = $client->getResponse(); foreach ($authors as $key => $data){ // echo $authors[$key]['user_login'] . $authors[$key]['user_id'] ."</br>"; if($authors[$key]['user_login'] == $author){ return $authors[$key]['user_id']; } } return "not found"; } /* */ function createCategory($catName,$catSlug,$catDescription){ global $username, $password,$client; $res = $client->query('wp.newCategory', '', $username, $password, array( 'name' => $catName, 'slug' => $catSlug, 'parent_id' => 0, 'description' => $catDescription ) ); } A: Here's some sample code to attach an image from a path not supported by WordPress (wp-content) <?php function attach_wordpress_images($productpicture,$newid) { include('../../../../wp-load.php'); $upload_dir = wp_upload_dir(); $dirr = $upload_dir['path'].'/'; $filename = $dirr . $productpicture; # print "the path is : $filename \n"; # print "Filnamn: $filename \n"; $uploads = wp_upload_dir(); // Array of key => value pairs # echo $uploads['basedir'] . '<br />'; $productpicture = str_replace('/uploads','',$productpicture); $localfile = $uploads['basedir'] .'/' .$productpicture; # echo "Local path = $localfile \n"; if (!file_exists($filename)) { echo "hittade inte $filename !"; die ("no image for flaska $id $newid !"); } if (!copy($filename, $localfile)) { wp_delete_post($newid); echo "Failed to copy the file $filename to $localfile "; die("Failed to copy the file $filename to $localfile "); } $wp_filetype = wp_check_filetype(basename($localfile), null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', basename($localfile)), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $localfile, $newid ); // you must first include the image.php file // for the function wp_generate_attachment_metadata() to work require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata( $attach_id, $localfile ); wp_update_attachment_metadata( $attach_id, $attach_data ); } ?> A: After calling the method metaWeblog.newMediaObject, we need to edit the image entry on the database to add a parent (the previously created post with metaWeblog.newPost). If we try with metaWeblog.editPost, it throws an error 401, which indicates that // Use wp.editPost to edit post types other than post and page. if ( ! in_array( $postdata[ 'post_type' ], array( 'post', 'page' ) ) ) return new IXR_Error( 401, __( 'Invalid post type' ) ); The solution is to call wp.editPost, which takes the following arguments: $blog_id = (int) $args[0]; $username = $args[1]; $password = $args[2]; $post_id = (int) $args[3]; $content_struct = $args[4]; So, just after newMediaObject, we do: $status = $rpc->query( 'metaWeblog.newMediaObject', $postID, WP_USERNAME, WP_PASSWORD, $data ); $response = $rpc->getResponse(); if( isset($response['id']) ) { // ATTACH IMAGE TO POST $image['post_parent'] = $postID; if( !$rpc->query('wp.editPost', '1', WP_USERNAME, WP_PASSWORD, $response['id'], $image)) { die( 'An error occurred - ' . $rpc->getErrorCode() . ":" . $rpc->getErrorMessage() ); } echo 'image: ' . $rpc->getResponse(); // SET FEATURED IMAGE $updatePost['custom_fields'] = array( array( 'key' => '_thumbnail_id', 'value' => $response['id'] ) ); if( !$rpc->query( 'metaWeblog.editPost', $postID, WP_USERNAME, WP_PASSWORD, $updatePost, $publishBool ) ) { die( 'An error occurred - ' . $rpc->getErrorCode() . ":" . $rpc->getErrorMessage() ); } echo 'update: ' . $rpc->getResponse(); } I've used the Incutio XML-RPC Library for PHP to test and the rest of the code is exactly as in the question. A: I had to do this several months ago. It is possible but not only is it hacky and undocumented I had to dig through wordpress source to figure it out. What I wrote up way back then: One thing that was absolutely un-documented was a method to attach an image to a post. After some digging I found attach_uploads() which is a function that wordpress calls every time a post is created or edited over xml-rpc. What it does is search through the list of un-attached media objects and see if the new/edited post contains a link to them. Since I was trying to attach images so that the theme’s gallery would use them I didn’t necessarily want to link to the images within the post, nor did I want to edit wordpress. So what I ended up doing was including the image url within an html comment. -- danieru.com Like I said messy but I searched high and low for a better method and I'm reasonably sure that none exists. A: As of Wordpress 3.5, newmediaobject now recognizes the hack semi-natively. it is no longer necessary to hack class-wp-xmlrpc-server.php. Instead, your xml-rpc client needs to send the post number to a variable called post_id. (Previously it was just the variable 'post') Hope that helps someone out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Exclude url from filter-mapping in web.xml I am using spring mvc and I need to exclude urls from filter-mapping. It means, I have static content like pictures and css and js ... and I need to not process these request, for example from security filter. I tried urlrewrite, but I was not able to redirect the urls directly to defaultServlet, which is defined in catalina web.xml. I need to jump over filters, because I have a lot of them. Is there a way? Thanks EDIT - I thought maybe I could create filter which will if decided jump over other filters and execute the servlet at the end. Is it possible to do that? Thanks A: In the end I used: <filter> <filter-name>UrlRewriteFilter</filter-name> <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class> <init-param> <param-name>logLevel</param-name> <param-value>Warn</param-value> </init-param> </filter> and url rewrite was defined: <urlrewrite default-match-type="wildcard"> <rule> <from>/static/**</from> <to>/static/$1</to> </rule> A: Some example solution: http://java-espresso.blogspot.com/2011/09/webxml-problem-and-solution-for-url.html another one: http://www.xinotes.org/notes/note/1024/ and another one: http://blog.ericdaugherty.com/2010/02/excluding-content-from-url-pattern-in.html Hope that helps... Konrad
{ "language": "en", "url": "https://stackoverflow.com/questions/7607479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: soap webservice with ASIHTTPREQUEST I am trying to implement my soap web services with ASIHTTPREQUEST and i am facing some error. Here is my code. [request addRequestHeader:@"Content-Type" value:@"application/xml; charset=utf-8"]; [request addRequestHeader:@"SOAPAction" value:[xmlnsString stringByAppendingString:@"GetDetail"]]; [request addRequestHeader:@"Content-Length" value:msgLength]; [request setRequestMethod:@"POST"]; [request appendPostData: [yourPOSTstring dataUsingEncoding:NSUTF8StringEncoding]]; [request setDefaultResponseEncoding:NSUTF8StringEncoding]; and i am facing this error The server cannot service the request because the media type is unsupported. i have done some googling on this and found that there is some problem with "Content-Type". i am not sure about that. i tried this and many other option but its gives me "Bad Request" as a response string. [request addRequestHeader:@"Content-Type" value:@"text/xml; charset=utf-8"]; let me know if you have nay solution for this. A: Try this: [request addRequestHeader:@"Content-Type" value:@"application/soap+xml; charset=utf-8"]; Hope it works!
{ "language": "en", "url": "https://stackoverflow.com/questions/7607480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Querying a distant table in Silverstripe model I'm trying to get a sum of a field "cost" from a page type from another page type. (ProjectCategory), like this: class ProjectCategory extends Page { static $belongs_many_many = array( 'RelateToProject' => 'Project' ); function totalCost(){ $sqlQuery = new SQLQuery( "SUM(Project.cost)", // Select "Project", // From "what to do here?" // Where (optional) ); $totalVisits = $sqlQuery->execute()->value(); return $totalVisits; } What do I do for the where bit? How can I get the sum of cost for just this Category? (If I leave the where blank it returns the sum of all project costs for every category - which is no good). A: the "where" part should be: "ID = " . $this->RelateToProjectID oh, wait, the above will only work für $has_one, but you're using a many_many relationship. the following should do the trick for your many_many relationship: build an array of IDs of related projects: $projects = $this->RelateToProject(); $projectIDs = array(); if($projects) { foreach($projects as $project) { $projectIDs[] = $project->ID; } } then use them in your 'where' statement like so: "ID IN (" . join(',',$projectIDs) . ")"
{ "language": "en", "url": "https://stackoverflow.com/questions/7607481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting Started with HDF5 I'm trying to use HDF5 in a C# .NET application on a 32 bit Win XP machine. I am a total newbie to this HDF5 stuff. I downloaded the Windows binary distribution, "HDF5-1.8.7_win_x86.zip" from http://www.hdfgroup.org/HDF5/release/obtain5.html. I can't really follow the instructions in the "INSTALL_Windows.txt" because I don't have 'windows' directory under the downloaded stuff, from where the instructions ask me to run a 'copy_hdf.bat' file! My intention as of now, is to store some simple text & numeric data using HDF5. Can someone please suggest how do I get about it. A: Try to download HDF5-1.8.7_x86_static.zip instead. The instructions in the package you downloaded were probably a bit outdated. This one should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7607489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: F# Group or aggregate a record sequence/collection by a given criteria I am pretty new to functional programming and therefore F# and I have serious trouble to come up with the right solution for this problem. I have got a sequence of record types, say like: type Invoice = { GrpText : string GrpRef : int Article : int Wkz : int Text : string Price : decimal InvoiceRef : int } Now I want to group or aggregate the sequence of Invoices by a given criteria and i.e. sum their prices. Invoices that does not match the criteria should not be grouped and just returned as they are. A criteria function might look like this: /// determines whether to group the two given Invoice items or not let criteria item toCompareWith = (item.GrpRef > 0 && item.Article = toCompareWith.Article && item.InvoiceRef = toCompareWith.InvoiceRef) || (item.Wkz <> 0 && item.Text = toCompareWith.Text) The aggregation or grouping could look like this: /// aggregate the given Invoice items let combineInvoices item1 item2 = {item1 with Price = item1.Price + item2.Price; Wkz = 0} The problem looks kind of simple but I am currently not experienced enough in functional programming to connect the dots. Edit: I just modified the criteria function in order to better show that it might be a bit more complex than grouping by one or multiple fields. A: Unless I'm missing something, there are two steps involved: group and reduce. The easiest way to group is Seq.groupBy. Since you want to use custom equality you need to either apply the [<CustomEquality>] attribute to your type and override Equals and GetHashCode, or roll your own key generating function that uses your concept of equality. Here's an example of the latter. //custom key generator let genKeyWith compare = let lookup = ResizeArray() fun item -> match Seq.tryFindIndex (compare item) lookup with | Some idx -> idx | None -> lookup.Add(item) lookup.Count - 1 Usage let getKey = genKeyWith criteria let invoices = Seq.init 10 (fun _ -> Unchecked.defaultof<Invoice>) invoices |> Seq.groupBy getKey |> Seq.map (fun (_, items) -> Seq.reduce combineInvoices items) A: Something like this where Defaultinvoice is some sort of '0' invoice input |> Seq.groupBy (fun t -> t.Article) |> Seq.map (fun (a,b) -> a, (b |> List.fold (fun (c,d) -> combineInvoices c d) Defaultinvoice) EDIT - For more complicated combine function. So if your combine function is more complicated, the best approach is probably to use recursion and I think it is going to be hard to avoid a O(n^2) solution. I would go with something like let rec overallfunc input = let rec func input (valid:ResizeArray<_>) = match input with |[] -> valid //return list |h::t -> match valid.tryfindIndex (fun elem -> criteria h elem) with //see if we can combine with something |Some(index) -> valid.[index] <- combineInvoices (valid.[index]) h //very non-functional here |None -> valid.Add(h) func t valid //recurse here func input (ResizeArray<_>()) This solution is both highly non-functional and probably very slow, but it should work for arbitrarily complicated combination functions
{ "language": "en", "url": "https://stackoverflow.com/questions/7607490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }