text
stringlengths
8
267k
meta
dict
Q: Parse xml with jquery and display nodes-node names and node values- on screen Hi all I have the below xml: <root> <a>Value</a> <b>Value</b> <c>Value</c> </root> is there a way to get the root child elements and display them on screen like this <a>Value</a> <b>Value</b> <c>Value</c> ? I know that with text() method I can get only the "Value" part and with .nodeName only the "a" part.What I want is to take the whole <a>Value</a> .Any ideas would be really appreciated A: try this: var xml = "<root> <a>Value</a> <b>Value</b> <c>Value</c> </root> ", xmlDoc = $.parseXML( xml ), $xml = $( xmlDoc ), $root = $xml.find( "root" ); then maybe like $root.html(); You may have to play with that a little to make it give you what you want..but should work
{ "language": "en", "url": "https://stackoverflow.com/questions/7501202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing IP address in C# I have a c# program that needs to connect to another computer via a UDP connection. In order to perform this operation, I need to temporarily change the IP address of my network card on my computer, so they can talk to one another. I can do this just fine. However, when I'm done, I want to restore my IP address back to what it was before; which is to automatically obtain an IP address. Can someone tell me how to change my settings back to what they were previously? Thanks, Phil A: You may want to check this SwitchNetConfig project. The part that interest you is how to change the IP: public static void SetIP( string nicName, string IpAddresses, string SubnetMask, string Gateway, string DnsSearchOrder) { ManagementClass mc = new ManagementClass( "Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach(ManagementObject mo in moc) { // Make sure this is a IP enabled device. // Not something like memory card or VM Ware if( mo["IPEnabled"] as bool ) { if( mo["Caption"].Equals( nicName ) ) { ManagementBaseObject newIP = mo.GetMethodParameters( "EnableStatic" ); ManagementBaseObject newGate = mo.GetMethodParameters( "SetGateways" ); ManagementBaseObject newDNS = mo.GetMethodParameters( "SetDNSServerSearchOrder" ); newGate[ "DefaultIPGateway" ] = new string[] { Gateway }; newGate[ "GatewayCostMetric" ] = new int[] { 1 }; newIP[ "IPAddress" ] = IpAddresses.Split( ',' ); newIP[ "SubnetMask" ] = new string[] { SubnetMask }; newDNS[ "DNSServerSearchOrder" ] = DnsSearchOrder.Split(','); ManagementBaseObject setIP = mo.InvokeMethod( "EnableStatic", newIP, null); ManagementBaseObject setGateways = mo.InvokeMethod( "SetGateways", newGate, null); ManagementBaseObject setDNS = mo.InvokeMethod( "SetDNSServerSearchOrder", newDNS, null); break; } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Structuremap, odd behavior when using default instance and named instance Options Is anybody able to explain the following behavior? Especially why TestInitializeAndConfigure_Fails failes when TestUseAndAdd does not ... and why TestUse_Fails failes when TestUseOrderChanged does not. Thanks code interface IResource {} class TheFirstResource : IResource {} class TheSecondResource : IResource {} [TestFixture] class Test { [Test] public void TestUse_Fails() { ObjectFactory.Initialize(init => { init.For<IResource>().Singleton().Use<TheFirstResource>(); init.For<IResource>().Singleton().Use<TheSecondResource>().Named("test"); }); IResource r1 = ObjectFactory.GetInstance<IResource>(); IResource r2 = ObjectFactory.GetNamedInstance<IResource>("test"); Console.WriteLine(string.Format("TestUse_Fails \n{0}\n{1}", r1, r2)); } [Test] public void TestUseOrderChanged() { ObjectFactory.Initialize(init => { init.For<IResource>().Singleton().Use<TheSecondResource>().Named("test"); init.For<IResource>().Singleton().Use<TheFirstResource>(); }); IResource r1 = ObjectFactory.GetInstance<IResource>(); IResource r2 = ObjectFactory.GetNamedInstance<IResource>("test"); Console.WriteLine(string.Format("TestUseOrderChanged \n{0}\n{1}", r1, r2)); } [Test] public void TestUseAndAdd() { ObjectFactory.Initialize(init => { init.For<IResource>().Singleton().Use<TheFirstResource>(); init.For<IResource>().Singleton().Add<TheSecondResource>().Named("test"); }); IResource r1 = ObjectFactory.GetInstance<IResource>(); IResource r2 = ObjectFactory.GetNamedInstance<IResource>("test"); Console.WriteLine(string.Format("TestUseAndAdd \n{0}\n{1}", r1, r2)); } [Test] public void TestInitializeAndConfigure_Fails() { ObjectFactory.Initialize(init => { init.For<IResource>().Singleton().Use<TheFirstResource>(); }); ObjectFactory.Configure(init => { init.For<IResource>().Singleton().Add<TheSecondResource>().Named("test"); }); IResource r1 = ObjectFactory.GetInstance<IResource>(); IResource r2 = ObjectFactory.GetNamedInstance<IResource>("test"); Console.WriteLine(string.Format("TestInitializeAndConfigure_Fails \n{0}\n{1}", r1, r2)); } } output TestUse_Fails Smtesting.TheSecondResource Smtesting.TheSecondResource TestUseOrderChanged Smtesting.TheFirstResource Smtesting.TheSecondResource TestInitializeAndConfigure_Fails Smtesting.TheSecondResource Smtesting.TheSecondResource TestUseAndAdd Smtesting.TheFirstResource Smtesting.TheSecondResource A: Just to help the people who will stumble upon this, here is an answer from the man Jermey himself. He answered the question on his blog here. For().Use() is destructive. Do For().Use() once to get the default, and a second call to For().Add() to get the 2nd registration. Look at the Xml comments for those 2 API calls. A: TestUse_Fails makes sense to me, because calling Use<>() essentially means you are specifying the default instance for the type (and adding it). Last one in generally wins--I can't find explicit docs on this, but that's the way most containers work. The r1 call gets TheSecondResource (the last one set to be default), and the r2 call gets the named resource. TestUseOrderChanged works because the default after init/config is the TheFirstResource, but TheSecondResource has still been added to the container with a name. So r1 gets TheFirstResource (as it was last in and thus the default), and r2 correctly gets TheSecondResource as the named instance. TestInitializeAndConfigure_Fails is the odd one. From where I sit, r1 should get TheFirstResource, since the default has not been overwritten--Use<>() has not been called again. Calling Configure after calling Initialize should not reset the container according to the docs. I would try calling ObjectFactory.WhatDoIHave() and see if TheFirstResource is even registered after the Initialize() and Configure() calls. To me, this looks like a bug, and I would consider submitting it to the structuremap users group (http://groups.google.com/group/structuremap-users).
{ "language": "en", "url": "https://stackoverflow.com/questions/7501207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set the alignment in a platform independent way? In the latest draft of the c++11 standard, chapter 3.11 talks about the alignment. Later, the chapter 7.6.1 defines how to define an aligned structures (or variables?) If I define a structure like this : alignas(16) struct A { int n; unsigned char[ 1020 ]; }; does it means that all instances of the class A are going to be aligned to 16 bytes? Or, do I have to do it like in the next code? struct A { char data[300]; }; alignas(16) A a; If both examples are wrong, how to do it properly? PS I am not looking for a compiler dependent solution. A: Alignment is first and foremost a property of types. It can be overridden for a type with alignas; alignas can also be used to assign a new alignment value to a specific object. So, both examples are valid, and will have the semantics that you've presumed. [n3290: 3.11/1]: Object types have alignment requirements (3.9.1, 3.9.2) which place restrictions on the addresses at which an object of that type may be allocated. An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated. An object type imposes an alignment requirement on every object of that type; stricter alignment can be requested using the alignment specifier (7.6.2). [n3290: 7.6.2/1]: An alignment-specifier may be applied to a variable or to a class data member, but it shall not be applied to a bit-field, a function parameter, the formal parameter of a catch clause (15.3), or a variable declared with the register storage class specifier. An alignment-specifier may also be applied to the declaration of a class or enumeration type. An alignment-specifier with an ellipsis is a pack expansion (14.5.3). [n3290: 7.6.2/2]: When the alignment-specifier is of the form alignas( assignment-expression ): * *the assignment-expression shall be an integral constant expression *if the constant expression evaluates to a fundamental alignment, the alignment requirement of the declared entity shall be the specified fundamental alignment *if the constant expression evaluates to an extended alignment and the implementation supports that alignment in the context of the declaration, the alignment of the declared entity shall be that alignment *if the constant expression evaluates to an extended alignment and the implementation does not support that alignment in the context of the declaration, the program is ill-formed *if the constant expression evaluates to zero, the alignment specifier shall have no effect *otherwise, the program is ill-formed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Set up GPS and location services on blackberry i need to get latitude and longitude using gps on blackberry. When i check in simulator, i got the default latitude 43 and longitude 80. When i check on device, i got latitude 0.0 and longitude 0.0. I check on device, option-> Device ->Location setting. Gps data source is Device GPS and location services turns to location on. But till, latitude and longitude values are 0.0. Is there any settings to enable the gps? Pls help.. A: It will be the problem of GPS lock. please check the gps lock is obtained. thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7501212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't upload 5mb file using AJAX file uploader I am using the file uploader plugin (from: https://github.com/valums/file-uploader) to upload files to my website. If you are using a moden web browser (like Firefox 6 or Chrome 13), then it uploads by streaming the file in the POST body, and can give you a progress bar. If you're using IE (or an old browser), it falls back on the standard $_FILES (using a hidden iFrame). Everything was working fine, but suddenly I can't upload 5MB files in Chrome or Firefox. When I upload a 5MB file in Chome or Firefox I get a 500 error and my PHP code is never even ran. If I use Internet Explorer (which uses $_FILES), it works fine. This has to be a configuration problem, as my PHP code never even runs. So, I checked my settings. /etc/php.ini upload_max_filesize = 15M post_max_size = 16M I looked for LimitRequestBody, but that's nowhere to be found (and the default is unlimited). Settings look right. I debugged this for a while, and I can not figure out what is wrong. Is there a setting I'm missing? The server has suhosin installed, if that matters. Here is the backend (I'm using CodeIgniter) code I'm using. // Can we use the fancy file uploader? if($this->input->get('qqfile') !== FALSE){ // Yes we can :-) $name = preg_replace('/[^\-\(\)\d\w\.]/','_', $this->input->get('qqfile')); // Upload the file using black magic :-) $input = fopen("php://input", 'r'); $temp = tmpfile(); $fileSize = stream_copy_to_stream($input, $temp); fclose($input); if($fileSize > 15728640){ $ret['error'] = 'File not uploaded: file cannot be larger than 15 MB'; } elseif(isset($_SERVER['CONTENT_LENGTH']) && $fileSize === (int)$_SERVER['CONTENT_LENGTH']){ $path = $folder.'/'.$name; // Where to put the file // Put the temp uploaded file into the correct spot $target = fopen($path, 'w'); fseek($temp, 0, SEEK_SET); stream_copy_to_stream($temp, $target); fclose($target); fclose($temp); $ret['fileSize'] = $fileSize; $ret['success'] = true; } else{ $ret['error'] = 'File not uploaded: content length error'; } } else{ // IE 6-8 can't use the fancy uploader, so use the standard $_FILES $file = $_FILES['qqfile']; $file['name'] = preg_replace('/[^\-\(\)\d\w\.]/','_', $file['name']); $config['file_name'] = $file['name']; // Upload the file using CodeIgniter's upload class (using $_FILES) $_FILES['userfile'] = $_FILES['qqfile']; unset($_FILES['qqfile']); $config['upload_path'] = $folder; $config['allowed_types'] = '*'; $config['max_size'] = 15360; //15 MB $this->load->library('upload', $config); if($this->upload->do_upload()){ // Upload was successful :-) $upload = $this->upload->data(); $ret['success'] = true; $ret['fileSize'] = $upload['fileSize']/1000; } else{ // Upload was NOT successful $ret['error'] = 'File not uploaded: '.$this->upload->display_errors('', ''); $ret['type'] = $_FILES['userfile']['type']; } echo json_encode($ret); } I know my code works, as files less than 4MB upload fine (on all browsers). I only have a problem with files bigger than 5mb (using Chrome/Firefox). The weird thing is, this works fine on my test server, but not my production server. They probably have different settings (suhosin is on production, but not on test). A: Please check whether your php.ini settings are correctly loaded by viewing <?php phpinfo(); ?>. A: I looked in my apache logs, and found PHP Fatal error: Allowed memory size of 16777216 bytes exhausted (tried to allocate 5242881 bytes) I changed memory_limit to 64M, now it seems to be ok.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iphone: NSDATA dataWithContentsOfURL returning null I have a problem of getting NSData via [NSData dataWithContentsOfURL: url] and giving me an null object where the url is the NSURL got it from defaultRepresentation of the asset.. The url in the NSURL is : assets-library://asset/asset.JPG?id=1000000366&ext=JPG I went to other forum, they talked about something like file url... Do I have to convert the url to file path ? But i can have the thumbnail of the ALAsset on a view. Does anyone know why i get null NSData object? A: from what I know these URLs are just for identification or so - you cannot actually access them. maybe this helps ? ALAsset , send a photo to a web service including its exif data A: If what you're after is the image, you could do something like this... ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease]; NSURL *yourAssetUrl = ;//Insert Your ALAsset's URL here [library assetForURL:yourAssetUrl resultBlock:^(ALAsset *asset) { if (asset) { ALAssetRepresentation *imgRepresentation = [asset defaultRepresentation]; CGImageRef imgRef = [imgRepresentation fullScreenImage]; UIImage *img = [UIImage imageWithCGImage:imgRef]; CGImageRelease(imgRef); [self doSomethingWithImage:img]; } } failureBlock:^(NSError *error) { }];
{ "language": "en", "url": "https://stackoverflow.com/questions/7501214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET App authenticates in Firefox but not in IE When I open my ASP.NET app in IE it asks for username and password. I enter them and it rejects them. I do the same in Firefox and it works. Any ideas? Thanks! I have <authentication mode="Windows" /> A: Switch the Application Pool Identity to Network Service and it worked in both IE and Firefox. Before the Application Pool Identity was a user that was one a different domain than the domain of the user I was trying to login to the App as.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does filtering a new JSON object causes the old one to self-update? I have a JSON array named arr and a new array named new_arr that is created from arr. var arr = {"data": [ {"name":"Alan","height":"171","weight":"66"}, {"name":"Ben","height":"182","weight":"90"}, {"name":"Chris","height":"163","weight":"71"} ] }; var new_arr = arr; new_arr.data = jQuery.grep(new_arr.data, function(n, i){ return n.weight > 70; }); Both arrays arr and new_arr becomes: {"data": [ {"name":"Ben","height":"182","weight":"90"}, {"name":"Chris","height":"163","weight":"71"} ] }; My question is: "Why does modifying the new array changes the old one?" A: There is no new array. It's just a new reference to the old array. Try it in another example : var a = {}; var b = a; // check to see if they are equal alert(a === b); // modify one of them b.foo = 'bar'; // check to see if they are equal alert(a === b); // modify one of them a.bar = 'foo'; // check to see if they are equal alert(a === b); a and b refer to the same object, thus, when you modify a you also modify b and so on. If you use jquery you should use the extend method : var new_arr = $.extend(true,arr); A: You're referencing the same Array when you do: var new_arr = arr; If you want a copy, you need to make a copy: var new_arr = arr.data.slice( 0 ); // 0 is the optional starting index of the copy This just makes a shallow copy of the Array, so the nested objects will be referenced by both. If you need a deep clone of all nested objects, you'd need to traverse into each individual object, and make a copy. A: You should clone your array instead. I copied this from John Resig over here. See his post for more explanation. // Shallow copy var newObject = jQuery.extend({}, oldObject); // Deep copy var newObject = jQuery.extend(true, {}, oldObject); This should work for your arr and new_arr. A: may be because arr is an object and var new_arr = arr just assigns reference to it to new_arr ? try this new_arr = arr.clone()
{ "language": "en", "url": "https://stackoverflow.com/questions/7501226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Activity loading time issue( performance issue while loading Activity) Am moving from one Activity to another activity, in second activity am showing the listview. Am using arraylist's data to fill the listview, so for that i have used "for" condition for looping. so for that looping its taking time to load that page. That page loading time is depending up on the data in the arraylist, if there is more data in the arraylist then looping taking time. Is there any way to reduce page loading time. A: I would take a look into doing your long-running logic in an AsyncTask, and when it's completed, display your listview results. You can find more info on this at: http://developer.android.com/resources/articles/painless-threading.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7501234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to declare a template default value when using CRTP with several template parameters? I want to do: template <class Derived=BattleData> class BattleData : public BattleCommandManager<Derived> { }; But obviously BattleData isn't declared, so I tried a forward declaration: template <class T> class BattleData; template <class Derived=BattleData> class BattleData : public BattleCommandManager<Derived> { }; But then I get error: "wrong number of template parameter on the second line, with BattleData. I really fail to see a solution to this! Edit: The reason I'm doing this is because I want to be able to use BattleData directly as a class, but I also want to be able to subclass it in which case I have to specify the derived class as the second template parameter. For example let's say the corpus of my BattleData class is : template <class Derived> class BattleData: public BaseClass<Derived> { void foo1(){}; void foo2(){}; void foo3(){}; } And I have a subclass template class SubBattleData: public BattleData<SubBattleData> { void foo1(){}; } I would still want, in some cases, to be able to write code like this: BattleData *x = new BattleData(...); I can't even do the following without being able to use default arguments: BattleData<BattleData> *x = new BattleData<BattleData>(...); On one side, the reason functions aren't virtualized in the BattleData class is the benefit of having no virtual function. The other reason it doesn't work for me is that one of the parent CRTP classes invokes functions only if they're present in the derived type (using decltype(Derived::function) and enable-if like structures), and fall back to default behavior otherwise. Since there can be a great deal of those functions with a particular design pattern (like a CRTP that reads a protocol with many different cases and processes a case a particular way only if the derived class specify the corresponding function, otherwise just transfer it without processing). So those functions can be present in SubBattleData and not BattleData, but both classes would work fine if instantiated, yet it's impossible to instantiate BattleData. A: You should be able to accomplish your original design goals more naturally than the above. You can't use the actual Derived typename as the default clearly because what you're really trying to write is the following: template <class Derived=BattleData <BattleData <BattleData <...>>> class BattleData : public BattleCommandManager<Derived> { }; You get the idea. Instead, just use a placeholder like void: template <typename T = void> class BattleData : public BattleCommandManager < typename std::conditional < std::is_same <T, void>::value, BattleData <void>, T >::type> { }; Disclaimer: I did not compile the above. A: I don't see what you are trying to do. What is wrong with template <class T=DataContainer> class BattleData : public BattleCommandManager< BattleData<T> > { }; If you specify Derived to be something else than the actual derived class static polymorphism is not going to work and CRTP becomes somewhat useless anyway. Edit: From what I have gathered this is what you want to in abstract terms: template <class Derived> struct Base { void interface() { static_cast<Derived*>(this)->implementation(); } }; template<typename T> struct Derived : Base<Derived> { // dummy so we get you example T t; void implementation() { std::cout << "derived" << std::endl; } }; struct Derived2 : public Derived<int> { // hide implementation in Derived // but still have Base::interface make the right call statically void implementation() { std::cout << "derived2" << std::endl; } }; There is no way I know of that you can make this work. Another approach would be to use policy classes instead of CRTP. They are compatible with inheritance and you can achieve similar behaviour. template<typename Policy> struct BattleCmdManager : public Policy { using Policy::foo; }; template<typename T> struct BattleData { // ... protected: void foo(); }; struct BattleData2 : public BattleData<int { // ... protected: void foo(); }; A: Can't you use an Empty class for the second template parameter? template <class T=DataContainer, class Derived=BattleData<T, Empty> > class BattleData : public BattleCommandManager<Derived> { }; A: Here is how I solved it: template <class Derived> class BattleDataInh: public BaseClass<Derived> { void foo1(){}; void foo2(){}; void foo3(){}; }; template class SubBattleData: public BattleDataInh<SubBattleData> { void foo1(){}; }; class BattleData : public BattleDataInh<BattleData> { }; And that way, I can add any other template parameters too. The solution was in front of my eyes the whole time but I didn't see it...
{ "language": "en", "url": "https://stackoverflow.com/questions/7501235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why is this query not working for number 1? this query returns 5 results as expected select * from [SalesLogix].[sysdba].[LEAD] where USERFIELD1 like '0' but this query returns nothing select * from [SalesLogix].[sysdba].[LEAD] where USERFIELD1 like '1' the USERFIELD1 is a varchar 80 field Here is all the data that is in the DB and as you can see there are two records with USERFIELD1 = '1' but there seems to be a line break after them...maybe that is causing the issue...is there anyway to grab those two records LEADID,CREATEUSER,CREATEDATE,MODIFYUSER,MODIFYDATE,ACCOUNTMANAGERID,ASSIGNDATE,BUSINESSDESCRIPTION,COMPANY,COMPANY_UC,CREDITRATING,DATAQUALITY,DESCRIPTION,DIVISION,DONOTSOLICIT,EMAIL,EMPLOYEES,FAX,FIRSTNAME,HOMEPHONE,IMPORTID,IMPORTSOURCE,INDUSTRY,INTERESTS,ISPRIMARY,LASTCALLDATE,LASTNAME,LASTNAME_UC,LEADSOURCEID,MIDDLENAME,MOBILE,NEXTCALLDATE,NOTES,PREFERRED_CONTACT,PREFIX,PRIORITY,QUALIFICATION_CATEGORYID,REVENUE,SECCODEID,SICCODE,STATUS,SUFFIX,TICKER,TITLE,TOLLFREE,TYPE,USERFIELD1,USERFIELD2,USERFIELD3,USERFIELD4,USERFIELD5,USERFIELD6,USERFIELD7,USERFIELD8,USERFIELD9,USERFIELD10,WEBADDRESS,WORKPHONE,LEAD_ADDRESSID,DONOTEMAIL,DONOTFAX,DONOTMAIL,DONOTPHONE Q134915558 ,U6UJ9A00000S,2011-09-20 17:36:10.053,U6UJ9A00000S,2011-09-20 17:36:10.053,NULL,2011-09-20 17:36:10.053,NULL,Johndoe,JOHNDOE,NULL,NULL,NULL,NULL,0,test@gmail.com,NULL,NULL,Harry,NULL,NULL,NULL,NULL,Restaurant Pro Express demo download,T,NULL,Scott,SCOTT, ,NULL,NULL,NULL,this is from the site,NULL,NULL,NULL,NULL,NULL,SYST00000001,NULL,New,NULL,NULL,NULL,NULL,NULL,1 ,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4075559999,QQ134915558 ,NULL,NULL,NULL,NULL Q39769667 ,U6UJ9A00000S,2011-09-20 17:46:18.103,U6UJ9A00000S,2011-09-20 17:46:18.103,NULL,2011-09-20 17:46:18.103,NULL,scaoo,SCAOO,NULL,NULL,NULL,NULL,0,harry333@harry.com,NULL,NULL,upper2,NULL,NULL,NULL,NULL,Aldelo for Restaurants demo download,T,NULL,Scott,SCOTT,L6UJ9A000004,NULL,NULL,NULL,this is a download,NULL,NULL,NULL,NULL,NULL,SYST00000001,NULL,New,NULL,NULL,NULL,NULL,NULL,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4074615519,QQ39769667 ,NULL,NULL,NULL,NULL Q488888476 ,U6UJ9A00000S,2011-09-20 17:49:28.963,U6UJ9A00000S,2011-09-20 17:49:28.963,NULL,2011-09-20 17:49:28.963,NULL,Johndoe,JOHNDOE,NULL,NULL,NULL,NULL,0,markus@gmail.com,NULL,NULL,upper,NULL,NULL,NULL,sales,posnation.com online demo request,T,NULL,Scott,SCOTT,L6UJ9A000004,NULL,NULL,NULL,this is from upper,NULL,NULL,NULL,NULL,NULL,SYST00000001,NULL,New,NULL,NULL,NULL,NULL,NULL,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4074615519,QQ488888476 ,NULL,NULL,NULL,NULL Q504845720 ,U6UJ9A00000S,2011-09-20 17:06:10.053,U6UJ9A00000S,2011-09-20 17:06:10.053,U6UJ9A00000G,2011-09-20 17:06:10.053,NULL,Rafner ext.,RAFNER EXT.,NULL,NULL,NULL,NULL,0,raf@raf.com,NULL,NULL,James,4075615519,NULL,NULL,sales,NULL,NULL,NULL,Rafner,RAFNER, ,NULL,NULL,NULL,Raf associates is asking a question,NULL,NULL,NULL,NULL,NULL,SYST00000001,NULL,New,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,QQ504845720 ,NULL,NULL,NULL,NULL Q539171226 ,U6UJ9A00000S,2011-09-20 17:49:28.963,U6UJ9A00000S,2011-09-20 17:49:28.963,NULL,2011-09-20 17:49:28.963,NULL,scaoo,SCAOO,NULL,NULL,NULL,NULL,0,harry333@harry.com,NULL,NULL,upper3,NULL,NULL,NULL,NULL,Aldelo for Restaurants demo download,T,NULL,Scott,SCOTT,L6UJ9A000004,NULL,NULL,NULL,this is a download,NULL,NULL,NULL,NULL,NULL,SYST00000001,NULL,New,NULL,NULL,NULL,NULL,NULL,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4074615519,QQ539171226 ,NULL,NULL,NULL,NULL Q547088411 ,U6UJ9A00000S,2011-09-20 17:46:18.103,U6UJ9A00000S,2011-09-20 17:46:18.103,NULL,2011-09-20 17:46:18.103,NULL,Johndoe,JOHNDOE,NULL,NULL,NULL,NULL,0,markus@gmail.com,NULL,NULL,upper,NULL,NULL,NULL,sales,posnation.com online demo request,T,NULL,Scott,SCOTT,L6UJ9A000004,NULL,NULL,NULL,this is from upper,NULL,NULL,NULL,NULL,NULL,SYST00000001,NULL,New,NULL,NULL,NULL,NULL,NULL,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4074615519,QQ547088411 ,NULL,NULL,NULL,NULL Q913526837 ,U6UJ9A00000S,2011-09-20 17:36:10.053,U6UJ9A00000S,2011-09-20 17:36:10.053,NULL,2011-09-20 17:36:10.053,NULL,Johndoe,JOHNDOE,NULL,NULL,NULL,NULL,0,test@gmail.com,NULL,NULL,Parry,NULL,NULL,NULL,NULL,Restaurant Pro Express demo download,T,NULL,Scott,SCOTT, ,NULL,NULL,NULL,this is from the site agan,NULL,NULL,NULL,NULL,NULL,SYST00000001,NULL,New,NULL,NULL,NULL,NULL,NULL,1 ,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4075559999,QQ913526837 ,NULL,NULL,NULL,NULL Q925684753 ,U6UJ9A00000S,2011-09-21 09:36:10.420,U6UJ9A00000S,2011-09-21 09:36:10.420,NULL,2011-09-21 09:36:10.420,NULL,POSfasion,POSFASION,NULL,NULL,NULL,NULL,0,sdfa@ss.com,NULL,NULL,Maria,NULL,NULL,NULL,NULL,Aldelo for Restaurants demo download,T,NULL,becker4,BECKER4,L6UJ9A000004,NULL,NULL,NULL,this is another lead from the live site,NULL,NULL,NULL,NULL,NULL,SYST00000001,NULL,New,NULL,NULL,NULL,NULL,NULL,0,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,7778889999,QQ925684753 ,NULL,NULL,NULL,NULL A: If there are characters after the 1 in the userField1 then try using a wildcard, as shown below. select * from [SalesLogix].[sysdba].[LEAD] where USERFIELD1 like '1%' Also the statement you wrote select * from [SalesLogix].[sysdba].[LEAD] where USERFIELD1 like '1' Is essentially equivalent to select * from [SalesLogix].[sysdba].[LEAD] where USERFIELD1 = '1' You may want to read up on using the LIKE clause http://msdn.microsoft.com/en-us/library/ms179859.aspx A: Use where USERFIELD1 = '1 ' You don't need LIKE as you aren't using any wild cards. A: * *You're using LIKE wrong. Put a wildcard or a pattern in there or use an = operator. *Your data seems malformed. A: Try a like with the value surrounded by a wildcard ie USERFIELD1 like '1%' Should sort out whatever problem you're having if it is related to the line break field
{ "language": "en", "url": "https://stackoverflow.com/questions/7501248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails: Calling Devise authenticate_user! and handling invalid user/password exception I have a popup that will only allow to view/save some information if the user is authenticated. I am using devise. In the controller before_filter it checks if user is signed in and if not, show a sign in page. This sign in page is ripped down version of the site's sign in page, so that it fits nicely to the popup. On the authenticate action I call authenticate_user!. Everything works fine when the user enters valid credentials. But when the credential is invalid, devise automatically redirects to site's sign in page (which as I stated is different and not fit for a popup) I tried appending a rescue to the call, but to no avail. Anyone could suggest a better/right way to do this please? :) def authenticate authenticate_user! rescue redirect_to "/popup/sign_in" if user_signed_in? respond_to do |format| format.html { flash[:notice] = I18n.t("logged_in_succesfully") redirect_back_or_default(accounts_path) } else flash[:error] = I18n.t("devise.failure.invalid") render "/popup/sign_in" end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7501250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Android - NullPointerException on getReadableDatabase() I am writing an app that checks if the first value in the database matches a string. When I try to connect to the database, I get a NullPointerException. This happens on both getReadableDatabase() and getWritableDatabase() Here's my code: public class DataManager extends SQLiteOpenHelper { private final static String DB_TABLE = "Nums"; private final static String COL_KEY = "KEY"; private final static String COL_VALUE= "VALUE"; private static Context context; private ContentValues initialValues; private SQLiteDatabase db; private static DataManager dm; public static DataManager getInstance(Context _context) { if (dm==null) {dm=new DataManager(_context);} return dm; } private DataManager() { super(context, DB_TABLE, null, 1); } private DataManager(Context _context) { super(_context, DB_TABLE, null, 1); context=_context; initialValues = new ContentValues(); if (db==null) {db=getWritableDatabase();} } @Override public void onCreate(SQLiteDatabase db) { StringBuilder Query = new StringBuilder(); Query.append("CREATE TABLE IF NOT EXISTS "); Query.append(DB_TABLE); Query.append('('); Query.append(COL_KEY); Query.append(" TEXT PRIMARY KEY,"); Query.append(COL_VALUE); Query.append(" TEXT);"); Log.i(Constants.TAG,"CREATE STRING: "+Query.toString()); db.execSQL(Query.toString()); if(tableEmpty()) {setDefault();} } /** * Populate the database with numbers 1->MAXNUM giving each a value of 0. */ private void setDefault() { for (int i=1;i<=Constants.MAXNUM;i++) { setValue(String.valueOf(i),"0"); } } /** * Method to get the values, ordered by frequency * @return Comma seperated */ public String[] getAllValues() { Cursor c=null; int counter=0; String[] val = new String[Constants.MAXNUM]; try { c = getReadableDatabase().query(DB_TABLE, null,null, null, null, null, COL_VALUE); c.moveToFirst(); //Ensure there is something in the database if(c.getCount()>0) { // Make sure the cursor never goes over the edge while(!c.isAfterLast()) { // Append each value in order, seperated by a comma val[counter++]=c.getString(1); c.moveToNext(); } } } catch(SQLiteException e){ Log.e(Constants.TAG,"getValue::SQLiteException::"+e.getMessage()); e.printStackTrace(); } finally { c.close(); // Tidy up } return val; } public String getValueByKey(String _key) { String val = ""; try { Log.i(Constants.TAG,"key is: "+_key); Cursor c=getReadableDatabase().query(DB_TABLE,new String[]{COL_VALUE},COL_KEY + " LIKE ?",new String[]{_key},null,null,null); c.moveToFirst(); if(c.getCount()>0) { val = c.getString(0); } c.close(); } catch(SQLiteException e) { Log.e(Constants.TAG,"SQLiteException::"+e.getMessage()); e.printStackTrace(); } return val; } /** * Method checks to see if there are any records in the database * @return Boolean true if empty, false if not empty */ private boolean tableEmpty() { boolean result = false; if(!(getValueByKey("1") == "0") ) { result=true; } return result; } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {} } My database has 2 columns. The left column has the key, and the right has the value. I am trying to get the value of the first record and return it. The error message is a generic NullPointerError so I don't know much about the error, other than the fact that its to do with getReadableDatabase(). Can anyone see what I'm doing wrong? Thanks. EDIT: I've added the full code. Here's the stacktrace: 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): FATAL EXCEPTION: main 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): java.lang.NullPointerException 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at com.eoinzy.myApp.MyClass.openDatabase(MyClass.java:137) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at com.eoinzy.myApp.MyClass.getFrequency(MyClass.java:204) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at com.eoinzy.myApp.MyClass.tableEmpty(MyClass.java:252) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at com.eoinzy.myApp.MyClass.getAllValues(MyClass.java:169) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at com.eoinzy.myApp.MyClass.setupNumbers(MyClass.java:48) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at com.eoinzy.myApp.MyClass.<init>(MyClass.java:38) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at com.eoinzy.myApp.ButtonControl.onClick(ButtonControl.java:56) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at android.view.View.performClick(View.java:2501) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at android.view.View$PerformClick.run(View.java:9107) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at android.os.Handler.handleCallback(Handler.java:587) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at android.os.Handler.dispatchMessage(Handler.java:92) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at android.os.Looper.loop(Looper.java:130) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at android.app.ActivityThread.main(ActivityThread.java:3835) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at java.lang.reflect.Method.invokeNative(Native Method) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at java.lang.reflect.Method.invoke(Method.java:507) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605) 09-23 15:16:27.450: ERROR/AndroidRuntime(11825): at dalvik.system.NativeStart.main(Native Method) A: Try this way of Coding so that you can easily Debug you Error. Also Null Pointer comes for Lot of reason for Null values. private Cursor cursor_value; private DbHelper mDbHelper; mDbHelper = new DbHelper(this); mDbHelper.open(); try{ String cursor_link_value,cursor_time_value,cursor_name_value; cursor_value = mDbHelper.fetch_message_values(); Log.v("cursor_value", ""+cursor_value.getCount()); startManagingCursor(cursor_value); if (cursor_value.moveToFirst()) { do { value =cursor_value.getString(cursor_value.getColumnIndex(Column_Name)); } while (cursor_value.moveToNext()); } } catch(Exception e){ Log.v("Excepqqqqqqqqqqqqqqqqqqqq", ""+e); } For DB : Write your Query inside of DbHelper Class : public Cursor fetch_message_values() { // TODO Auto-generated method stub Cursor c=mDb.rawQuery("Your Query",null); Log.v("Cursor Count for Draft Table", ""+c.getCount()); return c; } For Further Reference Check this link for Notepad Example for Database
{ "language": "en", "url": "https://stackoverflow.com/questions/7501254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run multiple consoles from one class? I have three classes which all make different works but I need to run them together. When I run all of them in one class I just get one console and cant change this console. What I want is to run them in one class and see each console . How can I do that ? To be more clear , when I run first class, I get --> console 1 when I run secondclass, I get --> console 2 when I run third class, I get --> console 3 but instead of doing it seperatly, when I do it; Run 1,2,3 ----> I get console 1 The thing I want is Run 1,2,3 ----> I get console 1, 2 and 3 Thank you all EDIT 1 : Sorry for not-enough info I use Eclipse to run my code, and I am talking about Eclipse console. A: * *A certain way to do it would be to open 3 separate terminals and do java Class<n> (without .class extension) in each terminal. *I don't think you can do it in Eclipse with a single workspace (it could be possible though ...), one way to do it is to create separate projects for each class and open each project in a separate workspace simultaneously, but this is too much work IMO. 1. is probably the easiest/fastest way to do it. A: You have to invoke java command separately for each class in different console. With one java invocation, i think, there will be only one console associated. A: Obscure question. But it seems that you need separate console outputs for your classes. I don't think it is possible. That is operating system restriction. If operating system supported that you could somehow create additional consoles. As a solution you can give your classes PrintStream object which they will use to output data. A: You could run a server-like application which would accept messages and then display them in the console. The class would start each of your other main methods in new Threads, and then wait indefinitely for messages, ending when the other three threads close. A: INMO, if your underlying OS is Windows then you need to handle console and use JNA or JNI that allows you to call win32APIs from java, but if your underlying OS is Unix-like then you need to find a way to communicate with syscall APIs in java. by calling native APIs you can call native console and if you know how to create a native console then you can create multiple instances of native console.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with using aircrack-ng I have problem with install a Aircrack-ng. I was downloading aircrack from the official website and I followed to the ruls: cd aircrack-ng-1.1 make make install http://pastebin.com/XsMzCbGN A: Look at line 21: crypto.h:12:26: fatal error: openssl/hmac.h: Aucun fichier ou dossier de ce type It appears you don't have openssl properly installed? You also should run "make install" as sudo (if you don't have admin rights) Alternatively, if you're using Ubuntu (or similar distro), aircrack-ng should be in your repositories, so you don't need to install it from source: sudo apt-get install aircrack-ng
{ "language": "en", "url": "https://stackoverflow.com/questions/7501261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Testing variables in PHP Earlier today I tried to do this: Example 1: <?php echo $myVar || "rawr"; ?> I thought this might print out $myVar if it was set, and print "rawr" if not. It printed a 1, I assume this is the result of the OR test. What I then tried was this: Example 2: <?php if ($myVar) { echo $myVar; } else { echo "rawr"; } ?> Which is what I was trying to accomplish. I think I understand why the first prints the results of the OR test rather than one of the variables, and also why I tried it - been spending some time on the bash shell recently :) Can anyone tell me if there is a way to perform the text in example #2 but in similar syntax to example #1? A: PHP 5.3: echo $myVar ?: 'rawr'; Pre 5.3: echo $myVar ? $myVar : 'rawr'; If $myVar may not be set you'd have to use isset($myVar) and $myVar as the condition (which then wouldn't work with the shorthand ?: syntax, as this would echo 1 if it was set, rather than the value). echo (isset($myVar) and $myVar) ? $myVar : 'rawr'; A: In PHP 5.3+ it is possible to leave out the second argument: echo $myVar ?: 'rawr'; This is probably closest to what you want. A: PHP is notoriously inelegant in this department, and there really is no good way of making this test. As a general solution, you 'd need to use the ternary operator as in empty($var) ? "rawr" : $var. However, in practice what happens is that you have one of two scenarios: 1. Your own variable In this case where you define the variable yourself, the best solution is to just give it a known default value at the place you define it (possibly with the ternary operator). 2. Inside an array If the array is one that should not be touched like one of the superglobals, then you can wrap the test inside a function (pretty much that's what everyone does). If the array is one under your jurisdiction but it comes from an external source, you can use the "add the defaults" trick: $incoming = array(...); $defaults = array("foo" => "bar"); // Inject the defaults into $incoming without overwriting existing values $incoming += $defaults; At this point you know for a fact that every key inside $defaults also exists inside $incoming. A: Try this: echo $myVar = ($myVar) ? $myVar : 'rawr'; or echo $myVar ? $myVar : 'rawr'; A: I think you want to use something like var_dump($varname) or isset($varname) ? A: it's matter of operator precedence. you can't do that. two points as a food for thought * *if $myVar is not set, you'll get an error message, not "wawr"; *by the time you're going to echo some variables, every one of them should be defined and have value. That will make your template clean and readable. A: Try echo ($myVar != null ? $myVar : "Rawr!");
{ "language": "en", "url": "https://stackoverflow.com/questions/7501265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pasting hundreds of lines of text into Emacs Pasting 900 lines of text into console-mode Emacs (Shift-Ins) on an Ubuntu desktop machine results in only 842 lines of text appearing. I have experienced similar situations in the past where not all the text I've selected is pasted. Any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/7501266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook PHP SDK - Web App is working on one machine but not any others? I am on the verge of going crazy I think! I am logged into my Personal Facebook account on my work machine and the app I am using works fine but on any other machine logged in as me, the app admin or anyone else the page just seems to keep on constantly refreshing with the state parameter in the url just whirring away and changing between page loads. (I have a laptop sitting on my desk, both using Firefox aswell) I'm sure it was working on all machines that tested it the other day. Today it started with an error but I can't remember the error code but it was to do with the re-direct url not being owned by the domain but this doesn't seem to crop up now. I am not the admin of the app either. Here is the relevant code: <? error_reporting(0); // Facebook PHP SDK include_once "src/facebook.php"; // app id and seret from the facebook app $appId = 'xxxxxxxxxxxxxx'; $secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'; $facebook = new Facebook(array( 'appId' => $appId, 'secret' => $secret, 'cookie' => true, )); //Facebook Authentication part $user = $facebook->getUser(); $loginUrl = $facebook->getLoginUrl( array( 'canvas' => 1, 'fbconnect' => 0, 'scope' => 'user_status,publish_stream,user_photos' ) ); if ($user) { try { // page id and the feed we want $user_feed = $facebook->api('PAGENUMBER/feed'); echo "<div id=\"graph\">"; $count = 0; for ($i=0; $i<25; $i++) { // only want statuses - no videos, events, links etc. if ($user_feed['data'][$i]['type'] == "status") // just grabbing stuff and echoing it out // blah blah blah } } catch (FacebookApiException $e) { $user = null; } // close graph div echo "</div>"; } // if the user is not logged in then redirect to login page if (!$user) { echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>"; exit; } ?> A: This was a pain but took out the if ($user) and the try catch and the login redirect and all that seemed to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert String into Class for TitleWindow I don't know if this is possible, I am pulling the names for TitleWindows from my database as strings. Then from my main application I have to launch the TitleWindow. So in my function I need to convert the name of the TitleWindow which is a String to a Class, because the PopUpManager accepts a Class. Below is my code. When launching my application and trying to launch the TitleWindow I am getting the error: Implicit coercion of a value of type String to an unrelated type Class. I don't want to hard code the name of my popUp in the PopUpManager, that is why I am doing it like this. Any way to work around this? public function getScreen(screenName:String):void { var screen_Name:Class = new Class(); screen_Name = screenName; var popUpWindow:TitleWindow = PopUpManager.createPopUp(this, screen_Name, false) as TitleWindow; PopUpManager.centerPopUp(popUpWindow); } A: I have had to do something very similar recently. Here is the function I wrote to do it: //You have to provice the package signature private var viewPackage:String = "org.bishop"; //In my case, event.type is the name of a class var className: String = viewPackage + "." + event.type; try{ var classRef:Class = getDefinitionByName(className) as Class; viewNavigator.pushView(classRef); } catch(e:ViewError){ trace(e.message); logger.debug(e.message); } Note: for the class to be created correctly, you will need to include both an import statement: import org.bishop.Login; and also declare a variable of the class in the code as follows: Login; otherwise the classes will not be available to be created.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Random 0x80004003 invalid pointer error on child SSIS packages on new server We have a new SQL 2008 R2 instance that's part of a cluster (active/passive) on Windows 2008. I'm testing an SSIS package on the SQL instance that calls many child packages. It's been dying on random packages (rarely the same one twice) with the following error: Error 0x80004003 while preparing to load the package. Invalid pointer. I can run the individual package from the SSIS package store just fine. I can also run the master package from BIDS and it'll run perfectly. I've tried a repair on the SQL instance but there was no difference. I also tried removing and reimporting all the packages to the SSIS package store, with no change. My google-fu is weak, because I can't find anything useful in the cloud. Nothing is in either the SQL server error logs or any Windows error logs. Anyone have any ideas? A: I have the same issue. I closed the visual studio and restart it as an administrator (Shift + Right Click using the Mouse) and it worked fine with me. A: What worked for me was chaging the protection level on the packages. I set the protection level on the parent and all the child packages to DontSaveSensitive, and re-deployed. No longer received the errors. Hope this helps someone. A: Rebuilding the master package from the ground up fixed the issue. Still, if someone has an idea, I'd love to hear it; rebuilding it is a pain on a good day. A: I was facing same problem. I used Execute package Utility (EPU) to run Parent package created from BIDS 2008. somehow It gave me error Error 0x80004003 while loading the package. Invalid pointer. The issue was having two SQL Server, 2008 R2 and 2012. By default, "EPU" run from SQL Server 2012 which is failed because package created from BIDS 2008. You have to run EPU from SQL Server 2008 folder which execute package successfully. I hope this help you. * *Yatin Patel
{ "language": "en", "url": "https://stackoverflow.com/questions/7501275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: RWCString is dropping core In our code we use RWCString instead of std::string. One of the functions is dropping core and the stacktrace points to RWCString. The function looks like this. bool Eligible(const Message& message) { Table* tmpTable = GetTableFromMessage<Table>(message, "TABLE")); return ( tmpTable != NULL && tmpTable->getNumRows() > 0 ) ? ( getString((*tmpTable)("xyz")) == "xyz") : false; } ((*tmpTable)("xyz") returns RWDBValue getString returns RWCString. Don't consider the memory leak here. We are actually wrapping the Table* in a smart pointer. The stack trace is below. I am unable to figure out why RWCString is dumping core. fcac642c _lwp_kill (ffbfb530, fcaf7ba8, 3b15c, 0, fcaee2f4, fcaf83f4) + 8 fcab333c thr_panic (fcadc15c, 73, 3b088, fcab5788, ffbfb52f, a) + d8 fcabbcec _ceil_prio_inherit (b8, fcaf53c4, 32658, fcabbc60, fcaee2f4, fe092a00) + 5c fcabddbc mutex_lock_internal (13359f8, 0, 1, 0, 0, ae) + 170 00584db0 __1cL_RWSTDMutexHacquire6M_v_ (13359f8, 1, fcaf3700, 0, fe092a00, 13b2ce0) + 20 00583e20 __1cL_RWSTDGuard2t5B6MrnL_RWSTDMutex__v_ (ffbfb8d0, 13359f8, fe07d85b, ffbfb6d8, 2, 0) + 20 005846b8 __1cH__rwstdM__string_ref4CcnDstdLchar_traits4Cc__n0BJallocator4Cc___R__removeReference6M_l_ (13359f8, 0, 2, 0, 0, 0) + 28 00581a4c __1cDstdMbasic_string4Ccn0ALchar_traits4Cc__n0AJallocator4Cc___I__unLink6M_v_ (ffbfbaf0, ffbfb958, ffbfb95b, 243604, 0, 0) + 54 00580874 __1cDstdMbasic_string4Ccn0ALchar_traits4Cc__n0AJallocator4Cc___2T5B6M_v_ (ffbfbaf0, ffbfb9c8, ffbfb9f8, 0, fcaf5424, ffbfe278) + c **0057a3b4 __1cJRWCString2T5B6M_v_ (ffbfbaf0, 0, fcaf3700, 0, fe092a00, 0) + c** 0056dbfc __1cMConfirmKEligible6FrnKFXOMessage__b_ (ffbfe8f0, 0, 216b8c, 8a5668, 8a5668, 8bc550) + 1b4 00214da4 __1cPFXORTCConfirm_iOprocessMessage6MrknMFXOWLSModuleIFXOQdDData__h_ (99bc28, 9cdee0, fd171bc8, 400, 748, 2800) + 2414 0020f63c __1cRPOA_FXORTCConfirmGinvoke6MpnFCORBANServerRequest__v_ (99bc28, 9cf3d8, 8e4e50, fcfb7a40, 7c770, 0) + 1bc fd124f2c __1cSObjectStateManagerGinvoke6MpnJTPContext__v_ (8e56c8, ffbfebf8, 8e2a08, 8da8f8, 800, 8da8f8) + 60 fd12c338 __1cNObjectManagerGinvoke6MpnFCORBANServerRequest__v_ (8bf288, 9cf3d8, fd85d6cc, 70726f63, 80808080, 1) + 28 fd867a4c __1cHPOAImplOProcessRequest6MpnRServerRequestImpl_rnJErrorInfo__v_ (fd171a54, 9cf3d8, ffbfee60, fd12c3f4, fd171a54, fd85f908) + 270 fd85c65c __1cRObjectAdapterImplbBProcessRequestServerRequest6MpnRServerRequestImpl_rnJErrorInfo__v_ (8fe828, 9cf3d8, ffbfee60, 1, 70, 0) + b4 fc61c95c __1cNTGIOPProtocolHRequest6MrnORequestMessage_rnHBinding_rnJErrorInfo__v_ (8e9ea8, 99a1a0, 9d3508, ffbfee60, ffffff2c, 0) + 10 fc62525c __1cNTGIOPProtocolNCreateMessage6MpCLrirpcrlrnLGIOPMessageHMsgType_irnJErrorInfo__v_ (8e9ea8, ed5298, 1, 2, 1, aa9958) + 6c0 fc61f218 __1cNTGIOPProtocolMTGIOPService6Mpvrirpcrl_v_ (8e9ea8, 8dbde4, ffbfef38, ffbfef3c, ffbfef34, fc61f124) + f4 fcff0014 __1cRGIOPProtocolTowerMTGIOPService6Fpvrirpcrl_v_ (8dbde4, ffbfef38, ffbfef3c, ffbfef34, fd0db020, fd0e7c38) + b0 0068caf8 CORBA_SVC (8dbde4, 8dbde4, 0, ed51d0, 2e, 0) + 38 fcc54d04 _tmsvcdsp (0, 628, 0, 0, 62c, 0) + 1120 fcc798c0 _tmrunserver (8d7a38, 1400, fcd6e618, fb44be3c, 8e2a08, 8da8f8) + 1598 fcc537e4 _tmstartserver (13, ffbff644, 8a8a6c, 1d3c, 8d1238, 1) + 1b8 0020b228 main (13, ffbff644, ffbff694, 8a8000, fc9b6900, 0) + b0 00146490 _start (0, 0, 0, 0, 0, 0) + 108 A: It is hard to answer what exactly is causing this crash since you didn't post a complete code example that reproduces the problem. You have to use a memory profiler (for example - Valgrind) in order to find the place where memory gets corrupted or access goes out of bounds. A: If I had to guess (and that's all anyone can do with that little code) then I'd say that it's a thread safety issue. It looks like the crash happens because the allocator can't get the mutex lock when trying to update a reference count. I'd look for places where the same string was being modified in a different thread, or other strings were being allocated. Check the rw docs about it's thread safety policy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Placing PHP within Javascript I can't seem to get the PHP to echo out within a Javascript tag: places.push(new google.maps.LatLng("<?php echo the_field('lat', 1878); ?>")); What am I doing wrong? A: PHP works when you execute the page, and it should work. Please note that php does not execute when you run a JS function. Please also make sure that you really have that the_field function. A: Have you tried it without the quotes ? places.push(new google.maps.LatLng(<?php echo the_field('lat', 1878); ?>)); A: I suspect you have your " quotes in the LatLng method arguments when there shouldn't be any. Your php should output a string such as '50.123123123, 12.123144' (without the ' quotes). The LatLng method expects 2 values. places.push(new google.maps.LatLng(<?php echo the_field('lat', 1878); ?>)); Try that. A: If you're looking to populate a Google Map with markers as the result of a database query, you probably want to wrap it in a JSON web service. Something as simple as: <?php // file to query database and grab palces // do database connection $places = array(); $sql = "SELECT * FROM places"; $res = mysql_query($sql); while ($row = mysql_fetch_object($res)) { $places[] = $row; } header('Content-Type: application/json'); echo json_encode($places); exit; And then in your JavaScript file: // get places $.getJSON('getplaces.php', function(response) { for (var i = 0; i < response.length; i++) { place[] = response[i]; places.push(new google.maps.LatLng(place.lat, place.lng)); } }); A: If i understand what you are trying to do (maybe some more explanation of your problem is required for this), then this might be your answer: places.push(new google.maps.LatLng(<?php echo '"' . the_field('lat', 1878) . '"' ?>)); EDIT: removed the ;
{ "language": "en", "url": "https://stackoverflow.com/questions/7501278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP fread hangs when using SSL I'm using fsockopen to connect to an OpenVAS manager and send XML. The code I am using is: $connection = fsockopen('ssl://'.$server_data['host'], $server_data['port']); stream_set_timeout($connection, 5); fwrite($connection, $xml); while ($chunk = fread($connection, 2048)) { $response .= $chunk; } However after reading the first two chunks of data, PHP hangs on fread and doesn't time out after 5 seconds. I have tried using stream_get_contents, which gives the same result, BUT if I only use one fread, it works ok, just that I want to read everything, regardless of length. I am guessing, it is an issue with OpenVAS, which doesn't end the stream the way PHP expects it to, but that's a shot in the dark. How do I read the stream? A: I believe that fread is hanging up because on that last chunk, it is expecting 2048 bytes of information and is probably getting less that that, so it waits until it times out. You could try to refactor your code like this: $bytes_to_read = 2048; while ($chunk = fread($connection, $bytes_to_read)) { $response .= $chunk; $status = socket_get_status ($connection); $bytes_to_read = $status["unread_bytes"]; } That way, you'll read everything in two chunks.... I haven't tested this code, but I remember having a similar issue a while ago and fixing it with something like this. Hope it helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7501289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UDP client multicast : join a group, what address to specify? http://msdn.microsoft.com/en-us/library/ekd1t784.aspx The JoinMulticastGroup method subscribes the UdpClient to a multicast group using the specified IPAddress. What address should I specify? context: I have many computers, which I want to exchange messages between each other by udp multicasting so that one computer sends a message at once to all other members of a certain group. also, how do I multicast the message using the send routine of udpclient http://msdn.microsoft.com/en-us/library/08h8s12k.aspx ? A: While echoing @Vlad's suggestion on general network background, there is sample code in MSDN for the scenario you want here. The following code example demonstrates how to join a multicast group by providing a multicast address. Once you have members who have joined the group, any member can call Send to multicast to all members of the group. Working through the MSDN docs to understand the sample code and relate it to your own situation should give you all you need to know for simple UDP multicast scenarios.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing through many files and extract data to a new file? Ok! My grey hairs have started popping out because of this. I have 400 PDF files which I want to extract a line from. The line starts with DIR and then a number follows. But I will need the file name as well! So do anyone know a way to parse through PDFs (or I can convert them to txt) and then search for a term, expand, append file name to it and save it into a new file. Any help will be greatly appreciated!! Thanks, Tor A: You have Itext library that you can use for opening the pdf. Than you will need to scan each pdf for your pattern The link to the library www.itextpdf.com
{ "language": "en", "url": "https://stackoverflow.com/questions/7501298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: subclassing outputcache issues in mvc3 I am having some issues understanding what is happening when I create a simple subclass of OutputCacheAttribute in MVC3. Here is the code: public class ExampleOutputCacheAttribute : OutputCacheAttribute { public ExampleOutputCacheAttribute() { // breakpoint here } public override void OnActionExecuting(ActionExecutingContext filterContext) { // breakpoint here base.OnActionExecuting(filterContext); } public override void OnActionExecuted(ActionExecutedContext filterContext) { // breakpoint here base.OnActionExecuted(filterContext); } public override void OnResultExecuting(ResultExecutingContext filterContext) { // breakpoint here base.OnResultExecuting(filterContext); } public override void OnResultExecuted(ResultExecutedContext filterContext) { // breakpoint here base.OnResultExecuted(filterContext); } } The first time a controller action with this attribute is requested, the constructor and all overridden methods are hit, but if I refresh the page, none of the methods or the constructor are hit. It is as if the cache is being read from outside the OutputCacheAttribute, but looking at the MVC source code for OutputCacheAttribute, I can see that in OnActionExecuting, there is code for checking for a cached page and returning the result: filterContext.Result = new ContentResult() { Content = cachedValue }; Can anyone shed any light on what is happening? A: It seems as though the OutputCache filter is more complicated than it originally appears. For page caching, it hooks in to the standard ASP.NET output caching mechanism which uses the OutputCacheModule HttpModule in IIS. Once the filter is hit once and adds the page to the cache, subsequent requests do not hit the filter in any way. The OutputCacheModule intercepts these requests and returns the cached object higher up the pipeline. For action caching, a separate mechanism is used. This uses a static MemoryCache and the constructor and all overridden methods are hit on every request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to resize image after overlapping in asp.net I have a problem that I have two downloaded images on my webpage(second image is overlapped with first image), I have to resize second image which is overlapped, programmatically. I don't know how to achieve this? Please suggest me the right result. A: The jQuery library makes it easy to do a thing like this. If you identify the second image by setting it's id attribute id='secondImage', then you could write something like: $('#secondImage') .css('width','200px') .cssS('height','100px'); However, I want to say that plain CSS is likely a better solution. With plain CSS, you could just write #secondImage { width: 200px; height: 100px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Connection String Debug I guess my question is how do you debug a connection string? Background Info * *Dev Machine is 64bit but I have my build targeting 32bit *Windows Form App targeting .NET 2.0 *Has an embedded access database to hold look up values and store some basic information *In App.config add name="MyConnection" connectionString="Provider = Microsoft.Jet.OLEDB.4.0; Data Source =C:\Development\MyFolder\MyAccessData.mdb;" As soon as I hit F5 it sets a breakpoint on this line: connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ToString(); A: try this.. connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
{ "language": "en", "url": "https://stackoverflow.com/questions/7501304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem in dismissing fullscreen mode of MPMoviePlayerViewController In my application i am using MPMoviePlayerViewController to play online video. The video should play in fullscreen mode when in landscape and the fullscreen mode should be dismissed when it rotates to portrait mode. I am able to play the video in fullscreen mode. But not able to dismiss it when the device orientation changes to portrait mode. I am using [mpController.moviePlayer setFullscreen:FALSE animated:YES]; Someone please help. Thanks in advance. A: I assume you're trying to detect the orientation change in the view controller that present MPMoviePlayerViewController? This code won't be fired after the movie player view controller is presented because it—not its parent—will receive the rotation events. You can, however, subscribe to the device rotation notifications and dismiss the movie player view controller whenever you detect a rotation to portrait: [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [defaultCenter addObserver:self selector:@selector(deviceOrientationDidChange:) name: UIDeviceOrientationDidChangeNotification object:nil]; // Present MPMoviePlayerViewController here Elsewhere in the same view controller: - (void)deviceOrientationDidChange:(NSNotification *)notification { UIDevice *currentDevice = [UIDevice currentDevice]; [currentDevice endGeneratingDeviceOrientationNotifications]; if (...) // Check currentDevice.orientation to see if it's what you want { // Do whatever you want now that you have the orientation you want } [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil]; } A: Set observer for UIDeviceOrientationDidChangeNotification or UIApplicationWillChangeStatusBarOrientationNotification, check new required orientation and set new mode for MPMoviePlayerViewController.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference between minutes Say I have 2 strings in the following format: "09/21 10:06AM" "09/21 10:10AM" How do I find the time difference between these strings, stored as an int? This has to be robust enough to handle situations like 10:59AM and 11:02AM (odd number of minutes in between), 11:59AM and 12:03PM (AM to PM switch) etc. No need to worry about seconds. Thanks! A: I would suggest: * *Use Joda Time instead of the built-in API; it's much nicer. *Parse into LocalDateTime values *Find the difference between them with: Minutes period = Minutes.minutesBetween(first, second); int minutes = period.getMinutes(); A: * *DateFormat.Parse *Calculate difference between dates. A: Parse the strings to Date objects and get the difference between them in milliseconds. Then convert those milliseconds to minutes (divide by 60000 and take the ceiling of the result). A: If there is a switch to daylight savings the difference can be an hour more on one day than another. It best to use a library which does this already. JodaTime is best, but SimpleDateFormat and Date will probably do what you need. A: * *Convert the 2 Strings to Dates. *Subtract one from the other. *Multiply the result by 1440 (Number of minutes in a day). *Round the result to an Integer. Let me know if it works :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7501311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Moving compile items in msbuild into a separate file? This is probably a FAQ, but we weren't able to find a solution even after a lot of searching. We have a number of msbuild files that all operate on the same set of source files. (It's not particularly relevant but they compile to completely different platforms.) To make managing these a little simpler, we'd like to move the <Compile> source file names to a separate file and reference that from all the msbuild files. We tried cutting the <ItemGroup> containing the <Compile> items and pasting it into a new file, and surrounding it with <Project DefaultTargets="Build" ToolsVersion="3.5" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> and then referencing that file from the original with <Import Project="Common.files.csproj" /> but that does not work - the solution opens (with a warning since we hacked the default config), but no items appear in the Solution Explorer. What are we doing wrong? A: Tried with Visual Studio 2010: 1) Create your external .proj (or .target) file and add your files (I used a different item name but that shouldn't matter) <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <ExternalCompile Include="Program.cs" /> <ExternalCompile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> </Project> 2) Import your external .proj file at the top of your Visual Studio project file: <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="MyExternalSources.proj" /> <PropertyGroup> ... and modify the Compile ItemGroup like this: ... <ItemGroup> <Compile Include="@(ExternalCompile)" /> </ItemGroup> ... Warning: You'll have to add new items/files to your external .proj file - all items/files added from within Visual Studio will end up like this: ... <ItemGroup> <Compile Include="@(ExternalCompile)" /> <Compile Include="MyNewClass.cs" /> </ItemGroup> ... A: I've never seen "include" files work with MSBuild. Obviously Targets files work this way, but I haven't seen a partial msbuild file included in another. COuld you use a method such as illustrated in this? http://msdn.microsoft.com/en-us/library/ms171454(VS.80).aspx Using wildcards is how I've addressed this in the past.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: InitializeComponent() before adding WebContext to ApplicationLifetimeObjects or wait for the App.Current.Startup event? I have a Silverlight application architected using an MVVM approach. In my ViewModel it is time to load some data only after the user is LoggedIn, so I need to intercept this event to trigger my LoadData(). With default configuration, and I mean this in the App.xaml.cs: public App() { InitializeComponent(); // Create a WebContext and add it to the ApplicationLifetimeObjects // collection. This will then be available as WebContext.Current. WebContext webContext = new WebContext(); webContext.Authentication = new FormsAuthentication(); //webContext.Authentication = new WindowsAuthentication(); this.ApplicationLifetimeObjects.Add(webContext); If you try to subscribe to LoggedIn Or LoggedOut events in the ViewModel constructor, you get a bit of problems: WebContext doesn't exists yet. So I thought... I'll create my WebContext first and then I'll InitializeComponents() in my App but that made ExpressionBlend sad... So, here it is my solution, I like to share it with you because I'm not totally convinced that this would be the right approach: App.Current.Startup += (sender, eventArgs) => { WebContext.Current.Authentication.LoggedIn += WebContext_LoggedIn; WebContext.Current.Authentication.LoggedOut += WebContext_LoggedOut; }; In my ViewModel ctor I subscribe to App.Current.Startup and my delegate will subscribe my ViewModel to Login events, this way I have not changed my App.xaml.cs and I'm sure to subscribe to Login events when WebContext exists... So: private void WebContext_LoggedIn(object sender, AuthenticationEventArgs e) { LoadData(); } EDIT In this case I'm more interested in understanding if I'm right when I say that I shouldn't change the order between InitializeComponent() and the rest and that I need to listen for a particular event to trigger my LoadData(). Just for the sake of completeness, here it is my refactor to get rid of that dependency in my ViewModel: I created a message: public class UserLoginStatusChangedMessage : MessageBase { public bool IsLoggedIn { get; set; } } sent it here: private void Application_Startup(object sender, StartupEventArgs e) { // This will enable you to bind controls in XAML files to WebContext.Current // properties this.Resources.Add("WebContext", WebContext.Current); // This will automatically authenticate a user when using windows authentication // or when the user chose "Keep me signed in" on a previous login attempt WebContext.Current.Authentication.LoadUser(this.Application_UserLoaded, null); // Show some UI to the user while LoadUser is in progress this.InitializeRootVisual(); WebContext.Current.Authentication.LoggedIn += (s, a) => { Messenger.Default.Send(new UserLoginStatusChangedMessage { IsLoggedIn = true }); }; WebContext.Current.Authentication.LoggedOut += (s, a) => { Messenger.Default.Send(new UserLoginStatusChangedMessage { IsLoggedIn = false }); }; } and received it like this in ViewModel ctor: Messenger.Default.Register<UserLoginStatusChangedMessage>(this, msg => { if (msg.IsLoggedIn) { LoadData(); } }); A: I'd suggest using some kind of messenger class that would send a message when the user is logged in. MVVMLight has a nice messenger class that is easy to use. Then you would just send a message when the user's logged in state changes and subscribe to that event in your view model that needs to know if the user is logged in. You could check the WebContext to see if it is created and if it is created if the user is logged in when your viewmodel is created and then after that just use the messages to determine if/when this changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Call WCF service with XML I'm trying to call a WCF service. However, I have the request body as an XML document. So for instance, instead of this ListProductsRequest request = new ListProductsRequest(); request.Query = new RootQuery(); request.Query.Product = "milk"; request.Query.Group = "dairy"; ListProductsPortType client = new ListProductsPortTypeClient(); ListProductsResponse response = client.ListProducts(request); I wanna do this: String xml = "<Root xmlns=\"urn:ns\"><Query><Group>dairy</Group><Product>milk</Product></Query></Root>"; var request = // read in to XmlReader or XmlDocument or whatever ListProductsPortType client = new ListProductsPortTypeClient(); var response = client.ListProducts(request); Is there a way to use the generated proxy, with the advantage of having the data layer security and transport handled for me, but without using the proxy objects? Thanks, Brecht A: I don't think you can call a WCF service and passing what you want. The method ListProducts only accept a ListProductsRequest object. So you have to create this kind of object. String xml = "<Root xmlns=\"urn:ns\"><Query><Group>dairy</Group><Product>milk</Product></Query></Root>"; ListProductsRequest request = MappingObject(xml); ListProductsPortType client = new ListProductsPortTypeClient(); var response = client.ListProducts(request); And in the Mapping method you can work with your XML to create an ListproductRequest. I don't know if there is another way to do this. A: I got this far, thanks to 2GDev's comment. Code without handling exceptions or abnormal situations properly. This way I can use the generated stub's endpoint (and thus reuse the config etc.) public void CallWs() { WsdlRDListProductsPortTypeClient client = new WsdlRDListProductsPortTypeClient(); String req = "<Root xmlns=\"urn:ns\"><Query><Group>TV</Group><Product>TV</Product></Query></Root>"; CallWs(client.Endpoint, "ListProducts", GetRequestXml(req)); } public XmlElement CallWs(ServiceEndpoint endpoint, String operation, XmlElement request) { String soapAction = GetSoapAction(endpoint, operation); IChannelFactory<IRequestChannel> factory = null; try { factory = endpoint.Binding.BuildChannelFactory<IRequestChannel>(); factory.Open(); IRequestChannel channel = null; try { channel = factory.CreateChannel(endpoint.Address); channel.Open(); Message requestMsg = Message.CreateMessage(endpoint.Binding.MessageVersion, soapAction, request); Message response = channel.Request(requestMsg); return response.GetBody<XmlElement>(); } finally { if (channel != null) channel.Close(); } } finally { if (factory != null) factory.Close(); } } private String GetSoapAction(ServiceEndpoint endpoint, String operation) { foreach (OperationDescription opD in endpoint.Contract.Operations) { if (opD.Name == operation) { foreach (MessageDescription msgD in opD.Messages) if (msgD.Direction == MessageDirection.Input) { return msgD.Action; } } } return null; } When I try this with the basic ICalculator sample from msdn http://msdn.microsoft.com/en-us/library/ms734712.aspx Which is secured with SPNego, I have to change this a bit, because then we need an IRequestSessionChannel instead of an IRequestChannel. public XmlElement CallWs(ServiceEndpoint endpoint, String operation, XmlElement request) { String soapAction = GetSoapAction(endpoint, operation); IChannelFactory<IRequestSessionChannel> factory = null; try { factory = endpoint.Binding.BuildChannelFactory<IRequestSessionChannel>(); factory.Open(); IRequestSessionChannel channel = null; try { channel = factory.CreateChannel(endpoint.Address); channel.Open(); Message requestMsg = Message.CreateMessage(endpoint.Binding.MessageVersion, soapAction, request); Message response = channel.Request(requestMsg); return response.GetBody<XmlElement>(); } finally { if (channel != null) channel.Close(); } } finally { if (factory != null) factory.Close(); } } It does do the negotiation, and a message seems to be sent, but unfortunately I now get the following error message: No signature message parts were specified for messages with the 'http://Microsoft.ServiceModel.Samples/ICalculator/Add' action. A: I think you could use ListProductsRequest request = (ListProductsRequest) new XmlSerializer( typeof(ListProductsRequest)).Deserialize(); to create the corresponding object...
{ "language": "en", "url": "https://stackoverflow.com/questions/7501321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I show an dialog in which the permissions of a registry key can be set I'm working on a registry editor for Windows. I want to add an dialog which can be used to change the permissions for a specific registry key. This is the way it should look like: This dialog is used by regedit and also by third party registry editing software such as O&O Regeditor. I'm looking for a windows function which displays such a dialog. I already did a search on MSDN but couldn't find anything. A: You want the Access Control Editor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to build a javascript class which accept a callback object Let's suppose I want to create a javascript class/object/function which have a method that can accept a callback object like this: callbacks = { onSuccess : // method to be executed in case of success onComplete : // method to be executed in case of complete onFailure : // method to be executed in case of failure onError : // method to be executed in case of an error } So let's suppose the classes name definition are the following: var Obj = function () {}; Obj.prototype.exec = function (callbacks, event, caller, argument) { } And I want to use the object in this way: var mytest = new Test(); var myObj = new Obj(); Obj.exec(callbacks,["onSuccess", "onComplete"], mytest, arguments); How should Obj.prototype.exec be implemented? A: It's a little confusing what you are asking: Obj.prototype.exec = function (callbacks, event, caller, argument) { var $xhr; if (argument instanceof Array) $xhr = caller.ajax.apply(this, argument) else $xhr = caller.ajax.call(this, argument) // wire up the listeners for (var i = 0; i < event.length; i++) { $xhr[event[i]] = callbacks[event[i]]; } } something like this perhaps
{ "language": "en", "url": "https://stackoverflow.com/questions/7501324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding the exact location of an Element in a XML-Document I'm looking for a way to find the exact location of an Element within a XML-Document. I parse my Document with XOM and process it in the usual way. The tricky thing is, that in the XML document, some scripts are embedded (just text nodes) and in the case the scripts fail (parsing, logic, whatever) I want to report the user (which writes those scripts) the exact line number the script has been declared. The most ideal way would be something like this: int scriptLine = someElement.getFirstChildElement("script").getDeclaringLineNumber(); Sadly I couldn't find a way to do this, with or without XOM. If anyone has ideas or has already done something like this - I could use some help. :-) A: Way back I did this with JDOM. By extending the SAXBuilder and intercepting the startElement() and endElement() callback, specialized Element implementations could be updated with line number information usig the SAX Locator. The code should still be around .... yes here: http://jdom.org/dist/binary/jdom-contrib-1.1.1.zip Search for LineNumberSAXBuilder in the src directory. I belive XOM has a NodeFactory that could be extended in the same manner.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: send parameters from test suite to test case in junit 4 I've got four junit cases and I need to pass them a parameter, that is the same for all of them, but this parameter is created in a dynamic way in the test suite. How can I pass a parameter from the test suite to all the tests in the test case? A: If its just a string parameter, you can set the System Property and access it in test cases. If you want to programmatically do it, you can do it at one place System.setProperty("x","123"); otherwise you can always pass System properties from command line as -Dx=123. A: Instead of use system property, try to use a static class, store a class with all info that you want in memory. A: Try parameterized tests. It is a built-in JUnit feature designed to pass parameters to all tests inside a test case. See below link for examples: https://github.com/junit-team/junit4/wiki/Parameterized-tests
{ "language": "en", "url": "https://stackoverflow.com/questions/7501327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Extend JSF component CommandLink How can I extend a jsf primeface link? I want to use the actionListener attribute with the link and overwrite the encodeAll method. A: You could create a composite component as a wrapper and use a backing class: <composite:interface componentType="my.special.Class"> ... </composite:interface> <composite:implementation> // place your wrapped component here </composite:implementation> Overwrite the encodeChildren method in the backing Class. Please note: This is rather a hack than a clean solution. Depending on what you want to do a custom renderer would be appropriate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to remove the messages that are being displayed on the (build,run) tab everytime I compile a C++ program in netbeans most of the messages are useless for me and quite annoying For example "/bin/make" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf make[1]: Entering directory /c/Users/kostas/Documents/NetBeansProjects/CppApplication_2' "/bin/make" -f nbproject/Makefile-Debug.mk dist/Debug/MinGW-Windows/cppapplication_2.exe make[2]: Entering directory/c/Users/kostas/Documents/NetBeansProjects/CppApplication_2' mkdir -p build/Debug/MinGW-Windows rm -f build/Debug/MinGW-Windows/main.o.d g++.exe -c -g -I../../../../../MinGW/lib -MMD -MP -MF build/Debug/MinGW-Windows/main.o.d -o build/Debug/MinGW-Windows/main.o main.cpp make[2]: Leaving directory /c/Users/kostas/Documents/NetBeansProjects/CppApplication_2' make[1]: Leaving directory/c/Users/kostas/Documents/NetBeansProjects/CppApplication_2' I don't need these things to be displayed, how to remove them completely?
{ "language": "en", "url": "https://stackoverflow.com/questions/7501337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Overcoming Browser difference I'm creating a website, so far I've used mostly HTML, CSS, PHP and some JQuery. My problem is that my code is not displaying the same thing in different browsers especially in Internet Explorer. Google Chrome, Firefox and Opera seem to be the same but Internet Explorer is different. How do I overcome this? Please help, thanks. A: There's a number of different things you can try to balance out the differences between browsers. One of the the most common things to do tends to be using a CSS reset. This will override default styles that browsers apply automatically to your code. The HTML syntax you use also plays a large part as some browsers will support elements differently if at all. The same goes for CSS. If you're just starting out I suggest you look at using something like HTML5 boilerplate: http://html5boilerplate.com/ Once you've been developing web for a few years you tend to know where issues are going to arise between various browsers and know good alternatives or ways to work around those. Lately a lot of developers have started adopting the "doesn't have to look the same in all browsers" approach. Which is a fair argument as usability and accessibility is more important than how a site looks. After all websites are for serving content. A: Is your HTML valid? You can check this using the W3C validation service at: http://validator.w3.org/ If not, then I'm going to suggest something that may sound quite asshole-ish, but will still hold: Learn HTML. Many people think they "know" HTML, and that is the reason why the Internet is such a mess. Learn what is valid and what is not valid and familiarize yourself with the DTD. Despite the belief, there is in fact a proper way of writing HTML and not writing it such a way will cause problems on various browsers. Do not use non-standard code. If it's not in the DTD, don't use it. HTML should also not contain too much formatting, as this should be handled by your CSS. Also, if you're planning on using HTML 4.01 as opposed to 5, stick with the strict DTD, not the transistional. A: Without you updating this question with more information/examples, I can only assume: HTML is your most likely culprit. Internet Explorer has a difficult time supporting many browser technologies that most developers take for granted. The classic <!-- [IF IE]> ...<> </> <![endif]--> referenced: http://www.positioniseverything.net/articles/cc-plus.html approach is what you'll learn most times, especially in class/book settings. On the web, however, there is the time old advice: If the page looks bad, well....that's IE. Chalk up a "V" that it isn't mangled, and focus on your core group (20 & 30-somethings who swear IE to be the devil). From what I've gathered, unless you're doing some corporate sponsored "must-be-IE" type of project (for reasons involving security protocol appeasement), then consider IE an afterthought, and nothing more. EDIT Not to be forgotten is the crucial Chinese market. If you're designing a website for a Chinese client, remember that everyone uses IE6 (ripped from pirated version of XP). It is a common exception to the above advice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to create a timepicker using jQuery? I am new to javascripting. I am using script in html code and i am using jQuery.js. How to add a timepicker using the method in jQuery and what method is that? A: http://fgelinas.com/code/timepicker/ try this A: Two useful ones: http://www.trentrichardson.com/examples/timepicker/ http://www.ama3.com/anytime/
{ "language": "en", "url": "https://stackoverflow.com/questions/7501340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the term for non-size limited stream function? As far as I can understand streams are of a fixed size, whether they are memory or file streams. Is there a term for an open ended stream like a serial port or a network socket connection? I'm working in Delphi XE. I've looked at classes that are decended from TStream. I would like to make an interface to a general class that would apply to a serial port, network socket, keyboard entry or simulated data. These would be data flow of no specifed length, containing packets of usable data. I'm at a loss for the proper search term. Maybe the right term is a socket, but that seems to be a more specific network term. A: Stream, pipeline, socket, file, whatever... they are all similar, in the following: * *They are initialized (opened) then destroyed (closed); *You have an handle (instance) over this structure; *You use Read and Write methods which may retrieve less content than requested (it allows unsized/infinite/abstract stream). In the POSIX/UNIX world, for instance, "everything is a file", even a network, a setting, a cpu, a device... In Delphi, you can perfectly inherits from a TStream to implement this behavior. Even the Seek method does not need to handle all the cases. You can have one-way / unidirectional streams, read-only or write-only stream. Then you can share the same code with diverse TStream implementations, to/from a file, a network, some memory, the keyboard, a screen, whatever... You can even nest streams, in order to add on-the-fly compression, encryption, replication... So if you are in the Delphi world, just call it "stream", implements a TStream... and happy coding! A: It's still a stream. You might call it a sequential-access stream, to differentiate it from a random-access stream. When implementing your TStream descendant, you're free to have the Seek method throw an exception if someone calls it to seek backward, forward, or any other disallowed usage. Something that can be read from but not written to is a source, and something that can be written to but not read from is a sink. No fixed sizes are implied with those terms. A: Listening to a port,socket or other types of communication is sometimes called a sniffer or a protocol analyzer. To implement a general method for this is not trivial. You would have to implement a specific abstraction layer for each type of communication. For example, listening to a serial port without knowing the protocol format is doomed to fail.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to validate Battleship field? I am trying to validate battleship field with these rules: * *Ships don't touch with sides or corners; *Ships are straight; *There are 1×4-deck ship, 2×3-deck, 3×2-deck, 4×1-deck ships. The field is represented as byte[10][10] array. What algorithm could I use to accomplish this? The language I use is Java, but any language is good. A: Simple algorithm. Main idea: every "full" field must be assigned to some ship. * *for every possible ship shape construct small matrix which holds its pattern and note its width and height. Every ship should be bordered with margin of width 1 of empty fields to ensure no adjacency. *for every possible ship shape, go through the battlefield and check the underlying pattern - check if the ship is there. *if the pattern matches, i.e. the ship is there, then just mark all underlying squares as belonging to this ship. Empty margin of width of 1 field ensures that no other ships / battlefield margin touches this ship. *repeat steps 2 and 3 for all possible ship patterns *go through the battlefield and check whether each square is marked as belonging to some ship. If yes, then the field is correct. If no, then the battlefield is not correct. A: Pseudocode: initialise the ship map with pairs of (size, amount of ships) values initialise your map[12][12]: for every place at row and column coordinate of 0 or 11 (the border) mark it as visited for every other place mark it as not visited fill it with either ship or ocean tile from your input for each row from 1 to 10 for each column from 1 to 10 if that place has not been visited yet mark that place as visited if that place is a ship tile check the places to the "right" (bigger column numbers) ... and bottom (bigger "row" numbers) until you hit a visited or ocean tile the amount of ship tiles checked (including the first) is current ship's length decrease the amount of ships of that length in the ship map by one mark all ship tiles of the current ship as visited mark all tiles surrounding those ship tiles as visited if the ship map includes any pairs with non-zero (including negative) amount of ships the map is invalid else the map is valid A: A quick check for validity: 1×4-deck ship, 2×3-deck, 3×2-deck, 4×1-deck ships must occupy exactly 1*4 + 2*3 + 3*2 + 4*1 = 20 cells. So if your field does not contain 20 cells, it is invalid (either ships overlap, or there aren't enough ships) Now, you need to verify that you have exactly the correct number of each type of ship, and that ships do not touch. You can do this through connected component analysis. The simple two-pass algorithm will do here (there's pseudo-code and examples for you in the link). This will give you the size, location and shape of each "blob" in your field. From there, you just need to iterate over each blob and check that it's either a vertical or horizontal line. That's simple -- just count the blob's width (difference between maximum and minimum column values) and height (difference between maximum and minimum row values). One of these must be equal to 1. If not, then two ships were touching, and the field is invalid. Finally, check that you have the correct number of each ship type. If you don't, then the field is invalid. If you do, the field is valid, and you're done. EDIT Ships can also touch end-to-end, but this will reduce the overall number of ships (increase the number of ships of a certain type) and thus fail the last test. EDIT 2 Corrected to use the correct ship specifications. A: I don't understand indeep what do you need: But I think a ship in Battleship game should have basic struct: Ship{ //x, y: top, left of ship's position int: x; int: y; int: size;//[1,2,3,4] boolean: isHorizontal;//It means a ship is vertical or horizontal on the map. } All your ships, if you declare in array, for example: Ship[SHIP_NUMBER]: arrShip There are some ways to check the ships are overlapped I can show you one of them: * *If you consider each ship is a rectangle you can check if there is exist two ships are intersect. *If you consider each ship is set on the map, it will hold the position of the map, for instance: 2-deck ship-horizontal: shipmap[0][0] = 1, map[0][1] = 1. So you can not set the ship on the cells are hold. And to check a ship is out of map * *You can check if ship.x < 0 || ship.y < 0 || ship.x > 9 || ship.y > 9 A: I think a better data structure for representing the board position would simplify the project considerably. You define a Ship type, which contains three fields: the length of the ship, the orientation of the ship, and (depending on orientation) its upmost or leftmost square. You store all the ships you want in a list (it will have 10 entries). You validate your position by moving down the list, marking all the squares of the ship as occupied, and all the adjacent squares as forbidden. If, when you place a ship, you have to place the ship in a square that's occupied or forbidden, you know you have an invalid position. On the other hand, if you are able to place all the ships without conflicts, you know the board position is correct by construction. This has the added advantage of allowing you to place one ship at a time, and report an invalid configuration immediately, meaning it requires virtually no change to work with the user interface for a player to place their ships. A: Since you have 10 ships at max and your data structure is a byte array, why not just represent the water fields using value 0 and the ship fields using the values 1 to 10. Then you could iterate over the fields and check the surrounding ones (you can optimize based on the iteration direction, in order not to check the same combination twice). If you encounter a 0 value, continue. If you get a value > 0 then check whether the surrounding fields contain values other than 0 and the field's value (detect touching ships). Additionally if the surrounding fields contain the same value but touch at the corners you've found an illegal setup. L-shaped ships should also violate the non-diagonal rule. The last thing to check is whether the ship could contain holes. In that case just store a range of the fields you found per ship and check whether the newly checked field is next to that range. That would give you the number of ships as well, since you can query the length of each ship's range at the end. Consider the following partial board: A B C D E F G H I J _____________________ 1 | 0 0 2 0 0 0 0 0 0 0 2 | 0 1 0 0 3 3 0 4 0 4 3 | 0 0 0 0 0 3 0 0 0 0 If you now check all surrounding fields of B2 (which has value 1), you find value 2, which is an error. If you check E2, you'll find field F3 being diagonal although having the same value of 3 -> error If you check H2, you get range H2-H2 (length 1), since H2 is surrounded by empty fields. If you later check J2 you'll see that the difference between H and J is 2 (1 would be ok), so you found a duplicate ship (or one with a hole) -> error Basically, those rules could be stated as follows (applying to non-empty cells, those with ships): * *each cell's diagonal neighbors must be empty (value 0) *each cell's straight neighbors must have either the value 0 or the same value as the cell *if the value of the cell is on a list already, it must have at least one straight neighbor having the same value Those 3 rules should find any positional violations, if you keep the range of each ship in the list mentioned for rule 3, you can also validate the ship numbers constraint.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do I reply to a POST in my php script? Somehow, I have a feeling my question is very straightforward and noobish, but I tried googling and couldn't figure it out. Perhaps I didn't know the right keywords. Anyways, I have a short php script to receive POST info as below: <?php if (isset($_POST['name']) && isset($_POST['info'])) { echo "<strong>Post received.</strong> <br/> <br/> <strong>Name:</strong> " . $_POST['name'] . "<br/><strong>Info:</strong> " . $_POST['info']; } else { echo "Post not received."; } ?> How can I have my php script send a reply to the page / client that calls it? If I want to make the POST call via, say a C# app, how can I know if the POST was successful? Can my php script that is receiving the POST send back a response? A: The response is sent to the caller only, So it doesnt matter through which channel you call a script (whether with/without parameters). For example if you make the request via a web browser the response is shown by the browser. If you do an AJAX call then the response is recieved in the javascript callback function. And if as you say you call it via a C# app (via e.g. HttpWebRequest), then the responce recieved in HttpWebResponse is what you echo in your script A: You are using echo and its correct. Also header() is used for advanced communication. For details on how to use various HTTP 1.1 headers you may see the link. A: There are several ways to send back info. Basically you are already doing it by echoing some text. Or you can send back a html page or a formatted string (e.g. JSON).
{ "language": "en", "url": "https://stackoverflow.com/questions/7501346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Delphi: CoolTrayIcon's ShowBalloonHint is not working I used CoolTrayIcon, and ShowBalloonHint to warn user to incoming messages. Everything has been working fine till today. Today once I saw the Balloon, but later never. In these period some Windows update installed in the background as I think - later the system showed a "Restart" dialog. I tried to set all properties, and to make a new test project and to copy my old code. Nothing worked. Last chance I tried the CoolTrayIcon's demo. And it is also is not working for me!!! The environment is: Win7/x64, Delphi 6 professional (with updates), 4.4.4 CoolTrayIcon (last). So here is the question: Do you experienced same anomaly? May this caused the SP? Or what? I don't know how to determine that is this problem a System Failure (local), or caused Windows 7 update (then it is global, appearing everywhere)... A: I think CoolTrayIcon is a bit outdated. Try with TJvTrayIcon from JEDI Visual Component Library. TJvTrayIcon shows balloon hints on Windows 7. A: I found some information that might be handy on this case: http://blogs.msdn.com/b/hennings/archive/2010/01/08/delphi-notifyicondata-and-windows7.aspx Basically: The problem lies in the NOTIFYICONDATA Structure The member guidItem must no longer be 0 (zero) on Windows 7, but must contain the GUID of the icon that the notifier is associated with. Hope it helps someone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: play a set of sounds one by one using AVAudioPlayer I want to use AVAudioPlayer in my app. The logic is: firstly play a set of sounds at the same time and then play another set of sounds.But i found that the app only play all these sets together and cannot play one by one set.Being a newer,i found it is diffidult to me, anyone have ideas? Thank u for ur help and ideas. A: Use Delegate method to recognized finishing of the first song then in that method start new song. - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag { //play next song from List/Array of songs. } for playing song AVAudioPlayer code goes as below. NSString* filename = [soundsList objectAtIndex:YOURINDEXNUMBER]; NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"mp3"]; AVAudioPlayer * newAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; self.theAudio = newAudio; // automatically retain audio and dealloc old file if new file is loaded [newAudio release]; // release the audio safely theAudio.delegate = self; [theAudio prepareToPlay]; [theAudio setNumberOfLoops:0]; [theAudio play];
{ "language": "en", "url": "https://stackoverflow.com/questions/7501351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want Convert a Html page with all its content i.e. images like .png,.gif to ms word document with the same look and feel Can any one help me to convert a html page and its content to Microsoft Word file . Basically what i want is a ms word page which looks like my html page in Browser. i am using this code can any one suggest me something else. object filename1 = @"html file path"; object oMissing = System.Reflection.Missing.Value; object readOnly = false; object oFalse = false; Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Document oDoc = new Microsoft.Office.Interop.Word.Document(); oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); oWord.Visible = false; oDoc = oWord.Documents.Open(ref filename1, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); if (!Directory.Exists(@"D:\FileConverter\Temp\new.doc"))//path of destination file. { Directory.CreateDirectory(@"D:\FileConverter\Temp"); } if (!File.Exists(@"D:\FileConverter\Temp\new.doc")) { File.Create(@"D:\FileConverter\Temp\new.doc"); } filename1 = @"D:\FileConverter\Temp\new.doc"; object fileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument; oDoc.SaveAs(ref filename1, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.Close(ref oFalse, ref oMissing, ref oMissing); oWord.Quit(ref oMissing, ref oMissing, ref oMissing); A: here is the Code which any one can use to convert the html page and get the Images also.. const string filename = "C:/Temp/test.docx"; Response.ContentEncoding = System.Text.Encoding.UTF7; System.Text.StringBuilder SB = new System.Text.StringBuilder(); System.IO.StringWriter SW = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlTW = new System.Web.UI.HtmlTextWriter(SW); tbl.RenderControl(htmlTW); string strBody = "<html>" + "<body>" + "<div><b>" + htmlTW.InnerWriter.ToString() + "</b></div>" + "</body>" + "</html>"; string html = strBody; if (File.Exists(filename)) File.Delete(filename); using (MemoryStream generatedDocument = new MemoryStream()) { using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = package.MainDocumentPart; if (mainPart == null) { mainPart = package.AddMainDocumentPart(); new Document(new Body()).Save(mainPart); } HtmlConverter converter = new HtmlConverter(mainPart); converter.BaseImageUrl = new Uri("http://localhost:portnumber/"); Body body = mainPart.Document.Body; var paragraphs = converter.Parse(html); for (int i = 0; i < paragraphs.Count; i++) { body.Append(paragraphs[i]); } mainPart.Document.Save(); } File.WriteAllBytes(filename, generatedDocument.ToArray()); } System.Diagnostics.Process.Start(filename); TO get the .dll files ..use Link You can download notesfor.dll from here. It may be the name HTMLtoOpenXML. A: Not sure if this fits your problem domain, but... You could just render your html as usual, but change the response content type to application/msword and make sure the filename ends with .doc. That'll prompt your browser to download the file, and prompt your OS to open it as a word document. In my experience, MS Word does a decent job of converting other formats to something that looks like a word document. You might end up getting some popups in Word that would look annoying, but if that's not an issue, this would be a good bang-for-your-buck solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Escaping Special Characters for MS Access Query I want to store these characters " '^+%&/()=?_ " via an insert query for an ms access database. How do I do this and prevent from every cases? A: Use parameterized INSERT statement. It looks like your code is assembling the SQL command string. I have to tell you: if that's the case, it makes your code vulnerable to SQL Injection. A: In addition to using a parameterized query (see Adrian's Answer) you can use a Query Definition with a parameter and call it. For example you could create a query named qry_InsSomeTable with the following sql PARAMETERS P_SomeField Text ( 255 ); INSERT INTO tbl_SomeTable ( P_SomeField ) VALUES (P_SomeField ); Then you could call like you would any stored procedure using(var cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\Whatever.mdb") { var cmd = new OleDbCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = cmd.CommandText = "qry_InsSomeTable"; cmd.Parameters.AddWithValue("P_SomeField", "'^+%&/()=?_ "); cn.Open(); cmd.ExecuteNonQuery(); } Its particularly helpful when you have a table with a bunch of fields For example cmd.CommandText = @"Insert Into TableWithAlotofFields (field1, field2, field3, field4, field5,...) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?..)"; cmd.Parameters.Add("value1"); cmd.Parameters.Add("value2"); cmd.Parameters.Add("value3"); cmd.Parameters.Add("value4"); cmd.Parameters.Add("value5"); vs. Query already define in Access as PARAMETERS P_field1Text Text ( 255 ), P_field2 Number, P_field3 text(15), ...; Insert Into TableWithAlotofFields (field1, field2, field3, field4, field5,...) VALUES(P_field1, P_field2, P_field3, P_field4, P_field5,...) then in c# cmd.CommandText = cmd.CommandText = "qry_InsSomeTable"; cmd.Parameters.AddWithValue("P_field1", "value1"); cmd.Parameters.AddWithValue("P_field2", "value2"); cmd.Parameters.AddWithValue("P_field3", "value3"); cmd.Parameters.AddWithValue("P_field4", "value4"); cmd.Parameters.AddWithValue("P_field5", "value5"); However as @David-W-Fenton points out the names on the parameters are ignored and only the position is taken into account. e.g. This cmd.Parameters.AddWithValue("P_field1", "value1"); cmd.Parameters.AddWithValue("P_field2", "value2"); is not equivalent to cmd.Parameters.AddWithValue("P_field2", "value2"); cmd.Parameters.AddWithValue("P_field1", "value1"); So it seems it mostly stylistic in the differences. A: To insert special Characters you should enclose the special characters in brackets ([]). I hope this helps. A: on Visual Studio you must to convert the single to double character i.e.: sql = replace(sql, "'", "''");
{ "language": "en", "url": "https://stackoverflow.com/questions/7501354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XPath function normalize-space() and starts-with() don't find etem with   right befor item I have piece of such HTML code <td> <a href="CMenu?op=m&menuID=42&rurl={{rurl}}" title="Edit menu"> <img border="0" alt="" src="Images/application.gif"> &nbsp;Case </a> </td> and need to find text "Case". I use different XPath Queries, but no one is good, all find nothing: //a[text() = ' Case'] //a[text() = 'Case'] //td/a[normalize-space(text()) = 'Case'] //td[a[normalize-space(.) = 'Case']] //td[a[normalize-space(text()) = 'Case']] //*[starts-with(.," Case")] //*[starts-with(.,"Case")] But, when I try to find this item with //a[contains(.,'Case') and string-length() = 5] It works, but I can not accept hard code '5', I want make this XPath multipurpose for other relative items. And if I use //a[contains(.,'Case')] I find a lists of items which contains 'Case', but need only one with 'Case' and not more chars. Maybe I do something wrong, just want take it clear to me. My colleague tell me that I can use this one XPath //a[substring(text(),2)='Case'] just skip this space. I find out that it's work! but seems to me there is another way to solve my problem with out any skip or pass. A: Use: /td/a [starts-with(normalize-space(), '&#xA0;Case')] XPath isn't entities-aware and normalize-space() by definition only processes white-space characters: space, NL, CR and Tab -- so &#xA0; (which is to what the entity &nbsp; is expanded) isn't considered a whitespace character. XSLT - based verification: This transformation selects with the above XPath expression and outputs the result: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/"> <xsl:copy-of select= "/td/a [starts-with(normalize-space(), '&#xA0;Case')] "/> </xsl:template> </xsl:stylesheet> when applied on the provided XML document: <td> <a href="CMenu?op=m&amp;menuID=42&amp;rurl={{rurl}}" title="Edit menu"> <img border="0" alt="" src="Images/application.gif"/> &#xA0;Case </a> </td> the wanted, correct result is produced: <a href="CMenu?op=m&amp;menuID=42&amp;rurl={{rurl}}" title="Edit menu"> <img border="0" alt="" src="Images/application.gif" /> Case </a> A: You might also want to try //a[matches(., '^\W*Case\W*$')] which will match a elements with value "Case" possibly surrounded by some other non-word characters (anything but letters, numbers and _ I think).
{ "language": "en", "url": "https://stackoverflow.com/questions/7501357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to dynamically change a page title through some administration parameter I'm a newbie in CMSs, namely Joomla. I have a website in Joomla and I have made a custom template for my layout. When a specific menu item is loaded I want, for example, to change the page header title, or apply a css file. Desirably the page title or css file should be set in Joomla administration page. The goal is for some pages/menu items apply different titles or css files without create a new custom template. I've heard in custom parameters but I'm not sure if that do the job. Any hint? A: Look in the menu item into the System Parameters slider. There you can set different titles and CSS classes for the whole page. (You might have to change your template to actually use that feature the way you want. Just guessing that it might not be doing exactly what you want out of the box.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7501360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data upgrade script for base enum from AX 4.0 to AX 2009 Kindly assist me with some ideas in writing the Upgrade script for upgrading the base enum in AX from AX 4.0 to AX 2009. Also i would like to know the sequence of upgrading and the reasons behind. Like is it first we need to upgrade Enum? then Edt's etc etc. Thanks a lot in advance. A: Look for what others have done: see class ReleaseUpdateDB39_Basic method migrateIntercompanyCommerceGateway2AIF. Do not delete enum values, rather rename and prefix with "DEL_", then change the ConfigurationKey to "SysDeletedObjects40". This allow you to reference the old obsolete values in the upgrade script. See also Frameworks Introduction and How to Write Data Upgrade Scripts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using .NET Introspection / FxCop Rules functionality in Unit Tests is it possible to use the .NET Introspection functionality in unit tests? In our software I#d like to prohibit usage of some operations (comparison of enum values since there as a special method for that purpose). I remember that FxCop (Static Code Analysis) ofers access to the code model by means of Introspection. With it, you can inspect whether some function is used or not. I' d like to write a unit test making the same check but I'm not sure whether Introspection or something similar is offered to the unit test. Or maybe you have another idea how I could do it. Thank you in advance! A: It seems that FxCop internals cannot be used externally (except in FxCop itself or in Visual Studio). If you want to validate your architecture, you can try PostSharp feature Architecture validation or a FxCop Mono alternative Gendarme. A: I am not sure about FxCop, but you can use .NET Reflection (is that what you mean by introspection?) to enforce certain code behaviors. For example, I have used Reflection in some tests to make sure that certain "internal" types are not exposed via our public service API. We just looped over our public API and verified that no exposed types (method arguments, properties, etc...) were in the "internal" type list. This was very handy where we were wrapping 3rd-party components, but we wanted to ensure that none of the types in their library were exposed via our API. If you are not familiar with .NET reflection, it gives you an API which lets you query types for information like class methods, method arguments, class properties, etc... You can start with the overview here: http://msdn.microsoft.com/en-us/library/f7ykdhsy(v=vs.71).aspx A: The tool NDepend can help you do that thanks to NDepend.API. Disclaimer: I am one of the developers of the tool NDepend.API proposes the namespace NDepend.CodeModel that contains all types and member needed to introspect a .NET code base. With NDepend.API you can write unit tests to check a wide-range of issues, like unused methods for example. NDepend.CodeModel has been designed to be LINQ-syntax friendly, and 200 of LINQ default code rules are proposed by default (written with what we call CQLinq).
{ "language": "en", "url": "https://stackoverflow.com/questions/7501370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Include a jquery.tmpl template for knockout.js? Silly question, maybe, but I can't find a documented answer anywhere. I'm trying to save a jquery tmpl template, and include it as a script. Seems like this should work: <script src="my_tmpl.js" type="text/javascript" id="myTemplate"></script> But no luck. What am I doing wrong? Just for completeness' sake, here's the kind of binding I'm doing for knockout: <div id="myTemplatedBox" data-bind="template: 'myTemplate'"> Edit: Here's a very reduced version of the my_tmpl.js contents. It works fine when I keep it in the main html document. <div class="headerText">{{html header_text}}</div> {{each(i,v) answer_array}} <div class="questionText"><input type="radio" name="Q${i}" value="${i+1}">{{html v}}</input></div> {{/each}} A: Take a look at http://encosia.com/jquery-templates-composite-rendering-and-remote-loading/ It looks like you still need the script tag in your template file. <script id="invoiceTemplate" type="x-jquery-tmpl"> <div class="questionBox"> <div class="headerText">{{html header_text}}</div> {{each(i,v) answer_array}} <div class="questionText"><input type="radio" name="Q${i}" value="${i+1}">{{html v}}</input></div> {{/each}} </div> </script> A: Change the type to text\html and give it another go: <script src="my_tmpl.js" type="text/html" id="myTemplate"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7501371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How declare a javascript variable and assign the value to a php file which returns a boolean value For context: I am busy using javascript for checking fields in a form. The problem is to work around being unable to retrieve data from the database. All the checks except for making sure its a unique(not used in db) username are done. I looked around quite a while on the web, but the only answer that came close was this: "until you start needing the php page in question to return a value of some sort. in that case, just use the YUI connection manager or something of that nature". Since php is server side, when the button is clicked, can the php then be called, as there is no point in processing the php until there is text in the username field. Here is what I have done. When pressing the submit button, a js function is called. The checking works. <script type="text/javascript" src="regform_checks.js"></script> <h1>Welcome to Registration</h1> <form name="register" action="add_user.php" onsubmit="return validateForm()" method="post"> <table> <tr> <td>Choose a username*</td> <td><input type = "text" name="profile_id"/></td> </tr> This above is in my registration.php The below is my .js file: function validateForm() { var username=document.forms["register"]["profile_id"].value; var pw1=document.forms["register"]["profile_password"].value; var pw2=document.forms["register"]["profile_password2"].value; var invalid = " "; // Invalid character is a space var minLength2 = 3; // Minimum username length var minLength = 6; // Minimum password length var x=document.forms["register"]["profile_email"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); //check for a value in username field if (username==null || username=="") { alert("Please enter a username"); return false; } // check for username minimum length if (document.register.profile_id.value.length < minLength2) { alert('Your username must be at least ' + minLength2 + ' characters long.'); return false; } // check for a value in both fields. if (pw1 == "" || pw2 == "") { alert("Please enter your password in the Password and Re-enter password areas."); return false; } // check for password minimum length if (document.register.profile_password.value.length < minLength) { alert('Your password must be at least ' + minLength + ' characters long. Try again.'); return false; } // check for password consistency if (pw1 != pw2) { alert ("The passwords you have entered are not the same. Please re-enter your password."); return false; } //check for valid email address if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; } // check for spaces if (document.register.profile_id.value.indexOf(invalid) > -1) { alert("Sorry, spaces are not allowed in your username."); return false; } else if (document.register.profile_password.value.indexOf(invalid) > -1) { alert("Sorry, spaces are not allowed in your password."); return false; } else if (document.register.profile_email.value.indexOf(invalid) > -1) { alert("Sorry, spaces are not allowed in your email."); return false; } else { return true; } } What I have been unable to do: set a js variable as follows: var username_check=profile_id_check.php; This file looks like this: $query = "select profile_id from profile"; $result = mssql_query($query); $names = array(); for ($count=0; $row=@mssql_fetch_array($result); $count++) $names[$count]=$row; $idtest= True; foreach ($names as $name) { if($name[profile_id]==$profile_id) return false; print "$name[profile_id]"; } ?> The php code is still in progress of making, depending on what it needs done I realize I dont need the $idtest, as the if statement returns a boolean value. That last print statement just prints all the profile names(so I can be sure the code works, and it does). And its the profile name entered into the form that needs to be compared with all the profile names in the database to ensure it is unique. The endresult the way I see it: If username is unique, give no error or warning, if it isnt, the js must then... which I know how to code. Im open to suggestions that turns away from this method, though my knowledge is restricted to php, some js. (and obviously html) Thanks in advance. A: I think you need to get a grasp of certain concepts on how to pass data back and forth between the client and server. You cannot call a php file on the client side by doing var username_check=profile_id_check.php;. Data can be passed to the server via request methods. The most common of which are $_POST and $_GET. Have a look at the attributes on your form tag below <form name="register" action="add_user.php" onsubmit="return validateForm()" method="post"> The action is set to add_user.php and your method is set to post. So, you can access the form elements with a name attribute on the server side using the $_POST array. So as an example in your add_user.php you can access the profile_id in the following way. $profile_id = $_POST['profile_id']; Other ways you can send data back to the server is by ajax but i would suggest getting the basics down of submitting data via regular HTTP requests then move onto ajax later on. A: You should make an ajax request to the specific php file and register a callback function that handles the php output and sets your variable. So something like /* code block #1 */ var username_check=profile_id_check.php; /* code block #2 */ would be translated into something like : /* code block #1 */ var username_check; ajaxCall({ url : 'profile_id_check.php', callback : function(response){ username_check = response; /* code block #2 */ } }); A: I'm not 100% sure what you're asking, as there seems to be a bit of a language barrier issue, but it looks like you're asking how to have your JavaScript interact with your PHP. PHP is server-side. What's more is that PHP doesn't run as a process (usually...) on the server, so when you run a script, it's a one-shot deal. This ultimately means that by the time your PHP script renders output to the screen, the script itself has finished running. It is not sitting there awaiting input like, say, a console program. Because of this, you need to use AJAX in order to access your PHP script. What is AJAX? Simply put, it's a way for JavaScript to send HTTP requests to a server-side script, receive the results of those requests, and then dynamically use the DOM (Document Object Model - your HTML) to display those results. The simplest way to use AJAX is to use jQuery's ridiculously elegant AJAX functions: http://api.jquery.com/jQuery.get/ http://api.jquery.com/jQuery.post/ One final thought: Form validation with JavaScript is not a security measure. Make sure you have validation in your PHP script as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt: How to initialize dialog widgets? I would like to know what the established procedure is for initializing the controls within a Qt custom dialog box. In the code I am writing, the dialog would present a QListView containing directories from an object passed (by reference) to the dialog class during construction. When the dialog is displayed, I obviously want the list to display the directories currently configured in the object. Where should this be done though? Perhaps in the overridden showEvent() method? Background: I used to do a lot of MFC programming back in the day, and would have done this sort of stuff in the OnCreate method, or some such, once the window object had been created. A: Thankfully Qt doesn't require you to do any hooking to find the moment to create things (unless you want to). If you look over the Qt examples for dialogs, most do all the constructing in the constructor: http://doc.qt.io/archives/qt-4.7/examples-dialogs.html The tab dialog example--for instance--doesn't do "on-demand" initializing of tabs. Although you could wire something up via the currentChanged signal: http://doc.qt.io/archives/qt-4.7/qtabwidget.html#currentChanged Wizard-style dialogs have initializePage and cleanupPage methods: http://doc.qt.io/archives/qt-4.7/qwizardpage.html#initializePage http://doc.qt.io/archives/qt-4.7/qwizardpage.html#cleanupPage But by and large, you can just use the constructor. I guess the main exception would be if find yourself allocating the dialog at a much earlier time from when you actually display it (via exec), and you don't want to bear the performance burden for some part of that until it's actually shown. Such cases should be rare and probably the easiest thing to do is just add your own function that you call (like finalizeCreationBeforeExec).
{ "language": "en", "url": "https://stackoverflow.com/questions/7501376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Screen Scraping Just curious: What do you find to be your best tools for creating automated screen scrapes these days? is the .Net Agility pack a good option? What do you do about scraping sites that use a lot of AJAX? A: I find that if the page has a pretty static layout, then the HTML Agility Pack is perfect for getting all the data I need. I've not run into a single page that it hasn't been able to handle and not get me the results I wanted. If you find that the page is rendered with a great deal of dynamic code, you're going to have to do more than just download the page, you'll have to actually execute it. To do that, you'll need something like the WebKit .NET library (a .NET wrapper around the WebKit rendering engine) which will allow you to download the page and actually execute Javascript as well. Then, once you are sure the document has been rendered completely, you can get the page details. A: For the very basics I use: * *Asynchronous HTTP Client - notably faster than the standard HttpWeb* (preliminary tests showed that it was about 25% faster). *Majestic 12 HTML Parser - about 50-100% faster than HTML Agility Pack. I don't have JavaScript enabled yet, but I'm planning on using Google's V8 JavaScript Engine. This requires that you make calls to unmanaged code, but the performance of V8 justifies it. A: For automating screen scraping, Selenium is a good tool. There are 2 things- 1) install Selenium IDE (works only in Firefox). 2) Install Selenium RC Server After starting Selenium IDE, go to the site that you are trying to automate and start recording events that you do on the site. Think it as recording a macro in the browser. Afterwards, you get the code output for the language you want. Just so you know Browsermob uses Selenium for load testing and for automating tasks on browser. I've uploaded a ppt that I made a while back. This should save you a good amount of time- http://www.4shared.com/get/tlwT3qb_/SeleniumInstructions.html In the above link select the option of regular download. I spent good amount of time in figuring it out, so thought it may save somebody's time. A: The best tool "these days" is one that not only gives you the desired features (Javascript, automation), but also the one that you don't have to run yourself... I am, of course, alluding to using a cloud service. This approach will save you network bandwidth, will deliver results faster (because it can scale better than a custom solution you'll likely end up developing) and, most importantly, save you the IT and maintenance headache. On that note, check out a scraping solution called Bobik (http://usebobik.com). I've written an article about it at http://zscraper.wordpress.com/2012/07/03/a-comparison-shopping-android-app-without-backend/. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Magento is not recognising variables ($variable $_variable) I'm migrating a machine to my local server and there is something weird with the variables and other functions. For example, Magento shows this error: Notice: Undefined variable: key in [...]template/catalog/product/view/attributes.phtml If I go to that function, I see this: <?php foreach($this->getAvailableOrders() as $_key=>$_order): ?> <?php echo $key; if ($_order != 'Relevancia') : // Remove "Relevancia" from the sort option list ?> <option value="<?php echo $_key; // echo $this->getOrderUrl($_key, 'asc') ?>"<?php if($this->isOrderCurrent($_key)): ?> selected="selected"<?php endif; ?>> <?php echo $this->__($_order) ?> </option> <?php endif; ?> <?php endforeach; ?> It seems that magento can't recognise the «$key» as a «$_key», and this happens in the whole code. The thing is that this code is working in the production server so... I'm missing something, and I don't know what it is. Thanks for your help! A: PHP is complaining because you haven't defined the variable $key in the code snippet. <?php echo $key; The variable $key is distinct from the variable $_key The PHP error level here is Notice. A notice is the lowest PHP error level, and it's usually possible to continue execution after a notice has been issued. My guess is your production server is configured to not display error ini_set('display_errors', 0); And the developer mode constant set to false $_SERVER['MAGE_IS_DEVELOPER_MODE'] This allows Magento to continue past the notice. If you check your logs, it's probably still being issued. On your local machine, with display errors on your see the Notice in your browser. With developer mode on Magento will throw an exception for any simple error. It's also possible that prior to your code block, there's something conditionally defining $key base on database state, and it happens in production, but not with your dev configuration/database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: navigationBar of UINavigationController dissappears I have this: FirstViewController: SecondViewController *secondViewController = [[SecondViewController alloc] init]; [self.navigationController pushViewController:secondViewController animated:YES]; SecondViewController: - (void)viewDidLoad { [super viewDidLoad]; [self.navigationController setNavigationBarHidden:YES]; } My problem is that when I comeback from SecondViewController to FirstViewController the NavigationBar is still hidden.Is there a way to make it appear when I'm back in FirstViewController? A: In the FirstViewController.m: -(void)viewWillAppear:(BOOL)animated { [self.navigationController setNavigationBarHidden:NO]; } A: Yep, it's always possible that a different navigation controller will have set the bar to be hidden. So, in your viewWillAppear set the flag as follows: self.navigationController.navigationBarHidden = NO; A: You need to set [self.navigationController setNavigationBarHidden:NO]; This will do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a shift and copy cpu instruction that can be accessed from c#? I need to take an 8 bit number on a 64 bit cpu and shift it to the right 8 times. Each time I shift the number I need to shift the same 8 bit number in behind it so that I end up with the same 8 bit number repeating 8 times. This would end up being shift, add 8, shift add 8... etc. which ends up being 40+ cycles (correct me if I'm wrong). Is there a way to do this operation (of shift and copy) in 1 cycle so that I end up with the same value in the end? long _value = 0; byte _number = 7; for (int i = 0; i < 8; i++) { _value = (_value << 8) + _number; } EDIT: I'm trying to compare a stream of chars to detect keywords. I can't use string.contains because the string value may be across the boundary of the buffer. Also, the application has to run on embedded ARM cpus as well as desktop and server CPUs. Memory usage and cpu cycles are very important. A: Nowadays, there is no direct connection between number of instructions performed and the number of cpu cycles which are needed to execute them. You also seem to assume that a statement in C# corresponds to a single assembly/cpu instruction which also is wrong. Your code seem correctly do what your algorithm description says (note that long is signed, use ulong for unsigned behaviour). If you want to use specialized cpu extensions (like mmx,sse,whatever) that can do add-shift-assignment in one instruction, you need to use assembly code. But I am not sure if such a specific instruction exist. This may depend on the type of CPU you have. You cannot use assembly code directly together with c#, but you can use assembly together with c (either as linked object file use make it inline assembly). The compiled c-code can be used from c#/.net with interop. But the first and important question for you should be: What are you trying to accomplish? I doubt that performance is this critical for your app, and even if, you should honestly ask yourself if c# is the best language for your goal. A: Another idea would be to precompute all for all values of byte a lookup table. var lu = new long[256]; // init var n = 7; var v = lu[n]; Update Some benchmark results (in ms per 100000000 iterations): * *Loop: 272 *Unrolled: 207 *Unsafe: 351 *Lookup: 250 *HenkH: 216 The unrolled version is: long _value = 0; byte _number = 7; _value = (_value + _number) << 8; _value = (_value + _number) << 8; _value = (_value + _number) << 8; _value = (_value + _number) << 8; _value = (_value + _number) << 8; _value = (_value + _number) << 8; _value = (_value + _number) << 8; _value = (_value + _number) << 8; The unsafe version is: long _value = 0; byte _number = 7; byte* p = (byte*)&_value; *p++ = _number; *p++ = _number; *p++ = _number; *p++ = _number; *p++ = _number; *p++ = _number; *p++ = _number; *p++ = _number; Sadly not performing :( The lookup is just a read to an array. All compiled for x64/release. A: When you want it to be fast you could at least unroll your loop: ulong _value = 0; byte _number = 7; _value = _number; _value = (_value << 8) + _value; _value = (_value << 16) + _value; _value = (_value << 32) + _value; This would have fewer branches too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Does Android support multiple HTTP requests at the same time? In my app I'd like to handle downloading of several files at the same time. To do so I'm starting several services, one for each request. As I'm not sure, does Android support simultaneous http requests in parallel? In that case, is it good or bad habit to have one HTTPClient per request? Many thanks for your help! A: When equipped with a pooling connection manager such as ThreadSafeClientConnManager, HttpClient can be used to execute multiple requests simultaneously using multiple threads of execution. Here is a full example on how to use it: 2.9. Multithreaded request execution. Update: It took a while, but the ThreadSafeClientConnManager is now deprecated (see excerpt below from Apache Http Client Removal): Android 6.0 release removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead. This API is more efficient because it reduces network use through transparent compression and response caching, and minimizes power consumption. A: HttpClient is not asynchronous and does not support parallel connections per se. You could have multiple threads each performing download with separate HttpClient instances. You might also want to look at ExecutorService: http://developer.android.com/reference/java/util/concurrent/ExecutorService.html A: Do some testing to determine how many concurrent HTTPRequests work well. I recommend starting one service and having many Threads rather than multiple services.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Create thumbnail from a video url in IPhone SDK I am trying to acquire a thumbnail from a video url. The video is a stream (HLS) with the m3u8 format. I've already tried requestThumbnailImagesAtTimes from the MPMoviePlayerController, but that didn't work. Does anyone have a solution for that problem? If so how'd you do it? A: -(UIImage *)loadThumbNail:(NSURL *)urlVideo { AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:urlVideo options:nil]; AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset]; generate.appliesPreferredTrackTransform=TRUE; NSError *err = NULL; CMTime time = CMTimeMake(1, 60); CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err]; NSLog(@"err==%@, imageRef==%@", err, imgRef); return [[UIImage alloc] initWithCGImage:imgRef]; } Add AVFoundation framework in your project and don't forget to import <AVFoundation/AVFoundation.h> and you have to pass the path of your video saved in document directory as a parameter and receive the image as UIImage. A: If you don't want to use MPMoviePlayerController, you can do this: AVAsset *asset = [AVAsset assetWithURL:sourceURL]; AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset]; CMTime time = CMTimeMake(1, 1); CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL]; UIImage *thumbnail = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); // CGImageRef won't be released by ARC Here's an example in Swift: func thumbnail(sourceURL sourceURL:NSURL) -> UIImage { let asset = AVAsset(URL: sourceURL) let imageGenerator = AVAssetImageGenerator(asset: asset) let time = CMTime(seconds: 1, preferredTimescale: 1) do { let imageRef = try imageGenerator.copyCGImageAtTime(time, actualTime: nil) return UIImage(CGImage: imageRef) } catch { print(error) return UIImage(named: "some generic thumbnail")! } } I prefer using AVAssetImageGenerator over MPMoviePlayerController because it is thread-safe, and you can have more than one instantiated at a time. A: you can get the thumbnail from your video url with the use of below code MPMoviePlayerController *player = [[[MPMoviePlayerController alloc] initWithContentURL:videoURL]autorelease]; UIImage *thumbnail = [player thumbnailImageAtTime:0.0 timeOption:MPMovieTimeOptionNearestKeyFrame]; A: Acquire a thumbnail from a video url. NSString *strVideoURL = @"http://www.xyzvideourl.com/samplevideourl"; NSURL *videoURL = [NSURL URLWithString:strVideoURL] ; MPMoviePlayerController *player = [[[MPMoviePlayerController alloc] initWithContentURL:videoURL]autorelease]; UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame]; player = nil; Replace your video URL string with strVideoURL. You will get thumbnail as a output from video. And thumbnail is UIImage type data ! A: Maybe this is useful for someone else who faces the same problem. I needed an easy solution for creating a thumbnail for Images, PDFs and Videos. To solve that problem I've created the following Library (in Swift). https://github.com/prine/ROThumbnailGenerator The usage is very straightforward: var thumbnailImage = ROThumbnail.getThumbnail(url) It has internally three different implementations and depending on the file extension it does create the thumbnail. You can easily add your own implementation if you need a thumbnail creator for another file extension. A: Swift 3 Version : func createThumbnailOfVideoFromFileURL(videoURL: String) -> UIImage? { let asset = AVAsset(url: URL(string: videoURL)!) let assetImgGenerate = AVAssetImageGenerator(asset: asset) assetImgGenerate.appliesPreferredTrackTransform = true let time = CMTimeMakeWithSeconds(Float64(1), 100) do { let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil) let thumbnail = UIImage(cgImage: img) return thumbnail } catch { // Set a default image if Image is not acquired return UIImage(named: "ico_placeholder") } } A: For Swift 3.0: func generateThumbnailForVideoAtURL(filePathLocal: NSString) -> UIImage? { let vidURL = NSURL(fileURLWithPath:filePathLocal as String) let asset = AVURLAsset(url: vidURL as URL) let generator = AVAssetImageGenerator(asset: asset) generator.appliesPreferredTrackTransform = true let timestamp = CMTime(seconds: 1, preferredTimescale: 60) do { let imageRef = try generator.copyCGImage(at: timestamp, actualTime: nil) let frameImg : UIImage = UIImage(cgImage: imageRef) return frameImg } catch let error as NSError { print("Image generation failed with error ::\(error)") return nil } } A: For Swift 5 you can get it this way: First import AVKit or AVFoundation to ViewController import AVKit Code: // Get Thumbnail Image from URL private func getThumbnailFromUrl(_ url: String?, _ completion: @escaping ((_ image: UIImage?)->Void)) { guard let url = URL(string: url ?? "") else { return } DispatchQueue.main.async { let asset = AVAsset(url: url) let assetImgGenerate = AVAssetImageGenerator(asset: asset) assetImgGenerate.appliesPreferredTrackTransform = true let time = CMTimeMake(value: 2, timescale: 1) do { let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil) let thumbnail = UIImage(cgImage: img) completion(thumbnail) } catch { print("Error :: ", error.localizedDescription) completion(nil) } } } Usage @IBOutlet weak imgThumbnail: ImageView! and then call getThumbnailFromUrl method and pass URL as a Sting self.getThumbnailFromUrl(videoURL) { [weak self] (img) in guard let `self` = self else { return } if let img = img { self.imgThumbnail.image = img } } Thank you A: Swift 2 code with AVAssetImageGenerator: func thumbnailImageForVideo(url:NSURL) -> UIImage? { let asset = AVAsset(URL: url) let imageGenerator = AVAssetImageGenerator(asset: asset) imageGenerator.appliesPreferredTrackTransform = true var time = asset.duration //If possible - take not the first frame (it could be completely black or white on camara's videos) time.value = min(time.value, 2) do { let imageRef = try imageGenerator.copyCGImageAtTime(time, actualTime: nil) return UIImage(CGImage: imageRef) } catch let error as NSError { print("Image generation failed with error \(error)") return nil } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Visual Studio Setup Project - can you configure projects to install transitive dependencies in the correct order? I'm using Visual Studio 2010 to create an installer for my project. My installer includes my dependencies, such as .NET 3.5, and the 2007 Microsoft Office Primary Interop Assemblies (PIA). Additionally, PIA depends on .NET 3.5. I'm encountering a problem because Visual Studio 2010 does not recognize the transitive dependency that the PIA has on .NET 3.5. As a result, the generated setup executable installs these items in the wrong order, installing the PIA before .NET is installed, resulting in an error. What's the best way around this problem? Is there a way to configure the setup project, to indicate the correct ordering for these dependencies? I've heard about some third-party solutions such as Wix, but it seems like overkill for something this simple. Do I really need to resort to a third-party tool like Wix for this? A: Visual Studio doesn't support custom prerequisites order. You can try editing the project file (.vdproj) and change the bootstrapper Configurations manually, but I'm not sure if it will work. Usually the solution is another setup authoring tools which offers more control over prerequisites.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error MSBuild MSB3021 with CruiseControl.Net : Unable to copy file I have a "Unable to copy file X.DLL" in a MSBuild task on my CruiseControl.Net project. My CCNet project is like this : <project name="Trunk" queue="Back" queuePriority="1"> <tasks> <msbuild> <executable>C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable> <workingDirectory>D:\wwwroot\CruiseControl\Working\trunk</workingDirectory> <projectFile>kop.sln</projectFile> <buildArgs>/noconsolelogger /v:quiet /p:Configuration=Debug</buildArgs> <targets>ReBuild</targets> <timeout>600</timeout> </msbuild> </tasks> </project> The build report is as follows : <msbuild startTime="09/21/2011 15:56:11" elapsedTime="00:00:32" elapsedSeconds="32" success="false"> <warning line="0" column="0" timeStamp="09/21/2011 15:56:12"><![CDATA[MSB3021 : Impossible de copier le fichier "D:\wwwroot\CruiseControl\Working\trunk\Reporting\bin\Release\Reporting.dll" vers "back\\Bin\Reporting.dll". Impossible de trouver une partie du chemin d'accès 'D:\wwwroot\CruiseControl\Working\trunk\Reporting\bin\Release\Reporting.dll'.]]></warning> <warning line="0" column="0" timeStamp="09/21/2011 15:56:12"><![CDATA[MSB3021 : Impossible de copier le fichier "D:\wwwroot\CruiseControl\Working\trunk\KoamaOP\bin\Release\KoamaOP.dll" vers "back\\Bin\KoamaOP.dll". Impossible de trouver une partie du chemin d'accès 'D:\wwwroot\CruiseControl\Working\trunk\KoamaOP\bin\Release\KoamaOP.dll'.]]></warning> It works perfectly fine when I launch it from a console on my own computer. The file it tries to copy (\bin\ Release\KoamaOP.dll) does not exists, but \bin\ Debug\KoamaOP.dll exists. Why does it try to get the Release dll, although I specified /p:Configuration=Debug ? What can be the root of the problem ? Thanks A: Have you verified that the file D:\wwwroot\CruiseControl\Working\trunk\Reporting\bin\Release\Reporting.dll actually exists on the build box? It may be that the path is incorrect. The copy is trying to put the file under a "back" folder. Is this a pre-build or post-build step you added to save old versions of files? If so, you might have one of those steps misconfigured. As to it working on your box - I suspect you already have the Release version of the dll built, so the copy step doesn't fail. If you delete all of the dlls on your box and then rebuild, I suspect you will find the same problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best way to invoke method inhereted from Base class : use this , super or call implicitly I think it's not very useful question, but i think someone can say smth critical. public class Base{ public void boo(){} } public class Derivative extends Base{ 1:public void useBoo(){ boo(); } 2:public void useBoo(){ this.boo(); } 3:public void useBoo(){ super.boo(); } } [EDIT] The reason why I asked this question : to avoid recompilation or name confusion in future. And make code more readability and flexable to future changes. A: The best one to use is the one you feel is clearest. BTW: The first example will behave different to the third example, if you add a boo method to Derived. A: If you want to be sure that the method invoked is the super class method, definitely use super: super.boo(); If you want to use a method defined in the current class and if this is not present use the super method use: this.boo(); //or boo(); Personally in the second case, if the class is part of a hierarchy, I prefer to explicitly use this.boo() because it's more clear reading the code, to understand where the method is supposed to be. But it's my opinion. A: Use one of the first two, unless you explicitly want to limit the call to the superclass implementation. When you override a superclass method, and want to include the behavior of the superclass method, use the third. Elsewhere, if you use the third, and later you or someone else overrides the superclass implementation of boo() -- in this class or a subclass -- then useBoo() will not use the override. This is usually undesirable except in the override of boo() itself. Examples: /** Extends boo method. */ public void boo(){ super.boo(); // Good: you explicitly want to call the superclass method, not call this method again. } public void doSomethingThatInvolvesBoo() { boo(); // Good -- will call this object's implementation, // even if this is a subclass, even if there are code changes later. this.boo(); // Good (and equivalent to simply calling boo()). super.boo(): // Usually bad. } A: I would only use 1 and 2 (in my case I prefer 2, I like to be explicit about my intentions) public void useBoo(){ this.boo(); } I wouldn't use 3 because it means something else semantically, remember that Derivative can also be extended, and boo() may be overridden further down the class hierarchy, and unless you specifically want to call Base.boo() you shouldn't use the super keyword. A: Is there anything stopping you from just calling boo()? Or have you overridden it in your own code? 1 and 2 do the same thing, 3 calls the method of Base. edit: as Simeon said, using super would make it very clear you are calling the method from the Base class. A: Having readability in mind super is probably the best because it says here I'm invoking a method from the super class. While with this you could wonder 'where the hell is this method .. oh ok its in the super class'
{ "language": "en", "url": "https://stackoverflow.com/questions/7501422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Set title in the window popup Is it possible to set a title in the window popup? I have this in javascript: var popup = window.open('......'); popup.document.title = "my title"; but this does not work..still can't see any title EDIT: the page popup is displaying is .aspx and it HAS a title tag, but still can't see that on the popup window.. A: I was having problems with the accepted answer until I realized that if you open an existing, slow page that already has a <title> the browser will 1) set your title, then 2) once the document fully loads it will (re)set the popup title with the "normal" value. So, introducing a reasonable delay (function openPopupWithTitle): var overridePopupTitle = function(popup, title, delayFinal, delayRepeat) { // https://stackoverflow.com/a/7501545/1037948 // delay writing the title until after it's fully loaded, // because the webpage's actual title may take some time to appear if(popup.document) setTimeout(function() { popup.document.title = title; }, delayFinal || 1000); else setTimeout(function() { overridePopupTitle(popup, title); }, delayRepeat || 100); } var openPopupWithTitle = function(url, title, settings, delay) { var win = window.open(url, title, settings); overridePopupTitle(win, title, delay); return win; } A: Since popup.onload does not seem to work, here is a workaround: http://jsfiddle.net/WJdbk/. var win = window.open('', 'foo', ''); // open popup function check() { if(win.document) { // if loaded win.document.title = "test"; // set title } else { // if not loaded yet setTimeout(check, 10); // check in another 10ms } } check(); // start checking A: None of these answers worked for me. I was trying to open a popup with a PDF inside and kept getting permission denied trying to set the title using the above methods. I finally found another post that pointed me in the correct direction. Below is the code I ended up using. Source: How to Set the Title in Window Popup When Url Points to a PDF File var winLookup; var showToolbar = false; function openReportWindow(m_title, m_url, m_width, m_height) { var strURL; var intLeft, intTop; strURL = m_url; // Check if we've got an open window. if ((winLookup) && (!winLookup.closed)) winLookup.close(); // Set up the window so that it's centered. intLeft = (screen.width) ? ((screen.width - m_width) / 2) : 0; intTop = (screen.height) ? ((screen.height - m_height) / 2) : 0; // Open the window. winLookup = window.open('', 'winLookup','scrollbars=no,resizable=yes,toolbar='+(showToolbar?'yes':'no')+',height=' + m_height + ',width=' + m_width + ',top=' + intTop + ',left=' + intLeft); checkPopup(m_url, m_title); // Set the window opener. if ((document.window != null) && (!winLookup.opener)) winLookup.opener = document.window; // Set the focus. if (winLookup.focus) winLookup.focus(); } function checkPopup(m_url, m_title) { if(winLookup.document) { winLookup.document.write('<html><head><title>' + m_title + '</title></head><body height="100%" width="100%"><embed src="' +m_url + '" type="application/pdf" height="100%" width="100%" /></body></html>'); } else { // if not loaded yet setTimeout(checkPopup(m_url, m_title), 10); // check in another 10ms } } A: Not sure if this will help, function GetInput() { var userInput; var stringOutput; userInput = prompt('What should the title be?', ""); stringOutput = userInput; document.title = stringOutput; } <button type="button" onclick="GetInput()">Change Title</button> A: You can use also var popup = window.open('......'); popup.onload = function () { popup.document.title = "my title"; } A: var win= window.open('......'); win.document.writeln("<title>"+yourtitle+"</title>"); This works for me, tested in chromium browsers. A: I ended up creating a setTitle method in my popup window and calling it from my parent page. //popup page: function setTitle(t) { document.title = t; } //parent page popupWindow.setTitle('my title'); A: Try this, it will work. var timerObj, newWindow; function openDetailsPopUpWindow(url) { newWindow = window.open(url, '', 'height=500,width=700,menubar=no,resizable=yes,scrollbars=yes'); timerObj = window.setInterval("fun_To_ReTitle('~~newTitle~~ ')", 10); } function fun_To_ReTitle(newTitle){ if (newWindow.document.readyState == 'complete') { newWindow.document.title=newTitle; window.clearInterval(timerObj); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Can I set the PowerShell execution policy using a script? I would not be surprised if this is not possible, but I need to set the execution policy (on the 32 bit PowerShell environment) on several build servers - it would be much quicker if I could script this, but my current attempt, %SystemRoot%\syswow64\WindowsPowerShell\v1.0\ powershell.exe -Version 2 -Command "& {Set-ExecutionPolicy -ExecutionPolicy RemoteSigned}" completes without any visible error, but the execution policy is not being set. I guess it would create a bit of a security hole if users could be tricked into running a script that changed their execution policy, but I thought I would ask the question anyway. OK - so Richard and Craika are entirely correct and I am a little bit stupid. After retrying the command - I find that it does work (despite what I said in the question). I guess I must have been getting mixed up between 32 and 64 PowerShell windows (i.e. setting the execution policy in one and then checking the value in another). Apologies. A: You can do this, but the script will be run or not run under the currently (ie. before the script) in force execution policy. The obvious approach would be to sign the script with a trusted certificate. However if you want to manage the servers collectively, why not put them in an Active Directory OU or group and then use Group Policy to set the execution policy? (And don't forget you'll need to set it for both 32 and 64bit processes.) A: Your command will work (and does work on my computer) - the execution policy won't affect anything you pass directly into the Command parameter of powershell.exe (and even if it did there is also an ExecutionPolicy parameter). You're definitely running from a 64-bit session? If you did want to script it, you could run this from your local workstation: $LaunchLine = 'powershell.exe -Version 2 -Command "& {Set-ExecutionPolicy -ExecutionPolicy RemoteSigned}"' $ComputerList = "PC01", "PC02" foreach($Computer in $ComputerList) { [String]$wmiPath = "\\{0}\root\cimv2:win32_process" -f $computer try { [wmiclass]$Executor = $wmiPath $executor.Create($LaunchLine) } catch { continue; } } It creates a new process on each computer in $ComputerList and executes your command. Like I say, your command does work on my computer. I would think the problem lies in whether whether it's actually running the version of PowerShell you're after.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ANTLR : expression evaluator, division and pow I'm trying to write a grammar to evaluate expressions. I've started with the given example on the ANTLR website (it manage +,- and *). I added the division. But I would like to notify user if he tries to divide by 0. Moreover, I would like to add the pow in my evaluator (with an higher precedence than multiply and divide. (for example 2^3=8). Hope it's understandable. Here's my grammar Expr.g : grammar Expr; @header { import java.util.HashMap; } @members { /** Map variable name to Integer object holding value */ HashMap memory = new HashMap(); } prog: stat+ ; stat: expr NEWLINE {System.out.println($expr.value);} | ID '=' expr NEWLINE {memory.put($ID.text, new Integer($expr.value));} | NEWLINE ; expr returns [int value] : e=multExpr {$value = $e.value;} (( '+' e=multExpr {$value += $e.value;} | '-' e=multExpr {$value -= $e.value;} ))* ; multExpr returns [int value] : e=atom {$value = $e.value;} ('*' e=atom {$value *= $e.value;} |'/' e=atom {if (e != 0) $value /= $e.value; else System.err.println("Division par 0 !");} )* ; atom returns [int value] : INT {$value = Integer.parseInt($INT.text);} | ID { Integer v = (Integer)memory.get($ID.text); if ( v!=null ) $value = v.intValue(); else System.err.println("Variable indéfinie "+$ID.text); } | '(' expr ')' {$value = $expr.value;} ; ID : ('a'..'z'|'A'..'Z')+ ; INT : '0'..'9'+ ; NEWLINE:'\r'? '\n' ; WS : (' '|'\t')+ {skip();} ; Thanks in advance. Ed. A: eouti wrote: I added the division. But I would like to notify user if he tries to divide by 0. Inside your multExpr rule, you shouldn't do if (e != 0) ..., but you should access e's value attribute instead. Also, the left-hand-side of your expression is called e while the right-hand-side is also called e. You'd better give them unique names: multExpr returns [int value] : e1=atom {$value = $e1.value;} ( '*' e2=atom {$value *= $e2.value;} | '/' e2=atom {if ($e2.value != 0) $value /= $e2.value; else System.err.println("Division par 0 !");} )* ; But, do you really want to warn the user? After this warning, the calculation will just continue at the moment. IMO, you should just let the exception be thrown. eouti wrote: I would like to add the pow in my evaluator (with an higher precedence than multiply and divide. Then add a powExpr rule in between multExpr and atom and let multExpr use this powExpr rule instead of the atom rule: multExpr returns [int value] : e1=powExpr {...} ( '*' e2=powExpr {...} | '/' e2=powExpr {...} )* ; powExpr returns [int value] : atom {...} ('^' atom {...} )* ; atom returns [int value] : INT {...} | ID {...} | '(' expr ')' {...} ; (powExpr doesn't literally need to be in between these rules of course...) Also, you might want to change returns [int value] into returns [double value], especially since you're using division.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sql server database transaction deadlocks; visual studio insert procedures I have a sql server database setup that accepts insert transactions from a visual studio application that is running using threads. Now the transactions are getting deadlocked and I have a workaround in that when the visual studio 2010 code detects a timeout, it will just reattempt to insert the data. Looking at my text logs that I have setup, this is happening way too often and causing performance issues. Some of the online resources indicate finding the offending transaction and killing it but if my application is dependent on the results obtained in the database that may not be an option. Are there suggestions out there as to how to deal with this. I am using the Parallel Taskfactory in visual studion 2010, so there are at least 1000 threads running at any given time? some code to view: my insert code Any ideas really appreciated. sql table schema Table PostFeed id int entryid varchar(100) feed varchar(MAX) pubdate varchar(50) authorName nvarchar(100) authorId nvarchar(100) age nvarchar(50) locale nvarchar(50) pic nvarchar(50) searchterm nvarchar(100) dateadded datetime PK - entryid + searchterm stored procedure for insert so it does a whole bunch of inserts and relies on primary key constraints for dupe checking complete table create USE [Feeds] GO /****** Object: Table [dbo].[PostFeed] Script Date: 09/21/2011 11:21:38 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[PostFeed]( [id] [int] IDENTITY(1,1) NOT NULL, [entryId] [varchar](100) NOT NULL, [feed] [varchar](max) NULL, [entryContent] [nvarchar](max) NULL, [pubDate] [varchar](50) NOT NULL, [authorName] [nvarchar](100) NOT NULL, [authorId] [nvarchar](100) NULL, [age] [nvarchar](50) NULL, [sex] [nvarchar](50) NULL, [locale] [nvarchar](50) NULL, [pic] [nvarchar](100) NULL, [fanPage] [nvarchar](400) NULL, [faceTitle] [nvarchar](100) NULL, [feedtype] [varchar](50) NULL, [searchterm] [nvarchar](400) NOT NULL, [clientId] [nvarchar](100) NULL, [dateadded] [datetime] NULL, [matchfound] [nvarchar](50) NULL, [hashField] AS ([dbo].[getMd5Hash]([entryId])), CONSTRAINT [PK_Feed] PRIMARY KEY CLUSTERED ( [entryId] ASC, [searchterm] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO I tried exporting the deadlock graph, could not get it to work so here are few lines from trace Lock:Timeout 60468 sa 0X01 247 G01 sa 2011-09- 21 16:00:44.750 1:4557807 3463314605 .Net SqlClient Data Provider 0 0XEF8B45000100000000000000070006 22164 7 postFeeds 0 2011-09-21 16:00:44.750 1 G02 0 - LOCK 8 - IX 0 72057594075152384 1 - TRANSACTION 0 6 - PAGE Lock:Timeout 60469 sa 0X01 478 G01 sa 2011-09- 21 16:00:44.887 (7bf23fc490ce) 3463299315 .Net SqlClient Data Provider 0 0X3802000000017BF23FC490CE070007 17900 7 postFeeds 0 2011-09-21 16:00:44.887 1 G02 0 - LOCK 5 - X 0 72057594075152384 1 - TRANSACTION 0 7 - KEY Lock:Timeout 60470 sa 0X01 803 G01 sa 2011-09- 21 16:00:44.887 (379349b72c77) 3463296982 .Net SqlClient Data Provider 0 0X380200000001379349B72C77070007 17900 7 postFeeds 0 2011-09-21 16:00:44.887 1 G02 0 - LOCK 5 - X 0 72057594075152384 1 - TRANSACTION 0 7 - KEY Lock:Timeout 60471 tdbuser 0X048D73EF643661429B907E6106F78358 93 G01 tdbuser 2011-09-21 16:02:41.333 1:14386936 3463346220 .Net SqlClient Data Provider 0 A: I've ran into the same situation inserting a boat load of records with parallel threads. To get around my deadlock issue I specified a table lock upon insert... Insert dbo.MyTable WITH(TABLOCKX) (Column1) Values ( SomeValue); I tried using lowel level locks but I still got deadlocks. The TabLockX slowed the throughput down some but it still was a ton faster than serial inserts and no more deadlocks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compared effort when developing Android and iOS app Given: * *A desired application called APP wich will present 2 "forms" and will comunicate with a web server to call 3 Web Methods. *One developer with nearly equivalent expertise on iOS and Android platforms. *X: required effort to build APP for Android only. *Y: required effort to build APP for iOS only. *X = K1 * Y where K1 is a real number. *Z = K2 * (X + Y) where K2 is a real number and Z is defined as the required effort to build APP for both Android an iOS. Please answer: * *What is the approximate value of K1? *Assuming that the formula for Z is acceptable, what is the approximate value of K2? A: It depends so much on the actual specifications that I think it's impossible to estimate but based on my latest projects that don't have UI customizations I'll make one: * *K1 = 1.4 - I find developing on iOS much faster and easier in this case using Interface Builder and the ASIHTTPRequest library *K2 = 0.95 - It helps to know the protocol for the web server but in this case (3 methods it doesn't matter very much) A: IMHO: K1 = 1.5 Android development is usually slower than iOS and calling web services from Android can be tricky (kSOAP).
{ "language": "en", "url": "https://stackoverflow.com/questions/7501439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert several array of value different in new row from database I want insert in the row from database, array of values as that each of they put in new row from database. I not want insert all values in a row from database with use of serialize(json_encode or etc). For example:(in this example, i want three times insert data(value), because i have 3 value different) Update 4: this my value: <input name="name[0][]" value="11"> <input name="passport_number[0][]" value="11"> <input name="name[1][]" value="22"> <input name="passport_number[1][]" value="22"> i do it, but it not worked: $name_input = $this->input->post('name'); $passport_number_input = $this->input->post('passport_number'); //$term_passport_input = $this->input->post('term_passport'); //$date_of_birth_input = $this->input->post('date_of_birth'); //$age_input = $this->input->post('age'); //$national_number_input = $this->input->post('national_number'); //$mobile_input = $this->input->post('mobile'); //$address_input = $this->input->post('address'); $data = array(); foreach ($name_input as $idx => $name) { $data[] = array( 'name' => $name_input[0] 'passport_number' => $passport_number_input[0], //'term_passport' => $term_passport_input[$idx], //'date_of_birth' => $date_of_birth_input[$idx], //'age' => $age_input[$idx], //'national_number' => $national_number_input[$idx], //'mobile' => $mobile_input[$idx], //'address' => $address_input[$idx], ); }; var_dump($name_input); $this->db->insert_batch('customer_info', $data); This is output '$name_input' with var_dump: array(2) { [0] = > array(1) { [0] = > string(2)"11" }[1] = > array(1) { [0] = > string(2)"22" } } I get this error: A PHP Error was encountered Severity: Warning Message: Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\application\controllers\admin\tour_foreign.php:405) Filename: core/Common.php Line Number: 413 A Database Error Occurred Error Number: 1054 Unknown column '0' in 'field list' INSERT INTO customer_info (0) VALUES ('22') Filename: D:\xampp\htdocs\system\database\DB_driver.php Line Number: 330 A: Update 3: Per updated question (update 4) Looking at the var_dump of $name_input following code should work: $name_input = $this->input->post('name'); $passport_number_input = $this->input->post('passport_number'); $data = array(); foreach ($name_input as $idx => $name) { $data[] = array( 'name' => $name_input[$idx][0], 'passport_number' => $passport_number_input[$idx][0] ); }; $this->db->insert_batch('customer_info', $data); It is further needed to access the [0] element as the POST input is passes as an array of arrays Update 2: Seeing the problem is because the POST returns the data as a further array following code MIGHT work. I would need var_dump of POST inputs ($hi_input..) to give the exact code. $hi_input = $this->input->post('hi'); $hello_input = $this->input->post('hello'); $how_input = $this->input->post('how'); $data = array(); foreach ($hi_input as $idx => $name) { $data[] = array( 'hi' => $hi_input[$idx][0], 'hello' => $hello_input[$idx][0], 'how' => $how_input[$idx][0] ); }; $this->db->insert_batch('table', $data); The following code should work as I have tested it (I do not have CodeIgniter Installed). It does not use CodeIgniter to get post data. $hi_input = $_POST['hi']; $hello_input = $_POST['hello']; $how_input = $_POST['how']; $data = array(); foreach ($hi_input as $idx => $name) { $data[] = array( 'hi' => $hi_input[$idx][0], 'hello' => $hello_input[$idx][0], 'how' => $how_input[$idx][0] ); }; $this->db->insert_batch('table', $data); Update : You can also do this using $this->db->insert_batch();, like this : $hi_input = $this->input->post('hi'); $hello_input = $this->input->post('hello'); $how_input = $this->input->post('how'); $data = array(); foreach ($hi_input as $idx => $name) { $data[] = array( 'hi' => $hi_input[$idx], 'hello' => $hello_input[$idx], 'how' => $how_input[$idx] ); }; $this->db->insert_batch('table', $data); Old answer The CodeIgniter documentation on insert - http://codeigniter.com/user_guide/database/active_record.html#insert states that the $data parameter is an associative array with column names as keys and data to insert as values. So you need to call it once for each row. Thus Try this: $hi_input = $this->input->post('hi'); $hello_input = $this->input->post('hello'); $how_input = $this->input->post('how'); foreach ($hi_input as $idx => $name) { $data = array( 'hi' => $hi_input[$idx], 'hello' => $hello_input[$idx], 'how' => $how_input[$idx] ); $this->db->insert('table', $data); };
{ "language": "en", "url": "https://stackoverflow.com/questions/7501441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Intercepting ASP.NET MVC routes I need to transform some url parameters while creating link on server side. Example: @html.ActionLink("text","index","Home",null,new { id=Model.Id }); Now i have to transform id parameter so i can simply convert it and pass it into object objectRoute parameter or i can simply override ActionLink.But problem is that i have to make refactor on whole project. So i am looking a way to intercepting mechanism or handler mechanism. Is there any solution for this ? A: You could try using an ActionFilterAttribute: public class ConversionAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); var idValue = filterContext.RouteData.Values["id"]; var convertedIdValue = ConvertId(idValue); var newRouteValues = new RouteValueDictionary(filterContext.RouteData.Values); newRouteValues["id"] = convertedIdValue; filterContext.Result = new RedirectToRouteResult(newRouteValues); } } Then you'll need to apply the attribute to the action where you want this to happen: [Conversion] public ActionResult Index(int id) { // Your logic return View(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to store login credentials in localstorage If got a sencha touch application, with a login form. For returning users, I would like to store the login credentials in the local storage. User.js App.models.User = Ext.regModel('User', { fields: [ { name: 'username', type: 'string' }, { name: 'password', type: 'string' } ], proxy: { type: 'localstorage', id: 'p2s-users' } }); Users.js App.stores.users = new Ext.data.Store({ model: 'User', autoLoad: true }); Now I try to sync the form values with local storage, how can I do that, what's the activity flow for reading / getting it? For reading I would do: var model = new App.models.User(); users = App.stores.users.load(); if (users.data.length > 0 ) { model = users.getAt(0); } else { App.stores.users.create(); } form.load(model); Writing: form.model.set(form.data); form.model.save(); App.stores.users.sync(); Somehow it looks too complicate to me (and it doesn't work anyway). How would you solve the problem? A: First make sure your saving the models right. For example do this: var model = new App.models.User(); model.data.username = 'theUser'; model.data.password = 'thePass'; model.save(); //the actual saving. Use chrome developer tools to see the local storage Then load the model from the localstorage users = App.stores.users.load(); model = users.getAt(0); Check if the loaded model is OK and load that to the form with load(model) The form could be like this: new Ext.Application({ launch: function() { new Ext.form.FormPanel({ id:'theForm', fullscreen: true, defaults: { labelAlign: 'top', labelWidth: 'auto', }, items: [ { id : 'userName', name : 'username', label: 'Email', xtype: 'emailfield', }, { id : 'userPassword', name: 'password', label: 'Password', xtype: 'passwordfield', } ] }); } }); Then load the record like this Ext.getCmp('theForm').load(users.getAt(0)); To get the model from the form: Ext.getCmp('theForm').getRecord(); A: From a cursory look, it looks like a possible way to do it. But, you should create model instances from the model manager, for instance: Ext.ModelMgr.create({username: 'foo', password: 'bar'}, 'User');
{ "language": "en", "url": "https://stackoverflow.com/questions/7501444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TFS Team Build Log Unit Test Results We're using TFS 2010 Team Build which automatically runs our unit tests during the build process. If I click on View Log, I can see the list of tests run and each test result (Success/Fail). In the event of Failure, I want to see the test result output (so the developer can figure out what the cause of the failure is). Just running the unit test locally isn't enough because the issue could be environmental (if the test is failing because of some data, server, or physical path). How can I change my build process template to include the full results of the unit test in the log? MSTest command line from View Log page: e:\Program Files\Common7\IDE\MSTest.exe /nologo /usestderr /testSettings:"E:\Builds\1\1\Sources\Source\TestSettings.testsettings" /searchpathroot:"E:\Builds\1\1\Binaries" /resultsfileroot:"E:\Builds\1\1\TestResults" /testcontainer:"E:\Builds\1\1\Sources\Source\Testing\bin\Release\Testing.dll" /publish:"http://tfs:8080/tfs/Projects" /publishbuild:"vstfs:///Build/Build/196" /teamproject:"Project" /platform:"Any CPU" /flavor:"Release" Screenshot of summary http://imageshack.us/photo/my-images/28/tfsbuild.gif/ And of the Build Definition configuration http://imageshack.us/photo/my-images/835/builddefinition.gif/ Thanks. A: If you use the default template and run the test using the unit test framework provided by Microsoft, you should be able to see a link to the published test results on the View Summary page of the build details. When you click at this link, the test results will be downloaded from the database and put together in an trx file that will be displayed in your Test Window in Visual Studio. UPDATE: The problem was figured out after looking at the logs. The build template was customized to use another tool to build instead of MSBuild, and the summary nodes for each configuration (platform/flavor) were not created as a result. That's why the build details view was missing the summary, including the test results. A: There is one tiny, little detail that you need to know to get this to work. If you are using the web portal to view the test results for a build, You want to make sure that the Outcome column displays All (not just Failed). If all passed, nothing would be listed if the Outcome was set to Failed. Here is a little picture of what I'm talking about: Notice how I have set the Outcome column to All. Now, if I select All as the Outcome, I can see all the tests listed. If you double-click any test the TFS web app will navigate you to the Run summary. Any tests that are linked with automation will have a Link provided to the Summary and any TRX files will be attached. Opening the TRX file will show the TestContext.WriteLine output, plus other data, like Duration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Mercurial: which addremove --similarity default is recommended? For Hg's addremove command, I'm looking for a reasonable --similarity default. Which value works well for all kinds of files? Which value works well for which programming language? A: There is no one good value. If there was, it would already be the default. Language and filetypes are largely irrelevant. What matters is the size of the file relative to the size of the changes you're making. If you are simply moving files around without edits, 100 is the best answer. Mercurial probably won't make any mistakes guessing what adds and removes were actually renames. If you are making small edits to large files while moving them around, then 90 might work well. Mercurial probably won't be fooled unless you've got some very similar files. If you're making large changes to small files, you might need to go down to 50 to guess your rename. But the odds of Mercurial mistaking two different but similar files is now quite large. (For comparison, Git uses a 50% heuristic by default for diffs and merges, but since it doesn't actually record renames in history, there's less permanent downside of guessing wrong.) A: You can find out a suitable value for a specific situation by running Mercurial with the option --dry-run. Mercurial won't perform any action but show what it would do. You also see the similarity of each file, so you can adjust your value before performing the real action. Example: hg addremove --similarity 50 --dry-run ... recording removal of ../contact_form/views.py as rename to contact_form/views.py (98% similar) A: Note that the bug 3430 and the release note 2012-06-01 mention for addremove: addremove: document default similarity behavior -s100 So, while not the "best value", -s100 (identical, simple moves without edits) is officially the default one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Tomcat 6 and foreign characters (UTF-8 and non UTF-8 mixup) I have a problem displaying foreign language characters in web app with Tomcat 6. Previously we were using Tomcat 5.5 and we did not face this issue. To fix this issue I followed http://wiki.apache.org/tomcat/FAQ/CharacterEncoding#Q8 and made changes to my web app accordingly. Now the web app supports URF-8 encoding and most of the issues with encoding are fixed. The bigger problem that I am facing now is with the old data that is stored in the database using the app with Tomcat 5.5. The old data is not displayed correctly on the webapp with UTF-8 encoding. What is the best way to to have the webapp configured with UTF-8 encoding and also to be able to display the old data which are not UTF-8 encoded? Also, the I am not able to determine what encoding was used previously. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I get the ID of multiple inserted rows in MySQL? I am inserting some words into a two-column table with this command: INSERT IGNORE INTO terms (term) VALUES ('word1'), ('word2'), ('word3'); * *How can I get the ID (Primary Key) of the row in which each word is inserted. I mean returning a value like "55,56,57" after executing INSERT. Does MySQL have such a response? *The term column is UNIQUE. If a term already exists, MySQL will not insert it. Is it possible to return the reference for this duplication (i.e. the ID of the row in which the term exists)? A response like "55,12,56". A: * *You get it via SELECT LAST_INSERT_ID(); or via having your framework/MySQL library (in whatever language) call mysql_insert_id(). *That won't work. There you have to query the IDs after inserting. A: Why not just: SELECT ID FROM terms WHERE term IN ('word1', 'word2', 'word3') A: First, to get the id just inserted, you can make something like : SELECT LAST_INSERT_ID() ; Care, this will work only after your last INSERT query and it will return the first ID only if you have a multiple insert! Then, with the IGNORE option, I don't think that it is possible to get the lines that were not inserted. When you make an INSERT IGNORE, you just tell MySQL to ignore the lines that would have to create a duplicate entry. If you don't put this option, the INSERT will be stopped and you will have the line concerned by the duplication.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: Php output to xml error I am following step by step this tutorial http://code.google.com/apis/maps/articles/phpsqlajax.html . I have tried all the 3 ways to output data to an xml file . But i get error "error on line 9 at column 1: internal error" which is the line that php script begins. Connection to database is ok. tables and fields are ok. I tried and copy pasted the exact code from google's tutorial (same values everywhere) to check if there was a problem with my database engine or something and I got an error again this time error on line 10 at column 8: Extra content at the end of the document that is $xmlStr=str_replace('"','&quot;',$xmlStr); I am running XAMPP 1.7.4 [PHP: 5.3.5] A: Changed the php script not to include the file containing the username and password for the database. I manually included those to the script. Not sure why it wasnt working as provided from google instructions but anyway now i get the job done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I implement an interactive tutorial inside an app? I have C# add-in for Word and would like to implement an interactive tutorial like games usually have. I'd like to somehow highlight (maybe by circling) certain visual elements and display text boxes that describe what the element does. For example, say the add-in is a generic workflow editor. I'd like to show to the user, step by step, what needs to be done by visually selecting elements and explaining what they do and what options (s)he has. My first question is: can this be done in C#? My second question is how? :) I suppose I'd have to get the positions of said visual elements and then draw an image on top but I don't know how that could be done. A: I'm a bit disappointed that not even a single member of the Stack Overflow community took the the time to at least give a hint about this. But such is life and I'm just going to share my findings here because I'm certain someone else will benefit from them. To be able to do an interactive tutorial you need three things: * *a method to find where a control is located in terms of screen coordinates *a method to point the user to the control by highlighting it or surrounding it with a red line for example. *a method to do its default action (ie: click a button). In other words, the idea is to have some sort of window with text describing a control and some graphical way of indicating the control in the app. Optionally, the window could provide something like a ShowMe button which shows the user how to use the control by taking control of the mouse and keyboard. This is trivial when the controls are made by yourself and thus have source code access. However, when doing such a thing for a black box app such as Word you can use the Windows IAccessible interface. Searching for that with your favorite search engine will yield everything you need to understand it and use it. IAccessible allows one to do many things but most importantly it can get a control's position and can also do the default action. Having sorted out these things the next step is to figure out how to graphically point out the control. There are many ways to do this but in my case I chose to surround it with a red rectangle. I did this by creating an invisible, borderless form with an empty red rectangle on it. Having the control's position and size, I had no problems placing the aforesaid form over the control. So there you have it. I laid out the building blocks that one needs to make an interactive tutorial for any app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Only some trace messages getting logged in my Azure app I have Trace.WriteLine() calls sprinkled about to track what the application is doing. What is stumping me is that some of these make it to the log and others don't. For example, this snippet of code from my worker role OnStart() method: Trace.WriteLine("WorkerRole: creating storage tables", "Information"); CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString"); CloudTableClient tableClient = account.CreateCloudTableClient(); if (tableClient.CreateTableIfNotExist("Devices")) { Trace.WriteLine("WorkerRole.OnStart: Devices table created", "Information"); }else{ Trace.WriteLine("WorkerRole.OnStart: Devices table not created. Already exists?", "Information"); } The first Trace gets logged. Neither of the Trace calls in the if statement gutted logged. Then a Trace method in a subsequently executing method does get logged. Any ideas? A: In your OnStart method for your role, are you adjusting the DiagnosticMonitorConfiguration? By default, trace logs aren't transfered to storage unless you tell it to: public override bool OnStart() { #region SetupDiagnostics Set up diagnostics DiagnosticMonitorConfiguration dmc = DiagnosticMonitor.GetDefaultIniialConfiguration(); TimeSpan tsOneMinute = TimeSpan.FromMinutes(1); dmc.Logs.ScheduledTransferPeriod = tsOneMinute; // Transfer logs every minute dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose; // Tansfer verbose, critical, etc. logs // Start up the diagnostic manager with the given configuration DiagnosticMonitor.Start("DiagnosticsConnectionString", dmc); #endregion }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: "Run destination iOS Device is not valid" for iPod Touch running 3.1.3 with XCode 4 I'm trying to test my application against a friend's old iPod touch running iOS 3.1.3. I have XCode 4 and receive this error message when trying to run the application: The run destination iOS Device is not valid for Running the scheme 'MyApp'. The scheme 'MyApp' contains no buildables that can be built for the architectures supported by the run destination iOS Device. Make sure your targets build for architectures compatible with the run destination iOS Device. I have set the deployment target to iOS 3.1.3. What else do I need to do in XCode 4 to build and test the app on this old iPod touch? I am using the "standard" build architecture, not optimised. A: In my Target->General, I selected Device "iPad" and was trying to run in an iPhone simulator. I just changed the Device option to universal (which was alright for me) and then run again. It solved my problem. A: I solved this by Autocreating schemes (Scheme > Manage schemes > Autocreate schemes) and then selecting the iPod Touch instead of "iOS Device" which had appeared in the schemes. D'oh!
{ "language": "en", "url": "https://stackoverflow.com/questions/7501484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Make h:dataTable cell editable by using h:selectbooleanCheckbox linked to HashMap in the bean I went through this question from SO How to use <h:selectBooleanCheckbox> in <h:dataTable> to select multiple rows? Using the single checkbox as shown in above question i want to find out whether i can make h:datatable cell editable so that user can edit all the rows and columns at once and submit Here is part of bean class public class bean { private List<Group> GroupList; private Map<Long, Boolean> checked = new HashMap<Long, Boolean>(); public void setChecked(Map<Long, Boolean> checked) { this.checked = checked; } public Map<Long, Boolean> getChecked() { return checked; } } And here is my JSF page <h:dataTable id="editTable" styleClass = "listtable" value="#{bean.GroupList}" var="group" border="1" first="0" rows="8" width="75%" frame="hsides" rules="all" cellpadding="5" headerClass="tableheading" rowClasses="firstrow, secondrow"> <f:facet name="header"> <h:outputText value="Groups"></h:outputText> </f:facet> <h:column> <f:facet name="header"> <h:outputText value="GroupId"></h:outputText> </f:facet> <h:outputText value="#{group.Id}" rendered=""></h:outputText> <h:inputText value="#{group.Id}" rendered=""/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="GroupName"></h:outputText> </f:facet> <h:outputText value="#{group.Name}" rendered=""></h:outputText> <h:inputText value="#{group.Name}" rendered=""/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Check to Enable/Disable"></h:outputText> </f:facet> <h:selectBooleanCheckbox value="#{bean.checked[group.Id]}" /> </h:column> </h:dataTable> What should be kept in rendered attribute so that when it is checked h:inputtext is rendered and when not checked h:outputtext is rendered? A: Just bind to the same property. It returns a Boolean anyway. You can use ! or not to negate it. <h:outputText value="#{group.Id}" rendered="#{!bean.checked[group.Id]}" /> <h:inputText value="#{group.Id}" rendered="#{bean.checked[group.Id]}" /> ... <h:outputText value="#{group.Name}" rendered="#{!bean.checked[group.Id]}" /> <h:inputText value="#{group.Name}" rendered="#{bean.checked[group.Id]}" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7501486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unable to show JSON data into Grid Panel. Shows only one blank row in Grid Unable to show JSON data into Grid. I got blank grid but you can see sequence no "1" and blank row, though number 1 is auto generated, it is not a JSON data. code Ext.onReady(function(){ // PRESSURE GRID - PRESSURE TAB // var proxy=new Ext.data.HttpProxy( {url:'',method: 'POST'} ); Ext.define('pressureModel', { extend: 'Ext.data.Model', fields: ['month', 'KOD', 'timePeriod', 'beachBank', 'manMade', 'charterBoat', 'privateRentalBoat'] }); var pressureGridStore=new Ext.data.Store({ id: "pressureG", model: 'pressureModel', proxy: proxy, reader:new Ext.data.JsonReader({ type : 'json', root: 'pressureFi', totalProperty: 'pressureResultLength' },[{name:'month'},{name:'KOD'},{name:'timePeriod'},{name:'beachBank'},{name:'manMade'},{name:'charterBoat'},{name:'privateRentalBoat'}] ) }); // Generic fields array to use in both store defs. var pressureFields = [ {name: 'month', mapping: 'month', type: 'string'}, {name: 'KOD', mapping: 'KOD', type: 'string'}, {name: 'timePeriod', mapping: 'timePeriod', type: 'string'}, {name: 'beachBank', mapping: 'beachBank', type: 'string'}, {name: 'manMade', mapping: 'manMade', type: 'string'}, {name: 'charterBoat', mapping: 'charterBoat', type: 'string'}, {name: 'privateRentalBoat', mapping: 'privateRentalBoat', type: 'string'} ]; var pressureGrid = new Ext.grid.GridPanel({ id : "pressure-grid", ddGroup : 'gridDDGroup', store : pressureGridStore, columns: [new Ext.grid.RowNumberer(), { text: 'Month', width: 70, dataIndex: 'month' },{ text: 'Kind of Day', width: 85, dataIndex: 'KOD' },{ text: 'Time Period', width: 95, dataIndex: 'month' },{ text: 'Beach/Bank', width: 65, dataIndex: 'beachBank' },{ text: 'Man/Made', width: 65, dataIndex: 'manMade' },{ text: 'Charter Boat', width: 75, dataIndex: 'charterBoat' },{ text: 'Private/Rental Boat', width: 105, dataIndex: 'privateRentalBoat' }], enableDragDrop : true, stripeRows : true, autoExpandColumn : 'name', width : 624, height : 325 }); function handleActivate(tab){ alert("in handle "); pressureGridStore.proxy.url='siteUtil.jsp'; pressureGridStore.load({params: {'method':'getSitePressureInfo'} }); } tabPanelObject = { getTabPanel: function(siteId) { var infoPanel = new Ext.tab.Panel({ id: 'tabPan', xtype: 'tabpanel', title: 'Site Information', height: 1000, width: '50.4%', items:[ { title: 'Pressure', id: 'pressureTab', listeners: {activate: handleActivate}, items:[ { xtype: "panel", width : '100%', height : 300, layout: 'fit', items: [ pressureGrid ] } ]} ] }); return infoPanel; } } }); Json Response is as follow {"pressureResultLength":"96","pressureFi":[{"charterBoat":9,"timePeriod":"0200- 0800","KOD":"WEEKDAY","beachBank":9,"month":"JAN","privateRentalBoat":9,"manMade":9}, {"charterBoat":0,"timePeriod":"0800-1400","KOD":"WEEKDAY","beachBank":9,"month":"JAN","privateRentalBoat":9,"manMade":9},{"charterBoat":0,"timePeriod":"1400-2000","KOD":"WEEKDAY","beachBank":9,"month":"JAN","privateRentalBoat":9,"manMade":9},{"charterBoat":9,"timePeriod":"2000-0200","KOD":"WEEKDAY","beachBank":9,"month":"JAN","privateRentalBoat":9,"manMade":9},{"charterBoat":9,"timePeriod":"0200-0800","KOD":"WEEKEND","beachBank":9,"month":"JAN","privateRentalBoat":9,"manMade":9},{"charterBoat":0,"timePeriod":"0800-1400","KOD":"WEEKEND","beachBank":9,"month":"JAN","privateRentalBoat":9,"manMade":9},{"charterBoat":0,"timePeriod":"1400-2000","KOD":"WEEKEND","beachBank":9,"month":"JAN","privateRentalBoat":9,"manMade":9},{"charterBoat":9,"timePeriod":"2000-0200","KOD":"WEEKEND","beachBank":9,"month":"JAN","privateRentalBoat":9,"manMade":9},{"charterBoat":9,"timePeriod":"0200-0800","KOD":"WEEKDAY","beachBank":9,"month":"FEB","privateRentalBoat":9,"manMade":9},{"charterBoat":0,"timePeriod":"0800-1400","KOD":"WEEKDAY","beachBank":9,"month":"FEB","privateRentalBoat":9,"manMade":9},{"charterBoat":0,"timePeriod":"1400-2000","KOD":"WEEKDAY","beachBank":9,"month":"FEB","privateRentalBoat":9,"manMade":9},{"charterBoat":9,"timePeriod":"2000-0200","KOD":"WEEKDAY","beachBank":9,"month":"FEB","privateRentalBoat":9,"manMade":9},{"charterBoat":9,"timePeriod":"0200-0800","KOD":"WEEKEND","beachBank":9,"month":"FEB","privateRentalBoat":9,"manMade":9},{"charterBoat":0,"timePeriod":"0800-1400","KOD":"WEEKEND","beachBank":9,"month":"FEB","privateRentalBoat":9,"manMade":9},{"charterBoat":0,"timePeriod":"1400-2000","KOD":"WEEKEND","beachBank":9,"month":"FEB","privateRentalBoat":9,"manMade":9},{"charterBoat":9,"timePeriod":"2000-0200","KOD":"WEEKEND","beachBank":9,"month":"FEB","privateRentalBoat":9,"manMade":9},{"charterBoat":9,"timePeriod":"0200-0800","KOD":"WEEKDAY","beachBank":9,"month":"MAR","privateRentalBoat":9,"manMade":9}]} I checked the FireBug Console. It returns the response as above but it is of type(actionmethod) 'GET' When I did pressureGridStore.on({ 'load':{ fn: function(store, records, options){ //store is loaded, now you can work with it's records, etc. console.info('store load, arguments:', arguments); console.info('Store count = ', store.getCount()); }, scope:this } }); I got Store Count = 1. -Ankit A: the problem is that your components aren't defined correctly. for instance, the reader config in extjs4 doesn't belong to store, it belongs to proxy see http://dev.sencha.com/deploy/ext-4.0.2a/docs/#/api/Ext.data.proxy.Ajax so for the proxy you should have var proxy=new Ext.data.HttpProxy( { url:'', reader:new Ext.data.JsonReader({ type : 'json', root: 'pressureFi', totalProperty: 'pressureResultLength' }) }) I think with this modification it should work
{ "language": "en", "url": "https://stackoverflow.com/questions/7501487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Removing space between fieldsets I have a fieldset that contains a number of nested fieldsets that are dynamically added and removed. However, I want the nested fieldsets to be displayed similar to a form e.g. with not much space between elements. However, each fieldset has a gap between then & I don't know how to remove this. I tried using bodystyle on the parent fieldset but that had no effect. I am using this method as it's easier to add/remove the "rows" in the form. A: You need to set bodyStyle on each of the nested fieldsets, not on the parent fieldset. Depends on the parent fielset's layout but try bodyStyle:'padding:0px' on each of nested fieldsets.On parent fieldset, you set defaults:{bodyStyle:'padding:0px'}
{ "language": "en", "url": "https://stackoverflow.com/questions/7501490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In the play framework, how do I run just one selenium test suite and have it run automatically? I am doing Test Driven Development using the Play Framework and want to keep run the current failing test quickly. I am finding clicking Start! to be to slow since I have a mostly keyboard driven workflow. So ideally I would like a way to just reload the page and have it rerun the currently failing test. A: I ended up leaving play test running and reloading the following page - note the auto=yes parameter http://localhost:9000/@tests?select=Application.test.html&auto=yes
{ "language": "en", "url": "https://stackoverflow.com/questions/7501493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is JAXB generated package-info.java I'm trying to find some information on what the package-info.java file generated by the JAXB xjc commandline app actually does. All that is in the file is @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.example.com", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package the.generated.package.path; What is this package-info.java file used for? A: This is also useful when you generate javadoc package-info.java - Can contain a package declaration, package annotations, package comments and Javadoc tags. This file is new in JDK 5.0, and is preferred over package.html. source : http://download.oracle.com/javase/6/docs/technotes/tools/solaris/javadoc.html#sourcefiles A: package-info.java is a way to apply java annotations at the package level. In this case Jaxb is using package-level annotations to indicate the namespace, and to specify namespace qualification for attributes (source). A: If you want to define default namespace for elements in your java model, you can define it in package-info.java
{ "language": "en", "url": "https://stackoverflow.com/questions/7501494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Windows Phone - Udp Does anyone try using Udp Unicast on Windows Phone 7.1 (RC)? I have a few questions that I like to ask you guys. * *According to the document http://msdn.microsoft.com/en-us/library/system.net.sockets.socket(v=VS.95).aspx, the only supported ProtocolType is the TCP protocol. Does it mean Udp Unicast is not fully supported? *I found that we can only call ReceiveFromAsync at the Completed event of SendToAsync. Otherwise, it will throws "An invalid argument was supplied" exception. Why does it work like that? Other also have the same issue Issues with async receiving UDP Unicast packets in Windows Phone 7 .. *I tested with MSDN sample and a few other C# Udp clients as well. I found that SendToAsync method is working fine. But ReceiveFromAsync is not working. Does anyone has any idea how to fix it? private void OnRecieve() { var receiveArgs = new SocketAsyncEventArgs(); receiveArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Any, PORT); receiveArgs.SetBuffer(new Byte[1024], 0, 1024); var strBdr = new StringBuilder(); receiveArgs.Completed += (__, result) => { var package = Encoding.UTF8.GetString(result.Buffer, 0, result.BytesTransferred); if (!string.IsNullOrEmpty(package)) { this.RaiseReceived(package); } socket.ReceiveFromAsync(receiveArgs); }; socket.ReceiveFromAsync(receiveArgs); } Thanks guys!! A: * *According to documentation "For Windows Phone OS 7.1, TCP unicast, UDP unicast, and UDP multicast clients are supported." (I used your link) *My understanding is that you can receive only from an IP you initiated a communication with, that's for security purposes.. *You are mixing c# code with Silverlight code, WP7 only supports Silverlight.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Showing the part of a hidden DIV within a DIV I'm missing something obvious today, guys - would appreciate some help please. I've got a horizontal row of DIVs inside another DIV. I want the third DIV to show as partly hidden by the top DIV. But it isn't showing at all. Here's the CSS: .outer { background: #800; height: 90px; width: 300px; overflow: hidden; white-space: nowrap; } .label { float: left; display: block; background: #888; width: 75px; height: 50px; margin: 10px; padding: 10px; line-height: 50px; font-size: 45px; text-align: center; } Here's the HTML: <div class="outer"> <div class="label">1</div> <div class="label">2</div> <div class="label">3</div> <div class="label">4</div> </div> Thanks for your help! A: I'm missing something obvious today, guys - would appreciate some help please. The "obvious" thing you're missing is that the third and fourth inner divs are dropping underneath because there is not enough horizontal space. For instance, if I check it using Chrome's Developer Tools: The simplest way to fix this is to switch from float: left to display: inline-block, with white-space: nowrap (you already have it!) on the containing element: http://jsfiddle.net/rGfNY/ A: you need to wrap them in a new div, give the div a width, (bigger than your outer div) it will be cut off by the outer div's overflow hidden. on thing to note: the width of that inner div is not adjusting with the content, either you specifically set it very high, or you have to calculate it to the content either just put it hardcoded in css, or use javascript. html: <div class="outer"> <div class="inner"> <div class="label">1</div> <div class="label">2</div> <div class="label">3</div> <div class="label">4</div> </div> </div> css: .outer { background: #800; height: 90px; width: 300px; overflow: hidden; white-space: nowrap; } .inner { width: 460px; } .label { float: left; display: block; background: #888; width: 75px; height: 50px; margin: 10px; padding: 10px; line-height: 50px; font-size: 45px; text-align: center; } working example: http://jsfiddle.net/f2wpm/
{ "language": "en", "url": "https://stackoverflow.com/questions/7501499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# extern alias I have two assemblies with the exact same interface (lets call them Assem1 and Assem2) Is it possible to use extern alias in order to call methods of Assem1 from Assem2? The source code is something like this: //Pre steps - set Reference in Assem1 to assem2 and set it's alias to Assem2Alias //Both assemblies named MyAssembly.dll, has exact same interface but different Guids //Assem1 code extern alias Assem2; using Assem2 = Assem2Alias.MyAssembly; namespace MyAssembly { public class MyClass { public int Foo() { return new Assem2.MyClass().Foo(); } } } //Assem2 code namespace MyAssembly { public class MyClass { public int Foo() { return 10; } } } Edited: As requested - I'm adding extra information regard the general task: I need to test application that uses ActiveX.exe to get data (responses) from external services. My task is to replace this ActiveX.exe so I will control the responses. Since the responses are large textual data, I would to generate the request using the original ActiveX.exe file. The new assembly (Assem1 in my question) must have the exact same interface as the original ActiveX.exe (Assem2). The general idea: Assem1 gets a request from the tested application. If the request matches response in its data source --> it read the response and return it to the application. If it does not match any of the responses, then Assem1 requests Assem2 for response, adds it to its data source and response to the tested application. As mentioned both must have the exact same interface, so I uses extern alias to refer to the original ActiveX.exe. All the examples on the internet using extern alias in C# specified to one assembly refering to two assemblies with the same interface, but not from one to each other.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Metro UI styled libraries for Silverlight I know Microsoft will be releasing Metro UI styles and themes for Silverlight but do any of you already know of similar libraries? I am especially interested in tile animations like those you can see on Windows 8 home screen. PS: I am not asking about Silverlight metro app themes. Thanks in advance. A: Have a look at this!
{ "language": "en", "url": "https://stackoverflow.com/questions/7501507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Real-time timer on Android In what way that I can have a real-time timer for task scheduling on Android? Currently I am using Java.util.timer for my real-time application? However, the timer is missing firing when garbage collection is running or other other stuff. The description on java.util.timer says "this class does not offer guarantees about the real-time nature of task scheduling.". Then, which class that I should use on Android then? Or are there any other approach to have a real-time guarantee timer on Android? Forgot to mention that the timer that I need is at 20 - 40 milliseconds precision level. That means, I need it to fire every 20 - 40 milliseconds. A: Handler.postDelayed(Runnable r, long delayMillis); Does not have a note about whether or not it guarantees it to happen on time. I've used this mechanism before and never noticed any inconsistency with it. However, i've only used it for relatively short intervals (less than a minute) If you are looking for something farther out than that I would suggest you take a look at the AlarmClock application in the Android source. That will probably give you a good approach. That being said if you are looking for extreme precision(down to seconds or farther) I doubt you're going to be able to find anything with guarantees. There are too many things that could be going on that could cause potential misfires.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JavaScript IE 9: Custom sort function In IE 9, if I type this in the console: [1, 4, 2, 3].sort(function (a, b) { return a < b; }); The resulting array is: [1, 4, 2, 3]. If I do this in FF/Chrome, I get it, reverse-sorted: [4, 3, 2, 1]. How come this doesn't work in IE? EDIT: Is there a function out there that abstracts these browser differences? In other words, is there a function I can pass function(a, b) { return a < b; } in and get the same result in all browsers? Any open-source stuff? A: Maybe because the function is supposed to return -1 if a is smaller, 0 if they are equal, and 1 if a is larger (or vice versa if you want reverse order). Edit: In fact, it must be zero, a positive or negative number (as @pimvdb pointed out, and that's what I make use of in the example below). Your function will never return -1 though and that might create problems. Consider 1 and 3. Your function returns 1 for 1 < 3, which is ok, but returns 0 for 3 < 1. In one case the number are different, in the other you are saying that they are equal. That FF/Chrome sort it in reverse order might be due to the sorting algorithm they are using. Try: [1, 4, 2, 3].sort(function (a, b) { return b - a; }); Update: To substantiate this, we can have a look at the specification, Section 15.4.4.11 Array.prototype.sort(comparefn), where the properties are given which have to be fulfilled by a comparison function: A function comparefn is a consistent comparison function for a set of values S if all of the requirements below are met for all values a, b, and c (possibly the same value) in the set S: The notation a <CF b means comparefn(a,b) < 0; a =CF b means comparefn(a,b) = 0 (of either sign); and a >CF b means comparefn(a,b) > 0. * *Calling comparefn(a,b) always returns the same value v when given a specific pair of values a and b as its two arguments. Furthermore, Type(v) is Number, and v is not NaN. Note that this implies that exactly one of a <CF b, a =CF b, and a >CF b will be true for a given pair of a and b. *Calling comparefn(a,b) does not modify the this object. *a =CF a (reflexivity) *If a =CF b, then b =CF a (symmetry) *If a =CF b and b =CF c, then a =CF c (transitivity of =CF) *If a <CF b and b <CF c, then a <CF c (transitivity of <CF) *If a >CF b and b >CF c, then a >CF c (transitivity of >CF) NOTE The above conditions are necessary and sufficient to ensure that comparefn divides the set S into equivalence classes and that these equivalence classes are totally ordered.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do browsers parse and interpret JavaScript code? How does a browser go about parsing JavaScript it loads from files or inline? I am trying to get at the core of what a browser does. What happens when a page loads and it has <script> references to external files, and actual JavaScript on the page too. Any good articles out there? A: This is defined in the ECMAScript standard. First the source text (the stuff between the <script> tags) is converted into a series of tokens (according to the Lexical Grammar of the language): The source text of an ECMAScript program is first converted into a sequence of input elements, which are tokens, line terminators, comments, or white space. The source text is scanned from left to right, repeatedly taking the longest possible sequence of characters as the next input element. Read here: http://es5.github.com/#x7 That series of tokens is treated as a Program, which is then evaluated according to the Syntactic Grammar of the language which is defined in chapters 11 to 14 of the ECMAScript standard. The syntactic grammar for ECMAScript is given in clauses 11, 12, 13 and 14. This grammar has ECMAScript tokens defined by the lexical grammar as its terminal symbols (5.1.2). It defines a set of productions, starting from the goal symbol Program, that describe how sequences of tokens can form syntactically correct ECMAScript programs. Read here: http://es5.github.com/#x5.1.4 It starts in chapter 14: http://es5.github.com/#x14 Note that each <script> element represents a separate JavaScript program. Read here: How many JavaScript programs are executed for a single web-page in the browser? A: This is probably the best description of what a browser does according to the ECMAScript standard Javascript Closures: Identifier Resolution, Execution Contexts and scope chains
{ "language": "en", "url": "https://stackoverflow.com/questions/7501520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Timers in Windows Service I want to use timers in my service. But I heard that timers cause deadlock issues. Suppose If I set my timer to start every 10 mins. My service takes 5 mins to finish its current execution. But in some cases it will take more time.(Its unpredictable). So what happens if my service couldn't finish current execution within 10 mins.A new timer event will fire?? And what happens to my current execution of the service? Appreciate your help. A: you can use timers in Windows service as it also stated on MSDN A service application is designed to be long running. As such, it usually polls or monitors something in the system. The monitoring is set up in the OnStart method. However, OnStart does not actually do the monitoring. The OnStart method must return to the operating system once the service's operation has begun. It must not loop forever or block. To set up a simple polling mechanism, you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring. despite the above you still need to create your logic to avoid both deadlock or the code specified within the Elapsed event takes longer then the interval itself. The Elapsed event is raised on a ThreadPool thread. If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. Thus, the event handler should be reentrant. http://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.80%29.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7501521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Lucene doesn't search text having '_' Possible Duplicate: Lucene search and underscores I am using Lucene full text search for searching in my application. But for example, if I search for 'Turbo_Boost' it returns 0 results. For other text it works fine. Any Idea? A: Assuming you are using the StandardTokenizer, it will split on the underscore character. You can get around this by providing your own Tokenizer which will keep the underscore in the Token that's returned (either through a combination of Filter instances or TokenFilter instances). A: A general rule of thumb with Lucene is to tokenize your search queries using the same Tokenizer/Analyzer you used to index the data. see http://wiki.apache.org/lucene-java/LuceneFAQ#Why_is_it_important_to_use_the_same_analyzer_type_during_indexing_and_search.3F A: I can only think of a few reasons why your query would fail: First, and probably the least likely, considering other text searches fine, you didn't set the document's field to be analyzed. It won't be tokenized, so you can only search against the exact value of the whole field. Again, this one is probably not your issue. The second (related to the third), and fairly likely, would depend on how you're executing the search. If you are not using the QueryParser (which analyzes your text the same way you index it if constructed properly) and instead say you are using a TermQuery like: var tq = new TermQuery("Field", "Turbo_Boost"); That could cause your search to possibly fail. This has to do with the Analyzer you used to index the document splitting or changing the case of "Turbo_Boost" when it was indexed, causing the string comparison at search-time to f The third, and even more likely, has to do with the Analyzer class you're using to index your items, versus the one you're using to search with. Using the same analyzer is important, because each analyzer uses a different Tokenizer that splits the text into searchable terms. Let me give you some examples using your own Turbo_Boost query on how each analyzer will split the text into terms: KeywordAnalyzer, WhitespaceAnalyzer -> Field:Turbo_Boost SimpleAnalyzer, StopAnalyzer -> Field:turbo Field:boost StandardAnalyzer -> Field:turbo Field:boost You'll notice some of the Analyzers are splitting the term on the underscore character, while KeywordAnalyzer keeps it. It is extremely important that you use the same analyzer when you search, because you may not get the same results. It can also cause issues where sometimes the query will find results and other times it won't, all this depending on the query used. As a side note, if you are using the StandardAnalyzer, it's also important that you pass it the same Version to the IndexWriter and QueryParser, because there are differences in how the parsing is done depending on which version of Lucene you expect it to emulate. My guess your issue is one of those above reasons.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rake aborted - Unable to find platform. How to resolve? when I try to install my Ruby on Rails App, exactly when I digit: sudo rake db:migrate terminal returns to me: ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment rake aborted! Unable to find Platform /Users/ladmin/Sites/IkarosGest/vendor/plugins/wicked_pdf/lib/wicked_pdf.rb:17 /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require' /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `require' /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require' /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in' /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require' /Users/ladmin/Sites/IkarosGest/vendor/plugins/wicked_pdf/init.rb:1:in `evaluate_init_rb' /Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/rails/plugin.rb:158:in `evaluate_init_rb' /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings' /Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/rails/plugin.rb:154:in `evaluate_init_rb' /Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/rails/plugin.rb:48:in `load' /Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/rails/plugin/loader.rb:38:in `load_plugins' /Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/rails/plugin/loader.rb:37:in `each' /Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/rails/plugin/loader.rb:37:in `load_plugins' /Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/initializer.rb:369:in `load_plugins' /Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/initializer.rb:165:in `process' /Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/initializer.rb:113:in `send' /Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/initializer.rb:113:in `run' /Users/ladmin/Sites/IkarosGest/config/environment.rb:6 /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require' /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `require' /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require' /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in' /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require' /Library/Ruby/Gems/1.8/gems/rails-2.3.5/lib/tasks/misc.rake:4 /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:205:in `call' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:205:in `execute' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:200:in `each' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:200:in `execute' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:158:in `invoke_with_call_chain' /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:242:in `synchronize' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:151:in `invoke_with_call_chain' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:176:in `invoke_prerequisites' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:174:in `each' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:174:in `invoke_prerequisites' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:157:in `invoke_with_call_chain' /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:242:in `synchronize' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:151:in `invoke_with_call_chain' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/task.rb:144:in `invoke' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:112:in `invoke_task' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:90:in `top_level' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:90:in `each' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:90:in `top_level' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:84:in `top_level' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:62:in `run' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/lib/rake/application.rb:59:in `run' /Library/Ruby/Gems/1.8/gems/rake-0.9.2/bin/rake:32 /usr/bin/rake:19:in `load' /usr/bin/rake:19 Tasks: TOP => db:migrate => environment A: Resolved it! The problem was in "wickedpdf.rb" in this piece of code: if Platform.is_windows? include Win32PdfRenderer elsif Platform.is_linux? include NixPdfRenderer else raise "Unable to find Platform" end because I'm on Mac :D A: Don't use sudo for rake db:migrate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CollectionDataContract serialization not adding custom properties (DataMember) We have a legacy system that needs to be fed (XML) data in a most unstructured format. Is the following even possible with the .NET DataContractSerializer? Given the following DataContracts [CollectionDataContract(Name = "Options", ItemName = "Option")] public class OptionItemCollection : List<OptionItem> { [DataMember(Name = "Name")] public string Name { get; set; } public OptionItemCollection() { } public OptionItemCollection(IEnumerable<OptionItem> items) : base(items) { } } [DataContract(Name = "Option")] public class OptionItem { [DataMember] public string Text { get; set; } [DataMember] public string Value { get; set; } } Is it possible to serialize this collection directly into the following XML representation: <Options> <Name>Juices</Name> <Option Value="1">Orange Juice</Option> <Option Value="2">Pineapple</Option> <Option Value="3">Fruit Punch</Option> </Options> NOTE: This is exactly how the legacy system expects the data to be submitted. Or Even: <Options> <Name>Juices</Name> <Option><Value>1</Value><Text>Orange Juice</Text></Option> <Option><Value>2</Value><Text>Pineapple</Text></Option> <Option><Value>3</Value><Text>Fruit Punch</Text></Option> </Options> Also NOTE that the emphasis is on the Name and Option element residing within the Options element. A: Yes. Although the DataContractSerializer doesn't explicitly support XML attributes, you can hand-roll it. Try this: [CollectionDataContract(Name = "Options", ItemName = "Option")] public class OptionItemCollection : List<OptionItem> { [DataMember(Name = "Name")] public string Name { get; set; } public OptionItemCollection() { } public OptionItemCollection(IEnumerable<OptionItem> items) : base(items) { } } // note, remove attributes public class OptionItem : IXmlSerializable { public string Text { get; set; } public string Value { get; set; } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Value", Value); writer.WriteElementString("Text", Text); } public void ReadXml(XmlReader reader) { // implement if necessary throw new NotImplementedException(); } public System.Xml.Schema.XmlSchema GetSchema() { throw new NotImplementedException(); } } A: No, this is not possible with the DataContractSerializer (DCS). The DCS doesn't allow unwrapped collection elements. So you cannot have this: <a> <b/> <b/> <b/> <c/> </a> But you can have this: <a> <bb> <b/> <b/> <b/> </bb> <c/> </a> In your scenario you'll need to use the XmlSerializer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Windows Installer is invoking the RunOnce key immediately In my MSI installer package I have a custom action which adds a RunOnce key. However, it surprised me to observe that, at the end of the install, the RunOnce key is invoked immediately (and then deleted), whereas I was anticipating this to occur only when the pc is restarted. Is this behaviour standard, or can it be switched off? This is happening on Windows 7 64-bit. Any help gratefully received, many thanks in advance. Cheers, Andrew. A: Can you try the package on another Win7 machine, even virtual machine? From what I know only the restart should invoke the key, so maybe there is something corrupted on this machine that causes the behavior. EDIT: After posting I found this MSDN blog which says the key can get invoked in certain conditions. http://blogs.msdn.com/b/junfeng/archive/2006/09/19/761765.aspx To avoid the key invocation you could try to execute the custom action that creates it as late as possible during the installation. A: I solved my problem by using the RunOnceEx reg key, instead of RunOnce. Everything works as expected now. Cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/7501530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse + PyDev define function based on function call I have noticed a particular feature in Visual Studio and I am wondering if this feature is also available in Eclipse + PyDev. In Visual Studio, if one were to type a function call and that particular function does not already exist, VS would show a code error and give an option to generate a new empty function matching the signature provided in the function call. In other words, same I am working in a particular Python function or class and I realize I need a new function to process some string. In my current function I type processString(myString), which returns an error because the processString function does not currently exist. Is there some way to then click on the processString function call and create a new block in my module: def processString(myString): pass Thanks in advance for your help. A: Thank you @Eric Wilson. If I type the function call processString(myString) then hit 'CTRL+1' the code completion/template window appears offering me the option to create a new class, method, assign to a field, or assign to a variable. This was exactly what I was looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Entity Framework: how to use multple tables for the same entity? My situation is as follows. I'm using entity framework (4.0) in which I have defined a relatively simple model like, let's say, two entities: * *user *transaction A user can have multiple transactions in this scenario. When generating the database this would result (obviously) in 2 database tables names 'user' and 'transaction'. The problem is that I want to use the code as a webservice where different companies should have their own environment (read: own users and transactions). A simple solution would be to add a column to both tables like, lets say 'company_id' to identify one user/transactions for companya from the user/transaction from companyb. What I would like to have is a duplication of the tables like so: * *compa_user *compa_transaction *compb_user *compb_transaction This way..all data would be nicely separated and if company a generates a lot of transactions, company b would not notice that the system is getting slow or whatsoever. My question: is there a way to accomplish this based on entity framework. So, can I have multiple tables representing one entity in my model and switch from table to table depending on which company is connecting to the service. Any help appreciated! A: If you really want to keep the tables seperate, then a seperate database for each client would be the easiest - only need to change the connection string in EF. The other benefit of this model (seperate databases) is that the database will scale quite easily as each database could theoretically be on a different database server should the DB ever become the bottleneck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }