text
stringlengths
8
267k
meta
dict
Q: Call an Adobe Flex/ActionScript method from JavaScript? I need to know why JavaScript can't talk back to Flex. I have a project that is going to use JavaScript to play a given video file. Its running on a custom MVC framework where asset files are loaded via the /static prefix. Example: http://helloworld/static/swf/movie.swf` I compile my Flex application using the mxmlc binary with options -static-link-runtime-shared-libraries=true, -use-network=true and --debug=true. Flex <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="init()"> <fx:Script> <![CDATA[ import mx.controls.Alert; import flash.external.ExternalInterface; private function init():void { log("Logging..."); if (ExternalInterface.available) { ExternalInterface.call("HelloWorld.initFlash"); ExternalInterface.addCallback("playVideo", playVideo); } } public function playVideo():void { log("Playing video..."); } public function log(message:String):void { if (ExternalInterface.available) { ExternalInterface.call( "function log(msg){ if (window.console) { console.log(msg); } }", message); } } ]]> </fx:Script> <s:Panel id="myPanel" title="Hello World" x="20" y="20"> <s:layout> <s:HorizontalLayout paddingLeft="10" paddingRight="10" paddingTop="10" paddingBottom="10" gap="5" /> </s:layout> </s:Panel> </s:Application> HTML <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Hello World</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script> <script type="text/javascript"> $(function(){ var swfVersionStr = "10.1.0"; var xiSwfUrlStr = "playerProductInstall.swf"; var flashvars = {}; var params = {}; var attributes = {}; params.allowscriptaccess = "sameDomain"; params.quality = "high"; params.bgcolor = "#FFFFFF"; params.allowfullscreen = "true"; attributes.id = "HelloWorld"; attributes.name = "HelloWorld"; attributes.align = "left"; swfobject.embedSWF( "HelloWorld.swf", "flash-content", "100%", "100%", swfVersionStr, xiSwfUrlStr, flashvars, params, attributes ); HelloWorld = function(){ return { initFlash : function() { console.log("Called from Flex..."); console.log($("#HelloWorld").get(0).playVideo("be6336f9-280a-4b1f-a6bc-78246128259d")); } } }(); }); </script> <style type="text/css"> #flash-content-container { width : 400px; height : 300px; } </style> </head> <body> <div id="layout"> <div id="header"><h1>Hello World</h1></div> <div id="flash-content-container"> <div id="flash-content"></div> </div> </div> </body> </html> Output Logging... Called from Flex... A: I had the same issue, in the link provided by Chris Cashwell it shows the base for the solution. Flex MXML <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="init()"> <fx:Script> <![CDATA[ import mx.controls.Alert; import flash.external.ExternalInterface; private function init():void { consoleLog("Hello World"); try { Security.allowDomain("*"); //I need to add this. ExternalInterface.marshallExceptions = true; ExternalInterface.addCallback("sendAlert",sendAlert); ExternalInterface.call("initCallBack"); } catch (error:Error) { consoleLog("Error in ExternalInterface"); consoleLog("Error" + error.message); } } public function sendAlert(s:String):void { Alert.show(s); } public function consoleLog(message:String):void { if (ExternalInterface.available) { ExternalInterface.call( "function log(msg){ if (window.console) { console.log(msg); } }", message); } } ]]> </fx:Script> <s:Panel id="panel1" title="Hello World" x="20" y="20"> <s:layout> <s:HorizontalLayout paddingLeft="10" paddingRight="10" paddingTop="10" paddingBottom="10" gap="5" /> </s:layout> <s:TextArea id="textarea1" width="300" height="100" text="Hello World" /> </s:Panel> </s:Application> HTML <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Hello World</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script> <script type="text/javascript"> var flexApp; function initCallBack() { flexApp = document.getElementById("HelloWorldFlex"); if (flexApp != undefined) { try { flexApp.sendAlert( "Hello World" ); } catch(err) { console.log("There was an error on the flex callback."); console.log(err); } } else { console.log("The flex object does not exist yet"); } return; } $(function(){ HelloWorld = function(){ return { init : function() { var swfVersionStr = "10.1.0"; var xiSwfUrlStr = "playerProductInstall.swf"; var flashvars = { bridgeName : "flex", }; var params = {}; var attributes = {}; params.allowscriptaccess = "always"; params.quality = "high"; params.bgcolor = "#FFFFFF"; params.allowfullscreen = "true"; attributes.id = "HelloWorldFlex"; attributes.name = "HelloWorldFlex"; attributes.align = "left"; swfobject.embedSWF( "HelloWorld.swf", "flash-content", "100%", "100%", swfVersionStr, xiSwfUrlStr, flashvars, params, attributes ); } } }(); HelloWorld.init(); }); </script> <style type="text/css"> #flash-content-container { width : 400px; height : 300px; } </style> </head> <body> <div id="layout"> <div id="header"><h1>Hello World</h1></div> <div id="flash-content-container"> <div id="flash-content"></div> </div> </div> </body> I tested it on Flex 4.1, please notice that i had to add the bin-debug folder (C:\flexworkspaces\project\bin-debug) to the flash security app ( http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.htmlconfiguration ) Please notice that this internet URL is in fact an app that modifies the Flex local configuration. The logs can be displayed in the Firebug console. A: Decided to go with FABridge. For others heres a working example. MXML <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:bridge="bridge.*" creationComplete="init()"> <fx:Declarations> <bridge:FABridge bridgeName="flex" /> </fx:Declarations> <fx:Script> <![CDATA[ import mx.controls.Alert; import flash.external.ExternalInterface; private function init():void { consoleLog("Hello World"); } public function sendAlert(s:String):void { Alert.show(s); } public function consoleLog(message:String):void { if (ExternalInterface.available) { ExternalInterface.call( "function log(msg){ if (window.console) { console.log(msg); } }", message); } } ]]> </fx:Script> <s:Panel id="panel1" title="Hello World" x="20" y="20"> <s:layout> <s:HorizontalLayout paddingLeft="10" paddingRight="10" paddingTop="10" paddingBottom="10" gap="5" /> </s:layout> <s:TextArea id="textarea1" width="300" height="100" text="Hello World" /> </s:Panel> </s:Application> HTML <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Hello World</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script> <script type="text/javascript" src="bridge/FABridge.js"></script> <script type="text/javascript"> var flexApp; var initCallback = function() { flexApp = FABridge.flex.root(); var textarea1 = flexApp.getTextarea1(); textarea1.setText( "Hello World (Updated)" ); flexApp.sendAlert( "Hello World" ); return; } $(function(){ HelloWorld = function(){ return { init : function() { var swfVersionStr = "10.1.0"; var xiSwfUrlStr = "playerProductInstall.swf"; var flashvars = { bridgeName : "flex", }; var params = {}; var attributes = {}; params.allowscriptaccess = "sameDomain"; params.quality = "high"; params.bgcolor = "#FFFFFF"; params.allowfullscreen = "true"; attributes.id = "HelloWorld"; attributes.name = "HelloWorld"; attributes.align = "left"; swfobject.embedSWF( "HelloWorld.swf", "flash-content", "100%", "100%", swfVersionStr, xiSwfUrlStr, flashvars, params, attributes ); FABridge.addInitializationCallback( "flex", initCallback ); } } }(); HelloWorld.init(); }); </script> <style type="text/css"> #flash-content-container { width : 400px; height : 300px; } </style> </head> <body> <div id="layout"> <div id="header"><h1>Hello World</h1></div> <div id="flash-content-container"> <div id="flash-content"></div> </div> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7519112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone Facebook Dialog Feed not displaying Post to Wall I am using [facebook dialog:@"feed" andParams:params andDelegate:self]; If user is not logged in, the Facebook login dialog will be displayed. Once logged in, it goes to the Facebook Mobile page (Profile, Messages, More). How can I have it go to the Post to Your Wall page? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7519113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Visual Studio Setup Project and Custom Action Usage (Installer Class) I have an installer, an MSI file, when executed interactively (by an end user), it installs just fine. Specicially, the Custom Action I added to the MSI via an Installer class, executes as part of the users installation. However if I execute the installation, via Scheduling a Task on Windows 7, as the SYSTEM user account, the MSI seems to install, but it looks like my Custom Action does not get fired. I get no errors and the Scheduled Tasks says the installation was successfull. Does anyone know why or how a Custom Action would be skipped and not executed which seems to be the situation. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7519123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC 3 Not Recognizing Windows Role (Group)? Has anybody come across occurrences where MVC does not recognize roles from Windows? I thought that roles translated to groups in Windows, but for some reason when I add a user to a group, check in MVC (using windows authentication) if that user.IsInRole("GroupJustAddedTo") always returns false. I have no idea why....Working in Server 2003 R2 with Windows Authentication enabled around the board. Confused :~( ??? A: Without knowing anything else, it makes me wonder if perhaps your MVC is not really connected to your AD server. Also, perhaps the user that is fetching the groups doesn't have sufficient privileges? Just some initial thoughts. EDIT We ended up writing our own RoleProvider. Here is the overloaded GetRolesForUser code public override string[] GetRolesForUser(string userName) { List<string> allRoles = new List<string>(); PrincipalContext context; context = new PrincipalContext(ContextType.Domain, "hlpusd.k12.ca.us", "DC=hlpusd,DC=k12,DC=ca,DC=us"); UserPrincipal user = UserPrincipal.FindByIdentity(context, userName); PrincipalSearchResult<Principal> usergroups = user.GetGroups(); // list of AD groups the user is member of IEnumerator<Principal> eGroup = usergroups.GetEnumerator(); while (eGroup.MoveNext()) { allRoles.Add(eGroup.Current.Name); } return allRoles.ToArray(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7519124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert NSString to binary string I have a NSString representing sha1 hash of some data and I need to convert it to binary string, but cant find any good solution to do that. It should be equivalent to PHP's pack function. The result should be like this: 0xb7, 0xc7, 0x91, ..., 0x90. I than need to convert this binary to base64-encoded string. A: You can easily to do so with a NSString+Base64 catalog. And the code should like this: #import "NSString+base64.h" //.... //some codes //.... NSString *yourNSString = @"Some string you want to be encoded"; NSString *base64string = [yourNSString base64String]; Here is the Code of NSString+Base64.h file for example: // // NSString+Base64.h // HudsonGrowl // // Created by Benjamin Broll on 06.12.10. // // This source code is licensed under the terms of the BSD license. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #import <Foundation/Foundation.h> @interface NSString (Base64) + (NSString *) base64StringFromData: (NSData *)data; - (NSString *)base64String; @end And the NSString+Base64.m file: // // NSString+Base64.m // HudsonGrowl // // Created by Benjamin Broll on 06.12.10. // // This source code is licensed under the terms of the BSD license. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #import "NSString+Base64.h" @implementation NSString (Base64) + (NSString *)encode:(const uint8_t *)input length:(NSInteger)length { // this code seems to be floating on a lot of stackoverflow posts. // i'm not aware of any license issues but let me know in case there are // problems including the source in this project. static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; uint8_t *output = (uint8_t *)data.mutableBytes; for (NSInteger i = 0; i < length; i += 3) { NSInteger value = 0; for (NSInteger j = i; j < (i + 3); j++) { value <<= 8; if (j < length) { value |= (0xFF & input[j]); } } NSInteger index = (i / 3) * 4; output[index + 0] = table[(value >> 18) & 0x3F]; output[index + 1] = table[(value >> 12) & 0x3F]; output[index + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '='; output[index + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '='; } return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease]; } + (NSString *) base64StringFromData: (NSData *)data { return [self encode:data.bytes length:data.length]; } - (NSString *)base64String { NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding]; return [NSString base64StringFromData:data]; } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7519126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Beans, beans, and more beans...what does what? I've recently been given a project to work on that involves writing a web application. I've never done Java EE before. A lot of resources on the web are dated and I'm having trouble figuring out what the current differences are between the various standards and Java technologies. Originally I thought I really needed EJB 3.1 due to dependency injection, JPA, session management, and web services. I started experimenting with Glassfish but was told that we had to write the thing in Tomcat. So I've been trying to figure out what I need as well as what and how to put into Tomcat to get there. I've begun to question whether I even need EJB at all. I want to use JFS, I think, for the MVC architecture. In learning about that I've run into both ManagedBeans and CDI, which according to some renders the former obsolete and also seems to provide all the dependency injection stuff I want to enable unit testing. I've also come to realize that I can get JPA outside of EJB in the form of Hibernate and maybe a few others. Additionally it seems that web services, which I don't know that I need anyway, come in the form of another standard I can't think of the name right now and this also can be installed independently. My major issue here is session management and state. It seems to me that all which remains for EJB to do is provide @Stateless/@Stateful and @Local/@Remote. However, as I understand it, some of this is already exists in the form of session management in the servlet container...but I don't know how much or what the major differences are that I need to account for in order to decide if I need these things at all. So my question is, what are the basic, essential differences that I need to know in order to decide if EJB is worth looking at or if I have enough in the form of other libraries and technologies? I've been all over google and Usenet and have not been able to find this information anywhere. Just thought of another bit. As I understand it, the @Stateful bean annotation provides me thread-safe state saving. I'm probably not going to directly use threads, but I know Java does so behind the scenes a lot and suspect EE especially so. When I need to keep state I don't want to be dealing with threads if this already provides it. A: ManagedBean Java EE 6 has three different ways of defining beans that are managed in one way or another: @javax.faces.bean.ManagedBean JSF 2.0 introduced this annotation declaring managed beans in faces-config.xml. This annotation is used to access a bean from the Expression Language. @javax.inject.Named In an EE 6 container CDI this annotation is a built-in qualifier types to provide a name to a bean, making it accessible through EL. @javax.annotation.ManagedBean This annotation attempts to generalize JSF managed beans for use elsewhere in Java EE. If you deploy in an EE 6 container (If you use Tomcat or another servlet container, you can also get CDI by adding the Weld jar to your web app), then there is really no reason to use @javax.faces.bean.ManagedBean. Just use @javax.inject.Namedand start taking advantage of CDI sevices. CDI One of the objectives of CDI specification is to bring together the Web tier and the transactional services, making easy for developers to use EJB along with JSF in web applications of the Java EE platform. With CDI you have the following services among others : well-defined lifecycle contexts(influenced by seam 2 and conversation scope), Dependency injection, loose coupling facilities like interceptors, decorators and events and portable extensions, which allows third-party frameworks to integrate in the Java EE 6 environment like SEAM 3 extensions Managed beans and EJB Services First of all CDI applies to any managed bean. Some managed beans are EJBs. When we need to use the EJB services in a managed bean, we just add a @Stateless, @Stateful or @Singleton annotation. IMO they act as complementary technologies allowing you to have a flexible and gradual development just only adding some annotations. So, when should we use a session bean instead of a plain managed bean? When you need some EJB features that CDI is missing : declarative transactions, concurrency management, pooling, remote or web service invocation ,timers and asynchronous method invokation. Of course you could also get all aspects using third party libraries - but this would introduce additional complexity to your project. In terms of functionality IMHO EJB are the place to implement : * *Business logic, allowing you to have a cleaning separation of busniness logic and web tier logic (implemented by "JSF backing beans" which are CDI managed beans but no EJB) *Functionality which makes most sense for components which are entrypoints to the application (endpoints for remote invocations delivered via RMI or HTTP) Finally if you need EJB services then you need an Aplication Server (eg. GlassFish or Jboss AS) if you only need CDI services you need a Servlet Container(e.g Tomcat) plus CDI libraries. A: Do you need the features provided by EJBs, i.e. security and transaction management? If the answer is yes, EJBs might be a good option. If the answer is no, and you only need dependency injection, CDI could then be a good option. You can also get similar capabilities with other 3rd party products, like Spring (dependency injection, Spring security, etc), but deciding whether you use one (EJB) or the other (e.g. Spring) is in many of the cases a matter of previous skillset. In my opinion, if there are no previous constraints, going Java spec compliant is a good investment. A: I would suggest you to start with the CDI and proceed to the EJB's (which is really adding one annotation on top of your POJO) if the requirements needs them (just as it was told - transactionality, web services, JMX, timers, EJB asynchronous invocations). It's quite reasonable to develop an application in which your entry point is an EJB which encompasses your call in the transaction and allows you to define multiple entry points. The EJB then invokes the CDI beans with the business logic in them. It's also worth noticing that the TomEE is a certified Java EE 6 Web Profile developed on top of the Apache Tomcat.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drupal 7: Make custom content translatable I'm creating a custom module which enables me to add Countries to a custom table in the database. I'll do later more with it, but as I got stuck at the beginning, I can't go on. First my piece of code: function partners_schema() { $schema['partners_country'] = array( 'description' => 'TODO: please describe this table!', 'fields' => array( 'id' => array( 'description' => 'auto inc id of country', 'type' => 'serial', 'not null' => true, ), 'name' => array( 'description' => 'name of country', 'type' => 'varchar', 'length' => '255', 'not null' => true, 'translatable' => true, ), 'needDistributor' => array( 'description' => 'is a distributor needed', 'type' => 'int', 'size' => 'tiny', 'not null' => true, ), ), 'primary key' => array('id'), ); return $schema; } The code above generates my Database table. After searching I found that I can add 'translatable' => true to my schema, so Drupal knows that this field is translatable content. I've added a form, to insert data into that schema, but now I got stuck. What do I have to do, that the user is able to translate the column name? Thanks for your help. A: Have a look at the accepted answer on this post it should help clear a few things up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a Draft message in Gmail using the imaplib in Python I want to write a python module that sends data to a draft message in a G-mail account. I have written a script about two weeks ago that worked perfectly using imaplib. A simplified example of my module is below. (I have created a test email address for anyone to test this script on.) import imaplib import time conn = imaplib.IMAP4_SSL('imap.gmail.com', port = 993) conn.login('testpythoncreatedraft@gmail.com', '123456aaa') conn.select('[Gmail]/Drafts') conn.append("[Gmail]/Drafts", '', imaplib.Time2Internaldate(time.time()), "TEST") It utilized the .append function, but today when I run the module and it produces the following error: Traceback (most recent call last): File "C:/Windows/System32/email_append_test.py", line 6, in <module> conn.append("[Gmail]/Drafts", '', imaplib.Time2Internaldate(time.time()), "TEST") File "C:\Python26\lib\imaplib.py", line 317, in append return self._simple_command(name, mailbox, flags, date_time) File "C:\Python26\lib\imaplib.py", line 1060, in _simple_command return self._command_complete(name, self._command(name, *args)) File "C:\Python26\lib\imaplib.py", line 895, in _command_complete raise self.error('%s command error: %s %s' % (name, typ, data)) imaplib.error: APPEND command error: BAD ['Invalid Command'] As I said before, this module worked before. It successfully created draft messages with the string "Test" in its body. Since this script used to work, it seems more likely that it has something to do with a change Google made to the G-mail accounts IMAP features, but the error seems to indicate an error in the APPEND command. I have tested the python script on two different computer to see if my library file was corrupt, but the same error remained. Also, I am using Python 2.6. Any help is appreciated. A: Before the conn.append, add the following: import email Then change the conn.append line to read: conn.append("[Gmail]/Drafts", '', imaplib.Time2Internaldate(time.time()), str(email.message_from_string('TEST')))
{ "language": "en", "url": "https://stackoverflow.com/questions/7519135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: CoreData: transient property and localizedCaseInsensitiveCompare In coredata, i have a transient property to use has sections. The transient property code is here: - (NSString *) firstLetter_transient { [self willAccessValueForKey:@"firstLetter_transient"]; NSString *initial = [[[self memberName] substringToIndex:1] uppercaseString]; [self didAccessValueForKey:@"firstLetter_transient"]; return initial; } When I apply this, in Portuguese language, I get, for example "Á" has the first letter. Question Nr 1: how can I put "Á" in the "A" section? I have an error with this: "The operation couldn’t be completed. (Cocoa error 134060.)" Question Nr 2: when it comes to numbers, how can I affect the numbers to section named "#"? Now, the number 1 creates a section "1", and so on. Thanks all, RL A: You should use UILocalizedIndexedCollation for doing sorting and categorizing entries into sections. The code for implementing this is in the question NSFetchedResultsController v.s. UILocalizedIndexedCollation The UILocalizedIndexedCollation was built to be able to on a per-language basis categorize words based on the current language settings. Á and à will be put in section A.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Good idea to resolve User roles in the application layer? The reason I need a role-based system: * *Restrict access to pages. *Restrict access to certain features on pages. *Check/validation inside service layer. So I'm guessing, I can just create an enum and if I need a new role, just add it to the app code (the app would change anyways so requires a recompile). So right now I have public class User { /* .. */ public virtual ICollection<UserRole> Roles {get; set;} } public enum UserRoleType { Administrator, User } public class UserRole { public int UserRoleId { get; set; } public int RoleTypeValue { get; set; } public UserRoleType RoleType { get { return (UserRoleType)RoleTypeValue; } set { RoleTypeValue = (int)value; } } public virtual User User { get; set; } } This is a 1 to many. The pros I see for this is that instead of a many-many, there is a 1-many and joins are less. The application already knows what the role is based on what the int resolves the enum to. Are there any flaws in the way Im doing this? Is there anything you have met in your experience that would require me to store the actual values in the database? A: To be clear, you are suggesting that you don't need an actual lookup table in the database for Roles? Instead, they just have an int that is not a foreign key to anything--it is simply a representation of the enum in the application? It's impossible to answer definitively without knowing all the details of your application. That disclaimer aside, I see nothing inherently problematic about it. It would certainly work fine for some systems. Possible downsides: * *There is no source of valid values enforced on the database side via referential integrity. What is to stop someone from entering "12452" for the RoleId in the database column? There are other ways around this like using check constraints, but they are not necessarily easier to maintain than a lookup table. *There is no way to effectively query the user/roles tables and have a human-readable representation of roles without knowing what the RoleIds represent (you will have to have the enum in front of you to make sense of the query result). *If the database is used for other applications, the roles will need to be represented (and maintained) in that application as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Character sets of the pattern symbols Is there a way to get sets of the pattern symbols? For example, I have a regular expression [az]+[A-Z]*. Then the symbol set of the first symbols is a and z. Then the symbol set of the second symbol is a and z. Then the symbol set of the third symbol is a and z. .... The task is: I have a pattern and a string. Now I want to know whether the string start with the same characters as one of the string which match to the pattern. UPDATE: For example, I have a regular expression [az]\\:[A-Z]*. Then the symbol set of the first symbols is a and z. Then the symbol set of the second symbol is :. Then the symbol set of the third symbol is A-Z. Then the symbol set of the fourth symbol is A-Z. .... A: It sounds like you are asking for a function that takes a regular expression as an argument and returns a set of characters that could match at a given offset into a string to be matched: Set<Character> getSymbols(String regEx, int offset); This is non-trivial. Using your example: getSymbols("[az]\\:[A-Z]*", 1) should return ['a', 'z'], getSymbols("[az]\\:[A-Z]*", 2) should return [':'], getSymbols("[az]\\:[A-Z]*", 3) should return ['A', 'B', 'C', ..... 'Y', 'Z'] But this is a trivial input. What if the input was: getSymbols("[abc]*FRED[xzy]*", 5) Now you have to factor in the fact that any number of "abc" characters could proceed FRED, and would shift everything else, leading to a result set like this: 1: ['a', 'b', 'c', 'F'] 2: ['a', 'b', 'c', 'F', 'R'] 3: ['a', 'b', 'c', 'F', 'R', 'E'] 4: ['a', 'b', 'c', 'F', 'R', 'E', 'D'] 5: ['a', 'b', 'c', 'x', 'y', 'z', 'F', 'R', 'E', 'D'] The code that solves that has to parse regular expressions, which has a lot of expressiveness with all the escape characters (\w for whitespace, etc. etc.), then needs a recursive algorithm to build the output set. If this is what you intend, the next question is, "What problem are you really trying to solve?"
{ "language": "en", "url": "https://stackoverflow.com/questions/7519138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Using Regular expression to search for a value but exlude that string from the results? This is prob really simple, I'm new to regular expressions but say I wanted to find the 2 numbers preceding some characters. i.e "12 qty" So I'm using \d\d.qty to bring back the match "12 qty" but I want to exclude the word qty? I have tried using \d\d.qty*([^qty]*) but it doesn't work. A: You need to use a positive look ahead, depends on which language of course: (\d\d)(?=\sqty) A: You could use (\d\d)(.qty) so you get back Array ( [0] => Array ( [0] => 12 qty ) [1] => Array ( [0] => 12 ) [2] => Array ( [0] => qty ) ) Now use second item of the array and you have, what you want
{ "language": "en", "url": "https://stackoverflow.com/questions/7519139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pattern matching on Class[_] type? I'm trying to use Scala pattern matching on Java Class[_] (in context of using Java reflection from Scala) but I'm getting some unexpected error. The following gives "unreachable code" on the line with case jLong def foo[T](paramType: Class[_]): Unit = { val jInteger = classOf[java.lang.Integer] val jLong = classOf[java.lang.Long] paramType match { case jInteger => println("int") case jLong => println("long") } } Any ideas why this is happening ? A: On your pattern matching, each of these 2 cases try to create place holder names instead of matching the class type as expected. If you use upper case in the starting character, you'll be fine def foo[T](paramType: Class[_]): Unit = { val JInteger = classOf[Int] val JLong = classOf[Long] paramType match { case JInteger => println("int") case JLong => println("long") } } scala> foo(1.getClass) int A: The code works as expected if you change the variable names to upper case (or surround them with backticks in the pattern): scala> def foo[T](paramType: Class[_]): Unit = { | val jInteger = classOf[java.lang.Integer] | val jLong = classOf[java.lang.Long] | paramType match { | case `jInteger` => println("int") | case `jLong` => println("long") | } | } foo: [T](paramType: Class[_])Unit scala> foo(classOf[java.lang.Integer]) int In your code the jInteger in the first pattern is a new variable—it's not the jInteger from the surrounding scope. From the specification: 8.1.1 Variable Patterns ... A variable pattern x is a simple identifier which starts with a lower case letter. It matches any value, and binds the variable name to that value. ... 8.1.5 Stable Identifier Patterns ... To resolve the syntactic overlap with a variable pattern, a stable identifier pattern may not be a simple name starting with a lower-case letter. However, it is possible to enclose a such a variable name in backquotes; then it is treated as a stable identifier pattern. See this question for more information. A: JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features. matches(data).as( Integer.class, i -> { System.out.println(i * i); }, Byte.class, b -> { System.out.println(b * b); }, Long.class, l -> { System.out.println(l * l); }, String.class, s -> { System.out.println(s * s); }, Null.class, () -> { System.out.println("Null value "); }, Else.class, () -> { System.out.println("Default value: " + data); } );
{ "language": "en", "url": "https://stackoverflow.com/questions/7519140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: (Pre)select checkboxes in a ListActivity using 'simple_list_item_checked' I'm using the ListActivity class in conjunction with the simple_list_item_checked-layout which implements simple list items with checkboxes. Everything is working fine - clicking added items calls onListItemClick() and I can check/uncheck respective checkboxes of entries via the 'View v' parameter. However what I wasn't able to figure out yet is, how to (pre)select checkboxes without any userinteraction? Minimal so far working code snippet showing my intend: package org.test; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.CheckedTextView; import android.widget.ListView; public class TestActivity extends ListActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ArrayAdapter<String> list_elems = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked); list_elems.add("foobar"); //TODO: check added entry labeled "foobar" setListAdapter(list_elems); } protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); CheckedTextView check = (CheckedTextView)v; check.setChecked(!check.isChecked()); } } Thanks a lot in advance! daten A: This works for me: You have to set the choicemode of the underlying ListView to single or multiple. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ArrayAdapter<String> list_elems = new ArrayAdapter<String>(this, Android.R.layout.simple_list_item_checked); list_elems.add("foobar"); //TODO: check added entry labeled "foobar" setListAdapter(list_elems); ListView lv = getListView(); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); lv.setItemChecked(0, true); } A: Use a SimpleListAdapter as the ListAdapter for your ListActivity. Use two columns (one for your string and the other for the checked value), and the system should take care of it by itself. Here is a good example
{ "language": "en", "url": "https://stackoverflow.com/questions/7519142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding x/y coordinates that fall within filled canvas arcs Here is the fiddle The arcs I've drawn around the outside of the circle - I'd like to know how to find all of the x/y coordinates that they cover so that I don't have to re-draw them every time using isPointInPath() to determine whether the mouse cursor is over them or not. I was thinking about writing all of the x/y coordinates to an array that I could check against the mouse position x/y coordinates and if I find a match then I change the cursor. The problem is, I don't know the code to derive all of the x/y values. A: This is the method you should use: http://en.wikipedia.org/wiki/Point_in_polygon The way it works is actually extremely simple: if the amount of times a ray that ends at any point passes through the polygon perimeter is even, the respective point HAS to be outside of the polygon. If it's odd, it's within the polygon. Here's a function found by Pimvdb: function isPointInPoly(poly, pt){ for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) ((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y)) && (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x) && (c = !c); return c; } A: You don't actually have to redraw your arcs to use .isPointInPath()-- just omit any calls to .fill() or .stroke() and you'll have a path which you can use to test whether it contains a point. I would suggest having one function which outlines the arc path (.beginPath(), path commands, .closePath()) and then two functions which call it-- one which calls the arc path function, then sets the fill style and fills the path to draw it, and another which calls the arc path function and then just tests whether a point is in the path. A: I wouldn't call what you have 'arcs' (they're more like bowed rectangles), but here's a broad sketch of how to write a function to determine if a point is within such a thing: * *Calculate the center of the circle from the end points and radius. * *If the point is closer to the center than the close arc (distance-to-center-squared is greater than close-radius-squared) then return false. *If the point is farther from the center than the far arc then return false. *Calculate the start and end angles for the endpoints of your rectangles with respect to the center of the circle. (Hint: Math.atan2) * *Calculate the angle for the point with respect to the center of the circle. If it is not between the angles for the end points, return false. * *Beware endpoints that cross the wrapping values for Math.atan2. *Return true if other tests passed. You can't calculate "all" points in this region, as there an an infinite number of them. Creating a lookup table of all integer pixel coordinates in your image is possible, but wasteful. What I would do, instead of what you are proposing, is use a retained-mode graphics system (hint: SVG) and let it track mouse events for me using its far-more-efficient code. A: Here's an easier method: I've altered the drawtabs function to also check if mouse is within a tab: http://jsfiddle.net/kkDqz/4/ WARNING This method is easy, but requires you to redraw EVERYTHING on mousemove.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why can't I get this Git alias to work? I've installed git for windows. I want com to be an alias for commit -m, so that I can write for example git com "dumb commit message" and it works the same way as if I'd written git commit -m "dumb commit message" I added this line to the "gitconfig" file (why do these linux types have such a hatred of file extensions?): [alias] com = 'commit -m' This doesn't work. I get error: pathspec 'dumb commit message' did not match any file(s) known to git. I tried variations on the above syntax in "gitconfig" and I tried to define it from within Git Bash. I can't seem to get it right. A: Do not use quotes around the value, just the plain command: [alias] com = commit -m
{ "language": "en", "url": "https://stackoverflow.com/questions/7519147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to mix annotations with faces-config.xml Using JBoss 6.0.0.Final, Richfaces 3.3.3.Final, MyFaces 2.0.6, facelets 1.1.15.B1 (a limitation of RF 3). I'm on a legacy project which contains hundreds of beans defined in faces-config.xml. I'd like to keep those defined in faces-config.xml but use annotations for new beans. However, when I've tried this I've not had success. The beans defined by annotation i.e. @ManagedBean @ViewScoped public class Foobar implements Serializable { // ... } The bean is not accessible from my JSF page. I believe I've specified the 2.0 version in my faces-config.xml by using the proper header. <faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version="2.0"> Is there anything else I need to do in the faces-config.xml to allow annotations to also be used? A: Annotated beans will fail in the following cases: * */WEB-INF/faces-config.xml is not declared to conform to JSF 2.0. *@ManagedBean is of javax.annotation package instead of javax.faces.bean. *Bean class is not been compiled/built into WAR's /WEB-INF/classes. *Bean is packaged in a JAR file which is missing /META-INF/faces-config.xml. *A wrong managed bean name is being used in EL, it should be the bean class name with 1st character lower cased according Javabeans spec. So in your particular example, #{fooBar} should work, but #{FooBar} won't. *Webapp is actually using JSF 1.x libs (you can read JSF version in server startup log).
{ "language": "en", "url": "https://stackoverflow.com/questions/7519151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Using Ctypes to wrap .LIB files I need to control a device in python using Ctypes. However, the libraries that come with the device are compiled .LIB files, not .DLLs. Is it still possible to use Ctypes? A: No. Not directly anyway. CTypes uses the dynamic linker (LoadLibrary, GetProcAddress) to work. You could wrap the LIB file in your own DLL possibly, but you won't be able to use Ctypes directly with the lib file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Scrolling down recipients scroll bar in chat script My previous chat script worked perfect at sender side. When ever a new message is added from textbox to databinder the scroll bar used to come down with the help of javascript but the issue is it is unable to scroll down the recipient's side chat script. I interfaced scroll down code to button using OnClientClick. So, on each button click scroll bar used to come down but how can I able to scroll down recipient's scroll bar too when I click on enter? A: So I believe you are having issues with the recipient of a chat message. After the new message is added to the list of messages, the content holder doesn't scroll down to the new message. I'm guessing you are using a textarea or a div to hold the content. I found two other questions on StackOverflow with good answers: var objDiv = document.getElementById("your_div"); objDiv.scrollTop = objDiv.scrollHeight; StackOverflow: Scroll to bottom of div? function moveCursorToEnd(input) { var lastPosition = input.value.length - 1; if (input.setSelectionRange) { input.focus(); input.setSelectionRange(lastPosition, lastPosition); } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', lastPosition); range.moveStart('character', lastPosition); range.select(); } } Tested Firefox 6 and IE8: http://jsfiddle.net/nXa4d/ StackOverflow: With help from: jQuery Set Cursor Position in Text Area
{ "language": "en", "url": "https://stackoverflow.com/questions/7519154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails adding resource id to another resource via HABTM I have 3 pertinent models: class User < ActiveRecord::Base has_and_belongs_to_many :groups end class Group < ActiveRecord::Base has_and_belongs_to_many :users has_many :galleries end class Gallery < ActiveRecord::Base belongs_to :group end I want to be able to create users and galleries within a group so that only users who are members of the group can view the galleries that belong to that group. I also want users to be able to view galleries of other groups they belong to (hence the HABTM association). I'm having difficulty in conceptualizing how this works with controllers, and perhaps I'm over thinking the problem. If I create a Group, and then I go to create a user, what is the best way to go about adding the current group_id to the user model? Same thing goes for the gallery model... Does that make sense? Let me know if I need to clarify or add code samples. Thank you very much for your help. EDIT: Clarification I definitely didn't make any sense in my initial question, but I did manage to find the answer, with help from a friend. What I ended up doing is passing the group_id to the form via the params hash like so: <%= link_to "Add User", new_admin_user_path(:group_id => @group.id) %> <%= link_to "Add Gallery", new_gallery_path(:group_id => @group.id) %> Then using a hidden field in my form, assigning the group_id to the "group_id" hidden field: <%= hidden_field_tag :group_id, params[:group_id] %> And, finally, in my create methods, adding these lines before the save assigns the group_id perfectly: # Gallery only has one group @gallery.group_id = params[:group_id] # Users can belong to many groups @user.groups << Group.find(params[:group_id]) I'll still need to sit down and wrap my head around the answers you both provided. Thank you very much for taking the time to help me out. I really appreciate it. A: When you are using find method from your controller you can make it like this: Gallery.find :all, :joins => "INNER JOIN groups ON groups.gallery_id = galleries.id INNER JOIN users ON users.group_id = groups.id", :conditions => "users.id = #{@your_current_user_id}" It must find all galleries of groups which the user belongs. A: I would not define this in the controller as Sebes suggests, but rather in the User model. Adapting his idea: def galleries Gallery.joins(:groups => :users).where("users.id = ?", self.id) end Then to get a collection of the galleries for the current_user object: current_user.galleries
{ "language": "en", "url": "https://stackoverflow.com/questions/7519156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically loading Dictionary KVPs into Anonymous types I want to load all the KeyValuePairs in a Dictionary<string, string> into anonymous types during runtime. There will be no knowledge ahead of time of the contents of the Dictionary. Dictionary<string, string> callParams = new Dictionary<string, string>(); logger.WithParams(() => new { Val1= val1, Val2= val2, Val3= val3 }); How can I add the KVPs of callParams to the set of anonymous types? A: It's not really clear what you mean - but if you're trying to get the property names to depend on the keys in the dictionary, you're out of luck: anonymous types are created for you by the compiler at compile-time, with the property names that you specify. If you don't know the keys until execution time, you can't have the anonymous types... If you're using .NET 4 you could potentially use ExpandoObject and dynamic typing... but what's the bigger picture here? Why can't you just pass the dictionary around as it is?
{ "language": "en", "url": "https://stackoverflow.com/questions/7519158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby: Ping.pingecho missing Ruby used to have a Ping.pingecho method, but it seems as if (and the Ping module) have disappeared sometime: % rvm use 1.8.7 Using ~/.rvm/gems/ruby-1.8.7-p334 % ruby -rping -e 'p Ping.pingecho "127.0.0.1"' true % rvm use 1.9.2 Using ~/.rvm/gems/ruby-1.9.2-p180 % ruby -rping -e 'p Ping.pingecho "127.0.0.1"' <internal:lib/rubygems/custom_require>:29:in `require': no such file to load -- ping (LoadError) from <internal:lib/rubygems/custom_require>:29:in `require' % ruby -e 'p Ping.pingecho "127.0.0.1"' -e:1:in `<main>': uninitialized constant Object::Ping (NameError) Has it moved to a different library (so what should I require to load it?), or has it been deleted, and replaced with a different module (so what should I use to determine whether a IP is reachable?). A: Don know why or where it has gone. Rails still has a Ping class. A slight adaptation (to use a class method) would be: require 'timeout' require 'socket' class Ping def self.pingecho(host, timeout=5, service="echo") begin timeout(timeout) do s = TCPSocket.new(host, service) s.close end rescue Errno::ECONNREFUSED return true rescue Timeout::Error, StandardError return false end return true end end p Ping.pingecho("127.0.0.1") #=> true p Ping.pingecho("localhost") #=> true A: I just encountered this issue. I settled with the net-ping gem as a replacement. It has a clear TCP ping example in gems/net-ping-1.7.7/examples/example_pingtcp.rb: p1 = Net::Ping::TCP.new(good, 'http') p p1.ping? The rubydoc.info link at the time of this writing is not working, but here is a useful comment in the source of the module (tcp.rb) # This method attempts to ping a host and port using a TCPSocket with # the host, port and timeout values passed in the constructor. Returns # true if successful, or false otherwise. So I swapped this: return Ping.pingecho(server, 5, 22) With this: p = Net::Ping::TCP.new(server, 22, 5) p.ping? There are two caveats in moving from the old to the new equivalent module: * *The arguments to the constructor are reversed (port and timeout) *The actual invocation of a ping is accomplished by calling the ping? method, rather than just instantiating.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android overlay a view ontop of everything? Can you overlay a view on top of everything in android? In iPhone I would get the new view set its frame.origin to (0,0) and its width and height to the width and height of self.view. Adding it to self.view would then cause it to act as an overlay, covering the content behind (or if it had a transparent background then showing the view behind). Is there a similar technique in android? I realise that the views are slightly different (there are three types (or more...) relativelayout, linearlayout and framelayout) but is there any way to just overlay a view on top of everything indiscriminately? A: The best way is ViewOverlay , You can add any drawable as overlay to any view as its overlay since Android JellyBeanMR2(Api 18). Add mMyDrawable to mMyView as its overlay: mMyDrawable.setBounds(0, 0, mMyView.getMeasuredWidth(), mMyView.getMeasuredHeight()) mMyView.getOverlay().add(mMyDrawable) A: <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:id = "@+id/Everything" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <!-- other actual layout stuff here EVERYTHING HERE --> </LinearLayout> <LinearLayout android:id="@+id/overlay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" > </LinearLayout> Now any view you add under LinearLayout with android:id = "@+id/overlay" will appear as overlay with gravity = right on Linear Layout with android:id="@+id/Everything" A: Simply use RelativeLayout or FrameLayout. The last child view will overlay everything else. Android supports a pattern which Cocoa Touch SDK doesn't: Layout management. Layout for iPhone means to position everything absolute (besides some strech factors). Layout in android means that children will be placed in relation to eachother. Example (second EditText will completely cover the first one): <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/root_view"> <EditText android:layout_width="fill_parent" android:id="@+id/editText1" android:layout_height="fill_parent"> </EditText> <EditText android:layout_width="fill_parent" android:id="@+id/editText2" android:layout_height="fill_parent"> <requestFocus></requestFocus> </EditText> </FrameLayout> FrameLayout is some kind of view stack. Made for special cases. RelativeLayout is pretty powerful. You can define rules like View A has to align parent layout bottom, View B has to align A bottom to top, etc Update based on comment Usually you set the content with setContentView(R.layout.your_layout) in onCreate (it will inflate the layout for you). You can do that manually and call setContentView(inflatedView), there's no difference. The view itself might be a single view (like TextView) or a complex layout hierarchy (nested layouts, since all layouts are views themselves). After calling setContentView your activity knows what its content looks like and you can use (FrameLayout) findViewById(R.id.root_view) to retrieve any view int this hierarchy (General pattern (ClassOfTheViewWithThisId) findViewById(R.id.declared_id_of_view)). A: You can use bringToFront: View view=findViewById(R.id.btnStartGame); view.bringToFront(); A: I have just made a solution for it. I made a library for this to do that in a reusable way that's why you don't need to recode in your XML. Here is documentation on how to use it in Java and Kotlin. First, initialize it from an activity from where you want to show the overlay- AppWaterMarkBuilder.doConfigure() .setAppCompatActivity(MainActivity.this) .setWatermarkProperty(R.layout.layout_water_mark) .showWatermarkAfterConfig(); Then you can hide and show it from anywhere in your app - /* For hiding the watermark*/ AppWaterMarkBuilder.hideWatermark() /* For showing the watermark*/ AppWaterMarkBuilder.showWatermark() Gif preview - A: I have tried the awnsers before but this did not work. Now I jsut used a LinearLayout instead of a TextureView, now it is working without any problem. Hope it helps some others who have the same problem. :) view = (LinearLayout) findViewById(R.id.view); //this is initialized in the constructor openWindowOnButtonClick(); public void openWindowOnButtonClick() { view.setAlpha((float)0.5); FloatingActionButton fb = (FloatingActionButton) findViewById(R.id.floatingActionButton); final InputMethodManager keyboard = (InputMethodManager) getSystemService(getBaseContext().INPUT_METHOD_SERVICE); fb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // check if the Overlay should be visible. If this value is false, it is not shown -> show it. if(view.getVisibility() == View.INVISIBLE) { view.setVisibility(View.VISIBLE); keyboard.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); Log.d("Overlay", "Klick"); } else if(view.getVisibility() == View.VISIBLE) { view.setVisibility(View.INVISIBLE); keyboard.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); } A: bringToFront() is super easy for programmatic adjustments, as stated above. I had some trouble getting that to work with button z order because of stateListAnimator. If you end up needing to programmatically adjust view overlays, and those views happen to be buttons, make sure to set stateListAnimator to null in your xml layout file. stateListAnimator is android's under-the-hood process to adjust translationZ of buttons when they are clicked, so the button that is clicked ends up visible on top. This is not always what you want... for full Z order control, do this:
{ "language": "en", "url": "https://stackoverflow.com/questions/7519160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "79" }
Q: Python, GIS and Fortran: Trying to create multiple polygons from xy point data I've been working on this problem for awhile and have found no joy on the ESRI forum page or with some FORTRAN triangulation script I wrote. I have two .csv files with hundreds of xy point data in. These points represent the high and low end of an intertidal range. The high and low points run parallel to each other and I want to create polygon slivers that connect four of those points every foot into separate polygons. The height of the polygon would be x depending upon the distance between the high and low points. The below link shows two images that illustrate what I mean: http://forums.arcgis.com/threads/39757-Feature-to-Line..?p=135880&posted=1#post135880 The main problem has been scripting the polygons to form correctly in the corners. I understand that you cannot have a polygon that is 1ft in diameter at the bottom and 1ft in diameter at the top when moving round a bend. But this is just one of many problems I've encountered in trying to solve this... Any help would be greatly appreciated, Thanks A: This should work for the interpolation (say the tide line is x, y distance from some control point on shore): import math example_triangle = [[0,0], [5,5], [0,5], [0,0]] high_tide_line = [[0, 0], [5., 1.5], [10., 3.2], [20., 1.], [30., 4.5], [80.,2.], [80,0]] low_tide_line = [[0, 10.], [5., 11.5], [10., 13.2], [20., 11.], [30., 14.5], [80., 12.], [80, 10]] def points_from_geom(geom): idx = 0 line_lengths = [] unit_vectors = [] interpolated_points = [] while idx < (len(geom) - 1): dy, dx = ((geom[idx+1][1] - geom[idx][1]), (geom[idx+1][0] - geom[idx][0])) line_lengths.append(math.sqrt(dy**2 + dx**2)) try: angle = math.atan(dy/dx) unit_vectors.append([math.cos(angle)*cmp(dx, 0), math.sin(angle)*cmp(dy, 0)]) except ZeroDivisionError: if geom[idx+1][1] < geom[idx][1]: direction = [0, -1] else: direction = [0, 1] unit_vectors.append(direction) idx += 1 for i, length in enumerate(line_lengths): inter = 0 while inter <= length: interpolated_points.append([geom[i][0] + unit_vectors[i][0]*inter,\ geom[i][1] + unit_vectors[i][1]*inter]) inter += .3048 # a ft in proper units ;) return interpolated_points ln1 = points_from_geom(example_triangle) ln2 = points_from_geom(high_tide_line) ln3 = points_from_geom(low_tide_line) print ln1, ln2, ln3 There are a lot of different ways to do the polygons. What I might try is determine a reference shoreline, then take perpendicular lines to it at fixed intervals, or in the middle of each line segment, then make a polygon or bounding box with the intersection on the adjacent shoreline. BTW in a real application you would need to make sure cmp is not operating on (0,0).
{ "language": "en", "url": "https://stackoverflow.com/questions/7519162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Comments on my MVP pattern for Android I am planning to use MVP pattern for my new Android project. I have done some sample code and I would like to know, have I implemented it correctly? Please give comments on the code and also post your suggestions. my activity class I am extending it from my BaseView class and I am implementing an interface. this activity simply calls an webservice in a new thread and updates the value in the textview. public class CougarTestView extends BaseView implements ICougarView, OnClickListener { CougarTestPresenter _presenter; public String activityName = "CougarHome"; /** Called when the activity is first created. */`enter code here` @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState, activityName); setContentView(R.layout.main); _presenter = new CougarTestPresenter(this); getSubmitBtn().setOnClickListener(this); getCallInfoBtn().setOnClickListener(this); } private Button getCallInfoBtn() { return (Button) findViewById(R.id.btn_callinfo); } public void setServiceValue(String retVal) { // TODO Auto-generated method stub getResultLabel().setText(retVal); setPbar(false); // toastMsg(retVal); } public void ResetPbar() { getProgressBtn().setProgress(0); } public void setProcessProgress(int progress) { if (getProgressBtn().getProgress() < 100) { getProgressBtn().incrementProgressBy(progress); } else { setPbar(false); } } private TextView getResultLabel() { return (TextView) findViewById(R.id.result); } private Button getSubmitBtn() { return (Button) findViewById(R.id.btn_triptype); } private ProgressBar getProgressBtn() { return (ProgressBar) findViewById(R.id.pgs_br); } public void setPbar(boolean visible) { if (!visible) { getProgressBtn().setVisibility(View.GONE); } else getProgressBtn().setVisibility(View.VISIBLE); } @Override public void setHttpResult(String retVal) { // TODO Auto-generated method stub setServiceValue(retVal); } private void toastMsg(String msg) { Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btn_triptype: { try { _presenter.valueFromService(RequestType.CallInfo, 0); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } default: setServiceValue("default"); } } } My activity class: in my activity class i am having a textview and a button. when i press the button , it call the webservice to get the data in the presenter class. the presenter class calls the webservice parses the response and sets the value in the textview of the activity. My presenter class public class CougarTestPresenter { ICougarView mIci; RequestType mRtype; public String result= "thisi s result i"; Handler mHandle; public CougarTestPresenter(ICougarView ici) { mIci = ici; } public void valueFromService(RequestType type, int x) throws Exception{ String url = getURLByType(type); // GetServiceresult service = new GetServiceresult(); // service.execute(url); Handler handle = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case Globals.IO_EXPECTION: { Toast.makeText(mIci.getContext(), msg.toString(), Toast.LENGTH_LONG).show(); NetworkConnectivityListener connectivityListener = NetworkConnectivityListener .getInstace(); mHandle = CustomHandler.getInstance(mIci.getContext(), connectivityListener, mIci); connectivityListener.registerHandler(mHandle, Globals.CONNECTIVITY_MSG); connectivityListener.startListening(mIci.getContext()); mIci.setPbar(false); } break; case Globals.RHAPSODY_EXCEPTION:{ ExceptionInfo exInfo =null; try { exInfo = Utility.ParseExceptionData(msg.obj.toString()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } mIci.setServiceValue(exInfo.Message + exInfo.Type +exInfo.Detail); // new HandleRhapsodyException(mIsa, exInfo); } break; default: { Toast.makeText(mIci.getContext(), msg.toString(), Toast.LENGTH_LONG).show(); mIci.setServiceValue(msg.obj.toString()); } } } }; ServiceResult thread = new ServiceResult(handle, url); mIci.setPbar(true); thread.start(); } public String getURLByType(RequestType type) { // TODO Auto-generated method stub switch (type) { case CallInfo: { return ("www.gmail.com"); } case TripType: { return ("www.google.com"); } default: return ("www.cnet.com"); } } private class ServiceResult extends Thread { Handler handle; String url; public ServiceResult(Handler handle, String url) { this.handle = handle; this.url = url; } public void run() { sendExceptionLog(handle); } } public void sendExceptionLog(Handler handle) { DebugHttpClient httpClient = new DebugHttpClient(); HttpGet get = new HttpGet( "https://192.168.194.141/TripService/service1/"); try { HttpResponse response = httpClient.execute(get); HttpEntity r_entity = response.getEntity(); String xmlString = EntityUtils.toString(r_entity); // setdvrid.setText(xmlString + " " // + response.getStatusLine().getStatusCode()); httpClient.getConnectionManager().shutdown(); if (response.getStatusLine().getStatusCode() != 200) { handle.sendMessage(Message.obtain(handle, Globals.RHAPSODY_EXCEPTION, xmlString)); result= Utility.ParseExceptionData(xmlString).Message; } else { handle.sendMessage(Message.obtain(handle, Globals.SERVICE_REPONSE, response.getStatusLine().getStatusCode() + response.getStatusLine().getReasonPhrase() + xmlString)); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block handle.sendMessage(Message.obtain(handle, Globals.OTHER_EXPECTION, e.getMessage().toString() + "she")); } catch (IOException e) { // TODO Auto-generated catch block handle.sendMessage(Message.obtain(handle, Globals.IO_EXPECTION, e .getMessage().toString() + "he")); } catch (Exception e) { handle.sendMessage(Message.obtain(handle, Globals.OTHER_EXPECTION, e.getMessage().toString() + "it")); } } the below interface is implemented in the activity class and the instance of the activity class is sent as interface object to the constructor of the presenter class. my view interface public interface ICougarView { public void setServiceValue(String retVal); public void setProcessProgress(int progress); public void setPbar(boolean b); public void ResetPbar(); public Context getContext(); } A: Sorry for the late :) I've use MVP on Android this way. Activities are presenters. Every presenter has a link to model(s) (sometimes it is services, sometimes not, depending from the task) and to view(s). I create custom view and set it as the content view for activity. See: public class ExampleModel { private ExampleActivity presenter; public ExampleModel(ExampleActivity presenter) { this.presenter = presenter; } //domain logic and so on } public class ExampleActivity extends Activity { private ExampleModel model; private ExampleView view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); model = new ExampleModel(this); view = new ExampleView(this); setContentView(view); } // different presenter methods } public class ExampleView extends LinearLayout { public ExampleView(Context context) { super(context); } } Also, I've discussed this topic here. I should warn you, that Activity shouldn't be considered as the view. We had very bad expirience with it, when we wrote with PureMVC which considered Activity as view component. Activity is excellently suitable for controller/presenter/view model (I've tried all of them, I like MVP the most), it has excellent instrumentation for managing the views (View, Dialog and so on) while it's not a view itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: MVVM access other view's element from viewModel I started working with the MVVM pattern in a new project. Everything is ok, but i came to the following problem. The implementation looks like this: I have a MainView, the main app window. In this window i have a telerik RadGroupPanel in wich I host the rest of the app views as tabs. The rest of the viewModels does not know about this RadGroupPanel which is hosted in MainVIew. How should i correctly add those views to the RadGroupPanel from the commands in the viewModels? Thanks. A: Have you considered injecting your view into the ViewModel using an interface to maintain separation? I know this breaks MVVM but I've successfully used this on a number of WPF projects. I call it MiVVM or Model Interface-to-View ViewModel. The pattern is simple. Your Usercontrol should have an interface, call it IView. Then in the ViewModel you have a property with a setter of type IMyView, say public IMyView InjectedView { set { _injectedView = value; } } Then in the view you create a dependency property called This public MyUserControl : IMyView { public static readonly DependencyProperty ThisProperty = DependencyProperty.Register("This", typeof(IMyView), typeof(MyUserControl)); public MyUserControl() { SetValue(ThisProperty, this); } public IMyView This { get { return GetValue(ThisProperty); } set { /* do nothing */ } } } finally in Xaml you can inject the view directly into the ViewModel using binding <MyUserControl This="{Binding InjectedView, Mode=OneWayToSource}"/> Try it out! I've used this pattern many times and you get an interface to the view injected once on startup. This means you maintain separation (Viewmodel can be tested as IView can be mocked), yet you get around the lack of binding support in many third party controls. Plus, its fast. Did you know binding uses reflection? There's a demo project showcasing this pattern on the blog link above. I'd advocate trying out the Attached Property implementation of MiVVM if you are using a third party control. A: You can have the list of viewmodels that you need to add controls for in an ObservableCollection in your main window viewmodel. You can then bind the ItemsSource of the RadGroupPanel to that collection and use the ItemTemplateSelector and ContentTemplateSelector of the RadGroupPanel to select the right template to use based on the viewmodel that is bound.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CarrierWave: create 1 uploader for multiple types of files I want to create 1 uploader for multiple types of files (images, pdf, video) For each content_type will different actions How I can define what content_type of file? For example: if image? version :thumb do process :proper_resize end elsif video? version :thumb do something end end A: I came across this, and it looks like an example of how to solve this problem: https://gist.github.com/995663. The uploader first gets loaded when you call mount_uploader, at which point things like if image? or elsif video? won't work, because there is no file to upload defined yet. You'll need the methods to be called when the class is instantiated instead. What the link I gave above does, is rewrite the process method, so that it takes a list of file extensions, and processes only if your file matches one of those extensions # create a new "process_extensions" method. It is like "process", except # it takes an array of extensions as the first parameter, and registers # a trampoline method which checks the extension before invocation def self.process_extensions(*args) extensions = args.shift args.each do |arg| if arg.is_a?(Hash) arg.each do |method, args| processors.push([:process_trampoline, [extensions, method, args]]) end else processors.push([:process_trampoline, [extensions, arg, []]]) end end end # our trampoline method which only performs processing if the extension matches def process_trampoline(extensions, method, args) extension = File.extname(original_filename).downcase extension = extension[1..-1] if extension[0,1] == '.' self.send(method, *args) if extensions.include?(extension) end You can then use this to call what used to be process IMAGE_EXTENSIONS = %w(jpg jpeg gif png) DOCUMENT_EXTENSIONS = %(exe pdf doc docm xls) def extension_white_list IMAGE_EXTENSIONS + DOCUMENT_EXTENSIONS end process_extensions IMAGE_EXTENSIONS, :resize_to_fit => [1024, 768] For versions, there's a page on the carrierwave wiki that allows you to conditionally process versions, if you're on >0.5.4. https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Do-conditional-processing. You'll have to change the version code to look like this: version :big, :if => :image? do process :resize_to_limit => [160, 100] end protected def image?(new_file) new_file.content_type.include? 'image' end
{ "language": "en", "url": "https://stackoverflow.com/questions/7519172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: SQL: If var = '' do nothing else add a condition to a WHERE clause I would like to perform one part of a WHERE clause on the condition that a variable has a value. I have tried writing this in many different ways but always hit an error and was wondering if someone could help. The code below is my current SQL statement that works but will return nothing if my @itemId is empty. I would only like to reduce the results if the @itemId as a value. DECLARE @itemId nvarchar(max) SET @itemId = 'someId' SELECT SalesOrdersItems.Id, CASE WHEN SalesOrderItems.ItemType = 'P' THEN Products.ProductId WHEN SalesOrderItems.ItemType = 'S' THEN Sundries.SundryId WHEN SalesOrderItems.ItemType = 'F' THEN FreightMethods.FreightMethodId ELSE SalesOrderItems.FreeTextItem END AS ItemId FROM SalesOrderItems LEFT OUTER JOIN Products ON SalesOrderItems.Product = Products.Product LEFT OUTER JOIN Sundries ON SalesOrderItems.Sundry = Sundries.Sundry LEFT OUTER JOIN FreightMethods ON SalesOrderItems.FreightMethod = FreightMethods.FreightMethod WHERE SalesOrdersItems.area LIKE 'SE%' AND (Products.ProductId = @itemId OR Sundries.SundryId = @itemId OR FreightMethods.FreightMethodId = @itemId OR SalesOrderItems.FreeTextItem = @itemId) I have tried writing the last line like this(see code below) but it doesn't work. AND CASE WHEN @itemId = '' THEN 1 ELSE (Products.ProductId = @itemId OR Sundries.SundryId = @itemId OR FreightMethods.FreightMethodId = @itemId OR SalesOrderItems.FreeTextItem = @itemId) END Does anyone have any ideas where I am going wrong? A: If I'm misunderstanding please let me know, I'm assuming that if you have a blank @itemID you want all results, otherwise you'll limit the results. WHERE SalesOrdersItems.area LIKE 'SE%' AND ((@itemId != '' AND (Products.ProductId = @itemId OR Sundries.SundryId = @itemId OR FreightMethods.FreightMethodId = @itemId OR SalesOrderItems.FreeTextItem = @itemId)) OR @itemId = '') I believe I have the parens correct, but they might be uneven. Hopefully it is it clear enough to understand my intent. A: ... WHERE 1 = CASE WHEN ... THEN 1 ELSE 0 END ... A: You could probably use NULLIF() AND CASE WHEN NULLIF(@itemId, '') IS NULL THEN 1 ELSE (Products.ProductId = @itemId OR Sundries.SundryId = @itemId OR FreightMethods.FreightMethodId = @itemId OR SalesOrderItems.FreeTextItem = @itemId) END A: As per my understanding, you should do something like below. (Products.ProductId = @itemId OR ISNULL(@itemId, '') = '') OR (Sundries.SundryId = @itemId OR ISNULL(@itemId, '') = '') OR (FreightMethods.FreightMethodId = @itemId OR ISNULL(@itemId, '') = '') OR (FreightMethods.FreeTextItem = @itemId OR ISNULL(@itemId, '') = '') Hope this helps!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7519174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Stop TextChanged event from firing Leave event I'm working on a simple WinForms application for a public school where users can identify themselves by entering either their network IDs (which are not protected information) or their system IDs (which are protected information). I want to switch to a password character when the program detects a system ID (which is working just fine); however, when I do this, my application also fires the textbox's Leave event, which tells users to fix a problem with the login data...before there's even a problem. Here's my code: void login_TextChanged(object sender, EventArgs e) { login.UseSystemPasswordChar = login.Text.StartsWith(<prefix-goes-here>); } private void login_Leave(object sender, EventArgs e) { if (login.Text.StartsWith(<prefix-goes-here>) && login.Text.Length != 9) { signInError.SetError(login, "Your System ID must be nine digits."); login.BackColor = Color.LightPink; } else if (login.Text.IsNullOrWhiteSpace()) { signInError.SetError(login, "Please enter your username or System ID."); login.BackColor = Color.LightPink; } else { signInError.SetError(login, string.Empty); login.BackColor = Color.White; } } Ultimately, I don't know that this will cause a ton of problems, and I could move this validation step to the Click event of the sign in button on my form, but I'd rather do validation piece-by-piece if possible. A: Putting the TextBox inside a GroupBox does reproduce that behavior-- which is odd. If you want to keep your GroupBox, here is a work around: private void login_TextChanged(object sender, EventArgs e) { login.Leave -= login_Leave; login.UseSystemPasswordChar = login.Text.StartsWith(<prefix-goes-here>); login.Leave += login_Leave; } A: For whatever reason, the Leave event fires when the login TextBox is inside a GroupBox control. Replacing the GroupBox with a simple Label control prevented the code within the TextChanged event from firing the Leave event. A: Yes, this is a quirk of the UseSystemPasswordChar property. It is a property that must be specified when the native edit control is created (ES_PASSWORD). Changing it requires Winforms to destroy that native control and recreate it. That has side-effects, one of them is that the focus can't stay on the textbox since the window disappears. Windows fires the WM_KILLFOCUS notificaiton. Being inside a GroupBox is indeed a necessary ingredient, Winforms doesn't suppress the Leave event when it gets the notification. Bug. Many possible fixes. You could set a flag that the Leave event handler can check to know that it was caused by changing the property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Stopping IntentService by clicking Notification I'm doing some background work in an IntentService and trying to make it stop by clicking a notification. For stopping the work I have a static method, that sets a flag. public static void stopService() { if (task != null) { task.setCancelFlag(true); } } The notification has a PendingIntent, that sends a Broadcast to a Receiver, that attempts to stop the service. Intent intent = new Intent(this, AlarmReceiver.class); intent.setAction(AlarmReceiver.STOP_SERVICE); PendingIntent contentIntent = PendingIntent.getBroadcast(getBaseContext(), 0, intent, 0); notification.contentIntent = contentIntent; The Receiver calls the stopService() method when it receives a broadcast. if (intent.getAction().equals(STOP_SERVICE)) { UpdateCheckService.stopService(); } Strangely enough, the stopService() method is not called properly. If I try to log it, the part with the flag setting is not executed. Even if I set a breakpoint on the Receiver and try to debug it, it doesn't work. However, if I call the same method from an Activity by clicking a button, everything works as intended. Does somebody know, where this strange behavior comes from? A: I did it using the intent of IntentService to create the PendingIntent In onHandleIntent I invoke the notification : @Override protected void onHandleIntent(Intent intent) { PendingIntent pStopSelf = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); Then I added the stop button and call my notification (insert this line on NotificationCompat.Builder): .addAction(R.drawable.ic_close_white_24dp, "Stop", pStopSelf) Clicking the stop on the notification will not trigger onHandleIntent, but invoke onStartCommand. Here you can check if the intent contains the flag we set to stop the service. private boolean shouldStop = false; @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent.getFlags() == PendingIntent.FLAG_CANCEL_CURRENT) { Log.d(TAG, "Stop pressed"); stopSelf(); shouldStop = true; return Service.START_NOT_STICKY; } return super.onStartCommand(intent, flags, startId); } stopSelf() stops any intents containing work requests to do more work in the intent service to restart the service. But it does not stop the service itself. To stop the service from continuing to execute, use the boolean previously set to check if the work should continue like this in onHandleIntent() @Override protected void onHandleIntent(Intent intent) { //Invoke notification doStuff(); } private void doStuff() { // do something // check the condition if (shouldContinue == false) { return; } } Use the boolean to check in between the code to check if service should stop and return from the method. A: You should not use the IntentService class for your case. IntentService use a queue to process one Intent at a time. Just create your own class that extend Service as the example here. Then handle the stop request as you did to stop the worker thread. A: The mystery is solved: My BroadcastReceiver had the remote process flag set, which I copied from some tutorial on the web without too much thinking. Removing this tag made everything work as expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: After appending, want to remove I have some zoom buttons being added to my Map container I want to remove these zoom buttons when a particular map image is being used Code: JS: Map = function() { //private: var $MapContainer; this.initMap = function($container, zoomHidden) { $MapContainer = $container; $MapContainer.append("<div class='MapImage'></div>"); if(!zoomHidden) { $MapContainer.append("<div id='mapZoomIn' class='MapZoomInButton'>+</div>"); $MapContainer.append("<div id='mapZoomOut' class='MapZoomOutButton'>-</div>"); } } this.setMapProperties = function(mapImage) { $('.MapImage').css('background-image','url("'+mapImage+'")'); // Where I want to remove the zoom buttons if($('.MapImage').css('background-image') === "../images/mapImages/noZooMap.jpg") { $('.MapZoomInButton').remove(); $('.MapZoomOutButton').remove(); } } } CSS: .MapImage { position:absolute; height:100%; width:100%; top:0; right:0; background-image: url("../images/mapImages/GenericMapImage.jpg"); background-repeat:no-repeat; } I'm not sure the proper way to "remove" the Zoom Buttons after I've appended them in a separate method, since the way I show you above is not functioning (the buttons are still present when running the program) A: You could create a method within Map like this and use it when you want to remove the buttons. Map = function() { var $MapContainer; this.initMap = function($container, zoomHidden) { $MapContainer = $container; $MapContainer.append("<div class='MapImage'></div>"); if(!zoomHidden) { $MapContainer.append("<div id='mapZoomIn' class='MapZoomInButton'>+</div>"); $MapContainer.append("<div id='mapZoomOut' class='MapZoomOutButton'>-</div>"); } } this.removeZoomButtons = function ($container) { $container.remove("#mapZoomIn"); $container.remove("#mapZoomOut"); } this.setMapProperties = function(mapImage) { $('.MapImage').css('background-image','url('+mapImage+')'); // Where I want to remove the zoom buttons if($('.MapImage').css('background-image') === "url(../images/mapImages/noZooMap.jpg)") { this.removeZoomButtons($MapContainer); } } } A: Is this line: $('.MapImage').css('background-image','url("mapImage")'); exactly what you have in your code? If so, it's looking for an image at the literal URL "mapImage" rather than at the location specified in the mapImage variable. Changing it to $('.MapImage').css('background-image','url('+mapImage+')'); should do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What type of files can be signed with codesign on a Mac? I have an xml document I would like to package and sign on the Mac. I know on Windows you can sign exes, dlls, cabs, and ocxs with signtool, but so far I've only been able to sign .apps on Mac. What other types of files can be signed with codesign on Mac? A: Everything. If you read Apple's documentation on what to code sign, they say: You sign all the individual components of your app, leaving no gaps, including: * *Nested code. First, you recursively sign all of the helpers, tools, libraries, frameworks, and other components that your app relies on, and that are bundled with your app. See Ensuring Proper Code Signatures for Nested Code for a discussion of how to properly embed and sign nested code in your app bundle. Also see Using Library Validation for additional information about verifying libraries as a matter of system policy. *Mach-O executables. The signing software applies individual signatures to each architectural component of a universal binary that represents the main executable of your app. These are independent, and usually only the native architecture on the end user's system is verified. To apply the signature, the codesign utility adds the signature directly to the executable file. *Resources. Everything in an application bundle that is not explicit code (either nested code bundles or the main executable) is a resource, and all resources are signed. The resource files themselves are not modified as a result of signing. Instead, codesign places the digital signatures corresponding to all the application bundle’s non-code files in a special plist file within the bundle, namely Contents/_CodeSignature/CodeResources. The codesign utility places the signatures of any nested code here as well, which is why nested code is signed first.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: An entity object cannot be referenced by multiple instances of IEntityChangeTracker? Private WorkOrderServicesController As New WorkOrderServicesController Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click Dim _WorkOrderServices As New WorkOrderServices _WorkOrderServices.Quantity = 1 _WorkOrderServices.ServiceID = 1 _WorkOrderServices.UnitCost = 10 _WorkOrderServices.CreatedBy = StateManager.UserID _WorkOrderServices.CreatedDate = Now lstWorkOrderServices.Add(_WorkOrderServices) grdServices_Fill() End Sub Protected Sub grdServices_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdServices.RowCommand If (e.CommandName.Equals("Delete")) Then Dim ServiceID = e.CommandArgument Dim _WorkOrderService = lstWorkOrderServices.Where(Function(os) os.ServiceID = ServiceID).SingleOrDefault If Not _WorkOrderService Is Nothing Then If _WorkOrderService.iWOServicesID > 0 Then With _WorkOrderService .Deleted = True .DeletedBy = StateManager.UserID .DeletedDate = Now End With WorkOrderServicesController.UpdateWorkOrderService(_WorkOrderService) Else lstWorkOrderServices.Remove(_WorkOrderService) End If End If End If End Sub Once I pass the EntityObject through UI to DAL and try to Update an Entity, face with an error "entity object cannot be referenced by multiple instances of" ** MyDAL.DLL ** Public Class WorkOrderServicesDAL Private _context As LAITEntities Public Sub New() _context = New LAITEntities End Sub Function UpdateWorkOrderService(ByVal vWorkOrderService As WorkOrderServices) As Boolean Try 'An entity object cannot be referenced by multiple instances of IEntityChangeTracker. _context.WorkOrderServices.Attach(vWorkOrderService) _context.ObjectStateManager.ChangeObjectState(vWorkOrderService, EntityState.Modified) _context.SaveChanges() Return True Catch ex As Exception Return False End Try End Function End Class A: You are probably creating an ObjectContext in your DAL, passing the returned object into your UI (at which point the ObjectContext you used to retrieve the object with goes out of scope), and then passing the object back into your DAL where you create another ObjectContext and try to save your changes with this new context. You can't do this; you either need to keep the original context around, and re-use it (maybe through an instance member on your object) to save the changes back, or you need to Detach the object from the first context instance and re-attach it to the new context. See this link for details on attaching and detatching.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I designate a separate private key for each git repository I connect to? I have multiple git repositories I need to connect to. For each one, the person in charge emailed me a public/private keypair to use to access the repository. I stored them in my .ssh directory along with my personal key: $ ls ~/.ssh id_rsa id_dsa_site1 id_rsa_site2 id_rsa.pub id_dsa_site1.pub id_rsa_site2.pub Then, I read some articles online that recommended I set up a config file, which I did: $ cat ~/.ssh/config Host site1.sub.domain.com User gitosis IdentityFile ~/.ssh/id_dsa_site1 Host git.site2.sub.domain.com User gitosis IdentityFile ~/.ssh/id_rsa_site2 However, when I try to clone the repos, I'm still being prompted for a password: $ git clone gitosis@site1.sub.domain.com:myrepo.git Initialized empty Git repository in /home/robert/myrepo/.git/ gitosis@site1.sub.domain.com's password: It looks like the key isn't associating properly. No google/so search I can think of is solving the problem. Any ideas? A: The config file belongs in your .ssh directory, too Right now the file is not being used so you are prompted for a password A: Solution Found (for future people with this problem) Logging out and back in solved the problem for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bash Scripting to pull data out of a csv I have a file with the following data: 20,2011/09/22,HUOT ,CLAUDE J, ,DEX ,006403,MTRL,07:10,QBEC,10:29 020,2011/09/22,HUOT ,CLAUDE J,02001,DEX ,003470,MTRL,07:10,QBEC,10:29 020,2011/09/22,HUOT ,CLAUDE J,02003,DEX ,003307,MTRL,07:10,QBEC,10:29 020,2011/09/22,HUOT ,CLAUDE J,02004,DEX ,003309,MTRL,07:10,QBEC,10:29 020,2011/09/22,HUOT ,CLAUDE J, ,DEX ,003310,MTRL,07:10,QBEC,10:29 I am trying to extract numbers in a specific field and in a specific range. 3400s, 4000s, and 7300s. For the code above a would like to get 3470 as a result. What is the best means of doing this in a bash script? A: awk is a good tool for this job. awk -F, '$7 ~ /(34|40|73)[0-9][0-9]$/ {print}' filename A: You can do something like this: cut -d, -f9 data_file | while read number ; do if test $number -gt 3400 -a $number -lt 3500 ; then echo $number ; done A: this will give you 3470 as result: awk -F, '$7~/^00(34|40|70)/{print 1*$7}' inputFile And for your given example, grep can do that as well: grep -oP "(?<=00)(34|40|70)\d+" inputFile the above grep cmd will give you 3470 too. A: Bash #!/bin/bash OLDIFS="$IFS" IFS="," while read -r line do set -- $line [[ ${7:2} =~ ^(34|40|73) ]] && echo "${7:2}" done < "file" IFS="$OLDIFS"
{ "language": "en", "url": "https://stackoverflow.com/questions/7519202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is this a memory leak in JavaScript? I was reading this article ( http://www.ibm.com/developerworks/web/library/wa-memleak/ ) on IBM's website about memory leaks in JavaScript when I came across a memory leak that didn't quite look liked it leaked: <html> <body> <script type="text/javascript"> document.write("Program to illustrate memory leak via closure"); window.onload=function outerFunction(){ var obj = document.getElementById("element"); obj.onclick=function innerFunction(){ alert("Hi! I will leak"); }; obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX")); // This is used to make the leak significant }; </script> <button id="element">Click Me</button> </body> </html> I understood all the other leaks but this one stood out. It says there's a circular reference between the DOM and JavaScript object but I don't see it. Can anyone shed some light on this? EDIT: The link seems to have been taken down (I even refreshed the page I had up and it was down). Here's Google's cache (for as long as that lasts: http://webcache.googleusercontent.com/search?q=cache:kLR-FJUeKv0J:www.ibm.com/developerworks/web/library/wa-memleak/+memory+management+in+javascript&cd=1&hl=en&ct=clnk&gl=us&client=firefox-a ) A: The assignment to onclick of the innerFunction creates a function closure that preserves the value of the variables that are in scope of innerFunction. This allows the code in innerFunction to reference variables above it and is a desirable feature of javascript (something some other languages don't have). Those variables that are in scope of innerFunction include obj. So, as long as there is a reference to this closure, the variables in that closure are preserved. It's a one-time piece of memory usage so it doesn't accumulate over time and thus isn't usually significant. But, if you put big data into one of those variables, then and expected it to be freed, then "yes" you would be using more browser memory than you expected. Where this can cause problems is in this particular example, you have a circular reference between JS <==> DOM. In JS, you have preserved (in the function closure) a reference to the DOM object in the obj variable. In the DOM object, you have preserved a reference to the JS code and the function closure with the assignment to the onclick attribute. Some older browsers are dumb enough that even if you remove the "element" object from the DOM, the circular reference will keep the garbage collector from ever freeing the memory. This is not a problem in modern browsers as they are smart enough to see this circular reference and still free the object if there are no outside references to it. In your particular code, you haven't actually created a leak because the element is still in the DOM. bigString is just a big chunk of data you've attached to the DOM element and it will stay there until you remove that attribute or remove the DOM object. That's not a leak, that's just storage. The only way this would become a leak in IE6 is if you did this: <html> <body> <script type="text/javascript"> document.write("Program to illustrate memory leak via closure"); window.onload=function outerFunction(){ var obj = document.getElementById("element"); obj.onclick=function innerFunction(){ alert("Hi! I will leak"); }; obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX")); // This is used to make the leak significant }; // called later in your code function freeObject() { var obj = document.getElementById("element"); obj.parentNode.removeChild(obj); // remove object from DOM } </script> <button id="element">Click Me</button> </body> </html> Now, you've removed the object from the DOM (sometime later in your code) and probably expected all memory associated with it to be freed, but the circular reference keeps that from happening in IE6. You could work-around that by doing the following: <html> <body> <script type="text/javascript"> document.write("Program to illustrate memory leak via closure"); window.onload=function outerFunction(){ var obj = document.getElementById("element"); obj.onclick=function innerFunction(){ alert("Hi! I will leak"); }; obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX")); // This is used to make the leak significant }; // called later in your code function freeObject() { var obj = document.getElementById("element"); obj.onclick=null; // clear handler and closure reference obj.parentNode.removeChild(obj); // remove object from DOM } </script> <button id="element">Click Me</button> </body> </html> or, if you don't need the obj reference in the closure, you could null the reference from the closure entirely with this: <html> <body> <script type="text/javascript"> document.write("Program to illustrate memory leak via closure"); window.onload=function outerFunction(){ var obj = document.getElementById("element"); obj.onclick=function innerFunction(){ alert("Hi! I will leak"); }; obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX")); // This is used to make the leak significant obj = null; // kills the circular reference, obj will be null if you access if from innerFunction() }; </script> <button id="element">Click Me</button> </body> </html> In practice, this is only a meaningful issue in a few cases when the memory usage of a leak could be significant. * *If you have large chunks of data that you store as DOM attributes, then a single object leak could leak a large amount of data. That's usually solved by not storing large chunks of data on DOM objects. Store them in JS where you control the lifetime explicitly. *If you have a long lived page with lots of javascript interaction and an operation that creates/destroys DOM objects can be done many, many times. For example, a slideshow that runs unattended may be creating/destroying DOM objects over and over and over again. Even small amounts of memory leakage per item could eventually add up and cause a problem. In a slideshow I wrote, I just made sure that I didn't put any custom attributes on these particular DOM objects that I was add/removing and that all event handlers were removed before removing the object from the DOM. This should assure that there could be no circular references to them. *Any kind of DOM operation you're doing over and over in a big loop. A: This leaks memory due to an IE6 bug. obj references innerFunction from onclick, and innerFunction references obj because it captures obj from the outer scope.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Jquery CSS Selector Requiring Three Criteria to be Met I am trying to write a CSS selector that requires multiple (three criteria) to be met in order to enact an action. $('div[class*="clickout"]') $('div[class*="preferred"]') $('div[class*="test"]') Basically I want to ensure that all three conditions are met. A: Chain the attribute selectors: $('div[class*="clickout"][class*="preferred"][class*="test"]') If you're looking for an element with the three exact class names, like <!-- 3 classes: "clickout", "preferred" and "test" --> <div class="clickout preferred test"></div> rather than with classes with the three words as partial or whole class names, like <!-- 2 classes: "clickout-preferred" and "testing" --> <div class="clickout-preferred testing"></div> Then you should chain class selectors instead of attribute selectors: $('div.clickout.preferred.test') A: $("div[class*='one'][class*='two'][class*='three']")
{ "language": "en", "url": "https://stackoverflow.com/questions/7519207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Toggling visibility of series of images: pie_1.png, bar_1.png, pie_2.png, bar_2.png I have webpages with several (and more is coming) types of data, each represented by a bar and a pie Google chart image: <h3>Data_1</h3> <p class="chart" align="center"> <img class="primary" src="pie_1.png"> <img class="secondary" src="bar_1.png"> </p> <h3>Data_2</h3> <p class="chart" align="center"> <img class="primary" src="pie_2.png"> <img class="secondary" src="bar_2.png"> </p> .... Initially I'd like to display pie-charts and hide bar-charts. When user clicks a pie-chart, I'd like to toggle it to bar-chart with a slide effect. I think, I have a good idea how to do it with jQuery - using individual ids like #pie_1, #bar_1, #pie_2, #bar_2, ... But I wonder, if a more general approach is possible here? A: You can use the .next() and the .prev() jQuery methods, like this: bars.click(function () { $(this).slideUp().next().slideDown(); }); pies.click(function () { $(this).slideUp().prev().slideDown(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7519212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Git - need some explanations about rebase I tried google, no help. I got an active os project that keeps updating with good stuff and I'm developing on top of it, So lets say I got the git repository of the project (lets call the current state x) and the current status is: OS project x my project (added some y changes) x -> y Now OS project updated : x -> z and I wan't my project to contain z and look like x -> z -> y or z -> y Can someone explain how do I make it happen? A: The simple method is to use the following two commands (after you've stached or committed your changes): $ git fetch origin master $ git rebase FETCH_HEAD The first one fetches the changes in original repository from the remote named 'origin'. The second one moves your changes to the new remote HEAD. The important thing to note here is that you use git fetch and not git pull. The latter is a fetch followed by an automatic merge. You don't want that. In case you are looking for an alternative method, I always work on my separate branch. Then I can keep master equal to the maintainer's version, and I can keep rebasing my parallel branch. If there are other users of my branch I merge the master into it instead. A: Assuming x, y, and z are branches (and x and z are really the same branch), and you have y checked out, you would do this: git rebase z What this does is replay all your commits from the point at which y was created, on top of z, to produce a new y for you. Note that you are changing history when you do this. That is to say, all the SHAs of your commits on y before the rebase are changed. This isn't a problem if you're the only one working on y. If you are working in a team, and multiple people have committed to y, then rebasing may be a bad idea. In this case, you can merge from z to y. That achieves your goal without changing history.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to allow empty values in symfony2 validators I would like to apply validators on a object properties only when value is not empty ie. Now standard symfony behavior: class Entity { /** * @ORM\Column(type="string", nullable=true) * @Assert\Email() */ protected $email; (...) } that object will not pass validation if an email is null, or empty string, is there a way to tell validator to assert as a valid, an empty value, and validate only if field has data? PS I know that I can write callback validator, but writting callback for every field just to have "allowEmpty" feature isn't so nice. A: if i understand correctly you want server side validation only if value is entered. I am exactly in the same scenario. I want to validate a URL only if the URL is provided. The best way i came across was to write my own custom validation class. You can write a generic custom validation class. I followed this link https://symfony-docs-chs.readthedocs.org/en/2.0/cookbook/validation/custom_constraint.html except for few changes because of symfony's latest version. Here is the implementation Acme\BundleNameBundle\Validator\Constraints\cstmUrl namespace Acme\BundleNameBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\Url; /** * @Annotation */ class CstmUrl extends Url { public $message = 'The URL "%string%" is not valid'; } Acme\BundleNameBundle\Validator\Constraints\cstmUrlValidator namespace Acme\BundleNameBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\Url; use Symfony\Component\Validator\Constraints\UrlValidator; class CstmUrlValidator extends UrlValidator { public function validate($value, Constraint $constraint) { if(!$value || empty($value)) return true; parent::validate($value, $constraint); } } Validtion.yml Acme\BundleNameBundle\Entity\Student: Url: - Acme\BundleNameBundle\Validator\Constraints\CstmUrl: ~ inside Controller just bind the constraint you normally would do 'constraints'=> new CstmUrl(array("message"=>"Invalid url provided")) I am sure there can be other better ways of doing it, but for now i feel this does the job well. A: You must explicitly set 'required' => false in your FormBuilder class for all optional fields. Here's a paragraph describing field type options. Edit. Getting quite a few downvotes. By default all validators treat null values as valid, except NotNull and NotEmpty. Neither of the two was used in the question. The question is implicitly about how to turn off the client-side required attribute that is turned on by default. A: Setting the required option is not the solution: Also note that setting the required option to true will not result in server-side validation to be applied. In other words, if a user submits a blank value for the field (either with an old browser or web service, for example), it will be accepted as a valid value unless you use Symfony's NotBlank or NotNull validation constraint. http://symfony.com/doc/current/book/forms.html#field-type-options For my custom validators, I add a if (null == $value) { return true; } to the isValid() method. However, I'm not sure what would be the best way for the standard validator classes. A: Just in case anyone else comes across this same question. I prefer to personally solve it by adding the following attribute inside my Twig template: {{ form_row(form.<field>, {'required': false}) }} A: Here is the trick I found actually : https://github.com/symfony/symfony/issues/5906 You need to write a data transformer that does nothing, and then add it to your field. After that, juste call the submit() method with the second param to false. Note that it's ok with Symfony 2.3. A: The Field Type Guessing handle this. http://symfony.com/doc/current/book/forms.html#field-type-guessing It's depends on your form declaration : "The "guessing" is activated when you omit the second argument to the add() method (or if you pass null to it). If you pass an options array as the third argument (done for dueDate above), these options are applied to the guessed field."
{ "language": "en", "url": "https://stackoverflow.com/questions/7519214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: initializing a vector of vector c++ Hi I want to initialize a size 9 vector whose elements are vectors of the size, say 5. I want to initialize all the elements to the zero vector. Is this way correct? vector<double> z(5,0); vector< vector<double> > diff(9, z); OR is there a shorter way to do this? A: You can put it all in one line: vector<vector<double>> diff(9, vector<double>(5)); This avoids the unused local variable. (In pre-C++11 compilers you need to leave a space, > >.) A: vector< vector<double> > diff(9, std::vector<double>(5, 0)); However in the specific case where the sizes are known at compile time you could use a C array: double diff[9][5] = { { 0 } }; A: Pretty sure this will work: vector< vector<double> > diff(9, vector<double>(5,0)); A: If the sizes are fixed, you can go with std::array instead: std::array<std::array<double,5>,9> diff = {}; A: You could potentially do this in a single line: vector<vector<double> > diff(9, vector<double>(5)); You might also want to consider using boost::multi_array for more efficient storage and access (it avoids double pointer indirection).
{ "language": "en", "url": "https://stackoverflow.com/questions/7519215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: grabbing Html of $(this) in Jquery How can I grab the Html for $(this) in a following function allhdn.each(function (){ var $this = $(this); var newHtml = (str + $this.html()); }); $(this).html() returns empty string. A: I think you have a variable scope issue. var html; var newHtml; allhdn.each(function (){ html = $(this).html(); newHtml = (str + html); }); A: If it's an input you want .val() var newVal = (str + $this.val()); A: $(this).html() gets the inner html code for the tag. Because the tags you're iterating over are input fields, they don't have any inner tags. To fix this, I think you need to wrap in a new tag and take the inner html of that tag: // wrap in an enclosing tag $this.wrap('<span/>'); // get the code var newHtml = (str + $this.parent().html()); But as @Interstellar_Coder noted, are you sure you want the HTML, and not just the .val() on the hidden inputs?
{ "language": "en", "url": "https://stackoverflow.com/questions/7519218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why aren't the cookies saved ? why aren't the cookies saved when i run the following script: window.onload=init; function init() { var userName=""; if(document.cookie != "") { username=document.cookie.split("=")[1]; } document.getElementById("name_field").value = username; document.getElementById("name_field").onblur = setCookie; } function setCookie() { var exprDate = new Date(); exprDate.setMonth(exprDate.getMonth() + 6); var userName = document.getElementById("name_field").value; document.cookie = "username=" + username + ";path=/;expires=" + exprDate.toGMTString(); } When i refresh the page the text-field gets empty? why is so ? HTML <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript" src="writing_cookie.js"> </script> </head> <body> <form> <label>Enter your name&nbsp;&nbsp;<input type="text" id="name_field" /></label> <br/> <input type="submit" value="submit" /> </form> </body> </html> A: As @pimvdb says, you mix the case of username. In javascript, things are case sensitive - userName is not the same variable as username so you need to be consitant with your casing. The specific problem is that you assign the value of the name_field to userName in setCookie() but on the next line you save username to the cookie. username is uninitialised so you save an empty value to the cookie. This empty value is what you get from the cookie in init() Also, in init() you declare userName but assign the value of the cookie to username. This doesn't actually cause a problem but it could do with fixing all the same. Edit - I've just seen your reply to @pimvdb's comment and done a bit more research: When reading the cookie, you need to split on ";", not "=". This will then give you an array of "username=username", "path=path" and "expires=date". You then would extract the username from the first element of the array by looking for the "=" Your code splits on "=" which would give an array of "username", "username;path", "/;expires" and "date". I would have expected it to have put something in the text field with your code though (after you'd fixed the casing issue). (Reference page here)
{ "language": "en", "url": "https://stackoverflow.com/questions/7519221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is this also considered a subquery? I know how the following queries work, I'm just confused about the terminology. Each query begins with mandatory FROM clause and must end with either SELECT or GROUP clause. Between the two clauses we can put any number of optional FROM...LET...WHERE clauses. Subquery is simply a query within a query, which means it too has the same structure: var result = from p1 in artists from p3 in (from p2 in p1.albums select new { ID = p2.id, Title = p2.title }) select p3; But unlike the subquery in the above example, the following subquery ( from p2 in artist.Albums ) doesn't end with its very own SELECT/GROUP clause, so its structure is different in a sense that it begins with a FROM clause, but doesn't end with SELECT/GROUP clause. So my question is whether the term subquery also applies to from p2 in artist.Albums, even though its structure is a bit different? var result1 = from p1 in artists from p2 in p1.Albums select new { Artist_id = p1.id, Album_id = p2.id }; thank you A: No, at the bottom you're doing an implicit join, not a subquery. A join is where you query both tables at the same time (in the same query). A: In your second query, result1, there is no subquery, just a query with two from clauses. Behind the scenes, using two from clauses in this way will be translated into a SelectMany operation: artists.SelectMany( p1 => p1.albums ,(p1,p2) => new { Artist_id = p1.id, Album_id = p2.id })
{ "language": "en", "url": "https://stackoverflow.com/questions/7519226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Tomcat KeyStore Environment Path We have the following example: < Connector port="8443" maxThreads="200" scheme="https" secure="true" SSLEnabled="true" keystoreFile="${user.home}/.keystore" keystorePass="changeit" clientAuth="false" sslProtocol="TLS" /> How can I make the "keystoreFile" point to an environment variable? ${env.CATALINA_HOME}/conf/file.jks doesn't works for me. Thanks. A: I know this post is 3 years old....but i ran into the same problem today. So what I found out: tomcat searches the catalina_home as default, so you would just have to say keystoreFile="conf/file.jks" and it will find the keystore at ${env.CATALINA_HOME}/conf/file.jks Edit: When Starting Tomcat from eclipse this does not work, because the CATALINA_HOME environment variable changes! A: If what you actually want is the value of CATALINA_HOME, there is also a system property ${catalina.home} that you can use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: MVC Partial View rendering as full view in its div Having a lot of problems at the moment. We have written a web application using asp.net mvc 2 as well as telerik mvc extensions. In this case we have a problem with the tab strip control. I have a link that is meant to load a partial view. This partial view contains a telerik tab strip. Unfortunately, when the link is clicked in IE7 and IE8, instead of refreshing the contents as it should (as it does in other browsers), it instead for some reason displays the whole page, within the partial view section. I have a screenshot here: Any Ideas? I've been working on this problem for days and would appreciate any help whatsoever that I can get on this. FYI there appears to be no javascript errors. Thanks in advance! A: your partial view is not generated as partial view but as full view your normal page has code such as this: <%@ Page Title="" Language="C#" MasterPageFile="~/Areas/Admin/Views/Shared/Admin.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> and your partial view has code as this: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<NudaJeFuc.Areas.Admin.Models.AEventCategoryModel>" %> Check it...
{ "language": "en", "url": "https://stackoverflow.com/questions/7519236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Ajax and html events in chrome, firefox and Internet Explorer I have many select elements in a cart, when a select element changes option , a onclick event will be listened to , and an ajax function displayCart will execute. <select name="price"> <option value="peryear" onclick="dispCart('y',2,1100);">1100 Dollar/year</option> <option value="pertrimester" onclick="dispCart('t',2,300);" selected>300 Dollar/3 months</option> <option value="permonth" onclick="dispCart('m',2,120);">120 Dollar/month</option> </select> this is the ajax function: function dispCart(b,c,price){ var req1=new getXHR(); var altr=Math.random(); var url="cart.php?c="+altr+"&b="+b+"&c="+c+"&price="+price; req1.open('GET',url,true); req1.onreadystatechange=function(){ if(req1.readyState==4){ if(req1.status==200){ document.getElementById("cart").innerHTML=req1.responseText; } } }; req1.send(null); } The cart.php is a controller , which connects using some functions to connect to the database , change the cart data ( for example from paiement per month to paiement per year) then refreshes the cart and displays the new cart with the changes . the problem is that this cart works great with FF, but with IE and chrome it doesn't execute the dispCart javascript function. I don't know why??? thank you in advance. A: In IE you cannot bind events on the <option> element. You should bind the event to the <select> element and then find out which option is selected. Here is an example using onchange. A: Use onchange for the select, not onclick for the options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: icon in address bar isn't showen with jdbcrealm in tomcat i am trying to do a website with icon in address bar. it works in regular website. But i'm trying to use realm in tomcat (to protected my resources), the icon is in public role without any limitations. But it doesn't load the icon in address bar (even after i logged in). When i write a full path at the address line of my icon, i get the image on the browser. So i think that i have permission to load it. The path of icon is true, because i have another image in the same folder and it works. So why it doesn't work? And now my code. the jsp code which defines the icon: this tag is written in head tag <link rel="shortcut icon" href="img/icon0.png"> and the public permissions in web.xml are: <security-constraint> <web-resource-collection> <web-resource-name>public zone</web-resource-name> <url-pattern>/img/*</url-pattern> </web-resource-collection> and the admin role has permision for all files: <security-constraint> <web-resource-collection> <web-resource-name>adminzone</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> <role-name>student</role-name> </auth-constraint> thanks A: Your config is fine. You haven't mentioned which browser you are using but if it's Firefox it's probably a caching issue. There are a lot of articles about clearing the favicon cache of Firefox. Here is one: Clear Favicon Cache From Firefox. (I haven't tested.) Maybe restarting the browser also could help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get this resque job to work? I want to have a Resque worker get sentiment via the Viralheat API for tags for a brand instance (belongs to User) in the background, and then save the mood parameter of that response to a Tag. Update: I've revised the code and now the worker fails because it says undefined method score for nil:NilClass. That's happening because ActsAsTaggableOn::Tagging.find_by_tag_id(tag.id).score.create has no tag.id to check against, also I don't think .create is valid Ruby. Viralheat API response (JSON) format: {"prob":0.537702567133646,"mood":"positive","text":"hello, goodbye"} Controller: def update @brand = Brand.find(params[:id]) current_user.tag(@brand, :with => params[:brand][:tag_list], :on => :tags) if @brand.update_attributes(params[:brand]) redirect_to :root, :notice => "Brand tagged." else render :action => 'edit' end Resque.enqueue(SentimentJob, @brand.tags) end sentiment_job.rb Worker: require 'resque-retry' class SentimentJob @queue = :sentiment_pull def self.perform(tags) tags.each do |tag| url = "http://www.viralheat.com/api/sentiment/review.json" @sentiment_response = url.to_uri.get( :api_key => 'MY KEY', :text => tag.name.to_s ).deserialize #If I comment out the 3 lines below, the worker runs and I get 3 successful callbacks but can't save them. @sentiment_value = @sentiment_response[:mood] @sentiment_store = ActsAsTaggableOn::Tagging.find_by_tag_id(tag.id).score.create(@sentiment_value) @sentiment_store.save end end end Tagggings table: create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.string "taggable_type" t.integer "tagger_id" t.string "tagger_type" t.string "context" t.datetime "created_at" t.string "Sentiment" end A: You have a typo in your argument list: def self.perform(tag.id, user_id) should be def self.perform(tag_id, user_id) (note the underscore). Update You shouldn't be using instance variables in a Resque Job. You are actually trying to use @brand before you declare it. You are trying to get information from params. There is no request, and thus no params. You probably want to swap out that find argument with the tag_id argument. The order you are queueing arguments is getting flipped. Your enqueue call is specifying the user_id before the tag_id. The job is expecting the tag_id before the user_id. And since you updated your question, you have switched the tag_id argument into tags_id. I don't know if you realize this, but calling brand.tags.id will probably return just a single id (I'm not too familiar with acts_as_taggable). A: Step 1 - Fix your controller so it's only running the job on success. def update @brand = Brand.find(params[:id]) current_user.tag(@brand, :with => params[:brand][:tag_list], :on => :tags) if @brand.update_attributes(params[:brand]) redirect_to :root, :notice => "Brand tagged." #update was successful, create the job Resque.enqueue(SentimentJob, @brand.tags) else render :action => 'edit' end end Step 2 - Fix your table columns, you can't use the Camel Case naming with PG on heroku, saw in an earlier post you were on heroku, this will give you issue. so run rails g migration FixColumnName go into your db/migrate folder and find the migration paste this into it class FixColumnName < ActiveRecord::Migration def self.up rename_column :taggings, :Sentiment, :sentiment end def self.down # rename back if you need or do something else or do nothing end end run rake db:migrate Step 3 - Fix your worker so that it does what you want it to do. Please note - I have completely ignored your "score" method as there is no mention of it in your code, and you don't say anywhere in your question what it is used for or what it should be doing. require 'resque-retry' class SentimentJob @queue = :sentiment_pull def self.perform(tags) tags.each do |tag| url = "http://www.viralheat.com/api/sentiment/review.json" @sentiment_response = url.to_uri.get( :api_key => 'MY KEY', :text => tag.name.to_s ).deserialize #find the tag @tag = ActsAsTaggableOn::Tagging.find_by_tag_id(tag.id) #set the tags value for the field sentiment to @sentiment_response[:mood] @tag.sentiment = @sentiment_response[:mood] #save the tag @tag.save end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7519243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JAR Bundler using OSXAdapter causing application to lag or terminate I've created a simple Java application that each second for for 10 seconds consecutive seconds adds a new row to a JTable. It consists of three classes. The main class that gets called once the program is started public class JarBundlerProblem { public static void main(String[] args) { System.err.println("Initializing controller"); new Controller(); } } A controller that creates the GUI and alters it through doWork() public class Controller { public Controller() { doWork(null); } public static void doWork(String s) { GUI gui = new GUI(); for (int i=0; i<10; i++) { gui.addRow("Line "+(i+1)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } And finally, the GUI import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class GUI { private JFrame frame = new JFrame(); private DefaultTableModel model = new DefaultTableModel(); private JTable table = new JTable(model); private JScrollPane pane = new JScrollPane(table); public GUI() { model.addColumn("Name"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(pane); frame.pack(); frame.setVisible(true); } public void addRow(String name) { model.addRow(new Object[]{name}); } } Since I'm developing for OS X, and I need to be able to associate my application with a certain file type (let's say .jarbundlerproblem), I have to bundle my JAR file into an APP using Apple Jar Bundler. I have done this successfully, my application opens, counts to ten, writing out each second. Now, for the problem By default, double-clicking a .jarbundlerproblem, and associating the file with my application, will not pass the file I double-clicked as an argument to the application. Apparently, this is just Java on OS X works. Since I need to be able to see what file was double-clicked, I'm using OSXAdapter which is a Java library made by Apple for the purpose. This, I've implemented by altering the constructor of my Controller class and added another method registerForMacOSXEvents(): public Controller() { registerForMacOSXEvents(); //doWork(null); } public void registerForMacOSXEvents() { try { OSXAdapter.setFileHandler(this, getClass().getDeclaredMethod("doWork", new Class[] { String.class })); } catch (Exception e) { System.err.println("Error while loading the OSXAdapter:"); e.printStackTrace(); } } But after this (minor) modification, my application starts acting up. Sometimes, it doesn't open, even though I can see in the Console that it just started (Initializing controller is written), but after a few attempts, it will eventually start, but the windows will be completely blank for the first 10 seconds, and after that, the 10 rows will be added. Help Now, I've struggled with this quite a bit, and it seems like there isn't a lot of documentation regarding neither OSXAdapter nor Jar Bundler. What am I doing wrong? Or shouldn't I be using OSXAdapter or Jar Bundler in the first place? A: It looks like you're blocking the event dispatch thread(EDT). SwingWorker would be a better choice, but this example implements Runnable. Addendum: You might look at this project for an example of MVC architecture. It also shows how to construct a Mac OS application bundle without using JAR Bundler. More on MVC may be found here. As an aside, this example shows one approach to auto-scrolling a JTable. Click on the thumb to suspend scrolling; release to resume. Addendum: Your application lags for 10 seconds on startup. As this is the exact time for which the Controller sleeps, it's surely sleeping on the EDT. An sscce would be dispositive. Instead, do the work on another thread and update the model on the EDT. SwingWorker has a process() method that does so automatically, or you can use invokeLater() as shown below. Until your application is correctly synchronized, there's little hope of getting Apple events to work. Addendum: You can invoke isDispatchThread() in the Controller to check. The project cited includes a .dmg with a Mac application and an ant file that builds the bundle in situ via target dist2. Addendum: See also the alternate approaches shown here. import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /** @seehttps://stackoverflow.com/questions/7519244 */ public class TableAddTest extends JPanel implements Runnable { private static final int N_ROWS = 8; private static String[] header = {"ID", "String", "Number", "Boolean"}; private DefaultTableModel dtm = new DefaultTableModel(null, header) { @Override public Class<?> getColumnClass(int col) { return getValueAt(0, col).getClass(); } }; private JTable table = new JTable(dtm); private JScrollPane scrollPane = new JScrollPane(table); private JScrollBar vScroll = scrollPane.getVerticalScrollBar(); private JProgressBar jpb = new JProgressBar(); private int row; private boolean isAutoScroll; public TableAddTest() { this.setLayout(new BorderLayout()); jpb.setIndeterminate(true); this.add(jpb, BorderLayout.NORTH); Dimension d = new Dimension(320, N_ROWS * table.getRowHeight()); table.setPreferredScrollableViewportSize(d); for (int i = 0; i < N_ROWS; i++) { addRow(); } scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); vScroll.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { isAutoScroll = !e.getValueIsAdjusting(); } }); this.add(scrollPane, BorderLayout.CENTER); JPanel panel = new JPanel(); panel.add(new JButton(new AbstractAction("Add Row") { @Override public void actionPerformed(ActionEvent e) { addRow(); } })); this.add(panel, BorderLayout.SOUTH); } private void addRow() { char c = (char) ('A' + row++ % 26); dtm.addRow(new Object[]{ Character.valueOf(c), String.valueOf(c) + String.valueOf(row), Integer.valueOf(row), Boolean.valueOf(row % 2 == 0) }); } private void scrollToLast() { if (isAutoScroll) { int last = table.getModel().getRowCount() - 1; Rectangle r = table.getCellRect(last, 0, true); table.scrollRectToVisible(r); } } @Override public void run() { while (true) { EventQueue.invokeLater(new Runnable() { @Override public void run() { addRow(); } }); EventQueue.invokeLater(new Runnable() { @Override public void run() { scrollToLast(); } }); try { Thread.sleep(1000); // simulate latency } catch (InterruptedException ex) { System.err.println(ex); } } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); TableAddTest nlt = new TableAddTest(); f.add(nlt); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); new Thread(nlt).start(); } }); } } A: After doing it, I'm not fully convinced a SwingWorker is a simpler (aka: better) solution - still requires additional thread synching (between the worker thread and the "outer" thread which passes in the file/names). Anyway (taking the opportunity to learn, and be it by errors :), below is a crude proof of concept example for the basic idea: * *implement the Controller as SwingWorker, which funnels the input from the outer thread into the EDT *make it accept input (from the adapter, f.i.) via a method doWork(..) which queues the input for publishing *implement doInBackground to succesively publish the input open issues * *synch the access to the local list (not an expert in concurrency, but pretty sure that needs to be done) *reliably detecting the end of the outer thread (here simply stops when the input queue is empty) Feedback welcome :-) public class GUI { private JFrame frame = new JFrame(); private DefaultTableModel model = new DefaultTableModel(); private JTable table = new JTable(model); private JScrollPane pane = new JScrollPane(table); public GUI() { model.addColumn("Name"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(pane); frame.pack(); frame.setVisible(true); } public void addRow(String name) { model.addRow(new Object[] { name }); } /** * Controller is a SwingWorker. */ public static class Controller extends SwingWorker<Void, String> { private GUI gui; private List<String> pending; public Controller() { gui = new GUI(); } public void doWork(String newLine) { if (pending == null) { pending = new ArrayList<String>(); pending.add(newLine); execute(); } else { pending.add(newLine); } } @Override protected Void doInBackground() throws Exception { while (pending.size() > 0) { publish(pending.remove(0)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } return null; } /** * @inherited <p> */ @Override protected void process(List<String> chunks) { for (String object : chunks) { gui.addRow(object); } } } /** * Simulating the adapter. * * Obviously, the real-thingy wouldn't have a reference * to the controller, but message the doWork refectively */ public static class Adapter implements Runnable { Controller controller; public Adapter(Controller controller) { this.controller = controller; } @Override public void run() { for (int i=0; i<10; i++) { controller.doWork("Line "+(i+1)); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { System.err.println("Initializing controller"); new Adapter(new Controller()).run(); } @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger(GUI.class.getName()); } A: Here's a variation of @kleopatra's example in which a continuously running Controller accepts new entries in doWork(), while a SwingWorker processes the pending entries asynchronously in its background thread. ArrayBlockingQueue handles the synchronization. import java.awt.EventQueue; import java.util.List; import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingWorker; import javax.swing.table.DefaultTableModel; public class GUI { private static final Random rnd = new Random(); private JFrame frame = new JFrame(); private DefaultTableModel model = new DefaultTableModel(); private JTable table = new JTable(model); private JScrollPane pane = new JScrollPane(table); public GUI() { model.addColumn("Name"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(pane); frame.pack(); frame.setVisible(true); } public void addRow(String name) { model.addRow(new Object[]{name}); } /** * Controller is a SwingWorker. */ private static class Controller extends SwingWorker<Void, String> { private static final int MAX = 5; private GUI gui; private BlockingQueue<String> pending = new ArrayBlockingQueue<String>(MAX); public Controller() { EventQueue.invokeLater(new Runnable() { @Override public void run() { gui = new GUI(); } }); } private void doWork(String newLine) { try { pending.put(newLine); } catch (InterruptedException e) { e.printStackTrace(System.err); } } @Override protected Void doInBackground() throws Exception { while (true) { // may block if nothing pending publish(pending.take()); try { Thread.sleep(rnd.nextInt(500)); // simulate latency } catch (InterruptedException e) { e.printStackTrace(System.err); } } } @Override protected void process(List<String> chunks) { for (String object : chunks) { gui.addRow(object); } } } /** * Exercise the Controller. */ private static class Adapter implements Runnable { private Controller controller; private Adapter(Controller controller) { this.controller = controller; } @Override public void run() { controller.execute(); int i = 0; while (true) { // may block if Controller busy controller.doWork("Line " + (++i)); try { Thread.sleep(rnd.nextInt(500)); // simulate latency } catch (InterruptedException e) { e.printStackTrace(System.err); } } } } public static void main(String[] args) { System.out.println("Initializing controller"); // Could run on inital thread via // new Adapter(new Controller()).run(); // but we'll start a new one new Thread(new Adapter(new Controller())).start(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7519244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Problem with INNER JOIN in a VIEW I need a view that Show each Location(including prénom_Nom, numéro_Teléphone, niv,no_Modèle, année) and all Paiements. Finally order by id_Location. I try this but its not Work CREATE View On_locations_Clients_Paiements AS SelectClients.prénom_Nom,Clients.numéro_Teléphone,Véhicules.niv,Véhicules.no_Modèle, Véhicules.année,Paiements.montant FROM Location INNER JOIN Location ON Clients.id_Client=Location.id_Client INNER JOIN Véhicules ON Location.niv=Véhicules.niv INNER JOIN Modèle ON Véhicules.no_Modèle=Modèle.no_Modèle INNER JOIN Paiements ON Location.id_Location = Paiements.id_Location --ORDER BY where id_Location = id_Location This is the select (I'm not sure if its right) CREATE View On_locations_Clients_Paiements AS Select Clients.prénom_Nom,Clients.numéro_Teléphone,Véhicules.niv,Véhicules.no_Modèle,Véhicules.année,Paiements.montant Those are my tables CREATE TABLE [dbo].[Location]( PK[id_Location] [char](6) NOT NULL, [debut_Location] [datetime] NULL, [premier_Paiement] [datetime] NULL, [paiment_Mensuel] [smallmoney] NULL, [nombre_Mensualité] [char](2) NULL, FK[id_Client] [char](6) NULL, [no_Termes_location] [char](6) NULL, FK[niv] [char](20) NULL, CREATE TABLE [dbo].[Clients]( PK[id_Client] [char](6) NOT NULL, [prénom_Nom] [varchar](50) NULL, [adresse] [varchar](50) NULL, [ville] [varchar](20) NULL, [province] [varchar](20) NULL, [code_Postal] [char](6) NULL, [numéro_Teléphone] [numeric](10, 0) NULL, CREATE TABLE [dbo].[Véhicules]( PK[niv] [char](20) NOT NULL, [no_Modèle] [char](6) NULL, [année] [char](4) NULL, [kilométrage] [int] NULL, [location_Antérieure] [char](3) NULL, [valeur] [smallmoney] NULL, [tranmission_Automatique] [char](3) NULL, [airClimatise] [char](3) NULL, [antiDemarreur] [char](3) NULL, [no_Couleur] [char](6) NULL, CREATE TABLE [dbo].[Paiements]( PK[id_paiement] [char](6) NOT NULL, [date] [smalldatetime] NULL, [montant] [smallmoney] NULL, FK[id_Location] [char](6) NOT NULL, A: You need to take the second location out and the tables: CREATE View On_locations_Clients_Paiements AS Select c.prénom_Nom ,c.numéro_Teléphone ,v.niv ,v.no_Modèle ,v.année ,p.montant FROM Location AS l INNER JOIN Clients AS c ON c.id_Client=l.id_Client INNER JOIN Véhicules AS v ON l.niv=v.niv INNER JOIN Modèle AS m ON v.no_Modèle=m.no_Modèle INNER JOIN Paiements AS p ON l.id_Location = p.id_Location A: Change: FROM Location INNER JOIN Location ON Clients.id_Client=Location.id_Client to... FROM Location INNER JOIN Clients ON Clients.id_Client=Location.id_Client Updated - you are referencing Location twice and Clients never so I think you have a copy/paste error of some sort.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: 2D OpenGL ES Metaballs on android I have an array of points (balls) in 2D-space which I want to be displayed as 2D Metaballs. For learning purposes I implemented it on a canvas by * *create an array which represents each pixel *iterate through this array and set a value depending on the distance to every ball for each pixel *iterate again and remove everything below a threshold That works fine but is extremely slow, as expected. I am pretty new to OpenGL and played around with various samples but I did not manage to make 2D OpenGL Metaballs. Current state is that I have a working representation of my balls by drawing a sprite for each ball (using cocos2d-android-1 if that matters). Can you provide me some (newbie friendly) steps I need to take?
{ "language": "en", "url": "https://stackoverflow.com/questions/7519251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Read XML file in android I have an xml-file that contains data that I want to read. The code works in a desktop environment but I can't figure out how to store and read the file from an android device. Ideas? A: For write xml in android refer below link. Writing XML on Android For read xml there are mainly 3 ways 1) DOM Parser 2) SAX Parser 3) XML Pull Parser A: Put the xml file in the assets folder and fetch it using the AssetManager: http://developer.android.com/reference/android/content/res/AssetManager.html To read the file use the same java code that works for you on J2SE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Type declaration in Haskell I just started learning Haskell. I decided to set myself a goal of implementing an old algorithm of mine http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.79.7006&rep=rep1&type=pdf As a start I wrote the following code phi [] = [1..] phi (p:pl) = (phi pl) `minus` (map (p*) $ phi pl) primes x | x < 2 = [] | otherwise = smallprimes ++ (takeWhile (<=x) $tail $ phi $ reverse smallprimes) where smallprimes = primes $ sqrt x minus (x:xs) (y:ys) = case (compare x y) of LT -> x : minus xs (y:ys) EQ -> minus xs ys GT -> minus (x:xs) ys minus xs _ = xs This functions as expected, except that the list of primes comes as floating point! A little thought told me that since the signature of sqrt is sqrt :: (Floating a) => a -> a the Haskell compiler has decided that primes is returning a list of floats. However, when I tried to tell it that phi :: [Integer] -> [Integer] which is what I want, the compiler has a problem: No instance for (Floating Integer) arising from a use of `sqrt` at ... So how do I signify the phi takes as input a list of integers and as output produces an infinite list of Integers? A: The problem in your code is, that sqrt expects a floating point number and returns the same. You have to use a wrapper that converts the type to make it work. (That's essentially, what the error message says): smallprimes = primes . ceiling . sqrt . fromIntegral $ x Haskell has no automatic conversion between different numeric types, as this is not possible with the type system Haskell has. A: take a look at that: Converting numbers ceiling should too the trick (as FUZxxl pointed out allready) IMHO the difficult part here is that the languages we are used to cast types by pointing to your target - Haskell switches the logic in a mind-bending way here ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7519258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to break down a number with another from list? I'm a bit confused on how to approach this problem. I know what I want to do but can't wrap my head on how to logically solve this problem. say I have a list: numlist = [10,4] and I have the following values in another list: datalist = [10,5,4,2,1] how do I break down the numbers in numlist using only numbers from datalist? An example of an answer would be: 10, 4 10, 2,2 10, 2,1,1 10, 1,1,1,1 5,5, 4 5,5, 2,2 ...and so on. I understand how to do this vaguely. make a for loop, for each entry in the list and compare if it can be divided by the datalist, and if so print the result. I think I need recursions which is where I'm having trouble understanding. here's my code so far (I have some print statements for troubleshooting): def variableRecursion(self, solutionList): #solution list contrains ['red', 2, 'green', 1] which means 2 reds(value 4) and 1 green(value 2) #adding fake lookup list for now, in real code, I can use real data because I am reversing the order list = [('red', 4), ('green', 2), ('blue', 1) ] for x1, x2 in zip(solutionList[::2], solutionList[1::2]): for x in list: for y1, y2 in zip(x[::2], x[1::2]): #print x1, x2 keyName = x1 keyShares = x2 keyValue = lookup.get_value(x1) if ((keyValue%y2) == 0) and (keyValue != y2): tempList = [] #print 'You can break ', keyName, keyValue, ' with ', y1, y2, ' exactly ', keyValue/x2, ' times.' #newKeyShares = keyShares - 1 for a1, a2 in zip(solutionList[::2], solutionList[1::2]): #print a1, a2 print 'You can break ', keyName, keyValue, ' with ', y1, y2, ' exactly ', keyValue/y2, ' times.' newKeyShares = keyShares - 1 print 'there is a match', a1, a2, ' but we will change the shares to ', newKeyShares print a1 if (a1 == keyName): print 'a' tempList.append([(keyName), (newKeyShares)]) elif (a1 == y1): print 'b' tempList.append([(y1), (a2+keyValue/y2)]) else: print 'c' try: tempList.append([(y1), (a2+keyValue/y2)]) except e: tempList.append([(a1), (a2)]) print tempList appendList.appendList(tempList) tempList = [] #exit() #print solutionList A: This problem is very similar to Problem 31 of Project Euler: "How many different ways can £2 be made using any number of coins?". Only in your example, you are asking to enumerate all the ways you can add up numbers to get 10 and 4. The best way to approach the problem is to first try breaking up only a single number. Let's look at the possible breakups for five, using numbers [5,4,2,1]: [5] [4,1] [2,2,1] [2,1,1,1] [1,1,1,1,1] The following python code will give you a list of these combinations: def possibleSplits(value,validIncrements): ret = [] for increment in validIncrements: if increment > value: continue if increment == value: ret.append([increment]) continue if increment < value: remainder = value - increment toAdd = possibleSplits(remainder, validIncrements) for a in toAdd: ret.append([increment] + a) return ret This code assumes that different orderings of otherwise identical answers should be treated as distinct. For example, both [4,1] and [1,4] will appear as solutions when you split 5. If you prefer, you can constrain it to only have answers that are numerically ordered (so [1,4] appears but not [4,1]) def orderedPossibleSplits(value, validIncrements): ret = [] splits = possibleSplits(value, validIncrements) for value in splits: value.sort() if value not in ret: ret.append(value) return ret Now you can use this to find the possible splits for 10, and the possible splits for 4, and combine them: increments = [10, 5, 4, 2, 1] tenSplits = orderedPossibleSplits(10, increments) fourSplits = orderedPossibleSplits(4, increments) results = [] for tenSplit in tenSplits: for fourSplit in fourSplits: results.append(tenSplit + fourSplit) edit: As noted in the comments, calling possibleSplits with a value of 100 is very slow - upwards of ten minutes and counting. The reason this occurs is because possibleSplits(100) will recursively call possibleSplits(99), possibleSplits(98), and possibleSplits(96), each of which call three possibleSplits of their own, and so on. We can approximate the processing time of possibleSplits(N) with datalist[1,2,4] and large N as processingTime(N) = C + processingTime(N-1) + processingTime(N-2) + processingTime(N-4) For some constant time C. So the relative time for possibleSplits is N 1 | 2 | 3 | 4 | 5 ... 20 ... 98 | 99 | 100 Time 1 | 1 | 1 | 4 | 7 ... 69748 ... 30633138046209681029984497 | 56343125079040471808818753 | 103631163705253975385349220 Supposing possibleSplits(5) takes 7 ns, possibleSplits(100) takes about 3 * 10^9 years. This is probably an unsuitably long time for most practical programs. However, we can reduce this time by taking advantage of memoization. If we save the result of previously calculated calls, we can get linear time complexity, reducing possibleSplits(100) to 100 ns. The comments also noted that the expected value of orderedPossibleSplits(100) has about 700 elements. possibleSplits(100) will therefore have a much much larger number of elements, so it's impractical to use it even with memoization. Instead, we'll discard it and rewrite orderedPossibleSplits to use memoization, and to not depend on possibleSplits. #sorts each element of seq and returns it def orderedInnerLists(seq): return map(sorted, seq) #returns a copy of seq with duplicates removed def removeDuplicates(seq): ret = [] for value in seq: if value not in ret: ret.append(value) return ret memoizedResults = {} def orderedPossibleSplits(value,validIncrements): memoizeKey = (value, tuple(validIncrements)) if memoizeKey in memoizedResults: return memoizedResults[memoizeKey] ret = [] for increment in validIncrements: if increment > value: continue if increment == value: ret.append([increment]) continue if increment < value: remainder = value - increment toAdd = orderedPossibleSplits(remainder, validIncrements) for a in toAdd: ret.append([increment] + a) memoizeValue = removeDuplicates(orderedInnerLists(ret)) memoizedResults[memoizeKey] = memoizeValue return memoizeValue On my machine, orderedPossibleSplits(100, [1,2,4]) takes about ten seconds - much improved from our original three billion year run time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Passing a querystring value as part of an ActionResult I have an ActionResult return type inside my Controller which executes the default Index action. public **ActionResult** Index(int _page, string **tabIdx**) { if (tabIdx == null) ViewData.Add("TabIdx","0"); else ViewData.Add("TabIdx", tabIdx); **actionResult = View("Index");** return actionResult; } The ViewData variable is for processing inside my javascript, so you can ignore it for the purpose of this question. What I need to do is to simply pass a querystring value for the tabIdx field in the above boldfaced line of code. Something like View("Index") with a querystirng value appened to it. How can I accomplish this? A: You will have to use RedirectToAction. The URL already is set in stone after the request. However, there might be a way to pass that value somewhere else so that it can be used without a redirect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extending ValidationSummary in HTMLHelper to alter HTML output I have written my own ValidationSummary so I could change the output of the ValidationSummary however whenever I submit the form no warning messages are appearing. I then added a normal ValidationSummary on the same view with my new ValidationSummary and when the page is initially requested the output is exactly the same. As soon as the submit button is pressed the normal one works and outputs error messages but mine doesn't. It doesnt seem to do a post back to the server so am I missing something? public static MvcHtmlString MyValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message, IDictionary<string, object> htmlAttributes) { //<div class="validation-summary-errors" data-valmsg-summary="true"><ul><li>The User name field is required.</li><li>The Password field is required.</li></ul></div> /* * <div class="alert-wrapper error"> <div class="alert-text"> This is an error alert! <a href="#" class="close">Close</a> </div> </div> * */ if (htmlHelper == null) { throw new ArgumentNullException("htmlHelper"); } FormContext formContext = htmlHelper.ViewContext.FormContext; if (htmlHelper.ViewData.ModelState.IsValid) { if (formContext == null) { // No client side validation return null; } // TODO: This isn't really about unobtrusive; can we fix up non-unobtrusive to get rid of this, too? if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled && excludePropertyErrors) { // No client-side updates return null; } } string messageSpan; if (!String.IsNullOrEmpty(message)) { TagBuilder spanTag = new TagBuilder("span"); spanTag.SetInnerText(message); messageSpan = spanTag.ToString(TagRenderMode.Normal) + Environment.NewLine; } else { messageSpan = null; } StringBuilder htmlSummary = new StringBuilder(); //TagBuilder unorderedList = new TagBuilder("ul"); IEnumerable<ModelState> modelStates = null; if (excludePropertyErrors) { ModelState ms; htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out ms); if (ms != null) { modelStates = new ModelState[] { ms }; } } else { modelStates = htmlHelper.ViewData.ModelState.Values; } if (modelStates != null) { foreach (ModelState modelState in modelStates) { foreach (ModelError modelError in modelState.Errors) { string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */); if (!String.IsNullOrEmpty(errorText)) { //TagBuilder listItem = new TagBuilder("li"); //listItem.SetInnerText(errorText); htmlSummary.AppendLine(errorText); } } } } if (htmlSummary.Length == 0) { htmlSummary.AppendLine(_hiddenListItem); } //unorderedList.InnerHtml = htmlSummary.ToString(); TagBuilder divBuilder = new TagBuilder("div"); divBuilder.MergeAttributes(htmlAttributes); divBuilder.AddCssClass((htmlHelper.ViewData.ModelState.IsValid) ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName); TagBuilder innerDivBuilder = new TagBuilder("div"); innerDivBuilder.AddCssClass("alert-text"); TagBuilder closeBuilder = new TagBuilder("a"); closeBuilder.AddCssClass("close"); closeBuilder.Attributes.Add("href", "#"); divBuilder.InnerHtml = innerDivBuilder.InnerHtml + messageSpan + htmlSummary.ToString() + closeBuilder.InnerHtml; if (formContext != null) { if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled) { if (!excludePropertyErrors) { // Only put errors in the validation summary if they're supposed to be included there divBuilder.MergeAttribute("data-valmsg-summary", "true"); } } else { // client val summaries need an ID divBuilder.GenerateId("validationSummary"); formContext.ValidationSummaryId = divBuilder.Attributes["id"]; formContext.ReplaceValidationSummary = !excludePropertyErrors; } } return new MvcHtmlString(divBuilder.ToString(TagRenderMode.Normal)); //return divBuilder.ToMvcHtmlString(TagRenderMode.Normal); } A: So it turns out that you have to have a <ul> in your ValidationSummary and the javascript then appends <li> to the unorderelist client side so essentially you cannot change the HTML in ValidationSummary if you want it to work client side without then changing the validation javascript as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using JFreeChart library to draw axis on an awt.Image I have a class that needs to be able to take in an image and add a set of axis. I don't feel like writing out the code myself and would rather be lazy and utilize the JFreeChart library. Here's what I have so far, which isn't doing anything as far as I can tell: public void addAxis(Image sourceImage, double min, double max) { NumberAxis numAxis = new NumberAxis(); numAxis.setRange(min, max); int width = sourceImage.getWidth(null); int height = sourceImage.getHeight(null); Rectangle2D size = new Rectangle(width, height); Graphics2D graphics = (Graphics2D) sourceImage.getGraphics(); numAxis.draw(graphics, 0, size, size, RectangleEdge.LEFT, null); return; } The Image that I'm passing into it is created as a BufferedImage using TYPE_INT_ARGB. There may be other libraries that are better suited for this, but unfortunately it is difficult to get approval to add a library to my project and JFreeChart is already approved. Please feel free to mention alternative libraries anyways for the benefit of other readers. Edit: for various reasons, I need to draw the axis on the image, I cannot draw the image on a chart or do anything that would change it's size. A: Figured it out, posting for anyone who wants to do the same thing. The line numAxis.draw(graphics, 0, size, size, RectangleEdge.LEFT, null); should be numAxis.draw(graphics, 20, size, size, RectangleEdge.LEFT, null); Otherwise the axis is drawn off the image. I didn't figure this out (and I'm kicking myself for this one) because the axis was getting the last color I'd used on the graphics object, which happened to be drawing the background.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to access log4j configuration at runtime and echo its properties? i want to check if the logger configured properly, and anyway, what is configured at all. BTW stackoverflow is great. It remembered my not posted yet post through Firefox restart. This post!
{ "language": "en", "url": "https://stackoverflow.com/questions/7519273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: gdb: is it possible to cast/reinterpret a sequence in terms of a user-defined struct that isn't present in debug symbols Below is the problem statement. At the bottom is my actual question if you end up just skimming the problem statement. edit I forgot to mention: I'm linking with --no-strip-discarded --discard-none. One of the object files (pre-link) gets matched by grep when I search for the type in question, but I'm not finding that string after dumping info from the object file with nm, objdump, and readelf. I'm looking at some C code that uses an idiom along the lines of: // somecode.h typedef struct { // ... volatile unsigned char *member1; } Type1_t; typedef struct { unsigned int member1:16; unsigned int member2:32; unsigned int member3:16; } Type2_t; // somecode.c // ... void someFunction( Type1_t *type1Ptr ) { // ... doSomething( ((Type2_t*)type1Ptr->member1)->accessType2Member ); } Please ignore any objections you might have to the coding style, that isn't my question. In this case, no instance of Type2_t is ever instantiated, so as best I can tell the compiler determined it wasn't necessary to emit debugging information about the type. I'm attempting to monitor the behavior of code using this casted data to track down a problem, but the best I've managed to do is get gdb to print the array in question as an array of bytes. I can set a watch on the array with: watch {char[12]}type1Ptr->member1 ... but in addition to not actually displaying member1, member2, & member3, the pretty-printer for char arrays prints it out as a sequence of the form \000\032\021... etc (a note on this: I'm in solaris, and gdb 7.2 in Solaris has issues with libiconv, which gdb uses for code page translations. I'm stuck with ISO-8859-1 for now. I'm unsure if that's why it doesn't just print it as a sequence of hex characters), so I end up either having to print the contents with display or some other mechanism, then interpret the contents in my head. What I'm looking for: * *Is there a way to make gcc emit all debug symbols, even if the type in question only shows up when doing a cast? * *... or if the type isn't used at all in actual code *Can I just include a header in gdb somehow so the type is defined? *This one is probably far fetched, but: does gdb have any facility for doing more complex casts than just casting to currently defined types? As an example, is there a way to do something like the following (gdb) print {struct { unsigned int:16 member1; unsigned int:32 member2; unsigned int:16 member3;} }( type1Ptr->member1 ) A: It looks like this question/answer takes care of the 2nd question, and sort of alleviates the need for #3. A: I have an answer to the problem of type information not being available. I added -gstabs+ to my CFLAGS: CFLAGS = (...) -ggdb3 ----> -gstabs+ <---- (...) ... and now gdb can tell me useful stuff about the type in question. I'm still interested in answers to the other two questions, though, if anyone wants to take a shot at those.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to configure Xcode to not go to Debug Navigator upon run? How to configure Xcode to not go to Debug Navigator by default, upon run? Upon <command-R>, i'd like to stay on Project Navigator, if possible. A: It is under Behaviors in the Preferences pane. A: To expand on Monolos answer: Go to Xcode -> Preferences -> Behaviours -> OpenGL ES capture starts then untick the box next to "Show navigator 'Debug Navigator'"
{ "language": "en", "url": "https://stackoverflow.com/questions/7519279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MaxStepSize, MaxSteps seem to have no effect on NDSolve in MATHEMATICA I am a novice at mathematica so please bear with me! I am trying to solve a nonlinear PDE in mma using NDSolve. The solution process is cut short because of singularities occurring much before the time for the simulation runs out. I realize that stiff systems that possess such singularities can be dealt with (at least by brute force) by reducing step size. However "MaxSteps" or "MaxStepSize" doesn't seem to have a tangible effect on my code. What gives? Any other method that I might be missing? ** CODE: ** Needs["VectorAnalysis`"] Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"]; Clear[Eq4, EvapThickFilm, h, S, G, E1, K1, D1, VR, M, R] Eq4[h_, {S_, G_, E1_, K1_, D1_, VR_, M_, R_}] := \!\( \*SubscriptBox[\(\[PartialD]\), \(t\)]h\) + Div[-h^3 G Grad[h] + h^3 S Grad[Laplacian[h]] + (VR E1^2 h^3)/(D1 (h + K1)^3) Grad[h] + M (h/(1 + h))^2 Grad[h]] + E1/( h + K1) + (R/6) D[D[(h^2/(1 + h)), x] h^3, x] == 0; SetCoordinates[Cartesian[x, y, z]]; EvapThickFilm[S_, G_, E1_, K1_, D1_, VR_, M_, R_] := Eq4[h[x, y, t], {S, G, E1, K1, D1, VR, M, R}]; TraditionalForm[EvapThickFilm[S, G, E1, K1, D1, VR, M, R]]; L = 318; TMax = 7.0; Off[NDSolve::mxsst]; Clear[Kvar]; Kvar[t_] := Piecewise[{{0.01, t <= 4}, {0.05, t > 4}}] (*Ktemp = Array[0.001+0.001#^2&,13]*) hSol = h /. NDSolve[{ (*S,G,E,K,D,VR,M*) EvapThickFilm[1, 3, 0.1, Kvar[t], 0.01, 0.1, 0, 160], h[0, y, t] == h[L, y, t], h[x, 0, t] == h[x, L, t], (*h[x,y,0] == 1.1+Cos[x] Sin[2y] *) h[x, y, 0] == 1 + (-0.25 Cos[2 \[Pi] x/L] - 0.25 Sin[2 \[Pi] x/L]) Cos[ 2 \[Pi] y/L] }, h, {x, 0, L}, {y, 0, L}, {t, 0, TMax} ][[1]] Error message: NDSolve::ndsz: At t == 2.366570254802048`, step size is effectively zero; singularity or stiff system suspected. >> NDSolve::eerr: Warning: Scaled local spatial error estimate of 571455.5042645375at t = 2.366570254802048 in the direction of independent variable x is much greater than prescribed error tolerance. Grid spacing with 19 points may be too large to achieve the desired accuracy or precision. A singularity may have formed or you may want to specify a smaller grid spacing using the MaxStepSize or MinPoints method options. >> A: I you run into a "no more memory available" problem, the solution depends on what's causing the lack of memory. For example, I once had to run a simulation which required me to compute a 3D magnetic field over a large volume, as you might imagine, not only it took me a long time to compute it, but it also would be impractible to compute it everytime I had to run a simulation of the particles crossing it. To avoid memory problems and to make the program computationaly lighter, I decided to write the magnetic field data to a text file. A simple csv style of file with the B field vector for each point of space in a grid did the trick... So, my advice is, in case you are running out of memory because you are computing huge amounts of data, you should stream it to a file and then read the file on the next step of the program... I hope this technique helps ;) A: Try making TMax in your code smaller, say 2 or 1. This will remove the error. I found that if I solve using smaller time span, I can get away with even more accurate result (higher AccuracyGoal ->) and I can also use MaxSteps -> Infinity. The trick is that the starting time of your current NDSolve call, does NOT have to be the same as initial conditions time. The starting time can be much removed away from initial conditions. From help The point Subscript[x, 0] that appears in the initial or boundary conditions need not lie in the range Subscript[x, min] to Subscript[x, max] over which the solution is sought. This way, one can call NDSolve many more times, each for smaller time span, while all the time using the same initial conditions on each call. But in exchange, each step made, can be made more accurate. I found that calling NDSolve is very fast, and has no effect I could see on performance. i.e. change NDSolve time specifications to be {from,to} vs {0,TMax}, where from and to are both advanced in smaller values each time, such that the distance between them remains small. (You need to add small logic code to do this), until you have covered the overall time range you were interested in solving over. So, try changing your solver to solve for smaller steps, and I think you'll get much better results. Also, try using Method -> {"StiffnessSwitching"} in your options for NDSolver, as Mathematica says it is stiff system.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fastest way to check if a character is a digit? I am having issues with sqlserver's ISNUMERIC function where it is returning true for ',' I am parsing a postal code and trying to see if the second char (supposed to be a digit) is a 0 or not and do something different in each case. The issue is that I can't just cast the char by checking isNumeric first. Here is the code for my scalar-valued function to return the digit in the second char location, and -1 if it is not a digit. @declare firstDigit int IF ISNUMERIC(SUBSTRING(@postal,2,1) AS int) = 1 set @firstDigit = CAST(SUBSTRING(@postal,2,1) AS int) ELSE set @firstDigit = -1 RETURN @firstdigit Since this fails when the postal code is not quite valid. I am just trying to find out how to check if the nvarchar @postal 's second character is a digit from 0-9. I have seen different types of solutions such as using LIKE [0-9] or using PATINDEX etc. Is there a better/easier way to do this, and if not which method will be the fastest? EDIT: Code added as per Aaron Bertrand's suggestion ON z.postal = CASE WHEN CONVERT(INT, CASE WHEN SUBSTRING(v.patientPostal,2,1) LIKE '[0-9]' THEN SUBSTRING(v.patientPostal, 2,1) END) = 0 then v.patientPostal WHEN CONVERT(INT, CASE WHEN SUBSTRING(v.patientPostal,2,1) LIKE '[0-9]' THEN SUBSTRING(v.patientPostal, 2,1) END) > 0 then LEFT(v.patientPostal,3) A: I'd be very surprised if you would ever be able to detect any difference between WHERE col LIKE '[0-9]' and any other methods you come up with. But I agree with Denis, put that away in a function so that you use the same check consistently throughout all your code (or at least, if you're avoiding UDFs because of large scans etc., put a marker in your code that will make it easy to change on a wide scale later). That said, you are most certainly going to see more of a performance hit just by using a scalar UDF than what method you use to parse inside the function. You really ought to compare performance of the UDF vs. doing that inline using CASE. e.g. SELECT Postal = CONVERT(INT, CASE WHEN SUBSTRING(postal,2,1) LIKE '[0-9]' THEN SUBSTRING(postal, 2,1) END) FROM ... This will yield NULL if the character is not numeric. If you are only dealing with checking local variables, it really is not going to matter what parsing method you use, and you are better off focusing your optimization efforts elsewhere. EDIT adding suggestion to demonstrated JOIN clause. This will potentially lead to less constant scans but is a lot more readable (far fewer substring calls etc): ;WITH v AS ( SELECT /* other columns, */ patientPostal, ss = SUBSTRING(v.patientPostal,2,1), FROM [whatever table is aliased v in current query] ) SELECT /* column list */ FROM [whatever table is aliased z in current query] INNER JOIN v ON z.postal = CONVERT(INT, CASE WHEN v.ss = '0' THEN ss WHEN v.ss LIKE '[1-9]' THEN LEFT(v.patientPostal, 3) END); A: The best way to do it is this: IF SUBSTRING(@postal,2,1) LIKE [0-9] CAST(SUBSTRING(@postal,2,1) AS int) A: Take a look at IsNumeric, IsInt, IsNumber it has checks for those 3 types
{ "language": "en", "url": "https://stackoverflow.com/questions/7519283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: D3.js -- loading and manipulating external data I'm new to D3.js and am playing around with a variety of tutorials/exercises/etc, but my basic need for D3 is to load external data (usually JSON) and draw some interactive charts based on that data. The basic sunburst example is here: I successfully adapted it to my own data. However, I was hoping to simplify the delivery of data and handle some of the manipulation within D3.js. For instance, instead of a hierarchical array that is ready for sunburst diagram, I would like to deliver a flat data file that can be manipulated as needed by D3. But, I'm not sure how to draw a sunburst chart outside of one of D3's data functions. I tried the below code, and instead of loading the data via json included it inline so the structure is visible (unsurprisingly it did not work): var w = 960, h = 700, r = Math.min(w, h) / 2, color = d3.scale.category20c(); var vis = d3.select("#chart").append("svg:svg") .attr("width", w) .attr("height", h) .append("svg:g") .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")"); var partition = d3.layout.partition() .sort(null) .size([2 * Math.PI, r * r]) .value(function(d) { return 1; }); var arc = d3.svg.arc() .startAngle(function(d) { return d.x; }) .endAngle(function(d) { return d.x + d.dx; }) .innerRadius(function(d) { return Math.sqrt(d.y); }) .outerRadius(function(d) { return Math.sqrt(d.y + d.dy); }); var data = [ {'level1': 'Right Triangles and an Introduction to Trigonometry', 'level2': '', 'level3': '', 'level4': '', 'branch': 'TRI', 'subject': 'MAT'}, {'level1': '', 'level2': 'The Pythagorean Theorem', 'level3': '', 'level4': '', 'branch': 'TRI', 'subject': 'MAT'}, {'level1': '', 'level2': '', 'level3': 'The Pythagorean Theorem', 'level4': '', 'branch': 'TRI', 'subject': 'MAT'}, {'level1': '', 'level2': '', 'level3': 'Pythagorean Triples', 'level4': '', 'branch': 'TRI', 'subject': 'MAT'} ]; console.log(data); // looks good here var nest = d3.nest() .key(function(d) { return d.subject;}) .key(function(d) { return d.branch;}) .entries(data); console.log(nest); // looks good here var path = vis.selectAll("path") .data(nest) .enter().append("svg:path") .attr("display", function(d) { return d.depth ? null : "none"; }) // hide inner ring .attr("d", arc) .attr("fill-rule", "evenodd") .style("stroke", "#fff") .style("fill", function(d) { return color((d.children ? d : d.parent).name); }); Here's what the HTML looks like: <div class="gallery" id="chart"> <svg width="960" height="700"> <g transform="translate(480,350)"> <path display="none" d="MNaN,NaNANaN,NaN 0 1,1 NaN,NaNL0,0Z" fill-rule="evenodd" style="stroke: #ffffff; "/> </g> </svg> </div> I'm sure I'm doing something wrong that is pretty simple, but I'm having trouble getting my brain around how D3 will go through all the data and map out the diagram if I'm not nesting the drawing functions within a function like d3.json. Any thoughts? A: It looks like you've forgotten to call partition.nodes(nest) to populate the data with the appropriate layout positions for rendering the paths. In the sunburst example that you linked to, the JSON data is bound like this: var path = vis.data([json]).selectAll("path") .data(partition.nodes) .enter().append("path") // … This is equivalent to: var path = vis.selectAll("path") .data(partition.nodes(json)) .enter().append("path") // … Either approach would work, but you need to call partition.nodes somewhere otherwise the data will have no positions. Also note that your example data with the specified nesting would produce a hierarchy with a single node, since all the specified nested fields are the same.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: What is going wrong with my border layout in my swing app? I have a simple app where I want to show a large image in a scrollable panel. I'm using NavigableImagePanel from http://today.java.net/pub/a/today/2007/03/27/navigable-image-panel.html Firstly the result I'm getting - The image is currently a very small panel near the top buttons. This is with BorderLayout.CENTER The code for NavigableImagePanel: http://pastebin.com/1wHRwMJU and my OpenImage.java code: import java.awt.*; import java.awt.event.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class OpenImage extends JFrame implements ActionListener{ /** * */ private static final long serialVersionUID = 9066218264791891436L; Image img; public OpenImage() throws IOException{ super("Resize and Rotate"); setDefaultCloseOperation(EXIT_ON_CLOSE); BorderLayout grid = new BorderLayout(); //this.setLayout(grid); setSize(900,700); setVisible(true); //Row 1 holds some important buttons //FlowLayout layout1 = new FlowLayout(); //MigLayout mig = new MigLayout(); JPanel row1 = new JPanel(); //LayoutManager grid = new BoxLayout(row1, BoxLayout.X_AXIS); //row1.setLayout(grid); //row1.setLayout(BorderLayout.NORTH); //row1.setMaximumSize(new Dimension(100,100)); BorderLayout border = new BorderLayout(); //row1.setPreferredSize(new Dimension(0, 400)); JButton open = new JButton ("Open"); open.addActionListener(this); JButton rotate = new JButton("Rotate"); rotate.addActionListener(this); JButton resize = new JButton("Resize"); resize.addActionListener(this); JButton exit = new JButton ("Exit"); exit.addActionListener(this); row1.add(open); row1.add(rotate); row1.add(resize); row1.add(exit); //This section has a workable picture panel, but it is too large. //ImagePanel imagepanel = new ImagePanel(); BorderLayout grid1 = new BorderLayout(); Container cp = getContentPane(); cp.setLayout(grid1); //add(row1); //JScrollPane row2 = new JScrollPane(imagepanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); BufferedImage img = ImageIO.read(new File("/home/adam/snow.jpg")); NavigableImagePanel imagepanel = new NavigableImagePanel(img); JPanel row2 = new JPanel(); row2.add(imagepanel); //row2.repaint(); JButton save = new JButton("Save"); JPanel row3 = new JPanel(); row3.add(save); cp.add(BorderLayout.NORTH, row1); cp.add(BorderLayout.CENTER, row2); cp.add(BorderLayout.SOUTH, row3); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command == "Exit"){ System.exit(0); } if (command == "Open"){ JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showOpenDialog(this); } } //This method below is now being deprecat public static void main(String [] args){ try { //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } UIManager.put("swing.boldMetal", Boolean.FALSE); try { JFrame frame = new OpenImage(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } A: * *Code that you post here missed there lots of Java imports, can't see here any Java imports from Swing packages, and import for Image. *setVisible(true); must be last code line in the constructor. *In all case setBackground() can help you to find any problem. *In all case to try use pack() instead of setSize(900,700); *Since I set imagepanel.setPreferredSize(new Dimension(600, 400));, that's wrong JComponents to have to returns preferred size, then pack() will work correctly. *No idea from where you get this code, so hardly could be works without exceptions. *just cleanup useless mess from code import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import javax.swing.border.LineBorder; public class OpenImage extends JFrame implements ActionListener { private static final long serialVersionUID = 9066218264791891436L; private Image img; public OpenImage() { super("Resize and Rotate"); JButton open = new JButton("Open"); open.addActionListener(this); JButton rotate = new JButton("Rotate"); rotate.addActionListener(this); JButton resize = new JButton("Resize"); resize.addActionListener(this); JButton exit = new JButton("Exit"); exit.addActionListener(this); JPanel row1 = new JPanel(); row1.setBackground(Color.red); row1.setLayout(new FlowLayout()); row1.setBorder(new LineBorder(Color.black, 1)); row1.add(open); row1.add(rotate); row1.add(resize); row1.add(exit); JPanel imagepanel = new JPanel(); imagepanel.setLayout(new BorderLayout()); imagepanel.setBackground(Color.blue); imagepanel.setBorder(new LineBorder(Color.black, 1)); imagepanel.setPreferredSize(new Dimension(600, 400)); JPanel row2 = new JPanel(); row2.setLayout(new BorderLayout(10, 10)); row2.setBorder(new LineBorder(Color.black, 1)); row2.add(imagepanel, BorderLayout.CENTER); row2.setBackground(Color.red); JButton save = new JButton("Save"); JPanel row3 = new JPanel(); row3.setBorder(new LineBorder(Color.black, 1)); row3.setBackground(Color.green); row3.setLayout(new FlowLayout()); row3.add(save); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new BorderLayout(10, 10)); add(BorderLayout.NORTH, row1); add(BorderLayout.CENTER, row2); add(BorderLayout.SOUTH, row3); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command == "Exit") { System.exit(0); } if (command == "Open") { JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showOpenDialog(this); } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { OpenImage openImage = new OpenImage(); } }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7519288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding prefix to serialized XML element I have the following class which implements IXmlSerializable: [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Xml.Serialization.XmlSchemaProviderAttribute("ExportSchema")] [System.Xml.Serialization.XmlRootAttribute(IsNullable = false)] public partial class ExceptionReport : object, System.Xml.Serialization.IXmlSerializable { private System.Xml.XmlNode[] nodesField; private static System.Xml.XmlQualifiedName typeName = new System.Xml.XmlQualifiedName("ExceptionReport", "http://www.opengis.net/ows"); public System.Xml.XmlNode[] Nodes { get { return this.nodesField; } set { this.nodesField = value; } } public void ReadXml(System.Xml.XmlReader reader) { this.nodesField = System.Runtime.Serialization.XmlSerializableServices.ReadNodes(reader); } public void WriteXml(System.Xml.XmlWriter writer) { System.Runtime.Serialization.XmlSerializableServices.WriteNodes(writer, this.Nodes); } public System.Xml.Schema.XmlSchema GetSchema() { return null; } public static System.Xml.XmlQualifiedName ExportSchema(System.Xml.Schema.XmlSchemaSet schemas) { System.Runtime.Serialization.XmlSerializableServices.AddDefaultSchema(schemas, typeName); return typeName; } } When i throw an error like this: throw new FaultException<ExceptionReport>(exceptions.GetExceptionReport(), new FaultReason("A server exception was encountered."), new FaultCode("Receiver")); I get the following XML in the soap fault detail: ... <detail> <ExceptionReport xmlns="http://www.opengis.net/ows"> <ows:Exception exceptionCode="NoApplicableCode" locator="somewhere" xmlns:ows="http://www.opengis.net/ows"> <ows:ExceptionText>mymessage</ows:ExceptionText> </ows:Exception> </ExceptionReport> </detail> ... But what i really want is the "ows" prefix also on the root ExceptionReport element: ... <detail> <ows:ExceptionReport xmlns:ows="http://www.opengis.net/ows"> <ows:Exception exceptionCode="NoApplicableCode" locator="somewhere" xmlns:ows="http://www.opengis.net/ows"> <ows:ExceptionText>mymessage</ows:ExceptionText> </ows:Exception> </ows:ExceptionReport> </detail> ... How can i add that prefix? A: How about adding a property to ExceptionReport and decorating it with XmlNamespaceDeclarationsAttribute, and also setting the Namespace property of XmlRoot attribute on ExceptionReport class like this: ... [XmlRoot(IsNullable = false, Namespace = "http://www.opengis.net/ows")] public partial class ExceptionReport { [XmlNamespaceDeclarations()] public XmlSerializerNamespaces xmlns { get { XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(); xmlns.Add("ows", "http://www.opengis.net/ows"); return xmlns; } set { } } ... } Of course you can fill the namespaces in your constructor or wherever you'd like, the point is to have a property which returns the proper XmlSerializerNamespaces instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Custom sorting algorithms' speed problem I'm doing a project where I manually create sorting algorithms. After several tests I found out that my heapsort is way quicker than quicksort (I think it should be the other way around), my selection sort is also faster than insertion sort. does anyone know what's the problem here? I'm testing using integers from -100 to 100, randomly generated, 5000 values in an array (I modified this number several times, still the same problems). My quicksort isn't in-place. I thought that maybe flash's recursive functions are slow? my heapsort uses loops, unlike quicksort. That's just a hypothesis though. here are my codes, if they help. I start a timer, run the class's exec() function, stop the timer and calculate the elapsed time. Codes come from wikipedia. problem with heapsort vs quicksort: public class Quick { public static function exec(seq:Vector.<int>):Vector.<int> { if (seq.length<=1) { return seq; } var smallPart:Vector.<int>=new Vector.<int> var bigPart:Vector.<int>=new Vector.<int> var n:int=seq.length; var pivotPosition:int=Math.floor(Math.random()*n); var pivot:int=seq.splice(pivotPosition,1)[0]; for (var i:int=0; i<n-1; i++) { if (seq[i]<=pivot) { smallPart.push(seq[i]); } else { bigPart.push(seq[i]); } } seq=exec(smallPart).concat(exec(bigPart),Vector.<int>([pivot])); return seq; } } public class Heap{ public static function exec(seq:Vector.<int>) { var n:int=seq.length; heapify(seq); var end:int=n-1; while (end > 0) { var temp:int=seq[end]; seq[end]=seq[0]; seq[0]=temp; siftDown(seq, 0, end-1); end--; } return seq } public static function heapify(seq:Vector.<int>) { var n:int=seq.length var start:int=n/2-1 while (start >= 0) { siftDown(seq, start, n-1); start--; } } public static function siftDown(seq:Vector.<int>, start:int, end:int) { var root:int=start; while (root * 2 + 1 <= end) { var child:int=root*2+1; var swap:int=root; if (seq[swap]<seq[child]) { swap=child; } if (child+1<=end&&seq[swap]<seq[child+1]) { swap=child+1; } if (swap!=root) { var temp:int=seq[root]; seq[root]=seq[swap]; seq[swap]=temp; root=swap; } else { break; } } } } problem with insertion sort vs selection sort: public class Insertion{ public static function exec(seq:Vector.<int>) { var n:int=seq.length; for (var i:int=1; i<n; i++) { var holder:int=seq[i]; var j:int=i-1; while (seq[j]>holder) { seq[j+1]=seq[j]; j-=1; if (j<0) { break } } seq[j+1]=holder; } return seq } } public class Selection{ public static function exec(seq:Vector.<int>):void{ var currentMinimum:int; var n:int=seq.length; for (var i:int = 0; i < n-1; i++) { currentMinimum=i; for (var j:int = i+1; j < n; j++) { if (seq[j]<seq[currentMinimum]) { currentMinimum=j; } } if (currentMinimum!=i) { var temp:int=seq[i]; seq[i]=seq[currentMinimum]; seq[currentMinimum]=temp; } } } } A: Okay, so I don't actually know actionscript but there are many possibilities for this: Language problems I don't know how actionscript works but in C++ and potentially other languages, if you pass the vectors by value instead of reference it can significantly slow things down. (Thanks to alxx for clearing that up) In the quicksort case, you seem to be creating a lot of new vectors. If this operation is slow (I again remind you, I don't know actionscript) it could bias it in favour of heapsort. As The_asMan said, perhaps your method of timing is not accurate and perhaps you should use a different language feature. Algorithm problems You are using 5000 values from [-100, 100]. This means there are going to be a large number of duplicates. One of the main reasons quicksort is fast is that there are a lot of optimizations you can use. A plain (optimizationless) quicksort can be very slow if there are duplicate values. In addition there are many other optimizations that make quicksort often faster in practice. Perception problems Heh. Perception problems. Trololol ;) Insertion sort isn't necessarily faster than selection sort (I'm not sure where you got the idea from). The main case where insertion sort is very fast is when the list is almost sorted. In this case the insertion of each element only requires a few swaps. But in the general case (random numbers) it hasn't got a significant advantage over selection sort. Hope this helps. A: If you want to compare the speed of those sort algorithms. Then why don't you pre-create a random Vector/Array. Then test it's speed. Like : var source:Vector = new Vector().<5000, true>; genRandomNumber(source); var t:int = getTimer(); quicksort(source ....); t = getTimer() - t; trace("quicksort:" + t + "ms"); genRandomNumber(source); t = getTimer(); heapsort(source ...); t = getTimer() - t; trace("heapsort:" + t + "ms"); . . . Here's a quicksort demo by kirupa. I'v tested some sort algorithms before, and quicksort is the fastest. A: I think to really answer this question, you need to take a step back and examine your assumptions. When you say something like "heapsort should be faster than quicksort", what makes you say that? If your reason is "because one has a better big O notation", you need to review what big O really means. big O notation ignores constant factors, and when using small numbers like 5000, constant factors can overwhelm the asymptotic behavior. If your reason is "because wikipedia says one is usually faster", you need to focus on the "usually". A number of factors can influence which one is faster, like how big your sample size is, whether the numbers are already partially sorted, how many duplicate numbers you have. Other factors include cache behavior - some algorithms involve more localized memory access, and can take advantage of the cache better. On the other hand, an interpreted language may or may not screw up that locality compared to a compiled program, thus further confusing matters. One thing you should definitely try is running with some different test data - try 10 million items, where the items are numbers from 0 to 4 billion or so. Then try 10 items, varying from 0 to 20. You should not necessarily expect to see the same algorithm "win" for both cases. The test data you are using now is probably not the best use case for general purpose sorting algorithms. With 5000 numbers chosen out of a potential pool of only 200, you are guaranteed to have large numbers of duplicates. With so many duplicates, a counting sort is almost certainly fastest. Some other thing to consider - how confident are you in your timing function? Do you know if actionscript is interpreted or compiled? Are you running your tests 100 times or so to amoritize any initialization work that needs to be done?
{ "language": "en", "url": "https://stackoverflow.com/questions/7519297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Defensive programming and exception handling A couple days ago, I have following theoretical questions on the exam: (a) Explain what is meant by defensive programming when dealing with exceptional circumstances that may occur during the execution of a program. You may refer to examples seen in class or use pseudo code to describe the steps taken to prevent certain circumstances from occurring when trying to read a file for example. [5 marks] (b) Briefly describe in general terms what is meant by exception handling in Java and how this differs from defensive programming. [5 marks] I always thought that defensive programming is the whole paradigm of programming and that exception handling is the part of it. During exam I write that in "defensive programming", programmer try to find out all possible problems before executing the logic code, and later on return error value(example 0) from this function, whereas in exception handling the potential errors occurs and are caught by special mechanism, in which these errors are directly being interpreted. Is it right? What should be correct answers? A: Defensive programming, to me, means writing code to handle cases that you do not think will, or even can, happen, because you have a belief that your own beliefs are unreliable. For example (not compiled or tested, terms and conditions apply): private String findSmallestString(Collection<String> strings) { if (strings == null || strings.isEmpty()) return null; Iterator<String> stringsIt = strings.iterator(); try { String smallestString = stringsIt.next(); while (stringsIt.hasNext()) { String candidateString = stringsIt.next(); if (candidateString == null) continue; if (candidateString.compareTo(smallestString) < 0) { smallestString = candidateString; } } return smallestString; } catch (NoSuchElementException e) { return null; } } In there, arguably defensive features include: * *The null-or-empty guard clause at the top; this is a private method, so you should be in a position to ensure that it is never called with a null or empty collection *The try-catch for NoSuchElementException; you can prove that the code it contains will never throw this exception if the iterator fulfils its contract. *The nullity guard clause on the strings (other than the first!) coming out of the iterator; again, since this is a private method, you should probably be able to ensure that the collection parameter contains no nulls (and what would you be doing putting nulls in collections anyway?) Not everyone would agree that the null checks are defensive. The try-catch is, to the point of being completely pointless. For me, the acid test of defensive programming is that you don't think the defence will ever be used. A: For me defensive programming is assuming the worst case: that your users are complete crazy people and you must defend yourself and your program from their crazy inputs. I believe there is a lot of wisdom within this quote: Every day, the software industry is making bigger and better fool-proof software, and every day, nature is making bigger and better fools. So far nature is winning And never forget that your users are not only your clients. If you are responsible of a library API your users might be other department. In that case one of the most stellar complains I ever heard in my life was: Even after we deleted all failed unit tests, the program did not work
{ "language": "en", "url": "https://stackoverflow.com/questions/7519299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: iPhone: How to combine Long Press gesture and drag operation together on map? I've tried a number of things and to post code at this point would likely be confusing, so let me start with the concept. I need to somehow combine the operations of long press and touch drag into a single operation, something like LongPressThenDragGestureRecognizer. I'm trying to accomplish this on an MKMapView, so I can't just disable user interaction the entire time, because I want the pan and zoom functionality of the map. To complicate things a bit, the initial item (an MKOverlay object) that the user long-presses on to recognize interaction will need to be removed and replaced with a new drawn object. At that point, the the code doesn't care about the object anymore, only where the finger is at any given point (I will redraw the dragged object as they move). This is the workflow: * *User is presented an overlay on the map *User touches and holds on the item to let the app know they want to drag it *The app replaces the overlay with a drawn object and disables the map so that it doesn't start panning (rather than dragging). *User drags finger, and object redraws as they move. *User lifts finger to complete the drag *App replaces the drawn object with a new map overlay *App enables user interaction on the map to allow pan/zoom/annotation selection, etc. I've tried a number of things so far, with little success. The best results I have so far is listed below. This was done using a UILongPressGestureRecognizer on the MKMapView objects (checking intersection with overlay), and then overriding touchesBegan for map touch drag. * *Overlay is shown and user successfully performs a long-press gesture that gets recognized appropriately *Map user interaction is disabled and overlay is replaced with drawn object *User has to lift finger and touch down again to initiate the drag operation *When user lifts finger, new overlay is drawn and map interaction is enabled again I'm so close, I just don't know how to combine the gestures into one, so that the user doesn't have to lift his/her finger and touch down again to start the drag. Any ideas are greatly appreciated. A: If it's a complex gesture like this, I would be tempted to avoid a gesture recognizer altogether and move to touchesBegan, touchesMoved, touchedEnded, touchesCancelled with some state that you move though as the gesture happens to know where you are. MKMapView has a UIResponder base class so it should be easy to make your own derived version of MKMapView which responds to the touch events (remembering to passing them up to the super the map to maintain it's normal functionality).
{ "language": "en", "url": "https://stackoverflow.com/questions/7519302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Maven Hides Web.xml from Eclipse and JBossAS Tools after Update Project Configuration I'm using Eclipse Indigo, with the "Jboss Maven Integration" and "JBossAS Tools" plugins from JBoss Tools 3.3 installed (none of the other twenty or so JBoss Tools plugins). The application is being deployed to a JBoss 4.2 using the JBossAS Tools 4.2 runtime. Here are the steps to reproduce the problem... 1. Create Dynamic Web Project The project is created with a default deployment descriptor which contains a list of welcome files. The "Welcome Pages" icon can be expanded in the Project Explorer, listing the files in "web.xml". 2. Convert to Maven Project I right-click the project and select "Configure > Convert to Maven Project". I specify "war" packaging and give it a name and description. At this point, you can modify and save "web.xml" and the changes will immediately reflected in the Project Explorer. 3. Update Project Configuration Have Maven update the project configuration by right-clicking the project, then selecting "Maven > Update Project Configuration...". (Usually you would change some build configuration in the POM before doing this, but the problem happens even if you just update right away.) 4. Web.xml isn't Read by Eclipse Anymore Immediately after updating the project, everything looks fine. But the next time you save "web.xml" it is no longer properly displayed in the Project Explorer. It's really weird because even though "web.xml" isn't being displayed properly, Eclipse opens the file correctly when you double click on Deploymen Descriptor in the Project Explorer. The Project Explorer's inability to display the contents isn't the real problem. It just indicates that Eclipse can't see "web.xml" properly. The real problem is that using JBoss Tools, I can't redeploy the solution by pressing the "Touch Descriptors" button (the little hand) because it tells me the project doesn't have any descriptors to touch. It seems like Eclipse is unable to give a reference to "web.xml" to the JBoss plugin or something... Any ideas? :) A: It should "just work" assuming you have m2e-wtp installed. m2e-wtp is the plugin for m2e that does a best-effort to wire up Mavens project model with Eclipse's Web Project model. The simplest way of installing m2e-wtp and get additional automatic configuration for CDI, Hibernate, JSF, etc. is to install JBoss Maven Tools. If you for some reason do not want this additional ease-of-use then you can get m2e-wtp from Eclipse Marketplace. p.s. in recent versions of jboss tools you can also simply restart the individual modules in the server view - which is there to support descriptor less projects. The "touch descriptors" should be moved to support this instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Running lagged regressions with lapply and two arguments I am running multiple univariate regressions, like in this reproducible example: require(dynlm) data(USeconomic) US<-USeconomic vars<-colnames(US)[-2] a<-lapply(colnames(US),function(x) dynlm(log(GNP)~get(x),data=US)) a contains a list of 3 univariate regressions. Assume now I´d like to run the same regressions with 3 lags: l<-c(0,1,4) where 0 is of course the case I already got. Is there a way to use the vector ldirectly, like # this did not work for me, I obtain multivariate regressions including all lags at once lapply(colnames(US),function(x) dynlm(log(GNP)~L(get(x),l),data=US),l=l) After this did not work I tried another approach and added to following vector: lagged_vars <- paste("L(",rep(vars,each=3),",",l,")",sep="") to get: [1] "L(log(M1),0)" "L(log(M1),1)" "L(log(M1),4)" "L(rs,0)" "L(rs,1)" [6] "L(rs,4)" "L(rl,0)" "L(rl,1)" "L(rl,4)" Unfortunately, I can't run it with the new character vector, get() does not help. I can't understand why cause it works with vars but not lagged_vars which are both character vectors. Note, that the L() syntax comes from the dynlm package. Side question: If I just print a the coefficients from the regression result remain labelled get(x) – how can I change that? An i,j loop could be possible solution but I´d rather use lapply or something out of this family... EDIT: as.formula does not work together with L() from dynlm. I get the this error message: Error in merge.zoo(log(GNP), L(log(M1), 0), retclass = "list", all = FALSE) : could not find function "L" EDIT: found an interesting post bei Achim Zeileis referring to this problem. A: To construct R formula, you must paste it all together, not just the predictor side of it. So you need something like: formula <- as.formula( paste("log(GNP)~", paste("L(",rep(vars,each=3),",",l,")",sep=""), sep = "" ) ) and then run dynlm(formula, data = ...) A: Here is an approach using plyr library(plyr); library(dynlm); library(tseries) # FUNCTION TO RUN A SINGLE REGRESSION foo = function(x, l) dynlm(log(GNP) ~ L(get(as.character(x)), l), data = US) # CREATE PARAMETER GRID params = expand.grid(x = colnames(US)[-2], l = c(0, 1, 4)) # RUN REGRESSIONS regressions = mlply(params, foo) Each element of this list contains details on a single regression from which you can extract your desired output
{ "language": "en", "url": "https://stackoverflow.com/questions/7519306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Keeping view-local variable in JSF 2.0 I faced this situation quite a few times, and I found my solution but not sure if it's a good one. I need to call some service which interacts with the database and then share the result between multiple components. Consider this example: <p:outputPanel id="myPanel"> <c:set var="myVar" value="#{myService.retrieveVarFromDB(param)}" /> <my:comp1 val="#{myVar.field1}" /> <my:comp2 val="#{myVar.field2}" /> <my:comp3 val="#{myVar.field3}" /> </p:outputPanel> Here myVar could be reevaluated multiple times, upon ajax update requests. But the good thing is that myService is called only once every time, not for every component which uses myVar. Some of my colleagues do it like this: <my:comp1 val="#{myService.retrieveVarFromDB(param).field1}" /> <my:comp2 val="#{myService.retrieveVarFromDB(param).field2}" /> which is a total overhead. So far my solution satisfies me, but I also know that mixing JSF with JSTL tags could sometimes cause strange things to happen. And many of our co-developers try to avoid using them. So, is there more elegant solution to this problem without using <c:set />? Edit: Calculating myVar just once doesn work for me, because as I stated earlier I need to reevaluate it multiple times. For example when user chooses an item from some select component, an ajax request is sent to the server which in turn makes call to the database, reevaluating myVar value. Edit2: myService is actually a managed bean, which uses injected EJB reference to interact with the database. I called it this way to show what it does, but that happened to be misleading. Sorry about that. A: Getter calls are extraordinary cheap. They're only expensive if you're doing more in a getter than just returning the property. I suggest to do the job in bean's (post) constructor instead and provide a new getter which only returns that result. For aliasing of long EL expressions, you can always use <ui:param>. As to mixing JSTL with JSF, they can cause view scoped beans to break and they may lead to unexpected behaviour when used in iterating JSF components such as <ui:repeat> and <h:dataTable>. JSTL and JSF namely don't run in sync as you'd expect from the coding. It's JSTL which runs first from top to bottom during JSF view build time (to create the JSF component tree) and then it's JSF which runs from top to bottom again during JSF view render time (to generate HTML). See also: * *Why JSF calls getters multiple times *JSTL c:if doesn't work inside a JSF h:dataTable *Communication in JSF 2.0 - @ViewScoped fails in tag handlers Update, as per your edit: Calculating myVar just once doesn work for me, because as I stated earlier I need to reevaluate it multiple times. For example when user chooses an item from some select component, an ajax request is sent to the server which in turn makes call to the database, reevaluating myVar value. Just do that in the action listener method which is invoked by the ajax request. Do above all not abuse the getter for that. <f:ajax listener="#{bean.itemChanged}" /> with public void itemChanged() { myVar = myService.retrieveVarFromDB(param); } then you can use #{bean.myVar} in the view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Constrain PEX code-under-test to a single method? Can the code-under-test in PEX be constrained to a single method? I am aware you can constrain it to assemblies and classes, but what about members? I am essentially trying to achieve 100% code coverage for the following method: public virtual bool GetLastSymbol(string symbolHint, out string symbol) { if (symbolHint == null) { throw new ArgumentNullException("symbolHint"); } IEnumerable<string> symbols; symbol = this.VariableHints.TryGetValue(symbolHint, out symbols) ? symbols.Last() : null; return symbol != null; } The following PUT achieves 12/15 code coverage, because I’m only testing for 1 of the possible 2 values it can return: found = symbolManager.GetLastSymbol(symbolHint, out symbol); PexAssert.IsFalse(found); To achieve full coverage for this PUT, I need to change the object’s state so that the method hits both branches. I could satisfy this by using separate PUTs using a factory method to setup the different states, but this would leave me with 2 PUTs with incomplete code coverage, rather than 1 PUT with full coverage. I realise in theory the 2 PUTs would have a combined coverage of 100%, but I need that 100% figure in practice so I can setup CI properly. So, to reach the other branch in the same PUT, I must append the following code to the above 2 lines: symbolManager.CreateSymbol(symbolHint); // Ensure next call returns true. found = symbolManager.GetLastSymbol(symbolHint, out symbol); PexAssert.IsTrue(found); Presumably the code coverage for the GetLastSymbol method is now 100%, but because I’ve introduced another method call to the type under test, the code coverage now drops to 20/29. How can I constrain a PUT to only measure code coverage for a single method? I realise I may have misunderstood this metric entirely, so please explain why if this is the case :) A: The 'PEX API Reference' which comes installed with PEX was useful for solving this: The Microsoft.Pex.Framework.Coverage namespace includes several filter attributes which can exclude various facets from effecting code coverage. The one I wanted was: PexCoverageFilterMethodAttribute Using this method I was able to remove the CreateSymbol method from the coverage report: [PexCoverageFilterMethod(PexCoverageDomain.UserOrTestCode, "CreateVariable")] This now increased my code coverage to 13/15; higher than before, but still not the 100% I was expecting. Long story short, I discovered PEX was including the constructor in the coverage reports too... [PexCoverageFilterMethod(PexCoverageDomain.UserOrTestCode, "ctor")] I'm now receiving 13/13 for my code coverage. I'm a happy bunny :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7519308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't see Xcode after Installer says "Successfully Installed" I had the following version of Xcode on my MAC mimi - Version: 4.2 (4C128) Location: /Developer Applications: Xcode: 4.2 (821) Instruments: 4.2 (4209) Dashcode: 3.0.2 (335) SDKs: Mac OS X: 10.6: (4C128) iPhone OS: 5.0: (9A5259f) iPhone Simulator: 3.2: (7W367a) 4.0: (8A400) 4.1: (8B117) 4.2: (8C134) 4.3: (8H7) 5.0: (9A5259f) Everything was fine. But i had to install 4.1 snow-leopard ver (Mac Mini is running MAC OS X 10.6.8) for some reason. So, i removed the Xcode 4.2 ver using the following command - sudo /Developer/Library/uninstall-devtools --mode=all And then installed the 4.1 version. The installer program said it's completed the installation successfully. But, I am unable to find the Xcode.app either at the default /Developer/Applications or /Developer locations. I did a complete search for Xcode.app on my hard drive starting from root location. Still no luck - find / -name "Xcode.app" Can someone tell me what im missing here pls? Thanks. A: Look for an app called "Install Xcode". Run that to install Xcode, if you find it and you think that is what was installed, in fact. This new "meta install" appeared semi-recently, and I had to search around to find this "Install Xcode" app because I had the same experience: "Where's Xcode?!"
{ "language": "en", "url": "https://stackoverflow.com/questions/7519309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: dictionary insert causes error 'an item with the same key has already been added' enter code hereI keep running into this exception with ASP.NET MVC 3 application. The project has two simple classess. Project and Orders. Creation of Project works fine but when I try to create an order it keeps failing with the excption below. {"requestigAppLead":"ddd","requestingApplication":"sad","responsibleApp":"fff","responsibleAppLead":"ddd"}[ArgumentException: An item with the same key has already been added.] System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52 System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) +9374523 System.Linq.Enumerable.ToDictionary(IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer`1 comparer) +252 I still see the same issue. Below are complete details. @model DART.Models.Order @{ ViewBag.Title = "Create"; } <h2>Submit your order.</h2> <script type="text/javascript"> $(function () { $("#orderStatusID").change(function () { if ($("#orderStatusID").val() == "8") { // blocked by defect $("#divDefectDetails").show(); } else { $("#divDefectDetails").hide(); } }); $("#projectID").change(function () { //alert("select changed!!!" + $("#projectID").val()); var ur = "/SelectProject/" + $("#projectID").val(); var query = $("#projectID").val(); if (query == "") { $("#requesterLead").val(""); $("#requestingApp").val(""); $("#responsibleApp").val(""); $("#responsibleLead").val(""); return; } // get the JASON object back from Controler. // use the data to load the values into form $.getJSON("/Order/SelectProject", { id: query }, function (data) { //alert("data===" + data); jQuery.each(data, function (key, val) { if (key == "requestigAppLead") { $("#requesterLead").val(val); } else if (key == "requestingApplication") { $("#requestingApp").val(val); } else if (key == "responsibleApp") { $("#responsibleApp").val(val); } else if (key == "responsibleAppLead") { $("#responsibleLead").val(val); } }); }); }); }) </script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Enter Your Order Detalis</legend> <div class="editor-label"> @Html.LabelFor(model => model.projectProjectID, "Project") </div> <div class="editor-field" id="divProjectId"> @Html.DropDownList("projectID","Select Project") @Html.ValidationMessageFor(model => model.projectProjectID) </div> <div class="editor-label"> @Html.Label("Requester Lead") </div> <div class="editor-field"> @Html.EditorFor(model => model.requesterLead) @Html.ValidationMessageFor(model => model.requesterLead) </div> <div class="editor-label"> @Html.Label("Responsible CUID") </div> <div class="editor-field"> @Html.EditorFor(model => model.responsibleCUID) @Html.ValidationMessageFor(model => model.responsibleCUID) </div> <div class="editor-label"> @Html.Label("Responsible Lead") </div> <div class="editor-field"> @Html.EditorFor(model => model.responsibleLead) @Html.ValidationMessageFor(model => model.responsibleLead) </div> <div class="editor-label"> @Html.Label("Requesting Application") </div> <div class="editor-field"> @Html.EditorFor(model => model.requestingApp) @Html.ValidationMessageFor(model => model.requestingApp) </div> <div class="editor-label"> @Html.Label("Responsible Application") </div> <div class="editor-field"> @Html.EditorFor(model => model.responsibleApplication) @Html.ValidationMessageFor(model => model.responsibleApplication) </div> <div class="editor-label"> @Html.Label("RCBSCode") </div> <div class="editor-field"> @Html.EditorFor(model => model.rcbsCode) @Html.ValidationMessageFor(model => model.rcbsCode) </div> <div class="editor-label"> @Html.Label("Order Request Details") </div> <div class="editor-field"> @Html.TextAreaFor(model => model.orderRequestDetails,"width=100%") @Html.ValidationMessageFor(model => model.orderRequestDetails) </div> <div class="editor-label"> @Html.Label("Order Request Complete Details") </div> <div class="editor-field"> @Html.TextAreaFor(model => model.orderRequestCompleteDetails) @Html.ValidationMessageFor(model => model.orderRequestCompleteDetails) </div> <div class="editor-label"> @Html.Label("CreatedBy") </div> <div class="editor-field"> @Html.EditorFor(model => model.createdby) @Html.ValidationMessageFor(model => model.createdby) </div> <div class="editor-label"> @Html.Label("UpdatedBy") </div> <div class="editor-field"> @Html.EditorFor(model => model.updatedBy) @Html.ValidationMessageFor(model => model.updatedBy) </div> <div class="editor-label"> @Html.LabelFor(model => model.status, "OrderStatus") </div> <div class="editor-field" id="divStatus"> @Html.DropDownList("orderStatusID", "Select Order Status") @Html.ValidationMessageFor(model => model.Status) </div> <div id="divDefectDetails" style="display:none"> <div class="editor-label"> @Html.Label("Defect ID") </div> <div class="editor-field"> @Html.EditorFor(model => model.defectID) @Html.ValidationMessageFor(model => model.defectID) </div> <div class="editor-label"> @Html.Label("QC Project Name") </div> <div class="editor-field"> @Html.EditorFor(model => model.qcProjectName) @Html.ValidationMessageFor(model => model.qcProjectName) </div> <div class="editor-label"> @Html.Label("QC Application") </div> <div class="editor-field"> @Html.EditorFor(model => model.application) @Html.ValidationMessageFor(model => model.application) </div> <div class="editor-label"> @Html.Label("QC Status") </div> <div class="editor-field"> @Html.EditorFor(model => model.status) @Html.ValidationMessageFor(model => model.status) </div> <div class="editor-label"> @Html.Label("QC EFD") </div> <div class="editor-field"> @Html.EditorFor(model => model.efd) @Html.ValidationMessageFor(model => model.efd) </div> </div> <p> <input type="submit" id="CreateOrder" name="CreateOrder" value="Create Order" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> Control Code: // // GET: /Order/Create public ActionResult Create( ) { ViewBag.projectID = new SelectList(db.Projects.ToList(), "projectID", "projectName"); ViewBag.orderStatusID = new SelectList(db.OrderStatuses.ToList(), "orderStatusID", "description"); return View(); } Adding more details as requested below. // // Populate project details // [HttpGet] public virtual JsonResult SelectProject(long? id) { Project project = this.db.Projects.Find(1); var result = new { project.requestigAppLead, project.requestingApplication, project.responsibleApp, project.responsibleAppLead }; //ViewBag.projectID = new SelectList(db.Projects, "projectID", "projectName",id.ToString()); //return View(order); return Json(result, JsonRequestBehavior.AllowGet); } // // POST: /Order/Create [HttpPost, ActionName("Create")] public ActionResult Create(Order order) { if (ModelState.IsValid) { // // TO DO: if the order count is more than threshold raise an alert to the user and send an email to // leads // order.createDateTime = DateTime.Now; order.updateDateTime = DateTime.Now; db.Orders.Add(order); db.SaveChanges(); // send email util.EmailUtil.SendEmail(order); return RedirectToAction("Index"); } ViewBag.projectID = new SelectList(db.Projects, "projectID", "projectName", order.projectProjectID); return View(order); } A: Your linq query contains a duplicate entry. You need to figure out what that is and remove it OR if possible use .ToList() and not ToDictionary()
{ "language": "en", "url": "https://stackoverflow.com/questions/7519310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript ajax callback makes items list flicker I have a simple list of Reminders that a user can click and drag into a "delete drop zone" one at a time. It makes an ajax call to my Webmatrix webservice to delete the item. This all works great. However, in the javascript or ajax callback I am retrieving the remaining items and displaying them back to the list. For some reason, when this process happens the list flickers and then displays the newly updated amount. It kinda of steals the nice ajax effect away. Would be nice for the remaining items to sort of slide up to fill in the gap left from the item that was dragged away. Any help would be awesome and greatly appreciated! Here's the code on jsFiddle: (Note: it is not a "working" fiddle example. Just a good place to put all the code snippets): http://jsfiddle.net/cpeele00/4ugBt/ A: You get the flash because you are clearing the entire list and then repopulating it. var refreshReminderList = function(data) { $('#reminders-list').empty(); $('#reminders-listTmpl').tmpl(data).appendTo('#reminders-list'); }; Instead of emptying it - iterate through the list and remove any elements that are not in the new data list. It looks like you return the actual html, instead return a list of ids (or some identifier. //pseudocode $('reminder-list li').each( function(){ //if not in data list $(this).slideUp(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7519311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# replace links, replace multiple line not working I want to go through all html links (<a hef="" ><image/></a>) and I want to replace them with only href values. To do that I use HtmlAgilityPack to get all the links and then I try to replace any outer html of the link with the href. result = result.Replace(l.OuterHtml, l.Text + " " + l.Href); This works just fine with normal links but it is not working with long links that have images embedded in them. It works for <a href="http://www.domain.net/">www.domain.Net<br /></a> But it does not work for <a href="http://www.domain.net/property-details.aspx?state=50&amp;search=yes&amp;offset=0&amp;page=2&amp;offset=10&amp;page=3&amp;offset=20&amp;page=4&amp;offset=30&amp;page=5&amp;offset=40&amp;page=6&amp;pid=828"><image style="border: 1px solid #c99982; margin: 5px 0 0px 0;" src="http://domain.com/private/007jg5he/large_289572HESSEL_prop_photos_horse_areas_010-1" alt="Sebastopol" width="158" height="108" /></a> So how do I solve this? I want to show only the Text part of the link following with the href value. A: You don't need (nor should you use) regular expressions here. That's the whole point of using the parser in the first place. HtmlDocument doc = ...; var query = doc.DocumentNode.Descendants("a"); foreach (var a in query.ToArray()) { a.ParentNode.ReplaceChild(HtmlNode.CreateNode(a.Attributes["href"].Value), a); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7519314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EntityFramework4.1's .Local().ToBindingList() , How to filter then? Example Model: Customer -> Order contex.Order.Load(); orderBindingSource.DataSource = context.Order.Local().ToBindingList(); Then, how to filter? e.g. context.Order.Where(m=>m.customerID > 1) I want to get the BindingList implementation that stays in sync with the ObservableCollection returned by the Local property. A: Have you tried using select? contex.Order.Load(); orderBindingSource.DataSource = context.Order.Local().Select( m => m.customerID > 1).ToBindingList(); Edit Not entirely sure about this, it compiles but I do not have a full environment to test it. Perhaps if you try to load in the specific data, and then you can access it in local for the binding list. Like this: context.Order.Select( m => m.customerID > 1).Load(); orderBindingSource.DataSource = context.Order.Local.ToBindingList(); A: I think the best way. Is using load, you can see the details https://learn.microsoft.com/en-us/ef/ef6/querying/local-data You can use Load or best loadAsync like the example dbContext.Order.Where(m=>m.customerID > 1).LoadAsync().ContinueWith(loadTask => { // Bind data to control when loading complete orderBindingSource.DataSource = dbContext.Order.Local.ToBindingList(); }, System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());
{ "language": "en", "url": "https://stackoverflow.com/questions/7519315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Determine if running x64 or x86 operating system in MATLAB How is it possible in MATLAB to determine if the OS is x64 or x86? NOTE: I have found the computer function but it is mentioned that in case a x32 MATLAB is running on a x64 OS then it returns x32 (instead of x64) so this function will not do. A: From your comment, I assume you're running Windows. Take a look at the environment variables PROCESSOR_ARCHITECTURE and PROCESSOR_ARCHITEW6432. The combination of their presence and values will tell you what you're running under. x64 Matlab on x64 Windows: PROCESSOR_ARCHITECTURE=AMD64 x86 Matlab on x86 Windows: PROCESSOR_ARCHITECTURE=x86 x86 Matlab on x64 Windows: PROCESSOR_ARCHITECTURE=x86 PROCESSOR_ARCHITEW6432=AMD64 Then you can use the environment variables PROGRAMFILES, PROGRAMFILES(X86), and PROGRAMW6432 to find the right "Program Files" path to launch your external app from, if it's installed in the conventional location. Google "WoW64" for more info on how the Windows x64 and x86 environments interact. A: On Windows, you could try parsing the output of dos('systeminfo'), but it's not exactly fast. On Linux, you could try parsing the output of unix('uname -a').
{ "language": "en", "url": "https://stackoverflow.com/questions/7519321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Amazon S3 Access Control List and Amazon SDK for .NET I have an ASP.NET MVC 3 app that uses Amazon S3 to store movie files. Right now everything is public so I can access the files. Let's say I wanted to share these videos but only if people purchased a subscription to my website (on register). How would I go about making the videos private and only allowing registered users to access this amazon URL? Can I do this without making my subscribers sign up for an Amazon account? Thanks. A: If you make your files private, you can generate time limited urls to your files for your members. Its easy to generate these urls using the SDK for .NET Or you could use Amazons Identity and Access Management (IAM) service to restrict access to the files based on some criteria.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I ensure the right user is logged in when a website is called by a website Sorry for the strange, recursive wording of the title, but I couldn't think of a better title. As I have alluded to before, I have 2 websites A and B, and I am integrating B into A, so that B is still accessible as a standalone site, but also as part of A (in an iframe). Both sites have their login screens. I needed to bypass the login screen for site B when it was accessed from A. I got this done, as follows: First A checks if the location of B is the same as a (i.e. they are running on the server), if this is true, then the login information is stored in session variables and checked on b. If the location of B is a different server, then the login information is sent through the url (see here: I need to integrate two sites, what's the best way to carry over login information? ), this is probably not secure given that the url can be seen in the source code, but I couldn't think of a better solution. When website B is called, index.php is called, and index.php checks if a user is logged in or not (whether the session variable is set or not), if no user is authorized, index.php calls check.php which checks the authentication data sent by site a. If the data is a-ok, check.php authenticates the user and once the script ends we are back at index.php. Now, the only issue is that say if user ADMIN logs into website a, then clicks the link for website b, website b is displayed and he is now logged in as admin on both sites. After doing some stuff, ADMIN logs out of SITE A WITHOUT logging out of site b. Then, his boss, SUPER ADMIN walks over, shoves ADMIN of his seat and logs into site a. SUPER ADMIN then clicks on the link to site b, only to find that he is logged into site b as ADMIN. At this point, he picks up the phone, calls me, and proceeds to yell profanities at me. So, it isn't the most serious of issues, but it would be nice to solve. One solution I have in mind is to add a website b id field to each user of site a and send this in the url as well. So, when check.php is called, it stores the id field in a SESSION variable. So, when index.php is called again by website a, it checks if the Session variable is set, and if it is, then it compares the set variable to the new one being sent by $_GET. If the URL is different, it destroys the session, and includes checks.php, I can probably implement this solution, but it will take a bit of work, and I am not sure if this is a good idea or not, so I wanted to ask if there is another better way, or tips for the above solution. Thanks for your time, have a good day! A: Make the servers communicate with eachother. When a user wants to access site B through site A, send him to server A first. Server A negotiates some sort of login-token directly with server B before it redirects the user to site B with the newly created login token. The server to server communication is not so easily intercepted, so you can send the user info in plain text, but you can also encrypt this communication if you find it neccessary. When SUPER ADMIN arrives, he will get a new login-token, telling server B to terminate the active session, and log in the new user. It's not super secure, but it's quite simple and should work well enough for this scenario...
{ "language": "en", "url": "https://stackoverflow.com/questions/7519325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to stream data into GIT instead of passing in file names? We want to stream documents that do not exist in a file system (they are in a database) into GIT. Since there are thousands of documents, we dont want to create them on disk. We know that we can stream documents out of GIT using the GIT Blob classes. We want to pragmatically provide tree/path and filename and any other attributes, but the file will not actually exist. GIT itself streams data into itself at some point (when it reads the file) and stores file attribute data somehow. I know how to add files in GIT, I want to interface using a stream instead. Is this possible using C, C# or Java? A: You can use hash-object. gitid=$(echo hello world | git hash-object -w --stdin) This will set gitid to the git id of a new blob object based on the output of the echo command. You can then use git update-index to add an index entry using this blob and commit to make a commit object containing the new blob in your git repository. git update-index --add --cacheinfo 100644 "$gitid" new-blob.txt git commit -m "new commit" A: You could also create the objects "by hand", by creating the objects and trees from your code. Here is a video of GitHub's Tom Preston-Werner describing the structure: http://sea.ucar.edu/event/unlocking-secrets-git I don't know if that's the way to go for you, but it's an option
{ "language": "en", "url": "https://stackoverflow.com/questions/7519329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Site layout only in the browser – really or not? Hello I'm really only just started to create their own websites and there and I need in the layout of the site. Not long thinking I downloaded the notepad++ and began to impose. My friends advised me to get dreamweaver to make it easier but it To facilitate the work, but it seemed slow and difficult. I want make up only a web browser (like in Firebug and Developer Tools Google Chrome) without the other editors but the main difficulty is that they can not edit files directly in local folder on my PC (?) this is implemented in Opera (ctrl+U) but it is not entirely comfortable. There other solutions? Translation carried out with Google Translate with my edits - do not hurt me much:) A: Honestly, Dreamweaver is your best bet. I use dreamweaver, I have been for years and I haven't found anything that does the job better. It handles everything perfectly; HTML, javascript, PHP, CSS, everything a budding web designer needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Given a textarea, is there a way to restrict length based on # of lines? I have a textarea field and I want the user to be able to enter not more than 3 lines. Is that possible? A: Fiddle: http://jsfiddle.net/nvLBZ/1/ I have just (2 hours) created a script which always restricts the height of the text-area to 3 lines. * *The largest possible width of a character is calculated for the specific textarea (if not already calculated earlier). *The minimum words per line are calculated. *The textarea is cloned, to test whether it's necessary to continue with the function. When the input is valid, the function returns without interrupting the user. *Otherwise, the cloned textarea is used as a reference, and the user's textarea is erased. The user's textarea is also temporary invisible, for performance reasons. *The textarea gets filled using an efficient method: Blocks which are known to be smaller than the textarea's width are added into the textarea. *When the added blocks exceed the maximum size, the last characters are individually removed, until the maximum line limit has finally reached. *The defaults are restored. Code below, the code is implemented at the bottom ($(document).ready(...)). (function(){ var wordWidthMappers = {}; function checkHeight(textarea, maxLines){ if(!(textarea instanceof $)) return; /*JQuery is required*/ if(isNaN(maxLines) || !isFinite(maxLines) || maxLines == 0) return; var areaWidth = textarea.width(); var oldHeight = textarea.css("height"); var oldOverflow = textarea.css("overflow-y"); var lineHeight = parseFloat(textarea.css("line-height")); var maxTxtHeight = maxLines*lineHeight + "px"; /*Calculations for an efficient determination*/ var fontstyles = "font-size:"+textarea.css("font-size"); fontstyles += ";font-family:"+textarea.css("font-family"); fontstyles += ";font-weight:"+textarea.css("font-weight"); fontstyles += ";font-style:"+textarea.css("font-style"); fontstyles += ";font-variant:"+textarea.css("font-variant"); var wordWidth = wordWidthMappers[fontstyles]; if(!wordWidth){ var span = document.createElement("span"); span.style.cssText = fontstyles+";display:inline;width:auto;min-width:0;padding:0;margin:0;border:none;"; span.innerHTML = "W"; //Widest character document.body.appendChild(span); wordWidth = wordWidthMappers[fontstyles] = $(span).width(); document.body.removeChild(span); } textarea = textarea[0]; var temparea = textarea.cloneNode(false); temparea.style.visibility = "hidden"; temparea.style.height = maxTxtHeight; temparea.value = textarea.value; document.body.appendChild(temparea); /*Math.round is necessary, to deal with browser-specific interpretations of height*/ if(Math.round(temparea.scrollHeight/lineHeight) > maxLines){ textarea.value = ""; textarea.style.visibility = "hidden"; if(oldOverflow != "scroll") textarea.style.overflowY = "hidden"; textarea.style.height = maxTxtHeight; var i = 0; var textlen = temparea.value.length; var chars_per_line = Math.floor(areaWidth/wordWidth); while(i <= textlen){ var curLines = Math.round(textarea.scrollHeight/lineHeight); if(curLines <= maxLines){ var str_to_add = temparea.value.substring(i, i+chars_per_line); var nextLn = str_to_add.indexOf("\n"); if(nextLn > 0) str_to_add = str_to_add.substring(0, nextLn); else if(nextLn == 0) str_to_add = "\n"; i += str_to_add.length; textarea.value += str_to_add; } else if(curLines > maxLines){ textarea.value = textarea.value.substring(0, textarea.value.length-1); i--; if(Math.round(textarea.scrollHeight/lineHeight) <= maxLines) break; } } textarea.style.visibility = "visible"; textarea.style.height = oldHeight; textarea.style.overflowY = oldOverflow; } temparea.parentNode.removeChild(temparea); } $(document).ready(function(){/* Add checker to the document */ var tovalidate = $("#myTextarea"); tovalidate.keyup(function(){ /*Add keyup event handler. Optionally: onchange*/ checkHeight(tovalidate, 3); }); }); })(); A: Possible? Maybe. How do you measure a line? Do you include word wrap? If so, then you're not going to be able to do so reliably. If you only count line breaks as a 'line' then you could always add a keypress event to the textarea and check the number of breaks in the area and not allow more than three.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Print a simple text to a paper in Java I need to print to the default printer in windows with Java. I found some sample code on the internet. The code compiles without error. But when ran, I get the following error: ** Exception in thread "Thread-4" java.lang.NullPointerException at sun.awt.windows.WprinterJob.NullPointerException at sun.awt.windows.WprinterDialogPeer._show(Native Method) at sun.awt.windows.WprinterDialogPeer.access$000(Unknown Source) at sun.awt.windows.WprinterDialogPeer$1.run(Unknown Source) at java.lang.Thread.run(Unknown Source)** The program shows the dialog box. However, when I click on the print button it gives me the exception. I think this is a case with java Print component. What can i do to correct this? A: I think that the code is pretty old, but ok. I ran your code TestPrint under NetBeans 7 and Windows XP and it works fine. Have you a printer installed? What is your configuration? How do you run the compiled class? When I click on Print:
{ "language": "en", "url": "https://stackoverflow.com/questions/7519338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HashMap to return default value for non-found keys? Is it possible to have a HashMap return a default value for all keys that are not found in the set? A: Use Commons' DefaultedMap if you don't feel like reinventing the wheel, e.g., Map<String, String> map = new DefaultedMap<>("[NO ENTRY FOUND]"); String surname = map.get("Surname"); // surname == "[NO ENTRY FOUND]" You can also pass in an existing map if you're not in charge of creating the map in the first place. A: On java 8+ Map.getOrDefault(Object key,V defaultValue) A: Use: myHashMap.getOrDefault(key, defaultValue); A: Java 8 introduced a nice computeIfAbsent default method to Map interface which stores lazy-computed value and so doesn't break map contract: Map<Key, Graph> map = new HashMap<>(); map.computeIfAbsent(aKey, key -> createExpensiveGraph(key)); Origin: http://blog.javabien.net/2014/02/20/loadingcache-in-java-8-without-guava/ Disclamer: This answer doesn't match exactly what OP asked but may be handy in some cases matching question's title when keys number is limited and caching of different values would be profitable. It shouldn't be used in opposite case with plenty of keys and same default value as this would needlessly waste memory. A: It does this by default. It returns null. A: In Java 8, use Map.getOrDefault. It takes the key, and the value to return if no matching key is found. A: Can't you just create a static method that does exactly this? private static <K, V> V getOrDefault(Map<K,V> map, K key, V defaultValue) { return map.containsKey(key) ? map.get(key) : defaultValue; } A: [Update] As noted by other answers and commenters, as of Java 8 you can simply call Map#getOrDefault(...). [Original] There's no Map implementation that does this exactly but it would be trivial to implement your own by extending HashMap: public class DefaultHashMap<K,V> extends HashMap<K,V> { protected V defaultValue; public DefaultHashMap(V defaultValue) { this.defaultValue = defaultValue; } @Override public V get(Object k) { return containsKey(k) ? super.get(k) : defaultValue; } } A: You can simply create a new class that inherits HashMap and add getDefault method. Here is a sample code: public class DefaultHashMap<K,V> extends HashMap<K,V> { public V getDefault(K key, V defaultValue) { if (containsKey(key)) { return get(key); } return defaultValue; } } I think that you should not override get(K key) method in your implementation, because of the reasons specified by Ed Staub in his comment and because you will break the contract of Map interface (this can potentially lead to some hard-to-find bugs). A: I found the LazyMap quite helpful. When the get(Object) method is called with a key that does not exist in the map, the factory is used to create the object. The created object will be added to the map using the requested key. This allows you to do something like this: Map<String, AtomicInteger> map = LazyMap.lazyMap(new HashMap<>(), ()->new AtomicInteger(0)); map.get(notExistingKey).incrementAndGet(); The call to get creates a default value for the given key. You specify how to create the default value with the factory argument to LazyMap.lazyMap(map, factory). In the example above, the map is initialized to a new AtomicInteger with value 0. A: Not directly, but you can extend the class to modify its get method. Here is a ready to use example: http://www.java2s.com/Code/Java/Collections-Data-Structure/ExtendedVersionofjavautilHashMapthatprovidesanextendedgetmethodaccpetingadefaultvalue.htm A: /** * Extension of TreeMap to provide default value getter/creator. * * NOTE: This class performs no null key or value checking. * * @author N David Brown * * @param <K> Key type * @param <V> Value type */ public abstract class Hash<K, V> extends TreeMap<K, V> { private static final long serialVersionUID = 1905150272531272505L; /** * Same as {@link #get(Object)} but first stores result of * {@link #create(Object)} under given key if key doesn't exist. * * @param k * @return */ public V getOrCreate(final K k) { V v = get(k); if (v == null) { v = create(k); put(k, v); } return v; } /** * Same as {@link #get(Object)} but returns specified default value * if key doesn't exist. Note that default value isn't automatically * stored under the given key. * * @param k * @param _default * @return */ public V getDefault(final K k, final V _default) { V v = get(k); return v == null ? _default : v; } /** * Creates a default value for the specified key. * * @param k * @return */ abstract protected V create(final K k); } Example Usage: protected class HashList extends Hash<String, ArrayList<String>> { private static final long serialVersionUID = 6658900478219817746L; @Override public ArrayList<Short> create(Short key) { return new ArrayList<Short>(); } } final HashList haystack = new HashList(); final String needle = "hide and"; haystack.getOrCreate(needle).add("seek") System.out.println(haystack.get(needle).get(0)); A: I needed to read the results returned from a server in JSON where I couldn't guarantee the fields would be present. I'm using class org.json.simple.JSONObject which is derived from HashMap. Here are some helper functions I employed: public static String getString( final JSONObject response, final String key ) { return getString( response, key, "" ); } public static String getString( final JSONObject response, final String key, final String defVal ) { return response.containsKey( key ) ? (String)response.get( key ) : defVal; } public static long getLong( final JSONObject response, final String key ) { return getLong( response, key, 0 ); } public static long getLong( final JSONObject response, final String key, final long defVal ) { return response.containsKey( key ) ? (long)response.get( key ) : defVal; } public static float getFloat( final JSONObject response, final String key ) { return getFloat( response, key, 0.0f ); } public static float getFloat( final JSONObject response, final String key, final float defVal ) { return response.containsKey( key ) ? (float)response.get( key ) : defVal; } public static List<JSONObject> getList( final JSONObject response, final String key ) { return getList( response, key, new ArrayList<JSONObject>() ); } public static List<JSONObject> getList( final JSONObject response, final String key, final List<JSONObject> defVal ) { try { return response.containsKey( key ) ? (List<JSONObject>) response.get( key ) : defVal; } catch( ClassCastException e ) { return defVal; } } A: public final Map<String, List<String>> stringMap = new ConcurrentHashMap<String, List<String>>() { @Nullable @Override public List<String> get(@NonNull Object key) { return computeIfAbsent((String) key, s -> new ArrayList<String>()); } }; HashMap cause dead loop, so use ConcurrentHashMap instead of HashMap, A: In Map Using getOrDefault method if key is not found we can place the default value in right side parameter. Converting List to Map by doing grouping Status. Map<String, Long> mapClaimDecisionSummaryCount = reportList.stream().collect(Collectors.groupingBy(Report::getStatus, Collectors.counting())); Long status_approved = mapClaimDecisionSummaryCount.getOrDefault("APPROVED", 0L); Long status_declined = mapClaimDecisionSummaryCount.getOrDefault("DECLINED", 0L); Long status_cancelled = mapClaimDecisionSummaryCount.getOrDefault("CANCELLED", 0L);//If Key not found it takes defaultValue as 0 Long status_inprogress = mapClaimDecisionSummaryCount.getOrDefault("INPROGRESS", 0L); System.out.println("APPROVED: "+ status_approved); System.out.println("DECLINED: "+ status_declined); System.out.println("CANCELLED: "+ status_cancelled); System.out.println("INPROGRESS: "+ status_inprogress); OutPut: APPROVED: 20 DECLINED: 10 CANCELLED: 5 INPROGRESS: 0 As you see in the above output Status INPROGRESS is not found, so it takes Default value as 0 A: In mixed Java/Kotlin projects also consider Kotlin's Map.withDefault. See Accessing Kotlin extension functions from Java.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "185" }
Q: Unable to Customize EditForm.aspx with Document Sets in SharePoint 2010 I give...I am hoping someone has a good answer. I create a content type based on a Document Set (called A). I create a document library and allow this new custom content type to be added to the library. I add one column (say Car Phone) to the new content type(A). I want to be able to edit the EditForm.aspx to add some text or javascript. However, if I do anything to the editform.aspx through SharePoint designer it completely ignores any custom fields on my content type A. Now, when selecting the item, and selecting edit i do not see my Car Phone Property. This occurs only when i do anything to the editform.aspx that exists in the document library. Just copying to a new name and setting as the default edit form it ignores my custom properties on the content type A> Ideas? A: This is apparently an issue on the version for SharePoint 2010 that we were using. It is documented that attributes on document sets are not able to be edited with the version of SharePoint that we had installed. We updated the version of SharePoint we were using and this resolved our problem. We migrated to the version prior to sp1 and that was the resolution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ext JS Combo box with a text box I'm new to Ext JS and I wanted to know if there is a way I could do something like this? (I understand, I can have the Combo box as editable instead of this. But wanted to know if I can do this.) A: It can be done, but you have to extend ComboBox. One of the things you need to change is tpl. If you have never done something like that, you can look at Saki's LovCombo. A: var strCmbDip = Ext.create('Ext.data.Store', { storeId: 'strCmbDip', fields: ['id','name'], proxy: { type: 'ajax', url: 'rtvstore.php', reader: { root: 'rootCmbDip' } } }); var cmbDip = Ext.create('Ext.form.ComboBox', x: 150, width: 230, id: 'cmbDip', fieldLabel: 'Dip', labelAlign: 'top', selectOnFocus: true, allowBlank: false, emptyText: 'Select....', queryMode: 'remote', displayField: 'name', valueField: 'id', editable: true, triggerAction: 'all', minChars: 1, hideTrigger: true, loadingText: '', store: strCmbDip }); A: Changed the tpl in Ext Designer and it worked. Though the answer is what @Francesco said, I'm just adding the XTemplate I used for reference. <tpl for="."><li>{Name}</li></tpl><input type="text" value="Enter item"></input>
{ "language": "en", "url": "https://stackoverflow.com/questions/7519343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sort and display documents based on industry which is fetched from each entity I have an .xml file which is structured as such: <documents> <item> <title>Document Title</title> <customer>Customer Name1</customer> <description>Description 1 here</description> <image height="100" width="100"></image> <link filetype="pdf" language="English">/documents/document.pdf</link> <industry>Industry name 1</industry> </item> <item> <title>Document Title 2</title> <customer>Customer Name 2</customer> <description>Description 2 here</description> <image height="100" width="100"></image> <link filetype="pdf" language="English">/documents/document2.pdf</link> <industry>Industry name 2</industry> </item> What I need this to become, preferrably using XSL (as I know a bit about it already and I'd catch on quickly), is this: <h2>Industry name 1</h2> <div class="doc"> <h3>Document Title</h3> <p>Description 1 here <a href="/documents/document.pdf">Download!</a></p> </div> <h2>Industry name 2</h2> <div class="doc"> <h3>Document Title 2</h3> <p>Description 2 here <a href="/documents/document.pdf">Download!</a></p> </div> Where I am completely stumped, is how I could dynamically get the industries from within the XML, print the first one and then all documents relating to that industry, and then move on to the second industry, then the third, and fourth and so on. Where I start to wonder if this even possible, is when I consider that the XSL has to actually store each industry "tag" from each and compare them in order to see if it already has it. If it does, it should not print it, but simply print the rest of the information. I would rather avoid changing the schema of the XML file, as it's in use all over the place already serving other purposes. But, I realize it might have to be. Please also note that the file is completely unsorted. Latest file added is at the top, regardless of industry "tag" associated with it. This can be changed however. To me, this is a tough nut to crack, if it even can be using pure XSL as a parser? A: This XSLT 1.0 transformation: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:key name="kItemByInd" match="item" use="industry"/> <xsl:template match= "item[generate-id() = generate-id(key('kItemByInd', industry)[1]) ] "> <h2><xsl:value-of select="industry"/></h2> <xsl:apply-templates mode="inGroup" select="key('kItemByInd', industry)"/> </xsl:template> <xsl:template match="item"/> <xsl:template match="item" mode="inGroup"> <div class="doc"> <h3><xsl:value-of select="title"/></h3> <p> <xsl:value-of select="description"/> <a href="{link}"> Download!</a> </p> </div> </xsl:template> </xsl:stylesheet> when applied on the following XML document (obtained from the provided one by adding one more item -- to make it more interesting): <documents> <item> <title>Document Title</title> <customer>Customer Name1</customer> <description>Description 1 here</description> <image height="100" width="100"></image> <link filetype="pdf" language="English">/documents/document.pdf</link> <industry>Industry name 1</industry> </item> <item> <title>Document Title 2</title> <customer>Customer Name 2</customer> <description>Description 2 here</description> <image height="100" width="100"></image> <link filetype="pdf" language="English">/documents/document2.pdf</link> <industry>Industry name 2</industry> </item> <item> <title>Document Title 3</title> <customer>Customer Name 3</customer> <description>Description 3 here</description> <image height="100" width="100"></image> <link filetype="pdf" language="English">/documents/document3.pdf</link> <industry>Industry name 1</industry> </item> </documents> produces the wanted, correct result: <h2>Industry name 1</h2> <div class="doc"> <h3>Document Title</h3> <p>Description 1 here<a href="/documents/document.pdf"> Download!</a> </p> </div> <div class="doc"> <h3>Document Title 3</h3> <p>Description 3 here<a href="/documents/document3.pdf"> Download!</a> </p> </div> <h2>Industry name 2</h2> <div class="doc"> <h3>Document Title 2</h3> <p>Description 2 here<a href="/documents/document2.pdf"> Download!</a> </p> </div> and it displays in the browser as: Industry name 1 Document Title Description 1 here Download! Document Title 3 Description 3 here Download! Industry name 2 Document Title 2 Description 2 here Download! Explanation: Muenchian method for grouping. II. XSLT 2.0 Solution: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/*"> <xsl:for-each-group select="item" group-by="industry"> <h2><xsl:value-of select="industry"/></h2> <xsl:apply-templates select="current-group()"/> </xsl:for-each-group> </xsl:template> <xsl:template match="item"> <div class="doc"> <h3><xsl:value-of select="title"/></h3> <p> <xsl:value-of select="description"/> <a href="{link}"> Download!</a> </p> </div> </xsl:template> </xsl:stylesheet> when this XSLT 2.0 transformation is applied on the same XML document (above), again the same correct result is produced. Explanation: * *<xsl:for-each-group> *current-group() UPDATE: As per OP's request, here is a variation of the XSLT 1.0 solution, that also sorts by industry: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:key name="kItemByInd" match="item" use="industry"/> <xsl:template match="/*"> <xsl:apply-templates select= "item[generate-id() = generate-id(key('kItemByInd', industry)[1]) ] "> <xsl:sort select="industry"/> </xsl:apply-templates> </xsl:template> <xsl:template match="item"> <h2><xsl:value-of select="industry"/></h2> <xsl:apply-templates mode="inGroup" select="key('kItemByInd', industry)"/> </xsl:template> <xsl:template match="item" mode="inGroup"> <div class="doc"> <h3><xsl:value-of select="title"/></h3> <p> <xsl:value-of select="description"/> <a href="{link}"> Download!</a> </p> </div> </xsl:template> </xsl:stylesheet>
{ "language": "en", "url": "https://stackoverflow.com/questions/7519344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Help me understanding python's logging module and its handlers I really miss something basic about python's logging module. In the following code, I create a logger object (log) and add to it two handlers. One with 'INFO' level and one with 'WARNING' level. Both of them are supposed to print to stdout. I expect that calling to log.info(msg) will result in one copy of msg in my stdout and calling to log.warn(msg) sould result in two copies of msg printed to my stdout. Here is the code: import logging import sys logging.basicConfig() log = logging.getLogger('myLogger') log.handlers = [] h1 = logging.StreamHandler(sys.stdout) h1.level = logging.INFO h1.formatter = logging.Formatter('H1 H1 %(message)s ') h2 = logging.StreamHandler(sys.stdout) h2.level = logging.WARNING h2.formatter = logging.Formatter('H2 H2 %(message)s') log.addHandler(h1) log.addHandler(h2) print 'log.level == %s'%logging.getLevelName(log.level) print 'log.info' log.info('this is some info') print 'done' print 'log.warn' log.warn('this is a warning') print 'done' The output is really very strange to me. The .info call results in no visual effect. However, calling to warn results in two copies of msg printed to stdout (which is OK), but also one copy printed to stderr (why?). This is the output of the above code. Note the formatting of the last line in this output. This line is printed to stderr. log.level == NOTSET log.info done log.warn H1 H1 this is a warning H2 H2 this is a warning done WARNING:myLogger:this is a warning So my questions are: * *why does my call to info result in no output, despite the fact that h1's level is set to INFO? *why does my call to warn results in additional output to stderr? A: There are two things you need to know: * *The root logger is initialized with a level of WARNING. Any log message that reaches a logger is discarded if its level is below the logger's level. If a logger's level is not set, it will take its "effective level" from its parent logger. So if the root logger has a level of WARNING, all loggers have a default effective level of WARNING. If you don't configure it otherwise, all log messages with a level below that will be discarded. *When you call basicConfig(), the system automatically sets up a StreamHandler on the root logger that prints to the standard error stream. When your program prints out its log messages, there are actually three handlers: the two that you've added, which have their own levels, and one from the system that will print out any message not rejected by its logger. That's why you get the line WARNING:myLogger:this is a warning It comes from the system logger. It doesn't do this for the INFO level message, because as previously discussed, the root logger is configured to reject those messages by default. If you don't want this output, don't call basicConfig(). Further reading: http://docs.python.org/howto/logging.html A: There are actually five levels of logging: debug, info, warning, error, and critical. I see that when you are setting up your logger you aren't explicitly setting your level--I believe the logger may default to warning if the level is not set. As to why it is printing out multiple times for warning, I believe this is due to your creating two handlers for info & warning. What happens is that the logger cascades down in severity from warning -> info -> debug, calling the handler for each. Since your level is set to warning, the info handler is ignored. Also, I believe warning messages are normally written to sys.stderr. Try the following: logging.basicConfig(level=logging.INFO) See also: * *Logging module docs *Logging basic example
{ "language": "en", "url": "https://stackoverflow.com/questions/7519351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Executing CGI through Ruby web app behind Passenger I have a Rack app (call it Rails, Sinatra, etc.) running through Passenger with nginx as front server. I'm currently running on another place fossil-scm via CGI with multiple repos. I want to fuse those two making a request to the Ruby app so that the app can do the CGI request to fossil, and obtain the result back, add/modify/analyze whatever, and send it to the client. Normal fossil operations that can be done through the command line I have no problem. But to display the content of the tickets/wiki/etc. I need to run it through CGI but I don't want having CGI files for each repo lying around. I think it can/should be done with Ruby CGI lib by passing the ENV from rack to it and obtaining the response, but I'm not really sure how to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing variable from Magento I created a custom module in Magento that creates a variable with an array of order information anytime an order is placed. I now need to create some sort of mechanism or procedure that sends these variables to an external database. However, I'm not sure which route to take. Can someone point me in the right direction? EDIT: Here's what I have so far for the Observer.php file: <?php class Companyname_Dataport_Model_Observer { public function orderPaid(Varien_Event_Observer $observer) { $orderId = $observer->getPayment()->getOrder()->getId(); $orderdata = array(); $orderdata['id'] = $order->getIncrementId(); $orderdata['customername'] = $order->getCustomerFirstname() . " " . $order->getCustomerLastname(); $orderdata['price'] = $order->getPrice(); $orderdata['items'] = array(); foreach ($order->getAllItems() as $orderItem) { $item = array(); $item['productid'] = $orderItem->getProductId(); $item['qty'] = $orderItem->getQtyOrdered(); $orderdata['items'][] = $item; } // Writing to the DOM } } A: You can go around this several ways, here are two of them that I would go for: 1) Easiest: at the moment where the order is placed and you have the information, you can use PHP exec() function to call a standalone PHP file. (Where the variables are passed ofcourse) Example: exec("php /path/to/standalone/script.php ". $variable); (You might need to json_encode $variable if it's an array) This script just used the variables and connects to a local/remote database to run a query and update the information. 2) You could create a web service on the external server that can be called whenever you want from Magento There are still other ways to do this but I hope my answer contains useful information already that can get you started. A: I recomend you to use an observer, listening to an event related to order creation. For example, you could listen to sales_order_save_after and in the observer your method will take as parameter $observer. You can then access the order data with $order = $observer->getEvent()->getOrder();. Here is some code: * *config.xml: <config> ... <global> ... <events> <sales_order_save_after> <observers> <some_descriptive_string> <type>singleton</type> <class>themodelalias/observer</class> <method>theMethodToUse</method> </some_descriptive_string> </observers> </sales_order_save_after> </events> ... </global> ... </config> *Observer.php: class Yournamespace_Yourmodule_Model_Observer { public function theMethodToUse($observer) { $order = $observer->getEvent()->getOrder(); //here goes your code to send the information to your external db { } A: you can use cURL.... directly write the code in your observer.php. you will need the followung things while writing the curl.... * *url: the url where you would like to send the data *A user key and Secret *A script to receive your data at the remote site. Your data would be sent in json format.... Here is a sample sender example: $xurl='http://domain/Observer_test/';//open bravo or any other application's endpoint here $curl = curl_init(); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_URL, $xurl); curl_setopt($curl, CURLOPT_USERPWD, "111:abc"); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, array("data" => json_encode($data))); $resp = curl_exec($curl); curl_close($curl); $resp = json_decode($resp); And the sample receiver code in php(can be in any language): $userkey=$_SERVER["PHP_AUTH_USER"]; $usersecret=$_SERVER["PHP_AUTH_PW"]; $key = '111';//16 character $secret = 'abc';//32 character if(!($userkey==$key && $usersecret==$secret)) { http_response_code(403); }else{ $data = $_POST["data"]; $dir='/path/to/save/file'; $file = new SplFileObject($dir."fread.txt", "w"); $written = $file->fwrite($data); if($written){ header('Content-Type: application/json'); http_response_code(200); echo json_encode(array("stat"=>"SUCCESS")); } } So basically it is a web service following REST architecture
{ "language": "en", "url": "https://stackoverflow.com/questions/7519358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: URLs are inconsistently being redirected using ISAPI urlrewrite 3.0 I'm trying to create some friendly urls. * *search/real *searc/tpp everything is working fine except the browser changes to reflect the unfriendly url. Even though I am not specifying a redirect. Please see the last two lines of my .htaccess file below. It seems intermittent too. RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} (www.sarasotaproperty.net|www.sc-pa.net) [nc] RewriteRule ^(.*)$ http://www.sc-pa.com/$1 [R=301,NC,QSA] RewriteMap lc int:tolower RewriteCond %{REQUEST_URI} [A-Z] RewriteCond %{REQUEST_URI} !.*(js|css|inc|jpg|gif|png) RewriteRule (.*) ${lc:$1} [R=301,L] RewriteCond %{REQUEST_URI} !.*web_content/pdf/.* RewriteCond %{SCRIPT_FILENAME} !-d RewriteCond %{SCRIPT_FILENAME} !-f RewriteRule (?!.*/web_content/pdf/)([^/]*?\.pdf) /web_content/pdf/$1 [R=301] RewriteRule pasite-(.*\.asp)$ /content/$1 [R=301,QSA] RewriteRule home\.asp$ / [R=301,QSA,L] RewriteRule ^.*search/real/?$ /content/search_real_property.asp <--my problem child 1 RewriteRule ^.*search/tpp/?$ /content/search_tangible.asp <--problem child 2 # Rewrite script ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (2) init rewrite engine with requested uri /content/search_real_property.asp ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '^(.*)$' to uri 'content/search_real_property.asp' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '(.*)' to uri 'content/search_real_property.asp' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (4) RewriteCond: input='/content/search_real_property.asp' pattern='[A-Z]' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'content/search_real_property.asp' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'content/search_real_property.asp' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern 'home\.asp$' to uri 'content/search_real_property.asp' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '^.*search/real/?$' to uri 'content/search_real_property.asp' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'content/search_real_property.asp' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (2) init rewrite engine with requested uri /include/css/site.css ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern '^(.*)$' to uri 'include/css/site.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern '(.*)' to uri 'include/css/site.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (4) RewriteCond: input='/include/css/site.css' pattern='[A-Z]' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'include/css/site.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'include/css/site.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern 'home\.asp$' to uri 'include/css/site.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern '^.*search/real/?$' to uri 'include/css/site.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'include/css/site.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (2) init rewrite engine with requested uri /include/css/csshorizontalmenu.css ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern '^(.*)$' to uri 'include/css/csshorizontalmenu.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern '(.*)' to uri 'include/css/csshorizontalmenu.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (4) RewriteCond: input='/include/css/csshorizontalmenu.css' pattern='[A-Z]' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'include/css/csshorizontalmenu.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'include/css/csshorizontalmenu.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern 'home\.asp$' to uri 'include/css/csshorizontalmenu.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern '^.*search/real/?$' to uri 'include/css/csshorizontalmenu.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'include/css/csshorizontalmenu.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (2) init rewrite engine with requested uri /Include/js/JavaFunctions.js ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '^(.*)$' to uri 'Include/js/JavaFunctions.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '(.*)' to uri 'Include/js/JavaFunctions.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (4) RewriteCond: input='/Include/js/JavaFunctions.js' pattern='[A-Z]' => matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (4) RewriteCond: input='/Include/js/JavaFunctions.js' pattern='.*(js|css|inc|jpg|gif|png)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'Include/js/JavaFunctions.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'Include/js/JavaFunctions.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern 'home\.asp$' to uri 'Include/js/JavaFunctions.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '^.*search/real/?$' to uri 'Include/js/JavaFunctions.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'Include/js/JavaFunctions.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (2) init rewrite engine with requested uri /include/js/jquery-1.4.4.js ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (3) applying pattern '^(.*)$' to uri 'include/js/jquery-1.4.4.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (3) applying pattern '(.*)' to uri 'include/js/jquery-1.4.4.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (4) RewriteCond: input='/include/js/jquery-1.4.4.js' pattern='[A-Z]' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'include/js/jquery-1.4.4.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'include/js/jquery-1.4.4.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (3) applying pattern 'home\.asp$' to uri 'include/js/jquery-1.4.4.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (3) applying pattern '^.*search/real/?$' to uri 'include/js/jquery-1.4.4.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692832/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'include/js/jquery-1.4.4.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (2) init rewrite engine with requested uri /include/js/HoverDropDwn.js ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern '^(.*)$' to uri 'include/js/HoverDropDwn.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern '(.*)' to uri 'include/js/HoverDropDwn.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (4) RewriteCond: input='/include/js/HoverDropDwn.js' pattern='[A-Z]' => matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (4) RewriteCond: input='/include/js/HoverDropDwn.js' pattern='.*(js|css|inc|jpg|gif|png)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'include/js/HoverDropDwn.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'include/js/HoverDropDwn.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (2) init rewrite engine with requested uri /include/js/jquery.hoverIntent.minified.js ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern 'home\.asp$' to uri 'include/js/HoverDropDwn.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern '^.*search/real/?$' to uri 'include/js/HoverDropDwn.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'include/js/HoverDropDwn.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (3) applying pattern '^(.*)$' to uri 'include/js/jquery.hoverIntent.minified.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (3) applying pattern '(.*)' to uri 'include/js/jquery.hoverIntent.minified.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (4) RewriteCond: input='/include/js/jquery.hoverIntent.minified.js' pattern='[A-Z]' => matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (4) RewriteCond: input='/include/js/jquery.hoverIntent.minified.js' pattern='.*(js|css|inc|jpg|gif|png)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'include/js/jquery.hoverIntent.minified.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (2) init rewrite engine with requested uri /include/css/print.css ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'include/js/jquery.hoverIntent.minified.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (3) applying pattern 'home\.asp$' to uri 'include/js/jquery.hoverIntent.minified.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (3) applying pattern '^.*search/real/?$' to uri 'include/js/jquery.hoverIntent.minified.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691200/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'include/js/jquery.hoverIntent.minified.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '^(.*)$' to uri 'include/css/print.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '(.*)' to uri 'include/css/print.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (4) RewriteCond: input='/include/css/print.css' pattern='[A-Z]' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'include/css/print.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'include/css/print.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern 'home\.asp$' to uri 'include/css/print.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '^.*search/real/?$' to uri 'include/css/print.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'include/css/print.css' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (2) init rewrite engine with requested uri /include/js/jquery.cookie.js ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern '^(.*)$' to uri 'include/js/jquery.cookie.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern '(.*)' to uri 'include/js/jquery.cookie.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (4) RewriteCond: input='/include/js/jquery.cookie.js' pattern='[A-Z]' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'include/js/jquery.cookie.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'include/js/jquery.cookie.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern 'home\.asp$' to uri 'include/js/jquery.cookie.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern '^.*search/real/?$' to uri 'include/js/jquery.cookie.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'include/js/jquery.cookie.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (2) init rewrite engine with requested uri /include/js/jquery.easing.1.1.js ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern '^(.*)$' to uri 'include/js/jquery.easing.1.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern '(.*)' to uri 'include/js/jquery.easing.1.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (4) RewriteCond: input='/include/js/jquery.easing.1.1.js' pattern='[A-Z]' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (2) init rewrite engine with requested uri /images/header.jpg ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'include/js/jquery.easing.1.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'include/js/jquery.easing.1.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern 'home\.asp$' to uri 'include/js/jquery.easing.1.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern '^.*search/real/?$' to uri 'include/js/jquery.easing.1.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern '^(.*)$' to uri 'images/header.jpg' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern '(.*)' to uri 'images/header.jpg' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (4) RewriteCond: input='/images/header.jpg' pattern='[A-Z]' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'images/header.jpg' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'images/header.jpg' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern 'home\.asp$' to uri 'images/header.jpg' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern '^.*search/real/?$' to uri 'images/header.jpg' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17692424/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'images/header.jpg' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (2) init rewrite engine with requested uri /include/js/HoverImg.js ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '^(.*)$' to uri 'include/js/HoverImg.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '(.*)' to uri 'include/js/HoverImg.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (4) RewriteCond: input='/include/js/HoverImg.js' pattern='[A-Z]' => matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (4) RewriteCond: input='/include/js/HoverImg.js' pattern='.*(js|css|inc|jpg|gif|png)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'include/js/HoverImg.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'include/js/HoverImg.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern 'home\.asp$' to uri 'include/js/HoverImg.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '^.*search/real/?$' to uri 'include/js/HoverImg.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'include/js/HoverImg.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17689976/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'include/js/jquery.easing.1.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (2) init rewrite engine with requested uri /include/js/jcarousellite_1.0.1.js ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '^(.*)$' to uri 'include/js/jcarousellite_1.0.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '(.*)' to uri 'include/js/jcarousellite_1.0.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (4) RewriteCond: input='/include/js/jcarousellite_1.0.1.js' pattern='[A-Z]' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '(?!.*/web_content/pdf/)([^/]*?\.pdf)' to uri 'include/js/jcarousellite_1.0.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern 'pasite-(.*\.asp)$' to uri 'include/js/jcarousellite_1.0.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern 'home\.asp$' to uri 'include/js/jcarousellite_1.0.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '^.*search/real/?$' to uri 'include/js/jcarousellite_1.0.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17693240/initial] (3) applying pattern '^.*search/tpp/?$' to uri 'include/js/jcarousellite_1.0.1.js' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (2) init rewrite engine with requested uri /images/AllHazardsButton.jpg ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (1) Htaccess process request c:\proj\www\.htaccess ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '^(.*)$' to uri 'images/AllHazardsButton.jpg' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (4) RewriteCond: input='localhost' pattern='(www.sarasotaproperty.net|www.sc-pa.net)' => not-matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (3) applying pattern '(.*)' to uri 'images/AllHazardsButton.jpg' ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (4) RewriteCond: input='/images/AllHazardsButton.jpg' pattern='[A-Z]' => matched ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (2) init rewrite engine with requested uri /images/SheltersButton.jpg ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17690792/initial] (1) Htaccess process request C:\Program Files\Helicon\ISAPI_Rewrite3\httpd.conf ::1 ::1 Fri, 23-Sep-2011 11:25:04 GMT [localhost/sid#1][rid#17691608/initial] (4) RewriteCond: input='/images/AllHazardsButton.jpg' pattern='.*(js|css|inc|jpg|gif|png)' => not-matched A: If redirect occurs in ISAPI_Rewrite, you can see it in rewrite.log (you can show a part of it here and I'll tell you if redirect is there). And as LazyOne already said make sure redirect does not occur on your asp page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: stopping a function with animations in it with jquery/javascript Im building a custom timed image slider for a site, and im stuck on a basic principle. I have a recursive function that starts on the pageload. Im wondering how to immediatly stop the function and then restart it at the beginning with an onclick. In the follwing jsfiddle example, can someone please tell me how i make the red square start at margin 0 and then start the bounce() function again, when the 'blue' or 'green' button is clicked? for example: if the red square is towards the right, when 'blue' is clicked, how can i make the square appear at 'margin-left:0' and then have the bounce() function start again? Thanks so much. http://jsfiddle.net/hZ6xZ/7/ A: Fiddle - http://jsfiddle.net/mrtsherman/hZ6xZ/9/ Use jQuery's stop() to kill the current animation. Also take a look into method chaining which is more efficient than calling $('#box') a lot of times. $('#blue').click(function(){ repeat = clearTimeout(repeat); $('.box') .stop() .css({'background-color':'blue'}) .css({'margin-left':'0'}); bounce(); }); A: It's easy, jQuery got a function named stop() that stops animations, it also supports jump to end of animation and clear queue. Just form your bounce function like this: var repeat; function bounce(){ $('.box') .stop() .css({'margin-left':'0px'}) .animate({'margin-left':'100px'}) .animate({'margin-left':'0px'}); repeat = setTimeout(function() { bounce(); }, 2000); } For more details about stop: http://api.jquery.com/stop/
{ "language": "en", "url": "https://stackoverflow.com/questions/7519363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to embed an excel pivot graph as a webpart? I have published my Excel workbook (which is one sheet with pivot-data linked to SQL Server and one sheet with stacked graph based on that data) to sharepoint 2010, and can view the chart fine via excel services xlviewer.aspx I would now like to have the chart shows on our team's front page, by embedding a webpart to show the graph. I've been able to achieve this by adding a Page Viewer part (IFrame) that links to the workbook, but this doesn't seem ideal (it requires setting the height, and it shows all the extra toolbars etc.) I tried to insert a Chart web part linked to the excel workbook, but I do not know how to specifify the range name - I tried to use the same data range as in the pivot chart in my workbook ([Workbook.xlsx]WorkSheet!PivotTable), but I get the error: Exception has been thrown by the target of an invocation. Does anyone know if what I want it possible? A: Todd has answered it above (thanks!) Basically I (being a sharepoint novice) failed to find the Excel Web Access web part... once I'd got this, it was easy!
{ "language": "en", "url": "https://stackoverflow.com/questions/7519369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP displaying as plaintext http://www.clare-ents.com/test/index.php Using a new host... I know it's something to do with .htaccess and I've got it in the root folder: AddType application/x-httpd-php .php But it still doesn't work. Any ideas? A: A HEAD request to that URL says: Content-Type: application/x-httpd-php This suggests that your webserver does support .htaccess configuration but does not have the PHP module loaded. Consult your system administrator. A: Your server is probably missing PHP module loaded in your apache.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to automatically overwrite the output file when running `gpg` (i.e. without being prompted)? If I have the same filename in the target directory, decryption fails. The command I'm using to decrypt: gpg --passphrase-fd 0 -o D:/Notification/mytest.txt --batch \ --passphrase-file D:/passphrase.txt -d D:/Notification/mytest.gpg It doesn't overwrite the mytest.txt file so each time I need to delete the file before I execute the script. Is there any option to overwrite the output fie? A: Just add the --yes option to you command line. The --yes option assumes yes for most questions which gpg will prompt for. Source: http://www.gnupg.org/gph/de/manual/r1023.html A: Adding --batch --yes Example: gpg --batch --yes -u me@bbb.com -r "you@aaa.com" \ --output "OUTPUTFILENAME.xls.pgp" -a -s -e "FILE.xls" Complete example with passphrase file: gpg --batch --yes --passphrase-fd 0 -u me@bbb.com -r "you@aaa.com" \ --output "OUTPUTFILENAME.xls.pgp" -a -s -e "FILE.xls"< \ passphrase.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/7519375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "63" }
Q: NSTableView drag cell to NSView Could someone nudge me in the right direction on this. I want to drag a NSString from a table cell to a NSView and then do something based on that string but the drag and drop stuff has my head spinning a bit. Anyway know of a straight forward tutorial that can explain all this. Thanks A: The table view data source has a method for starting a drag operation. Here's a little code to start the dragging: - (BOOL)tableView:(NSTableView *)aTableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pboard { NSString *myString = ...; // code to get a string from the indexes in rowIndexes return [pboard setString:myString forType:NSPasteboardTypeString]; } For receiving drag operations, I think there has been enough written about it: This is an older tutorial (2002), but I think it should still be valid. Just be sure to check the documentation about deprecated methods/names (or look at the compiler warnings): http://cocoadevcentral.com/articles/000056.php Apples drag and drop programming guide Or this stack overflow question with links to sample code: Cocoa multi window drag and drop example
{ "language": "en", "url": "https://stackoverflow.com/questions/7519377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Optimization. Loading dialog doesn't appear right away when user submits a form I am working on a web application that allows user to view and interact with large (metabolic) networks displayed in SVG format. It can be viewd here link. I have fairly large amount of jQuery code that handles different events. Particularly when user submits a form the submit function gets executed. The first thing I do in the function is display modal dialog that blocks UI and tells user that the page is loading. $('#indexForm').submit(function() { dialog.dialog('open'); ... After that the function manipulates elements on the webpage, loads large network XML via AJAX and appends it to the page. After all of the manipulations are complete the dialog disappears and user can start interacting with the page again. My problem is in the latency that exists between the moment of clicking on submit button to the moment of showing the dialog. UI is frozen for a noticeable amount of time right after user presses submit. I am suspecting that the browser is overwhelmed by the amount of elements that are on the page (SVG map has a lot of elements ~3mb) therefore it cannot react on the events like form submit immediately. Looking forward for any explanations and suggestions to improve my code and fix this problem. A: try adding ur dialog to open on a click event and not within the submit so: $("#indexForm").click(function(){ dialog.dialog('open'); }); to see if that helps performance at all A: The problem is in the size of the SVG rendered in on the webpage. Latency started to decrease once I tried to optimize the SVG data (I got read of many elements).
{ "language": "en", "url": "https://stackoverflow.com/questions/7519387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use ThreadPool or Thread I had 1 collection which I was saving the content to a persistent storage. Then I ended up having 3 collections which i like to save to a persistent storage. At first I was using a ThreadPool to save one collection, but now I have 3 collections.Since each collection goes to a different storage, I dont want to combine them or save to same place. My question is should i use manual Threads and create one thread for each Save() method or should I create 3 thread pool for each method, or should i call all the 3 methods in one ThreadPool.QueueUserWorkItem call. 1.First Approach ThreadPool.QueueUserWorkItem(o => { Save<Foo>(ConcurrentCollectionStorage.Bus1); Save<Bar>(ConcurrentCollectionStorage.Bus2); Save<Car>(ConcurrentCollectionStorage.Bus3); }); 2. Second Approach ThreadPool.QueueUserWorkItem(o => { Save<Foo>ConcurrentCollectionStorage.Bus); }); ThreadPool.QueueUserWorkItem(o => { Save<Bar>(ConcurrentCollectionStorage.Bus2); }); ThreadPool.QueueUserWorkItem(o => { Save<Car>(ConcurrentCollectionStorage.Bus3); }); 3. Third Approach. Creating Thread Manually and join them. While doing these operations I dont want my application to hang. I want it to process and save the data, and complete, but not to affect the foreground processes, the whole application. What s the best way to do this? Which one should I use? Is there a better way to do this? A: Since each collection goes to a different storage, I dont want to combine them or save to same place. While doing these operations I dont want my application to hang. I want it to process and save the data, and complete, but not to affect the foreground processes, the whole application. Queue three threads in the thread pool. A: With .NET 4.0 you can use the Task Parallel Library: Task.Factory.StartNew(() => { Save<Foo>(ConcurrentCollectionStorage.Bus1); }); Task.Factory.StartNew(() => { Save<Bar>(ConcurrentCollectionStorage.Bus2); }); Task.Factory.StartNew(() => { Save<Car>(ConcurrentCollectionStorage.Bus3); }); However, it isn't clear from your question what the critical bottleneck is. The TPL can't help you if you're bottleneck is Disk IO or network latency. If you want your main thread to wait for them all to complete, you can do this (there are several ways to do it): Task t1 = Task.Factory.StartNew(() => { Save<Foo>(ConcurrentCollectionStorage.Bus1); }); Task t2 = Task.Factory.StartNew(() => { Save<Bar>(ConcurrentCollectionStorage.Bus2); }); Task t3 = Task.Factory.StartNew(() => { Save<Car>(ConcurrentCollectionStorage.Bus3); }); Task.WaitAll(t1,t2,t3); This way the thread running the tasks will wait until they finish. t1,t2, and t3 will be running asynchronously. A: if you are using .net 4 you should use TASK instead of calling the ThreadPool API. If your save operation is short use it as is. in case it is long and that is why you are considering manual thread then you should use task but mark it as "long running" HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/7519392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }