text
stringlengths
8
267k
meta
dict
Q: unity3d, animation stuck at 1st frame i have a menu scene and scene A, scene B. when i go to scene A, a 3D object will play some animation, and i have some button to click and make it animation also, but from menu if i go to scene B, i come back to menu then i go scene A, all the animation in scene A will not working, "animation.isPlaying" is showing true. if i disable the starting animation, and click those animate button, "animation.isPlaying" turn from false to true also. but it just wont move, just like stuck at 1st frame, any help will be appreciate... A: problem fix, in case you want to know why, is because i stop the "time" at another scene, and i didn't expect that it will still remain even when the scene was killed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In SharePoint 2010 how can I add user selected WebParts at run time? I am quite new to SharePoint and have been given an interesting problem to solve. My users have requested to each have a custom home page that they can customise with ease. The design I have been given is to have an almost blank page with space for 4 webparts organised in a 2 by 2 fashion (2 webparts by 2 webparts) each with a big '+' button in witch to click to select and add a widget of their choosing without having to play around with the ribbon. This is expected to look something like this: http://imageshack.us/photo/my-images/841/homepages.jpg/ Now when a user clicks a '+' a SharePoint dialog is to be displayed allowing the user to choose from all available web parts. On selecting one the home page is refreshed and the widget is displayed in the selected zone. I am currently trying to de-risk this request to see if it is possible to achieve in the time frame given. The problems I have at the moment are as follows: * *Programmatically getting a list of all available webparts to display in the dialog. *On the selection of the webpart programmatically adding that chosen webpart to the correct part of the home page without hard coding the type of webpart (so the code does not need to be changed when a new webpart is added to SharePoint for users to add). I would really appreciate any help or advice on this. Thanks in advance and sorry if the question is well phrased, this is my first Stack Overflow question! A: Just create a webpart that does that. Render a big plus sign and when a user clicks there, the event handler gets all webparts available and renders it to a dropdownlist for instance. The rest is easy, when a user selects one, get it (by guid/name whatever) and add it to the zone where the first webpart was present, not forgetting to remove the plus sign webpart from the clicked webpart zone first. This can be achieved using the SPLimitedWebPartManager. The tricky part could be the Webparts that are available on the SiteCollection, but you could research on that. Regards, Pedro
{ "language": "en", "url": "https://stackoverflow.com/questions/7636244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: The "property" property of the meta tag is missing in response when getting open graph data, using jquery, cross-domain ajax and YQL I'm using jquery 1.5.1, James Padolsey Cross Domain Ajax 0.11 which uses YQL to get external sites. this is my code $.ajax({ url: "http://ogp.me/", type: "GET", crossDomain: true, success: function (res) { console.log($(res.responseText)); }); The problem is that in the responseText, all meta tags are missing the "property" property. this is what the source code of the page looks like: <meta property="og:title" content="Open Graph Protocol" /> this is what firebug shows the responseText value is: <meta content="Open Graph Protocol"/> Is this a YQL problem? Is there a better way to get open graph data from external sites? A: For anyone that's still coming across this question, you just have to add AND compat="html5" to your queries and you will get the property attributes in your results. A: YQL's html data table, which is being used by that cross-domain AJAX plugin, runs HTML Tidy (info) on the HTML returned from the remote server. During this process, the property attributes that you are looking for are removed (likely because Tidy sees them as invalid).
{ "language": "en", "url": "https://stackoverflow.com/questions/7636247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LogCat error spamming: old mainboard version This error adds to my LogCat view for android many times a second! It occurs when I run my application from eclipse on my ZTE blade android 2.2. It does not matter what application I run by the way. Anyone know how I should find out how to solve this problem or actually knows what's wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/7636260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to retrieve String's and write them to a file or resource and overrwrite and reuse it? I am retrieving about 7 URL's from a service. I want to be able to write these URL's some where and have my application read from them in another activity. The thing that makes this tricky is the URL's change every week. So i would need to overwrite the current URL's. I don't want to make the url's stack up on top of each other where they never overrite and by the end of a month there are 24 unused URL's. What and how is the best way to do this? A: Use SharedPreferences! lol here is a sample: public void SetUrls(String url[]) { SharedPreferences settings = getSharedPreferences("myPrefs", 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("url0", url[0]); editor.putString("url1", url[1]); editor.putString("url2", url[2]); editor.putString("url3", url[3]); editor.putString("url4", url[4]); editor.putString("url5", url[5]); editor.putString("url6", url[6]); editor.commit(); } public String[] getUrls() { SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0); String url[] = new String[7]; url[0] = settings.getString("url0", "default"); url[1] = settings.getString("url1", "default"); url[2] = settings.getString("url2", "default"); url[3] = settings.getString("url3", "default"); url[4] = settings.getString("url4", "default"); url[5] = settings.getString("url5", "default"); url[6] = settings.getString("url6", "default"); return url; } A: it really depends on your client implementation, you can store them in sqlite, or in local cache or shared preferences. Android allows apps to have a small cache. As you store your urls you can timestamp them and check if they have expired and stuff. Refere to the docs on android Data Storage facilities.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: uiscrollview subclass just creating a subclass of uiscrollview here and im trying to catch a -(void)scrollViewDidScrollUIScrollView *)scrollView{} in it but for some reason it is not registering. @interface WallScrollView : UIScrollView{ } @end @implementation WallScrollView -(id)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; self.userInteractionEnabled = YES; return self; } -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ //some ultra fancy code //this code is not called for some reason } -(void)dealloc{ [super dealloc]; } @end any ideas as to what im missing or doing wrong here? basically want to catch viewdidscroll. thanks A: You do not need to subclass the UIScrollView. Simply implement the - (void)scrollViewDidScroll:(UIScrollView *)scrollView method in your delegate and set the delegate to your scrollview instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best way of create BroadcastReceiver? I have spent few days to work on Service + BroadcastReceiver, but still cannot make it perfect. I hope someone can help, thanks! I am writing a App that show user current location on map(The map that I wrote, not Google Map) and send out Notification alarm when user go inside a predefined zone. In my code. there are two main objects. A GPS service and Main Activity. The GPS service broadcast location when location changed. The Main Activity receive the latest location by BroadcastReceiver. I have done some researches on how to register BroadcastReceiver. There are two ways that I found: Method 1 - Register Broadcast Receiver inside Activity (I am using this method in my code. I need to update latest location on map) Main.java: public class Main extends Activity{ . . . public class MyLocReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Bundle bundle=intent.getExtras(); String locData = bundle.getString("loc"); // Some work } public MyLocReceiver(){ Log.e(TAG, "in MyReceiver()"); } } private MyLocReceiver myLocReceiver; // Register BroadcastReceiver if (myLocReceiver == null) { Common.writeFile("service.txt", "Main - in myBindService() register receiver" + "\n", true); myLocReceiver=new MyLocReceiver(); registerReceiver(myLocReceiver, new IntentFilter("com.nwfb.LOC_DATA")); } Method 2 - Register BroadcastReceiver at Manifest.xml Manifest.xml: <receiver android:name=".LocationBoardcastReceiver" android:enabled="true"> <intent-filter> <action android:name="com.abc.LOC_DATA" /> </intent-filter> </receiver> LocationBoardcastReceiver.java: public class LocationBoardcastReceiver extends BroadcastReceiver { private static final String TAG = LocationBoardcastReceiver.class.getSimpleName(); @Override public void onReceive(Context context, Intent intent) { Bundle bundle=intent.getExtras(); // Do something } } * What I want is the BroadcastReceiver MUST NOT KILLED by the OS in the application life time. Also the BroadcastReceiver must able to pass data to my Main.java I read this actical: http://developer.android.com/reference/android/content/BroadcastReceiver.html The section of 'Receiver Lifecycle' and 'Process Lifecycle' state that the BroadcastReceiver will be finished and no longer active after onReceive(Context, Intent) called. I am using Method 1, I can receive more than 1 Location data from the Service. I found that the BroadcastReceiver keeps alive if the BroadcastReceiver keeps receiving data from the Broadcast. If I turn off GPS at 'Setting -> Location ' and let the BroadcastReceiver idle for about 1 to 2 hours, then the BroadcastReceiver will killed by OS. Does the OS kill BroadcastReceiver if it idle too long? Does the OS NOT kill the BroadcastReceiver if it keeps receiving broadcast? Will the BroadcastReceiver (Method 1 and 2) killed by OS when it is under cases of extreme memory pressure? For Method 2, is it possible that the LocationBoardcastReceiver.java send data to a running activity (Eg: Main,java)? For Method 1, is it any way to keep the BroadcastReceiver alive during the life time of the Main.java (Main Activity)? A: * *Android OS can kill Services and Activities any time it pleases. There is nothing you can do about it. *You can set broadcast receiver to start a service even if app is not active. *If you want to receive location updates ALL THE TIME, you will need to have device awake all the time. This will drain battery in the matter of hours. For best practices on location updates read this: http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html?m=1 A: Does the OS kill BroadcastReceiver if it idle too long? Does the OS NOT kill the BroadcastReceiver if it keeps receiving broadcast? Will the BroadcastReceiver (Method 1 and 2) killed by OS when it is under cases of extreme memory pressure? Your receiver comes in action when it receives any notification and it's active duration is it's onReceive() Method. For Method 2, is it possible that the LocationBoardcastReceiver.java send data to a running activity (Eg: Main,java)? Bad idea. For Method 1, is it any way to keep the BroadcastReceiver alive during the life time of the Main.java (Main Activity)? Check above. Your best way will depend over your app what it requires. * *If your app wants to use BroadcastReceiver while app is in foreground then you should go for Method1 as you have mentioned. *If your app need to receive system's notification as Boot Completion etc then you should go for Method2 as you have mentioned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Select elements with class except one with specific id $('.ui-widget-content').css('border','none'); $('#helpDialog .ui-widget-content').addClass('HelpDialogBorder'); I am doing like this to remove border. But, there is an element where I want to keep border. Is there any way in first line itself to select all elements with class "ui-widget-content" but except one with id "helpDialog"? A: Sure, use :not(): $('.ui-widget-content:not(#helpDialog)').css('border', 0); A: Try this (also see my jsfiddle): $('.ui-widget-content').not('#helpDialog').css('border','none'); A: You can try this $('.ui-widget-content').not('#id')
{ "language": "en", "url": "https://stackoverflow.com/questions/7636275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Changing configuration options of a CKEditor instance I have a CKEditor instance attached to a textarea. I would like to be able change some configuration options of this instance after its creation, depending on the value of another form field. Is it possible to do this, or else it's necessary to destroy the instance and attach another one, with the new options? I've checked in the CKEditor docs, but found nothing about this subject. Thanks in advance, A: Usually the configuration options will work only upon creation. You might be able to perform some tricks and so get some of the options to work at a later time, but that's usually more difficult. A: I know I am late. But I would like to share this. If you decide on a config before the creation of a ckeditor instance and plan on overriding those configurations, it's not possible. You can definitely add more config options but cannot change any existing option. Say you pass a config object while creation of an instance. CKEDITOR will internally call replace function to create the instance. Which will, in turn, check if anything is present in config.js. You provide some extra config option and also, you try to override any existing option, for eg., toolbar. Internally, CKEDITOR will do an extend and will try to merge already existing config object and the new config object provided by config.js and finally create a new config object which it will use to create the instance. When it extends, i.e tries to merge both the config object, it will take all the new config options and assign to final new config object. But, for existing config options which you tried to override in config.js, it will take the original option and assign to this new config object. Hence, whatever you had provided to override existing config object is lost. One option which you have is to destroy the current instance and use your new config object to create the instance. I hope I was able to explain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to stop the loading circle in browsers? Imagine I have a flash mp3 player and when the page loads the player starts to play a song. So while flash is downloading the mp3 file the browser reports the page like it's still loading. Which I understand, there are still active downloads. But a client wants me to somehow tell the browser not to show this progress (like the circle in chrome) for the files the player downloads. Is there a way to do that? Thanks A: A similar question was posted here: How to hide "page loading"/"transferring data" indicators and spinners caused by loading a (hidden) iframe with a solution that might work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IIS 7 URL rewrite regular expression Using IIS7 URL rewrite module, I am trying to get the value of a specific query string parameter, and if it exists I need to get the value of that parameter. Example URL : test.aspx?F5REDIRECTION&SearchType=HeaderSearch&hiddendims=&Keyword=tshirt&nkw=1&vsp=2 I need to check if "Keyword" parameter exists and I need to get the value "t-shirt". If I test run this pattern : ^.*F5REDIRECTION&SearchType=Header.*Keyword=(.*)$ the result is "tshirt&nkw=1&vsp=2" How do I get only "tshirt"? A: Try something like this: (?<=\?|&)Keyword=(.*?)(?=&|$) Or if lookarounds aren't available: (?:\?|&)Keyword=(.*?)(?:&|$)
{ "language": "en", "url": "https://stackoverflow.com/questions/7636283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java 7 socket listen exception I have java 7 socket listen exception during jboss initialization. JAVA: c:\Program Files\Java\jdk1.7.0\\bin\java 17:14:15,388 INFO [WebService] Using RMI server codebase: http://127.0.0.1:8083/ 17:14:15,405 ERROR [AbstractKernelController] Error installing to Start: name=jboss:service=WebService state=Create mode=Manual requiredState=Installed java.net.SocketException: Permission denied: listen failed When I set JAVA_HOME to c:\Program Files\Java\jdk1.6.0.26 there are no exceptions during jboss initialization. A: My guess is that this is Windows firewall - that it's got an exception (i.e. a permission) for the JDK 6 binary, but not for the JDK 7 binary. I suggest you open up the Windows firewall configuration applet, check what's there (either by port or binary) and give JDK 7 the same permission. EDIT: I suggest you get JBoss out of the equation: write a small app which simply tries to listen on port 8083 on 127.0.0.1. Try running that on both JDK6 and JDK7. If that works in both out of the box, then try varying exactly how you specify the listening port.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Could not find artifact org.codehaus.mojo:mojo-sandbox:pom:3-SNAPSHOT in codehaus snapshot Does anyone know why I get this error even if I forced the update (-U) ? This error came about when I tried to build this POM.xml. [POM.XML] <?xml version="1.0" encoding="UTF-8"?><project> <modelVersion>4.0.0</modelVersion> <groupId>wrox</groupId> <artifactId>pixweb</artifactId> <packaging>war</packaging> <version>0.0.1</version> <description></description> <repositories> <repository> <id>New central Maven repo</id> <url>http://repo2.maven.org/maven2/</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>codehaus snapshot</id> <url>http://snapshots.repository.codehaus.org</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> <build> <sourceDirectory>src/main/java</sourceDirectory> <testSourceDirectory>src/test/java</testSourceDirectory> <resources> <resource> <filtering>true</filtering> <directory>src/main/java</directory> <excludes> <exclude>**/*.java</exclude> </excludes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> </resources> <testResources> <testResource> <filtering>true</filtering> <directory>src/test/java</directory> <excludes> <exclude>**/*.java</exclude> </excludes> </testResource> <testResource> <directory>src/test/resources</directory> </testResource> </testResources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> <plugin> <artifactId>maven-eclipse-plugin</artifactId> <configuration> <wtpversion>1.0</wtpversion> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>xfire-maven-plugin</artifactId> <version>1.0-SNAPSHOT</version> <executions> <execution> <goals> <goal>wsgen</goal> </goals> </execution> </executions> <configuration> <package>com.wrox.webservice.emailvalidation.client</package> <overwrtite>true</overwrtite> <generateServerStubs>false</generateServerStubs> <forceBare>false</forceBare> <outputDirectory>${project.build.directory}/generated-sources</outputDirectory> <wsdls> <wsdl>http://ws.xwebservices.com/XWebEmailValidation/V2/XWebEmailValidation.wsdl</wsdl> </wsdls> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${taglibs-standard-version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl-version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet-api-version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jpa</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.2.1.ga</version> <exclusions> <exclusion> <artifactId>jta</artifactId> <groupId>javax.transaction</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>geronimo-spec</groupId> <artifactId>geronimo-spec-jta</artifactId> <version>1.0.1B-rc4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webflow</artifactId> <version>${spring-webflow-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-mock</artifactId> <version>${spring-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>${hsqldb-version}</version> </dependency> <dependency> <groupId>org.directwebremoting</groupId> <artifactId>dwr</artifactId> <version>${dwr-version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>${commons-lang-version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j-version}</version> </dependency> <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>1.4.8</version> </dependency> <dependency> <groupId>rome</groupId> <artifactId>rome</artifactId> <version>0.9</version> </dependency> <dependency> <groupId>org.codehaus.xfire</groupId> <artifactId>xfire-aegis</artifactId> <version>${xfire-version}</version> </dependency> <dependency> <groupId>org.codehaus.xfire</groupId> <artifactId>xfire-core</artifactId> <version>${xfire-version}</version> </dependency> <dependency> <groupId>org.codehaus.xfire</groupId> <artifactId>xfire-spring</artifactId> <version>${xfire-version}</version> <exclusions> <exclusion> <artifactId>spring</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.codehaus.xfire</groupId> <artifactId>xfire-java5</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>org.codehaus.xfire</groupId> <artifactId>xfire-generator</artifactId> <version>${xfire-version}</version> <scope>compile</scope> <exclusions> <exclusion> <artifactId>spring</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.codehaus.xfire</groupId> <artifactId>xfire-jaxws</artifactId> <version>${xfire-version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-core</artifactId> <version>${activemq-version}</version> </dependency> <dependency> <groupId>fm.void.jetm</groupId> <artifactId>jetm</artifactId> <version>${jetm-version}</version> </dependency> <dependency> <groupId>fm.void.jetm</groupId> <artifactId>jetm-optional</artifactId> <version>${jetm-version}</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>${cglib-version}</version> </dependency> </dependencies> <properties> <activemq-version>4.1.1</activemq-version> <spring-webflow-version>1.0.3</spring-webflow-version> <spring-version>2.0.5</spring-version> <junit-version>3.8.2</junit-version> <commons-lang-version>2.1</commons-lang-version> <dwr-version>2.0.1</dwr-version> <jstl-version>1.0</jstl-version> <taglibs-standard-version>1.1.1</taglibs-standard-version> <hsqldb-version>1.8.0.7</hsqldb-version> <servlet-api-version>2.5</servlet-api-version> <log4j-version>1.2.14</log4j-version> <commons-fileupload-version>1.1.1</commons-fileupload-version> <xfire-version>1.2.4</xfire-version> <jetm-version>1.2.1</jetm-version> <cglib-version>2.1_3</cglib-version> </properties> </project> [ERROR MSG]. Btw, I replaced the http with http1. Error Trace here A: The error comes when maven is trying to download dependencies for Maven XFire plugin. According to the documentation, the plugin is deprecated. It was last updated in 2006. It is having a SNAPSHOT version and may be referring to dependencies which are incorrect/outdated. A: Had same problem. Changing the coordinates of the plugin to: <groupId>org.apache.servicemix.tooling</groupId> <artifactId>xfire-maven-plugin</artifactId> <version>4.0</version> made it work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Magento/Google import script I have the following script taken from another Stack Overflow answer. <?php define('SAVE_FEED_LOCATION','google_base_feed.txt'); set_time_limit(1800); require_once '../app/Mage.php'; Mage::app('default'); try{ $handle = fopen(SAVE_FEED_LOCATION, 'w'); $heading = array('id','mpn', 'upc','title','description','link','image_link','price','brand','product_type','condition', 'google_product_category', 'manufacturer', 'availability'); $feed_line=implode("\t", $heading)."\r\n"; fwrite($handle, $feed_line); $products = Mage::getModel('catalog/product')->getCollection(); $products->addAttributeToFilter('status', 1); $products->addAttributeToFilter('visibility', 4); $products->addAttributeToSelect('*'); $prodIds=$products->getAllIds(); $product = Mage::getModel('catalog/product'); $counter_test = 0; foreach($prodIds as $productId) { if (++$counter_test < 30000){ $product->load($productId); $product_data = array(); $product_data['sku'] = $product->getSku(); $product_data['mpn'] = $product->getData('upc'); $product_data['upc'] = $product->getData('upc'); $title_temp = $product->getName(); if (strlen($title_temp) > 70){ $title_temp = str_replace("Supply", "", $title_temp); $title_temp = str_replace(" ", " ", $title_temp); } $product_data['title'] = $title_temp; $product_data['description'] = substr(iconv("UTF-8","UTF-8//IGNORE",$product->getDescription()), 0, 900); $product_data['Deeplink'] = "http://www.myshop.co.uk/store/".$product->getUrlPath(); $product_data['image_link'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage(); $price_temp = round($product->getPrice(),2); $product_data['price'] = round($product->getPrice(),2) + 5; $product_data['brand'] = $product->getData('brand'); $product_data['product_type'] = 'Pet Products and Accessories'; $product_data['condition'] = "new"; $product_data['category'] = $product_data['brand']; $product_data['manufacturer'] = $product_data['brand']; $product_data['availability'] = "in stock"; foreach($product_data as $k=>$val){ $bad=array('"',"\r\n","\n","\r","\t"); $good=array(""," "," "," ",""); $product_data[$k] = '"'.str_replace($bad,$good,$val).'"'; } echo $counter_test . " "; $feed_line = implode("\t", $product_data)."\r\n"; fwrite($handle, $feed_line); fflush($handle); } } fclose($handle); } catch(Exception $e){ die($e->getMessage()); } If you look at the section that looks up the product price: $product_data['price'] = round($product->getPrice(),2) + 5; I don't understand what is happening in that line. For some reason the script is altering our price. The cost price of the example is £52.80, with a retail price of £56.54. The script is resulting in a price of £61.54. The script should be taking the price (£56.54) and adding VAT (20%). So once the script has been run, in the results text file the price should be £67.85. A) What is the price line actually doing? B) How do I change it to add 20% to the price? A: The price line is round the $product->getPrice() value to two decimal places, adding 5 and then assigning the value to $product_data['price']. To increase a number by a percentage of itself, say 20%, you multiply the number by itself plus the percentage you want (as a fraction of 1): $with_vat_number = $no_vat_number * 1.20; So to get the final rounded number, use round: $rounded_with_vat_number = round(($no_vat_number * 1.20), 2); A: Another way to have your prices in your Google Feed show as inclusive of vat, is to replace below: $price_temp = round($product->getPrice(),2); $product_data['price'] = round($product->getPrice(),2) + 5; With the Below Code: //VAT Stuff $vat = 20; //percent $pvat = $vat / 100; $product_data['price']= round( ($product->getPrice() + $product->getPrice() * $pvat),2); This way when VAT amount changes, then instead of having to work out fractions etc, just change the "$vat = 20; to whatever the new Vat Percentage is. So when it decreases back to 17.5 then you change the code to "$vat = 17.5;" (without quotation marks off course!)
{ "language": "en", "url": "https://stackoverflow.com/questions/7636288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c# regex parsing I am trying to parse data from a very long html content. I am just pasting here the important part I am interested in: Technical Details <div class="content"> <ul style="list-style: disc; padding-left: 25px;"> <li>1920x1080 Full HD 60p/24p Recording w/7MP still image</li> <li>32GB Flash Memory for up to 13 hours (LP mode) of HD recording</li> <li>Project your videos on the go anywhere, anytime.</li> <li>Wide Angle G lens to capture everything you want.</li> <li>Back-illuminated "Exmor R" CMOS sensor for superb low-light video</li> </ul> <div id="technicalProductFeatures"></div> I need to start parsing from : <div class="content"> til <ul and then until </ul> I have tried following regex but it did not work: Regex specsRegex = new Regex ("<div class=\"content\">[\\s]*<ul.[\\s]*</ul>"); this gives me nothing.. One other issue is sometimes it has a linebreak and sometimes not between initial div and ul tags like: <div class="content"> <ul style="list-style: disc; padding-left: 25px;"> or <div class="content"> <ul style="list-style: disc; padding-left: 25px;"> thanks for any help. A: I wouldn't suggest using regular expressions for this. It's like trying to fix a tire with a hammer. The hammer is a good tool, but it's not for everything. I'd use Html Agility Pack. It's not clear to me exactly what you're looking to extract. But I'll assume it's the list items. So you'd do something like this... var hdoc = new HtmlAgilityPack.HtmlDocument(); hdoc.LoadHtml(YourHtmlGoesHere); var MatchingNodes = hdoc.DocumentNode.SelectNodes("/html/body/div/ul/li"); As you can see, the syntax for the Html Agility Pack is based on XPATH and is much simpler for this task. It's also much more robust and something as silly as nested tags or a comment is not going to throw it off. Those types of things can throw off even the most carefully written regular expression in this scenario. UPDATE If you were determined to create a quick & dirty regular expression for this, it'd be something like this... <div class="content">.*?</ul> Ordinarily the .*? part matches anything except lines feeds 0 or more times, as few times as possible. So be sure to use RegexOptions.Singleline so that the . will match line feeds as well. This should work for the example you've given, but a commented bit of code with </ul> in it could throw it off, or a nested <ul></ul> could throw it off as well. UPDATE #2 This will grab everything between the <ul></ul>... (?<=<div class="content">\s*<ul[^>]*>).*?(?=</ul>) Again, be sure to use RegexOptions.Singleline. A: Regex isn't the best tool to parse html (to put it mildly). Use HtmlAgilityPack.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I use code contracts to work around the inability to have generic constructor constraints? I'm tying to write a class that will create immutable copies of another class, and the way I'm doing it requires that the copy takes a date and an instance of the original in the constructor. I know that you can't create a constructor constraint that specifies parameters, but is there a way to work around it using code contracts? public class Copier<o, c> where o : class, INotifyPropertyChanged where c : class, c // ideally new(datetime, o) { private Dictionary<DateTime, c> copies; public Copier(o original) { this.copies = new Dictionary<DateTime, c>(); original.PropertyChanged += this.propertyChangedHandler(object sender, PropertyChangedEventArgs args); } private void propertyChangedHandler(object sender, PropertyChangedEventArgs args) { var original = sender as o; var now = DateTime.Now; this.copies.Add(now, new c(now, original)); // error here } } The copy clases are created by me, inherit from the originals, override all of the properties to readonly and copy the values from the original in the constructor. Note: There is a requirement (imposed by me) that the original objects cannot be modified. A: As suggested, pass a creation delegate: public class Copier<o, c> where o : class, INotifyPropertyChanged where c : class, c // ideally new(datetime, o) { private Dictionary<DateTime, c> copies; private Func<o, DateTime, c> copyFunc; public Copier(o original, Func<o, DateTime, c> copyFunc) { this.copyFunc = copyFunc; this.copies = new Dictionary<DateTime, c>(); original.PropertyChanged += this.propertyChangedHandler(object sender, PropertyChangedEventArgs args); } private void propertyChangedHandler(object sender, PropertyChangedEventArgs args) { var original = sender as o; var now = DateTime.Now; this.copies.Add(copyFunc(now, original)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jquery find index() of same node name I have this setup, just to find the index() of an element, but it should look at elements of the same level with the same nodename. The returning numbers are not as expected. See the code comment. I want filteredByNodeNameIndex to be '2'. Hope this example code is clear enough: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>TestDrive</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript" > function TestDrive() { var $obj = $("#div2"); console.log("$obj.length:" + $obj.length); // returns: 1 var $filtered = $obj.parent().children($obj[0].nodeName); // find all divs in same parent console.log("$filtered.length:" + $filtered.length); // returns: 3 var $obj_clone = $filtered.find($obj); // find original element again. Is something wrong here? console.log("$objAgain.length:" + $obj_clone.length); // returns: 0 var filteredByNodeNameIndex = $obj_clone.index(); // i want the number 2 here console.log("filteredByNodeNameIndex:" + filteredByNodeNameIndex); // returns: -1 } </script> </head> <body onload="new TestDrive()"> <div id="container"> <!-- some random elements just for test --> <a></a> <div id='div1'></div> <div id='div2'></div> <span></span> <span></span> <a></a> <div></div> <a></a> </div> </body> </html> Who can spot where this is wrong? A: Try using .filter instead of .find: var $obj_clone = $filtered.filter($obj); The problem with .find is that it looks for children of the matched element, not siblings. From the docs: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. Compared to .filter: Reduce the set of matched elements to those that match the selector or pass the function's test. A: find only searches children of the selected node. You are trying to use filter's functionality. You need the following: var $obj_clone = $filtered.filter($obj); // find original element again. Is something wrong here? A: At the third attempt, you're trying to find the the child in itself, which obviously doesn't return the desired value. Illustrated: var $filtered = $obj.parent().children($obj[0].nodeName); //Select set A var $obj_clone = $filtered.find($obj); //Search for set A among the CHILDREN of set A --> Fails, obviously? var filteredByNodeNameIndex = $obj_clone.index(); //Unexpected results. A: try: var $obj_clone = $filtered.filter($obj); .find() only looks for children
{ "language": "en", "url": "https://stackoverflow.com/questions/7636307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I modify a va_list before passing it on? In my attempts to understand what I can and can't do with a va_list in (Objective-)C, I came across this little puzzle. I was hoping to create a category on NSString that would simplify the stringWithFormat: message a bit in some cases, just for the fun of it. What I was aiming for was being able to use the implementation like this: [@"My %@ format %@!" formattedWith:@"super", @"rocks"]; Hoping to end up with a string saying "My super format rocks!". My (incorrect) method implementation looks like this: - (NSString *)formattedWith:(NSString *)arguments, ... { va_list list; va_start(list, arguments); NSString *formatted = [[[NSString alloc] initWithFormat:self arguments:list] autorelease]; va_end(list); return formatted; } Now the problem is that as soon as va_start() is called, the va_list is 'shortened' (for lack of a better word) and only contains the rest of the arguments (in the case of the example only @"rocks" remains, plus the calling object which I don't care about). What's passed onto the initWithFormat: message therefore renders the wrong kind of result. On to the question. Are there ways to modify the va_list before I pass it to the initWithFormat: message, so I can somehow shift the first argument back onto the list? I'm not looking for an iterative process where I loop through the va_list myself, I'm looking to understand the limits of va_list as a whole. Thanks! A: The va_list can not be modified safely. The va_start argument also requires an argument to start the list which is excluded. The ways to work around this are to either pass an additional useless argument or use variadic macros. //Method declaration -(NSString*)formattedWith:(NSString*)ignored,...; //Opt 1 (pass anything for first value) [@"My %@ format %@!" formattedWith:nil, @"super", @"rocks"]; //Opt 2 (create a macro for the arguments) #define VA_OPT(...) nil, ##__VA_ARGS__ //VARIADIC OPTIONAL [@"My %@ format %@!" formattedWith:VA_OPT(@"super", @"rocks"]; //Opt 3 (just create a macro for the whole string format) //Obviously you should just use the NSString method directly before resorting to this #define FORMATTED_NSSTRING(str, ...) [NSString stringWithFormat:str, ##__VA_ARGS__] FORMATTED_NSSTRING(@"My %@ format %@!", @"super", @"rocks")
{ "language": "en", "url": "https://stackoverflow.com/questions/7636310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is it possible to convert a Jenkins free-style job to a multi-configuration job? I have quite a few free-style jobs in Jenkins that I would like to convert to multi-configuration jobs so I can build across multiple platforms under one job. These jobs specify quite a few build parameters and I would like to not have to set them up manually again by creating new multi-configuration jobs. Each job is currently limiting their builds to the platform we've been building on and the only other option I see is to clone the existing job and change the restriction to the new platform. This isn't ideal as I'll need to maintain 2 jobs where the only difference is the target platform. I don't see a way to do this via the UI, but wondering if there is another way. A: Just a note for those who would wish to switch from maven to freestyle job. * *Change maven2-moduleset tag to project. *Remove tags: rootModule, goals, mavenValidationLevel (should be close to each other). *Merge prebuilders and postbuilders into builders. A: I just wrote a script to convert about 10000 Jenkins Jobs from Maven Job Type to Freestyle. Please do not use it blindly. You might lose configuration options or end up in a broken Jenkins setup. The Python Part takes a config xml as argument and overwrites the same file with the converted data. I ran this live on the Jenkins Filesystem with the following command: cd /path/to/jenkins/jobs find * -maxdepth 2 -name config.xml -exec /path/to/maven2freestyle.py {} \; WARNING Again. This might break your Jenkins! Please keep a Backup! #!/usr/bin/env python2 import copy import sys from lxml import etree from lxml.etree import fromstring, tostring from StringIO import StringIO def parseXML(xmlFile): print(xmlFile) f = open(xmlFile) xml = f.read() f.close() e = etree.parse(xmlFile) root = e.getroot() if root.tag != 'maven2-moduleset': #print("WARNING: Skipping non Maven Project") return #change project type root.tag = "project" if 'plugin' in root.attrib: del root.attrib["plugin"] #get maven data rootModule = root.find('./rootModule') rootPOM = root.find('./rootPOM') goals = root.find('./goals') mavenName = root.find('./mavenName') mavenOpts = root.find('./mavenOpts') # merge prebuilders into builders prebuilders = root.findall("./prebuilders/*") builders = etree.Element("builders") root.insert(99, builders) if len(prebuilders) > 0: builders.append(copy.deepcopy(prebuilders[0])) #create maven builder maven = etree.Element("hudson.tasks.Maven") if not goals is None: etree.SubElement(maven, "targets").text = goals.text if not mavenName is None: etree.SubElement(maven, "mavenName").text = mavenName.text if not rootPOM is None: etree.SubElement(maven, "pom").text = rootPOM.text if not mavenOpts is None: etree.SubElement(maven, "javaOpts").text = mavenOpts.text builders.append(maven) #cleanup prebuilder = root.findall("./prebuilders") if len(prebuilder) > 0: root.remove(prebuilder[0]) if not rootModule is None: root.remove(rootModule) if not rootPOM is None: root.remove(rootPOM) if not goals is None: root.remove(goals) if not mavenName is None: root.remove(mavenName) if not mavenOpts is None: root.remove(mavenOpts) e.write(sys.argv[1], xml_declaration=True, pretty_print=True, encoding='utf-8', method="xml") if __name__ == "__main__": parseXML(sys.argv[1]) A: As far as I know, there's no way to convert the type of job in the UI. You'll have to either edit the job's config.xml, or copy and edit the config file and create a new job based on the edited configuration. You'll have to check the differences between a free-style and multi-configuration job with the various settings that you use. It might be as simple as changing the top-level element in config.xml from project to matrix-project. If you edit the existing job configuration, you'll need to either do it while Jenkins is offline, or tell Jenkins to reload its configuration via Manage Jenkins -> Reload Configuration from Disk. If you decide to create new jobs, this previous question might be helpful once you figure out what edits need to be made. Specifically this answer describes how to upload a config file to create a new job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Selecting a part of a string I have a string stored in variable say $input = 999 success: id:10.123/AVC13231 | ark:/asf4523/2425fsaf I want to select only a part of a string "10.123/AVC13231" say i want to achieve this: $output = 10.123/XXXXXXXX ; and no other part $input should be selected even the id: part The value 10.123 is constant and the value AVC13231 changes dynamically. How can i achieve the above? A: Here's a solution. $input = "999 success: id:10.123/AVC13231 | ark:/asf4523/2425fsaf"; $pos1 = strpos($input, 'id:')+3; // Remove 'id:' $pos2 = strpos($input, '|')-1; // Remove space before pipe $output = substr($input, $pos1, ($pos2 - $pos1)); A: And the mandatory regex solution: preg_match("/id:([^\s]*)/", $input, $matches); $output = $matches[1]; A: You could also use: $data = substr($input, $startpos=(strpos($input, "id:")+3), strpos($input, ' ', $startpos)-$startpos); Not tested, but the logic is there, just adapt correctly the algorithm... A: Try this $input = "999 success: id:10.123/AVC13231 | ark:/asf4523/2425fsaf"; $first_split=explode(" |",$input); $input_split1=$first_split[0]; $second_split=explode("10.123",$input_split1); $input_split2=$second_split[1]; $output="10.123".$input_split2; echo $output;
{ "language": "en", "url": "https://stackoverflow.com/questions/7636319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ vector size types I just started learning C++ and have a question about vectors. The book I'm reading states that if I want to extract the size of a vector of type double (for example), I should do something like: vector<double>::size_type vector_size; vector_size = myVector.size(); Whereas in Java I might do int vector_size; vector_size = myVector.size(); My question is, why is there a type named vector::size_type? Why doesn't C++ just use int? A: Java does not have unsigned integer types, so they have to go with int. Contrarily, C++ does and uses them where appropriate (where negative values are nonsensical), the canonical example being the length of something like an array. A: The C++ standard says that a container's size_type is an unsigned integral type, but it doesn't specify which one; one implementation might use unsigned int and another might use unsigned long, for example. C++ isn't "shielded" from platform-specific implementation details as much as Java is. The size_type alias helps to shield your code from such details, so it'll work properly regardless of what actual type should be used to represent a vector's size. A: C++ is a language for library writing*, and allowing the author to be as general as possible is one of its key strengths. Rather than prescribing the standard containers to use any particular data type, the more general approach is to decree that each container expose a size_type member type. This allows for greater flexibility and genericity. For example, consider this generic code: template <template <typename...> Container, typename T> void doStuff(const Container<T> & c) { typename Container<T>::size_type n = c.size(); // ... } This code will work on any container template (that can be instantiated with a single argument), and we don't impose any unnecessary restrictions on the user of our code. (In practice, most size types will resolve to std::size_t, which in turn is an unsigned type, usually unsigned int or unsigned long -- but why should we have to know that?) *) I'm not sure what the corresponding statement for Java would be. A: My personal feeling about this is that it is for a better code safety/readability. For me int is a type which conveys no special meaning: it can number apples, bananas, or anything. size_type, which is probably a typedef for size_t has a stronger meaning: it indicates a size, in bytes. That is, it is easier to know what a variable mean. Of course, following this rationale, there could be a lot of different types for different units. But a "buffer size" is really a common case so it somehow deserves a dedicated type. Another aspect is code maintability: if the container suddenly changes its size_type from say, uint64_t to unsigned int for instance, using size_type you don't have to change it in every source code relying on it. A: The book you’re reading states that if you want to extract the size of a vector of type double (for example), you should do something like: vector<double>::size_type vector_size; vector_size = myVector.size(); Whereas in Java you might do int vector_size; vector_size = myVector.size(); Both are inferior options in C++. The first is extremely verbose and unsafe (mostly due to implicit promotions). The second is verbose and extremely unsafe (due to number range). In C++, do ptrdiff_t const vectorSize = myVector.size(); Note that * *ptrdiff_t, from the stddef.h header, is a signed type that is guaranteed large enough. *Initialization is done in the declaration (this is better C++ style). *The same naming convention has been applied to both variables. In summary, doing the right thing is shorter and safer. Cheers & hth.,
{ "language": "en", "url": "https://stackoverflow.com/questions/7636323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Mobile Document Type Definition Mobile site is not showing correctly. I have to zoom in to view my site correctly even if I have the correct DTD: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.wapforum.org/DTD/xhtml-mobile12.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>MySite Mobile</title> <link rel="stylesheet" type="text/css" href="mobile.css"/> </head> <body> <!-- content --> </body> </html> Do I have the correct DTD? A: You are missing the viewport meta tag. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> view this link https://developer.mozilla.org/en/Mobile/Viewport_meta_tag
{ "language": "en", "url": "https://stackoverflow.com/questions/7636327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Crystal Reports Visual Studio 2008 and SQL Server 2008 R2 I have a Windows Forms application that was created in Visual Studio 2008 and targets .NET 3.5. It uses the embedded version of Crystal Reports that comes with VS 2008. It was calling a SQL 2000 database successfully. The company upgraded to SQL Server 2008 R2. The Windows Forms .Net application connections using ADO work fine with the new database. Unfortunately Crystal Reports now hangs. It opens the shell but doesn't open and populate the reports. Is there a compatibility issue? A: You were prompted the first time because you have the option checked for 'Verify on First Refresh'. * *Uncheck 'Save data in the report' and save/close. *Reopen and 'Set Datasource Location...' to new database server. *Click 'Verify Database'. (Should recieve success message) *If still not working 'Set Datasource Location...' to the old database server and verify it works at all. Then click on 'Show SQL Query' and verify statement returns results on new server by executing query manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP/jQuery form scripts sending duplicate emails? I've tried to fix this problem, or find a similar problem, but I'm still scratching my head over this one. I have an HTML form that I'm validating with a jQuery function, then passing it to a PHP script for mailing. The problem I'm having is once the functions run, there's a duplicate mail being sent, but the second one is blank, none of the data values are passed. The jQuery: $("#submit").click(function(){ var quit = false; if(validateName()){ name = validateName(); $("label#name_error").fadeOut(0); $("label#name_error2").fadeOut(0); } else if (validateInput('name')){ $("label#name_error").fadeOut(0); $("label#name_error2").fadeIn(250); quit = true; } else { $("label#name_error").fadeIn(250); $("label#name_error2").fadeOut(0); quit = true; } // several more validation checks for the other fields follow. if(quit){ return false; } var dataString = "name=" + name + "&email=" + email; //and other fields inserted here $.ajax({ type: "POST", url: "bin/MailHandler.php", data: dataString, success: function(){ $('.error').fadeOut(0); $('#contact-form').clearForm(); $('#contact').html("<div class='download-box'><h2>Thanks for contacting us!</h2><p>Someone will be in touch shortly!</p></div>").fadeOut(0).fadeIn(1500); } }); return false; }); Which then sends to the PHP (MailHandler.php): <?php $to = "email@email.com"; $from = $_REQUEST["email"]; $subject = "Testing the form " . $_REQUEST["name"]; $headers = "From: " . $_REQUEST["email"] . "\r\n" . "Reply-To: " . $_REQUEST["email"]; $messageBody = ""; $messageBody .= $_REQUEST["name"] . "\n"; $messageBody .= $_REQUEST["email"] . "\n"; //and the other fields added similarly. if (mail($to, $subject, $messageBody, $headers)){ echo ("Mail Sent"); } else { echo ("Mail Failed"); } ?> Once this runs, everything seems to process correctly, I get the success message and the email with all the correct data arrives. A few minutes later a second email arrives, but with none of the data from the form. All the headers and data values are blank. I've looked over the code, and I can't figure out where the second message is coming from. Does anyone see something I missed?? Any help is appreciated. Thanks! A: It appears the form is being submitted twice. Once by the form post, then once by the AJAX call. You might want to stick with the ajax call and not use a form tag, then also use a button other than a submit button to invoke the ajax call. A: In your MailHandler, you should check to see if the variables you need, aren't empty, before sending an e-mail. If the vars are empty (http://php.net/empty) then you shouldn't send the mail. It is possible that an antivirus (such as Trend Micro) check the page to make sure there aren't any viruses on it. A: * *It seems that your php script is somehow called twice. Check this using firebird. If you use submit button type, you should disable its default functionality like this: $('#submit').click(function(event) { event.preventDefault(); // rest of your code }); *Don't use $_REQUEST, use $_POST instead. *Check if your $_POST variables are not empty before sending the email. A: Maybe you will have more luck if you use the jquery .submit method rather just a click event, shown here : http://api.jquery.com/submit/ So in the case of your code: //where #target is your form ID $('#target').submit(function() { //your code return false; }); $('#submit').click(function() { $('#target').submit(); }); I think that will make it send the email once. A: Turns out it was something happening server-side, rather than my code. I moved the code to a different server and experienced no problem whatsoever.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django data model example for versioned collection of items I'm looking for an example of a Django models.py file implementing the following use case: * *A page with a list of items can be created (a Collection) *When the Collection gets reordered | is added to | is removed from and saved, the version number of the Collection is incremented by 1 (a Version) *A user can go back to a previous version of this Collection, compare any two versions, and also create new Collections, which also need to be versioned I'm mainly trying to get my head around the table relationships (do I need many-to-many in Items rather than ForeignKey), and how to automatically increment the version number. Here's some code to start with: class Collection(models.Model): """A collection of items""" label = models.CharField(blank=True, max_length=50) slug = models.SlugField() class Meta: verbose_name_plural = "Collections" def __unicode__(self): return self.label class Item(models.Model): """An item""" STATUS_CHOICES = ( (1, "Neutral"), (2, "Flagged Up"), (3, "Flagged Down"), ) title = models.CharField(max_length=100) slug = models.SlugField() collection = models.ForeignKey(Collection) owner = models.ForeignKey(User) status = models.IntegerField(choices=STATUS_CHOICES, default=1) created = models.DateTimeField(default=datetime.datetime.now) modified = models.DateTimeField(default=datetime.datetime.now) class Meta: ordering = ['modified'] verbose_name_plural = "Items" class Version(models.Model): """The version of a collection""" collection = models.ForeignKey(Collection) version_number = "??? how to auto increment, or do you I just use the primary key/auto field ???" class Meta: verbose_name_plural = "Versions" def __unicode__(self): return self.label A: Check out: http://stdbrouw.github.com/django-revisions/. It's one of the few apps for model versioning that's even somewhat actively developed. It also has a fairly simple API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Refine search results control I am using People Search Core Results PageLayout for my People Search WebPart. By default when you search it gives an option of Refine your search. As I observe its getting those options from a Control. <SEARCHWC:RefineSearchResults runat="server" Title="<%$Resources:sps,RefineByTitle%>" SearchProperty="JobTitle"/> I tried to edit the page layout and added my property in the Title value but it throw a error. <SEARCHWC:RefineSearchResults runat="server" Title="<%$Resources:sps,RefineBymyProperty%>" SearchProperty="myProperty"/> Can any one help me how to add myproperty on the page. Thanks in advance A: I found out that the RefineSeachResults control is sealed in Moss 2007 but in SharePoint 2010 its extendable. That is the reason you can't find it in the control templates even though it represents to be as user control. To add you propoerty for example in my case to show "myProperty" I have kept that inline and it worked. <SEARCHWC:RefineSearchResults runat="server" Title="RefineBy myProperty" SearchProperty="myProperty"/> If you have scenario where you want extra functionality other that OOB then the only option is write custom control. Hope this might help someone. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7636336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VBA: Unicode to ASCII conversion? I have a string that is in unicode format that I want to convert to ASCII format. If the character is not in the ASCII range, then it should be converted to the closest English letter. For example "Ǎǎǵǩȥȑȍ" to "Aagkzro". A: A quick web search pulled up the following link which partially works for you example. However, there are codes (ǵ) which will just return a question mark. In these cases, you will want to check for that value specifically and convert it to what you're expecting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Undefined variable - Passing a variable through the url I get cant get my variable to echo on the page even though it shows in the URL. Here is the link that passes it <a href='eventform.php?$eventname'> And the code to get it on a other page: $eventname = 0; if (isset($_GET['eventname'])) { $eventname = $_GET['eventname']; } echo $_GET['eventname']; It displays the 0 but not the Mountain 2012 which is in the url at the top. Please help me with this problem Am i displaying it correctly on the other page? A: You need: * *To give it a name in the query string *To sanitise the data for the URI *To sanitise the URI for the HTML Thus: <a href='eventform.php?eventname=<?php echo htmlspecialchars( urlencode( $eventname ) ); ?>'> A: You forgot to put eventname= in your url such as: <a href="eventform.php?eventname=<?php echo $eventname; ?>"> A: <a href='eventform.php?<?php=$eventname?>'> Or: <a href='eventform.php?<?php echo $eventname?>'> Although you might want: <a href='eventform.php?eventname=<?php echo $eventname?>'> ^^sets $_GET['eventname'] to $eventname
{ "language": "en", "url": "https://stackoverflow.com/questions/7636339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: htaccess redirects from old site to new site There is an existing site h*tp://www.oldsite.com/ which I need to redirect to the new site h*tp://www.newsite.co.za/. The oldsite is already setup as parked domain on the newsite host account. Below are the file structure of the newsite host. h*tp://www.newsite.co.za/ - /public_html h*tp://www.oldsite.com/ - /public_html/oldsite.com The newsite is a complete restructure of the oldsite, so I needed to redirect all indexed pages of the oldsite to some corresponding pages of the newsite. I have managed to redirect the static pages but Im having a hard time on the dynamic pages. For example: h*tp://www.oldsite.com/The_Wine_Shop/Bales_Private_Vintners.aspx?CatID=13&PageID=175&RefPageID=169 to h*tp://www.newsite.co.za/buy-wine/buy-wine-online/ There are several pages that needs to be redirected based on the example format above. What will be the easiest way to do the redirects. I'm thinking to just redirect all the files inside the "The_Wine_Shop" folder including the dynamic pages but I dont have any idea how to do that in this format. By the way here is the code for my oldsite to newsite index page redirect. Options +FollowSymLinks RewriteEngine On RewriteCond %{HTTP_HOST} ^oldsite\.com [OR] RewriteCond %{HTTP_HOST} ^www.oldsite\.com RewriteRule ^/?(.*) http://www\.newsite\.co\.za/$1 [R=permanent,L] A: You could add another ruleset to your .htaccess: RewriteCond %{REQUEST_URI} ^/The_Wine_Shop/ RewriteRule ^(.*)$ http://www.newsite.co.za/buy-wine/buy-wine-online/ [R=301,L] This would redirect every page beginning with /The_Wine_Shop/. If you want to check the requested URI and the querystring you can go with something like this: RewriteCond %{REQUEST_URI} ^/The_Wine_Shop/Bales_Private_Vintners\.aspx$ RewriteCond %{QUERY_STRING} CatID=13 RewriteCond %{QUERY_STRING} PageID=175 RewriteCond %{QUERY_STRING} RefPageID=169 RewriteRule ^(.*)$ http://www.newsite.co.za/buy-wine/buy-wine-online/ [R=301,L] If you don't care if the URL is written upper or lowercase add the NC-Flag to the conditions. You should also add the <link rel="canonical" href="http://new-and-correct-url" /> tag to your new sites <head>. More info on rel canonical.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Split a List into a List of Lists, splitting on an element Can the following be rewritten so that is uses LINQ, (rather an these old-fashioned foreach loops) IEnumerable<IEnumerable<T>> SplitIntoSections<T>(IEnumerable<T> content, Func<T, bool> isSectionDivider) { var sections = new List<List<T>>(); sections.Add(new List<T>()); foreach (var element in content) { if (isSectionDivider(element)) { sections.Add(new List<T>()); } else { sections.Last().Add(element); } } return sections; } I thought I almost had an way of doing this, (it involved FSharp colections) when i realised that it could be done with a foreach loop. A: You don't want to use LINQ here. You aren't going to be able to order and group the proper way without doing something gnarly. The easy thing to do is to take your code and make it defer execution using the yield statement. An easy way to do this is as follows: IEnumerable<IEnumerable<T>> SplitIntoSections<T>(this IEnumerable<T> source, Func<T, bool> sectionDivider) { // The items in the current group. IList<T> currentGroup = new List<T>(); // Cycle through the items. foreach (T item in source) { // Check to see if it is a section divider, if // it is, then return the previous section. // Also, only return if there are items. if (sectionDivider(item) && currentGroup.Count > 0) { // Return the list. yield return currentGroup; // Reset the list. currentGroup = new List<T>(); } // Add the item to the list. currentGroup.Add(item); } // If there are items in the list, yield it. if (currentGroup.Count > 0) yield return currentGroup; } There's a problem here; for very large groups, it's inefficient to store the sub-groups in a list, they should be streamed out as well. The problem with your approach is that you have a function that is required to be called on each item; it interferes with the stream operation since one can't reset the stream backwards once the grouping is found (as you effectively need two methods that yield results). A: You could use a side-effect which is only used within a well-defined area... it's pretty smelly, but: int id = 0; return content.Select(x => new { Id = isSectionDivider(x) ? id : ++id, Value = x }) .GroupBy(pair => pair.Id, pair.Value) .ToList(); There must be a better alternative though... Aggregate will get you there if necessary... return content.Aggregate(new List<List<T>>(), (lists, value) => { if (lists.Count == 0 || isSectionDivider(value)) { lists.Add(new List<T>()); }; lists[lists.Count - 1].Add(value); return lists; }); ... but overall I agree with casperOne, this is a situation best handled outside LINQ. A: Here's an inefficient but pure LINQ solution: var dividerIndices = content.Select((item, index) => new { Item = item, Index = index }) .Where(tuple => isSectionDivider(tuple.Item)) .Select(tuple => tuple.Index); return new[] { -1 } .Concat(dividerIndices) .Zip(dividerIndices.Concat(new[] { content.Count() }), (start, end) => content.Skip(start + 1).Take(end - start - 1)); A: Well, I use one LINQ method here, though it's not particularly in the spirit of your question, I think: static class Utility { // Helper method since Add is void static List<T> Plus<T>(this List<T> list, T newElement) { list.Add(newElement); return list; } // Helper method since Add is void static List<List<T>> PlusToLast<T>(this List<List<T>> lists, T newElement) { lists.Last().Add(newElement); return lists; } static IEnumerable<IEnumerable<T>> SplitIntoSections<T> (IEnumerable<T> content, Func<T, bool> isSectionDivider) { return content.Aggregate( // a LINQ method! new List<List<T>>(), // start with empty sections (sectionsSoFar, element) => isSectionDivider(element) ? sectionsSoFar.Plus(new List<T>()) // create new section when divider encountered : sectionsSoFar.PlusToLast(element) // add normal element to current section ); } } I trust you will note the complete lack of error checking, should you decide to use this code...
{ "language": "en", "url": "https://stackoverflow.com/questions/7636346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can we use Server.MapPath in Bitmap? recently i created a webpage, where in i have a img tag, whose source is linked to another page, where i am resizing the image, whose name is being sent from the src from previous page in query string. but when i create the new object of bitmap, i gets the error, Parameter is not valid. below is the code which holds image tag. <img src='/resize.aspx?file=PRO_06_11_Final-272.jpg&width=128&height=73' alt="Nothing" /> below is the code for the resize page where i am resizing image and sending the bitmap object through response if (Request.QueryString["file"] != null) { int lnHeight = Convert.ToInt32(Request.QueryString["height"]); int lnWidth = Convert.ToInt32(Request.QueryString["width"]); string imgUrl = Request.QueryString["file"].ToString(); Bitmap bmpOut = null; try { Bitmap loBMP; loBMP = new Bitmap(Server.MapPath(imgUrl)); //Parameter is not valid.. error is thrown here. System.Drawing.Imaging.ImageFormat loFormat = loBMP.RawFormat; decimal lnRatio; int lnNewWidth = 0; int lnNewHeight = 0; //-----If the image is smaller than a thumbnail just return it As it is----- if ((loBMP.Width < lnWidth && loBMP.Height < lnHeight)) { lnNewWidth = loBMP.Width; lnNewHeight = loBMP.Height; } if ((loBMP.Width > loBMP.Height)) { lnRatio = (decimal)lnHeight / loBMP.Height; lnNewHeight = lnHeight; decimal lnTemp = loBMP.Width * lnRatio; lnNewWidth = (int)lnTemp; if (lnNewWidth > 128) { lnNewWidth = 128; } } else { lnRatio = (decimal)lnHeight / loBMP.Height; lnNewHeight = lnHeight; decimal lnTemp = loBMP.Width * lnRatio; lnNewWidth = (int)lnTemp; if (lnNewWidth < 75) { lnNewWidth = 75; } } bmpOut = new Bitmap(lnNewWidth, lnNewHeight); Graphics g = Graphics.FromImage(bmpOut); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight); Response.ContentType = "image/jpeg"; bmpOut.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { HttpContext.Current.Response.Write("CreateThumbnail :" + ex.ToString()); } finally { } } the above code works fine in local Machine on FileSystem, but when i put the same code on dev server, the application starts throwing message.. can anyone tell me what could be the cause for this problem only on dev server. A: If you don't specify a root folder for Server.MapPath it will add the location of the currently executing aspx file. You can read more at msdn If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the .asp file being processed As Hanlet mentioned you need to add an images root folder. So your code will become string imgRoot = "~/images/"; try { ... loBMP = new Bitmap(Server.MapPath(imgRoot + imgUrl)); ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using phing to deploy different environments We're using phing to deploy our php application and we got into a little issue with deploying our environments. We have 2 different production environments (each one with different config files), and a separate testing environment. We don't have an issue with the testing environment, as we have a different branch for the testing environment. The problem is that we're using the same branch for both our production environments. Anyone has suggestions on how we can deploy into our production environments with different config / setting files? We rather keep the production branch as a single branch, but somehow separate the config files. We use zend framework, and I know about the different section we can have in the config files, but we also have a setting file for phing. I looked around, but I can't seem to find a way to pass command line arguments to phing. Something like this could be really useful: phing -f build.xml production_live1 A: You can use -D to set custom properties phing -Denvironment=production_live1 You can access it within your build file like every other property ${environment} Another solution would be, that you create different build files for every environment, which both includes the "main" build file build.xml and only contains the differences. phing -f production_live1.xml (and in production_live1.xml <project name="production_live1" basedir="." default="all"> <import file="main.xml" /> <!-- different tasks here --> </project>
{ "language": "en", "url": "https://stackoverflow.com/questions/7636352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why doesn't Tomcat 6 find my styles.css Trying to determine where/how to place style sheets in web app deployed to Tomcat 6 so that the styles.css can be resolved. I've tried every thing I can think of without success. I did these tests to ferret out were to put the file but little has been successful. 1.) put css in-line with style attribute to verify text display green. <div id="xxx" style="color:green;"> This worked. Then I removed the attribute and 2.) moved it into a in-file <style></style> stmt in the jsp. This also worked. I copied the css stmt into styles.css and disabled the in-line stmt in the jsp. 3.) added <link></link> stmts to file. I tried several path refs to the file. And I put the file in several different directory locations to see where it would get resolved. (none were found) <link rel="stylesheet" type="text/css" href="styles.css"> <link rel="stylesheet" type="text/css" href="css/styles.css"> <link rel="stylesheet" type="text/css" href="/css/styles.css"> Using FireBug (css tab) I see the follow information for these links * <link rel="stylesheet" type="text/css" href="styles.css"> this displays the src to index.html in the root dir * <link rel="stylesheet" type="text/css" href="css/styles.css"> this displays the msg Apache Tomcat/6.0.13 - Error report HTTP Status 404 The requested resource () is not available. * <link rel="stylesheet" type="text/css" href="/css/styles.css"> this displays Failed to load source for: http://192.168.5.24:9191/css/clStyles.css The contextPath is /microblog And basepath is http://192.168.5.24:9191/microblog Here is the test code I am using. I am using Spring 3. I have a simple JSP -- test.jsp -- <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <base href="<%=basePath%>"> <link rel="stylesheet" type="text/css" href="styles.css"> <link rel="stylesheet" type="text/css" href="css/styles.css"> <link rel="stylesheet" type="text/css" href="/css/styles.css"> <style> #Yxxx {color:green;} </style> </head> <body> <div id="xxx"> <h2>Test <%=path%> <%=basePath%></h2> </div> </body> </html> I've placed the styles.css file at many directory locations to see where it might get resolved but none appear to be found. In Tomcat 6 the deployed exploded web app directory structure webapps/microblog webapps/microblog/styles.css webapps/microblog/index.html webapps/microblog/css/styles.css webapps/microblog/WEB-INF/css/styles.css webapps/microblog/WEB-INF/jsp/admintest/styles.css webapps/microblog/WEB-INF/jsp/admintest/test.jsp So how to get Tomcat 6 to resolve .css files? A: Likely the relative CSS path is plain wrong. Make it domain-relative instead of path-relative. Prepend it with the context path (which is /microblog in your case): <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/styles.css"> Note that resources in /WEB-INF are not publicitly accessible. They're only accessible by RequestDispatcher in servlets or by <jsp:include> in JSPs. Put them outside /WEB-INF. If it still doesn't work, then likely a servlet or filter which is mapped on an URL pattern of / or /* is not doing its job properly. A: Probably it's quite late but I managed to resolve this in a different way. I have a simple html file inside my WebContent and a css folder: this was not working: <link rel="stylesheet" type="text/css" href="css/style.css"> and neither this: <link rel="stylesheet" type="text/css" href="/css/styles.css"> this IS working, but it's ugly (and it's also giving me a warning in Eclipse): <link rel="stylesheet" type="text/css" href="myproject/css/styles.css"> so I found that also this one is working, and seems the best approach to me: <link rel="stylesheet" type="text/css" href="./css/styles.css"> A: none of the following will work deploying to http://192.168.5.24:9191/microblog <link rel="stylesheet" type="text/css" href="styles.css"> This one points to http://192.168.5.24:9191/styles.css <link rel="stylesheet" type="text/css" href="css/styles.css"> This one points to http://192.168.5.24:9191/css/styles.css <link rel="stylesheet" type="text/css" href="/css/styles.css"> This one points to http://192.168.5.24:9191/css/styles.css You need to prefix the context path : <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/styles.css"> or the full path : <link rel="stylesheet" type="text/css" href="<%=basePath%>/styles.css"> The resources under /WEB-INF should be removed as they're not available for external requests A: Also consider using the HTML base tag so that you don't need to type ${pageContext.request.contextPath} all the time. A: This happened to me too. I solved it by simply typing a space anywhere in the css file and saving it. The path should just be "css/style.css". It seems to me that sometimes Tomcat wouldn't recognize your file immediately if that file (or the path to the file) is changed such as renamed or relocated. The only way I find to make Tomcat "realize" this change is to make some change in the file and save it, and redeploying or refreshing wouldn't help if this hasn't been done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: simple explanations for macsec and ipsec I need to implement IPSEC and MACSEC transformations on ethernet packets (i.e. I don't need to deal with setting up parameters, security associations, or key exchange issues, just do the transformations on the packets when that is already known. Also I can nick GCM/AES implementations so I don't have to implement the actual ciphering either.) Unfortunately I am just too stupid to understand the specifications. Does anyone know of a nice simple explanation, designed for an idiot, with diagrams and concrete examples, of what the transformations are supposed to look like? A: MACsec provides three sub-functions, namely: * *Encryption/decryption *Integrity protection *Replay protection These sub-functions are negotiated with other stations using MACsec Key Agreement protocol (MKA). MACsec uses MACsec Key Agreement protocol (MKA) for exchange and agreement of secure keys between supported devices. MKA uses the EAP framework specified in IEEE 802.1X-2010 forcommunication A: This illustrated guide is good for IPSEC http://unixwiz.net/techtips/iguide-ipsec.html And this was invaluable for packing and unpacking IP headers. http://www.daemon.org/ip.html#proto There appears to be a bit of a gap in the market for MACSEC though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using SSL/TLS when sending an email from PHP I am very new to email servers and sending email with PHP... Is it possible to have email sent from a PHP script on my server encrypted using SSL or TLS before it is sent to the recipient's mail server? I need to ensure only the intended recipient can read the email, in case the transmission is intercepted on its journey to their mail server. I am not sure if this is possible, as the recipient's mail server would not know the public key right? So how could it decrypt the email? As background, I am not actually hosting email accounts for anyone - so it is not a case of the users authenticating with my server and downloading emails for them hosted there. I just have a script triggering an alert email to be sent from "notifications@danbaylis.com" (which is not a real email address on the server so you can't reply to it) to the user's real email address (which my application knows). I need a way to make sure this email is securely sent from PHP on my server, to the recipients mail server. I have looked at the mail() function in PHP, as well as the PHPMailer class - but I am not sure how I would configure either of these methods to securely send the email. All my research just shows how to install SSL in on my server so users can securely download email stored on my server - which is not what I am trying to do here. I am running Centos5.7 which I believe has a mail server installed, though I am not sure if PHP actually uses that by default.. Thanks for any help! A: You can't guarantee that an email will be delivered to the recipient's mailbox. The ONLY place you is the connection between your mail client, and your outgoing SMTP server. After that, it's utterly out of your hands. If you need to guarantee privacy on the email, you'll have to encrypt the body of the email. What you want is an S/MIME or PGP message. Not that this still leaves SOME information publicly available - the mail body will be encrypted, but addressing information will necessarily still be readable - intermediate mail servers still need to know how to deliver the mail A: The type of encryption you are looking for is not SSL/TSL, which is used to encrypt transmission between the client (PHP) and the SMTP server which will send it on. SSL/TLS makes no guarantee that the data will be encrypted all the way to its endpoint. In fact, it almost certainly won't be as the data is relayed between SMTP servers and switches along the way. Instead you are looking for PGP encryption, which can be implemented in PHP using the GnuPG functions. You must encrypt the message using your recipient's public key. It can then only be decrypted and read with the recipient's private key, held by the recipient alone. To implement this in mail(), you would first encrypt the message body, then pass the encrypted, ascii armored block to mail() as its third parameter. Message headers will not be encrypted, only the body. Addendum The way secure message transmission is handled by most banks and medical services (in the US, anyway) is not to send email at all. Instead, messages which must be kept secure are stored in a user's "inbox" with the website. The user must login (over SSL) to the website to read messages in the secure inbox. Email is only sent to notify the user that new messages are waiting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to make Object bound to WPF control thread safe I have an Observable collection object whose value I am updating from my code. This collection is bound two way to a data grid. Now, is this collection thread safe - that is if I try to modify the value of the collection from the code and at the same time the user tries to modify it(as a result of editing the data grid), would the program throw an exception? If yes, can you please explain how to avoid this? Thanks... A: This looks like a duplicate here, and here but the short answer is that you're safe if you're modifying a property. As you're working with a collection there's a bit more you need to do if you're trying to modify an ObservableCollection on multiple threads and not just the UI thread. This has been covered a lot, and you can check out at either this link or this one However if you're doing your modifications within the UI thread, you are safe as this is what the ObservableCollection is intended for. The events will be created and handled on the UI theread as long as you are properly marshaling via Dispatcher.BeginInvoke().
{ "language": "en", "url": "https://stackoverflow.com/questions/7636365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a Document object in Java? I want to create a Document object with jdom. I have written a function but after I debug I can see that it is not created. and since I am new to XML I don't understand why I can not create. Can you please help me for that? public Document createSNMPMessage (){ Element root = new Element("message"); Document document = new Document(root); Element header = new Element("header"); Element messageType = new Element("messageType").setText("snmp"); Element sendFrom = new Element("sendFrom").setText("192.168.0.16"); Element hostName = new Element("hostName").setText("oghmasysMehmet"); Element sendTo = new Element("sendTo").setText("192.168.0.12"); Element receiverName = new Element("receiverName").setText("Mehmet"); Element date = new Element("date").setText("03/10/2011"); header.addContent(messageType); header.addContent(sendFrom); header.addContent(hostName); header.addContent(sendTo); header.addContent(receiverName); header.addContent(date); Element body = new Element("body"); Element snmpType = new Element("snmpType").setText("getbulk"); Element ip = new Element("ip").setText("127.0.0.1"); Element port = new Element("port").setText("161"); Element oids = new Element("oids"); Element oid = new Element("oid").setText("1.3.6.1.2.1.1.3.0"); oids.addContent(oid); Element community = new Element("community").setText("community"); Element nR = new Element("nR").setText("0"); Element mR = new Element("mR").setText("5"); body.addContent(snmpType); body.addContent(ip); body.addContent(port); body.addContent(oids); body.addContent(community); body.addContent(nR); body.addContent(mR); return document; } When I create it, I convert it to string by using that function ; public String xmlToString(Document doc) { XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); return outputter.outputString(doc); } and When I try to convert to string to see what is inside of the Document, i get; <?xml version="1.0" encoding="UTF-8"?> <message /> A: From what I can see, you are creating a Document object, and adding nodes to the header and body nodes, but these nodes are not being added to your Document object instance document. I believe you would want to add these nodes to the root element, which is already added to your document. So, you could add it to your document's root as shown below: public Document createSNMPMessage (){ Element root = new Element("message"); Document document = new Document(root); Element header = new Element("header"); ... ... Element body = new Element("body"); ... ... root.addContent(header); // NOTE THESE NEW LINES root.addContent(body); // NOTE THESE NEW LINES return document; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ignoring namespace in XmlReader I'm using an xmlreader to read an xml file. The problem is i have many undefined namespaces in the child elements. Because of it, I'm unable to read the content of the files. Is there any way to read the contents of the files avoiding this issue or is there any solution to handle these kind of scenarios? A: You can add the missing namespaces to the XmlReader like this. var settings = new XmlReaderSettings { NameTable = new NameTable(), }; XmlNamespaceManager xmlns = new XmlNamespaceManager(settings.NameTable); xmlns.AddNamespace("yourundeclarednamespace", "http://www.dummynamespace.org"); XmlParserContext context = new XmlParserContext(null, xmlns, "", XmlSpace.Default); using (var reader = XmlReader.Create(filePath, settings, context)) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I use the following events/delegates, written in C#, in VB.NET? I'm using JdSoft's APNS-Sharp library in my ASP.NET web app. The library is written in C#, and makes extensive use of Delegate Functions and Events for threading purposes. My application is written in VB.NET, and I'm a little confused on about how to translate the following sample code (C#): .... //Wireup the events service.Error += new FeedbackService.OnError(service_Error); .... } static void service_Error(object sender, Exception ex) { Console.WriteLine(...); } Here are the relevant members of the FeedbackService class: public delegate void OnError(object sender, Exception ex); public event OnError Error; Basically, I'm trying to figure out how to attach a function (like service_Error) to an event (like Error) in VB.NET. I'm unclear on what the += syntax means in this context, and VisualStudio says that the 'Error' event cannot be accessed directly by my VB.NET code for some reason. A: The += operator is basically subscribing the FeedbackService.OnError function to the Error invocation list. So when the Error event is raised, the OnError method is invoked. To translate the above code to VB.NET, it would look something like: // define delelgate/event Public Delegate Sub OnError(sender As Object, ex As Exception) Public Event OnError Error // attach method to event AddHandler service.Error, service_Error See How to: Raise and Consume Events for some examples in VB.NET. A: AddHandler service.Error, service_Error A: I'm not sure on the VB implementation I'm afraid, but the += syntax in C# with respect to delegates, adds a method to the delegates list of methods (invocation list)
{ "language": "en", "url": "https://stackoverflow.com/questions/7636382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mySQL not behaving as expected I am running the following query SELECT * FROM wp_posts WHERE (post_title LIKE 'Professionally') OR (post_content LIKE 'Professionally') AND post_type='post' AND post_status='publish' I know that I have a row that has post_type of post, and post_status of publish that starts with the word 'Professionally' (copied and pasted from phpmyadmin) but this query returns no results. Oddly, when the query successfully matches a popst_title it works as expected. A: When using LIKE, you use a % in order to do substring matches: SELECT * FROM wp_posts WHERE (post_title LIKE 'Professionally%' OR post_content LIKE 'Professionally%') AND post_type = 'post' AND post_status = 'publish' (I also modified your bracketing to better express what I think you are trying to do.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7636383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The simpliest way to change only colors in theme I'm using WPF Toolkit Themes( http://wpf.codeplex.com/wikipage?title=WPF%20Themes ). Actually I'm using only ExpressionDark. But I want to change colors for every control. Need I override all elements and write whole of the big code? Isnt there any siplier way to change only colors? I need only change hue. Isnt there any applications, addons or so on which can change the hue in every colors in this theme? A: I don't know of any addons, but usually I'd put all my Colors in a separate XAML file so I can swap out that resource dictionary as needed For example: <Color x:Key="BorderColor_Base">#FF8DB2E3</Color> <Color x:Key="BackgroundColor_Base">White</Color> <Color x:Key="BorderBrushDark">#FF8DB2E3</Color> <Color x:Key="BorderBrushLight">#FFC0F9FF</Color> You can also overwrite System colors, using syntax such as: <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Red" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7636384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I wait for SU access after request? My app requests SU access something like this: Process p = null; p = Runtime.getRuntime().exec("su"); That prompts the user to allow or deny the access, but my app continues to execute the next line of code while the choice is displayed on the screen. How can I make the app wait until the user makes a choice at the prompt? A: Just to this, I think it will work: Process p = Runtime.exec("foo"); int exitCode = p.waitFor(); it will wait for your process to end, and you'll also get the exit code. A: Similar to @jdourlens ans you can try this add this code before your actual "su" call. try { Process p2 = Runtime.getRuntime().exec("su -c ls"); int exitCode = p2.waitFor(); } catch(Exception e2) {//do something} So if the user selects "Always allow" option, things will work out. I was also trying to read code Chainfires's library as well his website: https://github.com/Chainfire/libsuperuser/blob/master/libsuperuser/src/eu/chainfire/libsuperuser/Shell.java What I could figure out was to do a Blocking I/O call while the user grants super user access. A good way is to write a temp file, or do some random commands. This is what I tried to do. Call ls with su, which will grants that process su access and then your next su call will have the appropriate access.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery ERB template not inserting HTML I'm a beginner at JQuery/JS and am trying to implement a dependent drop-down list in a Rails 3.1 app. I have the following form: <%= debug params %> <%= form_for([@wall.climbing_centre, @wall]) do |f| %> <% if @wall.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@wall.errors.count, "error") %> prohibited this wall from being saved:</h2> <ul> <% @wall.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div id="kind" class="field"> <%= f.label :kind %><br /> <%= f.select :kind, Wall::Kinds, :input_html => {:rel => "/kinds"} %> </div> <div class="field"> <%= f.label :wall_number %><br /> <%= f.text_field :number%> </div> <div id="gradelist" class="field"> <%= f.label :grade %><br /> <%= f.select :grade, Wall::BGrades %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> The Following JavaScript jQuery.ajaxSetup({ 'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") } }); jQuery(function($) { // when the #kind field changes $("#kind").change(function() { // make a POST call and replace the content $.post('/kinds', {id: $("#wall_kind").val()}, null, "script"); return false; }); }) The following JS.ERB template: $("#gradelist").html("<%= label :gbabe, 'Grade'%></br><%=select_tag :gbabe, options_for_select(@grades) %>"); The following action in my walls controller: def grades_by_kind if params[:id].present? @grades = (params[:id] == "Boulder" ? Wall::BGrades : Wall::FGrades) else @grades = [] end respond_to do |format| format.js end end I have the following constants in the wall model: FGrades = %w[5 5+ 6A 6A+ 6B 6B+ 6C 6C+ 7A 7A+ 7B 7B+ 8A 8A+ 8B 8B+ 9A 9A+] BGrades = %w[V0 V0+ V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 15] Kinds = ['Boulder', 'Leading', 'Top Rope'] Changing a selection in the :kind select box, triggers the JS post request, and receives the following response: $("#wall_grade").html("<label for="gbabe_Grade">Grade</label></br><select id="gbabe" name="gbabe"><option value="5">5</option> <option value="5+">5+</option> <option value="6A">6A</option> etc... <option value="8B+">8B+</option> <option value="9A">9A</option> <option value="9A+">9A+</option></select>"); However, the drop down values in the id="gradelist" div presented in the webpage aren't actually changing. Why isn't the HTML being changed? A: Your select isn't changing because you're not doing anything with the response you're getting from the server. You need to specify a callback in your $.post call. Also, you need to convert your grades to an html option list before returning them, perhaps with options_for_select
{ "language": "en", "url": "https://stackoverflow.com/questions/7636394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing command line arguments to mono-service Is there a way to pass command line arguments to a service invoked by mono-service? All of the command line arguments seem to be absorbed by mono-service instead of passed to the service. A: Update: as per my patch that went in end 2011 you can now use the intended interface of mono-service. AFAICT there is no way. The idiomatic way to do things would be to use an app.config file to contain Configuration Sections (in XML). Update That seems odd. The assebmblyArgs [sic] are being passed as part of the activationAttributes to AppDomain.CreateInstanceAndUnwrap Method (String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]), but being ignored in the call to OnStart. You could try compiling a modified version of mono-service.exe using the following source: * see github gist or commit for review Compile to mono-service.exe with -r:System.ServiceProcess.dll -r:Mono.Posix.dll -unsafe OLDER STUFF: Update 1 Strike that. Judging from the code you should just be able to pass options trailing the assembly name. This implies that the following should do what you expect: mono-service -l:/root/service-lock MyService.exe /Param1 /Param2 bla.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/7636395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Adding Snap to jQuery UI Slider, but keeping animation I setup a timeline-like content scroller to do a horizontal slider between 5 years. I wanted to add a snap to between them. This works, though now I don't see the animation sliding from one to the other. How do I have both the animation of scrolling between points and the snap. This is my jQuery snippet: //build slider var scrollbar = $( ".scroll-bar" ).slider({ value: 10, min: 0, max: 100, step: 25, slide: function( event, ui ) { if ( scrollContent.width() > scrollPane.width() ) { scrollContent.css( "margin-left", Math.round( ui.value / 100 * ( scrollPane.width() - scrollContent.width() ) ) + "px" ); } else { scrollContent.css( "margin-left", 0 ); } } }); A: slide: function(event, ui) { if (scrollContent.width() > scrollPane.width()) { scrollContent.animate({ "margin-left": Math.round(ui.value / 100 * (scrollPane.width() - scrollContent.width())) }, 20); } else { scrollContent.animate({ "margin-left": 0 }, 20); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to include logging in a Perl module? I'd like to include logging in a Perl module I am writing, but maintain portability so that applications that use it are not bound to a specific logging mechanism, such as Log::Log4Perl. I've considered; * *Logging to STDERR and leaving it to the application to redirect these messages to it's own logging mechanism (as mentioned in the Log::Log4Perl FAQ). *Including no logging in the module at all. I suspect there is a better way. A: Log::Any Log::Any allows CPAN modules to safely and efficiently log messages, while letting the application choose (or decline to choose) a logging mechanism such as Log::Dispatch or Log::Log4perl. A: Whatever way you end up doing, you're going to have to pick one, and that's going to tie it to a mechanism. So may as well pick one. Why not check if Log::Log4Perl is available? If it is, great, use it. If not, either implement a callback that your users can hook into, or a minimal set of API to let them control what (or if) you log at all?
{ "language": "en", "url": "https://stackoverflow.com/questions/7636404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to play wma file in iphone? I want to build a radio app in iPhone for which wma streaming is necessary. So if u have any idea please help me. thanks in advance A: Matt Gallagher published in his blog a good tutorial with code for playing MP3 streaming in iPhone. I don't know if it will work for WMA, however I think it's a good start point.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android WebView Java-Javascript bridge I wonder if it's possible to obtain Javascript variable value from Java code. In other words, I've got JS code in WebView and I need to be able to obtain variables from that JS code from WebView. A: Yes it's possible by installing Java-JS bridge and then injecting JS into page that collects the data and returns it via JS bridge. See this answer: How to call javascript from Android?
{ "language": "en", "url": "https://stackoverflow.com/questions/7636409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Call JSF action method from custom component with parameters and table I'm trying to make a composite component containing a table with a commandButton on each row, calling an actionmethod taking the row object as a parameter. It would look like this without being a custom component: <h:dataTable value=#{bean.objects} var="obj"> <h:column> <h:commandButton id="button" action="#{bean.doSomething(obj)}" value="Do something with obj" ajax=false"/> </h:column> </h:dataTable> What kind of composite:interface parameters would enable this to work? I've tried with composite:actionSource, composite:attribute with target="button" etc, making the action parameter a f:propertyActionListener etc, but nothing has worked so far. As an ugly solution, I send the controller as a parameter and call methods directly from it, but is there a more elegant way?
{ "language": "en", "url": "https://stackoverflow.com/questions/7636412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Adding methods/modifying classes of a jar Very silly question, I am doing a project and I can't think about any workaround I have implemented new functions in an open jar (let's call it converter), I want to modify one of these methods: ExchangeToEuro, ExchangeToDollar, CheckCurrency. My question is: Are there any mechanism for which I can add functionality (modifying of of these methods or even adding methods to this class) to the class without modifying the jar (without modifying the classes present in the jar)? I thought about a class decorator, but that wouldn't work as I would need to modify the jar itself. A: You can extend classes within Converter.jar, as long as they are not final, and override the methods contained within them, as long as they are visible and not final as well. Say Converter.jar had a class like this: public class ExchangeToDollar { public BigDecimal exchangeEuroToDollar(final BigDecimal euroValue) { ...method implementation.... } } You could extend and override like this: public class MyClass extends ExchangeToDollar { @Override public BigDecimal exchangeEuroToDollar(final BigDecimal euroValue) { ...your implementation.... } } The MyClass.exchangeEuroToDollar(BigDecimal) method overrides the exchangeEuroToDollar(BigDecimal) implementation that's contained within the ExchangeToDollar class in Converter.jar, meaning that when you call the method on an instance of MyClass, your implementation will be executed. The downside of this type of implementation is that any code that you do not have control over that uses ExchangeToDollar will not be able to use your overridden implementation, unless you can pass a MyClass instance in instead. A: It's not entirely clear what kind of modifications you need to make, but if you need to modify class methods themselves, you options are limited to things like AspectJ or less-clean forms of byte-code manipulation using tools like BCEL or ASM. You could conceivably create the additional functionality in a different JVM language like Groovy/etc., compile to .class files, and use those. You may need to provide more and/or less-contradictory info, though. A: Extend the classes, add what new functionality is required, and override that which should change.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VBA Excel - Reading data from another workbook So I'm just trying to call data from a cell in another workbook but my code is just returning "#name?" when I use "cells(3,3)". Cells(1, 1).Formula = "='\\Drcs8570168\shasad\[CR Status.xlsx]Sheet1'!cells(3,3)" However, this does work if I write it like this Cells(1, 1).Formula = "='\\Drcs8570168\shasad\[CR Status.xlsx]Sheet1'!c3" Can someone tell me why? The thing is that I need to use something like cells() so that I can run this through multiple cells and assign the values to an array. Can someone please help me out? Thanks! A: Cells() is a VBA function that doesn't make sense when used in a Formula. To refer to a cell using row and column numbers, you'll need to use the 'R1C1' reference style as described at the bottom of this page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What are the pros and cons of using serialVersionUID and @SuppressWarnings("serial") on classes implementing Serializable? This question has been the subject of some lively discussions in my team. My personal choice is to use @SuppressWarnings("serial") My thoughts are that it means there is one less thing to maintain compared to using serialVersionUID Am I correct in thinking that using this allows the compiler to generate the UID and is therefore more likely to pick up changes to the class? My biggest fear is that relying on a developer to change the UID when they change the class is more likely to lead to unforeseen errors. Are there any pitfalls to my approach? Has anyone else had good or bad experiences using either of these approaches? A: It boils down to this questions: * *Shall the serialized streams be read and written by the just same code or by different code? "Different code" can mean several things: * *old versions vs. new versions *two independent programs with perhaps old and new libraries *more of stuff like that. In these cases you should strongly adhere to the Serialization contracts - and this not done by just setting serialVersionUId - usually you must also overwrite the methods for serialization and deserialization to cope with different versions. If - on the other hand - the same program reads and writes the stuff for something like an internal cache and that cache can be rebuild from scratch on when the software is updated - then feel free to make your life as easy as you can. Between these extremes are of course various shades of grey. A: As usual, the definitive answer is in its own chapter of Effective Java. TL;DR. Using @SuppressWarnings("serial") is fine (and good for removing the warning) unless you actually want to serialize the class. In that case, you want to actually implement serialVersionUID, and do it properly, regenerating (or at least changing) it after every change in the class that would cause problems in deserialization. A: When serialising an Object, if it has a serial identifier it will be used, otherwise it will be generated. If the serial identifier is missing and the javac option -Xlint is specified, a warning will be generated. This warning can be muted with @SuppressWarnings("serial"). The purpose of this annotation is just to suppress the warning, it will not interfere in any other way with the serialisation. From Serializable Javadoc: The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. and also: If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Example: serialising a class with @SuppressWarnings("serial") Test.java : the class to be serialised import java.io.Serializable; @SuppressWarnings("serial") class Test implements Serializable { int a = 0; public Test() { } public Test(int arg) { a = arg; } } Writer.java : the class that writes an instance of Test to the file test.serial import java.io.*; class Writer { public static void main(String[] args) { Test t = new Test(2); String filename = "test.serial"; try { FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(fos); out.writeObject(t); out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } A: Not using serialVersionUID is the conservative approach. Any change in the serialized format will be considered an incompatible change. It means you may find errors when deserializing objects written by an older version, that might actually make sense to deserialize, had you written custom deserialization code and used serialVersionUID. Using it has the benefit of possibly preserving compatibility across more versions of the serialized object, but, introduces a new type of potential bug: if you forget to update serialVersionUID after changing a class in an incompatible way, the best thing that can happen is that you also get an error at runtime because the data can't be read sensibly. But, it might silently succeed, perhaps ignoring or misinterpreting serialized data in the process. So, first decide which one you want: use it or not? I definitely default to not using serialVersionUID unless it's clearly needed, and there's a commitment to maintain it correctly. If you don't use it, you can turn off warnings with @SuppressWarnings, but, you can also turn it off globally in javac with -Xlint:-serial. That's a coarse approach -- convenient perhaps, but make sure you really want to do that. It's appropriate if, for instance, you definitely don't use serialVersionUID anywhere. A: If you think you will need to add anything to this class in the future then go ahead and hardcode serialVersionUID to 1L if you don't have serialized objects already. If you do have serialized objects already and need to stay compatible with them use the serialver tool to find out what Java has set this to and use that value. This way you will be able to add attribute to this class in the future and be able to automatically stay compatible. If you don't do the above then this won't be handled automatically and you must write code to convert from the old classes to the new classes each time you add a field to the class. A: I have to say your choice of SuppressWarning is bad. You should explicitly define serialVersionUID. Maintaining it is not that much work while it'll save your life in future. Some time in future, you want to change the class definition (inevitable if your work is serious) while achieving backward compatibility, serialVersionUID will save your life. If you don't define it, Java will calculate serialVersionUID for you based on the class signature (?); simply reordering the variables would change the signature and break compatibility (or even adding a helper function). Seriously, defining serialVersionUID will save your life. You should read the Serialization section in Effective Java as suggested by other folks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: ComponentOne : C1NavigationList databinding with XMLDataSource In the process of Iphone View ability for a shopping cart system, where i am trying to implement using the ComponentOne tools for Iphone in the products listing.For which i have identified C1NavigationList control for the same. As i understand it is a Hierarchical data control, i am binding it to an XML DataSource, as i don't need any sub items but a collection of main items where the details as attributes of the XML node as below: Requirement: I would like to define a layout in the C1Navigation list template and XPath bind the data as in the given screen grab above. Given below is the code which i have tried to do but failed.It throws me the error :"Databinding methods such as Eval(), XPath(), and Bind() can only be used in the...." What am i doing wrong?.Please advice me. <asp:XmlDataSource ID="XmlDataSource1" runat="server" XPath="/NewDataSet/_x0028__x0028" DataFile="~/App_Data/Copy of Coffee____1__0__0_0_d.xml"> <C1NavigationList:C1NavigationList ID="C1NavigationList1" runat="server" DataSourceID="XmlDataSource1" Text="XMLDataSource" NavigationListType="RoundedCornersList" TrackItemsStructure="false"> <%# XPath("@item_smkt_desc")%> A: I would use a for loop to do this instead of XmlDataSource. Then you have more control over the UI anyways. I have used this method quite a bit successfully. Here is how I would write you code: System.Xml.Linq.XElement xEle = System.Xml.Linq.XElement.Load(Server.MapPath("~/App_Data/Copy of Coffee___1_0__0_0_d.xml")); var items = from c in xEle.Elements("NewDataSet") select c; foreach (System.Xml.Linq.XElement ele in items) { C1.Web.iPhone.C1NavigationList.C1NavigationListItem li = new C1.Web.iPhone.C1NavigationList.C1NavigationListItem(); li.Text = ele.Attribute("item_smkt_desc"); C1NavigationList1.Items.Add(li); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binding boolean DependencyProperty to a button's Visibility property in Generic.xaml I have a class called CarSystemWindow that descends from Window, and it has a CanPinWindow boolean dependency property: public class CarSystemWindow : Window { public static readonly DependencyProperty CanPinWindowProperty = DependencyProperty.Register( "CanPinWindow", typeof( bool ), typeof( CarSystemWindow ), new FrameworkPropertyMetadata( false, FrameworkPropertyMetadataOptions.AffectsArrange ) ); public bool CanPinWindow { get { return (bool) GetValue( CanPinWindowProperty ); } set { SetValue( CanPinWindowProperty, value ); } } . . . } In Generic.xaml, I have defined the default style for the CarSystemWindow class: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:CarSystem.CustomControls" xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" xmlns:Telerik_Windows_Controls_Chromes="clr-namespace:Telerik.Windows.Controls.Chromes;assembly=Telerik.Windows.Controls"> <BooleanToVisibilityConverter x:Key="BoolToVisbility" /> <Style TargetType="{x:Type local:CarSystemWindow}"> <Setter Property="WindowState" Value="Maximized" /> <Setter Property="WindowStyle" Value="None" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:CarSystemWindow}"> <Viewbox Name="LayoutRoot" Stretch="Uniform"> <StackPanel> <Grid Background="#FF3C4B66" Height="50" Name="PART_Title"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="50" /> <ColumnDefinition Width="50" /> <ColumnDefinition Width="50" /> </Grid.ColumnDefinitions> <Label Content="{TemplateBinding Title}" FontSize="32" Foreground="White" Grid.Column="0" HorizontalAlignment="Left" Name="PART_TitleLabel" /> <Button Grid.Column="1" Margin="5" Name="PART_PushpinButton" Visibility="{Binding CanPinWindow, Converter={StaticResource BoolToVisbility}, RelativeSource={RelativeSource Self}}"> <Image Name="PART_PushpinImage" Source="/CarSystem;component/Resources/Unpinned.png" /> </Button> <Button Grid.Column="2" Margin="5" Name="PART_MinimizeButton"> <Image Name="PART_MinimizeButtonImage" Source="/CarSystem;component/Resources/Minimize.png" /> </Button> <Button Grid.Column="3" Margin="5" Name="PART_CloseButton"> <Image Name="PART_CloseButtonImage" Source="/CarSystem;component/Resources/Close.png" /> </Button> </Grid> <Rectangle Fill="#FFE61E0F" Height="4" Name="PART_TitleBar" /> <Grid Background="#FF3C4B66" Height="25" Name="PART_SubTitle"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Label Content="{TemplateBinding DeviceType}" FontSize="22" Foreground="White" Grid.Column="0" HorizontalContentAlignment="Right" Margin="5" MinWidth="75" Name="PART_DeviceTypeLabel" /> <Label Content="{TemplateBinding DeviceName}" FontSize="22" Foreground="White" Grid.Column="1" HorizontalContentAlignment="Left" Margin="5" MinWidth="250" Name="PART_DeviceNameLabel" /> <Rectangle Fill="White" Grid.Column="2" Name="PART_SubTitleRight" /> </Grid> <Rectangle Fill="#FF3C4B66" Height="4" Name="PART_TitleBottom" /> <ContentPresenter Name="PART_ClientArea" /> </StackPanel> </Viewbox> </ControlTemplate> </Setter.Value> </Setter> </Style> . . . </ResourceDictionary> The binding for the PART_PushpinButton Button's Visibiility property isn't working. The button is always visible, even though the property defaults to false. What am I doing wrong? Tony A: I think the RelativeSource should be TemplatedParent, not Self. Or am I missing some part of your code? <Button Grid.Column="1" Margin="5" Name="PART_PushpinButton" Visibility="{Binding CanPinWindow, Converter= {StaticResource BoolToVisbility}, RelativeSource={RelativeSource TemplatedParent}}">
{ "language": "en", "url": "https://stackoverflow.com/questions/7636444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Facebook CSharp Api using graph api to get other users feed, issue Im trying to get o other users feed in ASP.NET using Facebook CSharp API LIB, but with no sucess. The results not cover all wall posts, only external posts to that came from other users to that user. Here is piece of my code that call facebook graph api get : var result = (IDictionary<string, object>)fb.Get(user.id + "/feed"); Might be something very simple that I couldn't figure out yet... A: I'm not sure i see a problem here, the /feed connection approximately represents that user's wall - you should be able to see any posts on the user's wall which are visible to the user whose access token you're using - is that not the case? A: Thanks, I discover that is the permission of app to "read_stream"
{ "language": "en", "url": "https://stackoverflow.com/questions/7636446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: "=~" raise "No instance for (RegexContext Regex [Char] [String])" OS: MacOSX 10.7.1 GHC and Haskell-platform from brew. GHCi, version 7.0.4: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Loading package ffi-1.0 ... linking ... done. Prelude> :m +Text.Regex.Posix Prelude Text.Regex.Posix> "foo" =~ "o" :: [String] <interactive>:1:7: No instance for (RegexContext Regex [Char] [String]) arising from a use of `=~' Possible fix: add an instance declaration for (RegexContext Regex [Char] [String]) In the expression: "foo" =~ "o" :: [String] In an equation for `it': it = "foo" =~ "o" :: [String] Prelude Text.Regex.Posix> "foo" =~ "o" :: String Loading package array-0.3.0.2 ... linking ... done. Loading package bytestring-0.9.1.10 ... linking ... done. Loading package containers-0.4.0.0 ... linking ... done. Loading package transformers-0.2.2.0 ... linking ... done. Loading package mtl-2.0.1.0 ... linking ... done. Loading package regex-base-0.93.2 ... linking ... done. Loading package regex-posix-0.95.1 ... linking ... done. "o" I believe libraries updated. And I think the output of "foo" =~ "o" :: [String] is ["o", "o"] Any suggestion will be appreciate. A: This also works ghci> getAllTextMatches $ "foo" =~ "o" :: [String] ["o","o"] A: Try this: Prelude Text.Regex.Posix> getAllTextMatches ("foo" =~ "o" :: AllTextMatches [] String) ["o","o"] A: Another possible solution is: map head $ "foo" =~ "o" :: [String] Explanation Binding the result of (=~) to [[String]] will yield a list of matches, in which each match is represented by list of strings. In each list, its head will be the whole match and it's tail the matches for each submatches: > "foo goo bar" =~ "(.)o(.)" :: [[String]] [["foo","f","o"],["goo","g","o"]] -- Get the second submatch (2) of the first match (0) > "foo goo bar" =~ "(.)o(.)" !! 0 !! 2 :: String "o" -- Get the first submatch (1) of the second match (1) > "foo goo bar" =~ "(.)o(.)" !! 1 !! 1 :: String "g" In short, map head $ string =~ regexp :: [String] contain the whole matches of regexp in string. map tail $ string =~ regexp :: [[String]] contain the sub-matches, indicated in the original regexp by encosing parentheses (). A: ghci> getAllTextMatches ("foo" =~ "o" :: AllTextMatches [] String) ["o", "o"] I haven't used regexes in Haskell much (which is I think Dan Burton's answer is more idiomatic). So the way I figured this out is I looked at your type error No instance for (RegexContext Regex [Char] [String]), and popped into ghci: ghci> :t (=~) (=~) :: (RegexMaker Regex CompOption ExecOption source, RegexContext Regex source1 target) => source1 -> source -> target So RegexContext Regex [Char] [String] is a class that includes the return type of "foo" =~ "o" :: [String]. So I looked to see what instances of this class did exist, so I could find out what the return value was allowed to be: ghci> :i RegexContext class RegexLike regex source => RegexContext regex source target where match :: regex -> source -> target matchM :: Monad m => regex -> source -> m target -- Defined in Text.Regex.Base.RegexLike instance RegexContext Regex String String -- Defined in Text.Regex.Posix.String instance RegexLike a b => RegexContext a b [[b]] -- Defined in Text.Regex.Base.Context ... instance RegexLike a b => RegexContext a b (AllTextMatches [] b) -- Defined in Text.Regex.Base.Context ... The AllTextMatches name seemed to indicate what you were looking for, so I checked that out: ghci> :i AllTextMatches newtype AllTextMatches f b = AllTextMatches {getAllTextMatches :: f b} -- Defined in Text.Regex.Base.RegexLike instance RegexLike a b => RegexContext a b (AllTextMatches [] b) -- Defined in Text.Regex.Base.Context So this was the type to use to extract all the text matches, as I suspected. All I needed to do was indicate that I wanted a return value of that type. Note also the possible return type of [[b]], which I assume returns a list of lists containing each complete match and all its submatches: ghci> "foo" =~ "o" :: [[String]] [["o"],["o"]] ghci> "foo bar baz" =~ "[aeiou](.)" :: [[String]] [["oo","o"],["ar","r"],["az","z"]] So maybe that's the type you meant to use, instead of [String]. I could see [String] as being slightly ambiguous when [[String]] existed - should "foo bar baz" =~ "[aeiou](.)" :: [String] be fst ("foo bar baz" =~ "[aeiou](.)" :: [[String]]) or map fst ("foo bar baz" =~ "[aeiou](.)" :: [[String]]).
{ "language": "en", "url": "https://stackoverflow.com/questions/7636447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Salesforce SOQL To Get Case Owner In One Hit Using Salesforce SOQL I can get the Owner's Id using the following: SELECT Case.OwnerId FROM Case WHERE Case.CaseNumber = '00001234' I can then get the User details for the User who owns the case in this query: SELECT User.Id, User.Name, User.Custom_Field__c FROM User WHERE User.Id = '001A0000001abc1DEF' But I can't get it to work in a single statement, I think this is because Owner != User, even though the owner is in fact a user in this case. I have tried: SELECT Owner.Custom_Field__c FROM Case WHERE Case.CaseNumber = '00001234' But I get an error that the Custom_Field__c is not a valid field. A: Owner on Case is a polymorphic relationship, it can be one of multiple different types. When that happens then using SOQL-R you can only select a subset of fields that are common to the types being pointed to (these are all exposed on a pseudo entity called "Name"), so you won't be able query the custom fields on User. You'd have to do a query on Case, then collect up the set of Owners and make a query to User and/or Group to the get more detailed information. A: You can do this with a semi-join in SOQL. I tested it out, and it still works even though Owner is polymorphic: SELECT Custom_Field__c FROM User WHERE Id IN (SELECT OwnerId FROM Case WHERE Case.CaseNumber = '00001234')
{ "language": "en", "url": "https://stackoverflow.com/questions/7636449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Different Java Code in a Project (How to reach variables) I wrote a simple drawing program, and for to create a menu, I used this source, http://download.oracle.com/javase/tutorial/displayCode.html?code=http://download.oracle.com/javase/tutorial/uiswing/examples/components/MenuLookDemoProject/src/components/MenuLookDemo.java Therefore in my program to show the menus, I only added these lines: MenuDemo demo = new MenuDemo(); frame.setJMenuBar(demo.createMenuBar()); When I started the program, menu successfully works, but on the other hand, for example, when I click sth on menu, in method "actionPerformed" I want to change my program's boolean variable. But "actionPerformed" is exist in "MenuLookDemo.java", therefore I cannot reach the variables. Can you suggest a solution please ? Thanks A: Maybe you can rewrite the class MenuDemo and pass your Object to MenuDemo to access your variable. class MenuDemo{ YourType obj; MenuDemo(YourType obj){ this.obj = obj; } // Now you can access elements of obj } A: Building off of what Pikaurd has above, do this: public class MyType { int x; public void doTheNeedful() { x = 5; } } Then make sure MenuDemo contains a field obj of class MyType. Inside actionPerformed(), call obj.doTheNeedful(). I'm deliberately not just giving you the code on this; the sentence above should be enough for you to figure it out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's difference between and null in JAXB? I am have created a Java Webservice application which uses JAXB. When I test my application using SoapUI and I send a SOAP message like <foo></foo>, it will convert to 0, but if there's no <foo> tag in my SOAP message, it will convert to null. Why is <foo></foo> not converted to null? How can I change it? @WebMethod public void test(Integer foo) { System.out.print(foo); } A: null generally indicates "unknown". Since foo isn't present, there is absolutely NO information about it. You can't assign a default 0, because that might be absolutely wrong/catastropic. All you can do is say "I don't know", which boils down to null. On the other hand, <foo></foo> means that foo is present and is empty, which does generally boil down to a 0. A: If you are using JAXB 2.2 then you can specify the @XmlElement(nillable=true) annotation at the parameter level to have the XML represented as xsi:nil="true". @WebMethod public void test(@XmlElement(nillable=true) Integer foo) { System.out.print(foo); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Passing Objects to table cell from plist i will like to seek advise on what should i do next in order to pass a list of data from Plist to an array. i will like to pass the plist data to my tableview BrowseViewController.m, but i do not know how to do it. i tried NSlog, the plist are passing info over but i don't know wat is my next step. can anyone teach me ? thanks alot. this is my Plist <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <dict> <key>AudioFileDescriptions</key> <array> <string></string> <string></string> <string></string> <string></string> </array> <key>CommonName</key> <string>Cane Toad </string> <key>ScientificName</key> <string>Bufo marinus </string> <key>Species</key> <string>marinus</string> </dict> my app delegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions { // Override point for customization after application launch. // Add the tab bar controller's current view as a subview of the window self.window.rootViewController = self.tabBarController; [self.window makeKeyAndVisible]; //load frog information from plist NSBundle *bundle = [NSBundle mainBundle]; NSString *eventsPath = [bundle pathForResource:@"Frog" ofType:@"plist"]; frogObject = [Frog frogObjectWithContentsOfFile:eventsPath]; return YES; } Frog.m + (id)frogObjectWithContentsOfFile:(NSString *)aPath { Frog *frogObject = [[Frog alloc] init]; if (frogObject) { // load all frogs from plist NSMutableArray *allFrogsArray = [NSArray arrayWithContentsOfFile:aPath]; //NSDictionary *allFrogsArray = [NSDictionary dictionaryWithContentsOfFile:aPath]; if (allFrogsArray == nil) { [frogObject release]; } [frogObject.allFrogs addObjectsFromArray:allFrogsArray]; // iterate through each event and put them into the correct array NSEnumerator *frogsEnumerator = [allFrogsArray objectEnumerator]; NSDictionary *currentFrog; while (currentFrog = [frogsEnumerator nextObject]) { [frogObject addFrog:currentFrog]; } // NSLog(@"FrogObject %@",allFrogsArray); } return frogObject; } - (void)addFrog:(NSDictionary *)anFrog; { NSLog(@"anFrog Value %@",anFrog); } A: You should probably rework the structure of the code, why does the "FrogObject" holds an array to all the frogs? It's semantically confusing, as you expect that a FrogObject holds the data for a single entity, not the whole set. A way would be to make the FrogObject know how to load multiple frogs, but return the array. For example, the frog object would look like: @interface Frog : NSObject @property (nonatomic,retain) NSString* commonName; @property (nonatomic,retain) NSString* scientificName @property (nonatomic,retain) NSString* species; + (NSArray*)frogsFromFile:(NSString*)filePath; - (Frog*)initWithDictionary:(NSDictionary*)frogDictionary; @end The frogsFromFile: can create multiple instances of frogs (each one with its own sub-dictionary with initWithDictionary:), but most importantly, it returns it, it doesn't hold it. Next, you can use to present it in a tableView, for example (BrowseViewController.h): @interface BrowseViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { NSArray *frogs; } BrowseViewController.m - (void)viewDidLoad { [super viewDidLoad]; frogs = [Frog frogsFromFile:[[NSBundle mainBundle] pathForResource:@"Frog" ofType:@"plist"]]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [frogs count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"frogCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease]; } Frog *frog = [frogs objectAtIndex:indexPath.row]; cell.textLabel.text = frog.commonName; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Want to stop the data going into OS/application after read using SetWindowsHookEx I am developing one simple application which is reading the keystrokes from the OS. I have used API "SetWindowsHookEx" to read the keystroke data. Currently data is read by the hook as well sent into the OS or application. I want to stop this data going into the OS or other applications. Is there any way to stop the data going into the windows 7 OS after read it using "SetWindowsHookEx"? A: Generally, to prevent any message to move to be sent to its target, don't call CallNextHookEx from the hook callback function. By default, hook callback calls CallNextHookEx. Bee careful with this feature and stop only some specific messages. For example, sometimes this function is called to disable some standard keys like Alt+F4, Alt+Tab etc. A: If you are using a "normal" Keyboard Hook you will find your answer on https://msdn.microsoft.com/en-us/ms644984.aspx: If code is less than zero, the hook procedure must return the value returned by CallNextHookEx. If code is greater than or equal to zero, and the hook procedure did not process the message, it is highly recommended that you call CallNextHookEx and return the value it returns; otherwise, other applications that have installed WH_KEYBOARD hooks will not receive hook notifications and may behave incorrectly as a result. If the hook procedure processed the message, it may return a nonzero value to prevent the system from passing the message to the rest of the hook chain or the target window procedure. If you are using a low level keyboard hook its written on https://msdn.microsoft.com/en-us/ms644985.aspx: If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. If nCode is greater than or equal to zero, and the hook procedure did not process the message, it is highly recommended that you call CallNextHookEx and return the value it returns; otherwise, other applications that have installed WH_KEYBOARD_LL hooks will not receive hook notifications and may behave incorrectly as a result. If the hook procedure processed the message, it may return a nonzero value to prevent the system from passing the message to the rest of the hook chain or the target window procedure. Summary: If you want to intercept a message - yust don't call CallNextHookEx and return a non-zero value prevent it from being passed down the chain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xcode 4.1 not adding library for BCTabBarViewController I wanted to try out BCTabBarController and added the files to my test-project by: * *Dragging the BCTabBarController.xcodeproj onto my project in the project navigator. *Going to my project/target/Build Phases/Target Dependencies and adding BCTabbarController (little house icon) *Going to project/target/Build Phases/Link Binaries With Libraries and add the libBCTabbarCOntroller. Usually when I add a library like this, the .a library file will show up in my project navigator (and I drag it to frameworks to keep things tidy). Strangely enough this did not happen with the libBCTabbarController.a file, it was nowhere. And surely enough, the BCTabBarController.h header is not recognized anywhere. What can cause this behavior? My debugging options are pretty limited, but I suspect that Xcode 4.1 finds something about the library it does not "like" and does not add it to my project. A: It would be a lot easier to just use the source code files in your current project then trying to build a library, import it, etc. Then that way you can customize the source if you desire, without having to rebuild the lib/framework and re-import it. A: Select the BCTabbar as a target and build it .then repeat the above it would add
{ "language": "en", "url": "https://stackoverflow.com/questions/7636477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Prevent entity from being created, but need entity for native query I have a native query that executes a stored procedure and the results is mapped to an entity, this works fine but the thing is the entity is created in the database (I'm referring to the actual table being created, but this table will always be empty), any way to prevent this? I'm using JPA with hibernate and Sql Server 2005 Thanks A: You shouldn't use an entity if it's not supposed to be stored in any database table. The query should return a list of objects which are instances of a class not annotated with @Entity. That being said, letting hibernate generate the database schema for you is something you should only do for quick prototyping, at the very beginning of a project. Later, the schema should not be created automatically anymore.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a curve vertex on OpenGL C++ I am learning how to make a 2D object with OpenGL. I made a simple rectangle with GL_QUADS with four vertex 3f example vertex1, vertex2, vertex3, vertex4. The question is, is there anyway so I can make a curve sides from that vertex(example : from v1 to v2 is the left side of the rectangle, I just want to know how to make a curve side from v1 to v2). A: Use a Bezier curve or something similar to generate additional vertices. A: AFAIK there is no way to draw a curve out of the box. What you could do is to draw several lines with GL_LINE_STRIP and to pass your vertices. Of course you have to create your own vertices. There are several curve algorithms, but as genpfault states, the Bezier Curves are a good-looking starting point.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: can search engine searches content in query-string? My page URL is www.xyz.com/default.aspx?name=searching-my-new-code Is google reads name query-string "name" value in searching algorithm??? Suppose i am searching on google "searching my new code" at that time google searching algo code can read this value from my URL or not? A: Search engines can easily read and parse query strings so your URL would be indexed just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Replacing a word by synonyms in Haskell I was going through this plagiarism detector and trying to write a program in Haskell which will read a file and replace some of its words with synonyms. Is there any dictionary available for this purpose in Haskell? Also, if you have any input regarding algorithm or any other input relevant for this problem, like how to avoid changing the context of a statement by replacing a word by its synonyms, then please post it. A: is there any dictionary available for this purpose in Haskell? I would imagine that what you are looking for is a plain text file, something like this: word1: word1synonym1, word1synonym2, ... word2: word2synonym1, ... ... In which case it wouldn't really be Haskell-specific. I'm unaware of any free text-file thesauruses like this, though I imagine if you dig around LibreOffice you would probably find one. how to avoid changing the context of a statement by replacing a word by its synonyms This is very hard for a computer to do, afaik. I would suggest not expending much effort working on this aspect of it. any input regarding algorithm You may find the concept of edit distance useful for this problem. See Approximate string matching and Wagner-Fischer algorithm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why use ? From a presentation perspective, if I write a text between a <label> tag it looks identical as to if I hadn't. So, why do we use this tag at all? A: HTML is not about presentation. It is a way of describing data. If you have some text that represents a label for an input, you wrap it in label tags not for presentation but because that's what it is. Without the label tag, that text is almost meaningless. With the label tag and its for attribute (or not*) you are providing meaning and structure and forming a relationship between your markup that can be better understood by computers/parsers/browsers/people. * you don't necessarily need the for if you wrap the label around the input: <label>My input <input type="text" id="my-input" /> </label> A: When you click on the label, the focus goes to the related input. Very handy for checkboxes when it is hard to hit the small rectangle. A: The for attribute of a label element corresponds to the id attribute of an input element. If you click the label, it puts focus on the input box. Example: <input type="checkbox" id="agree" /> <label for="agree">I agree with the Terms and Conditions</label> See this in action. If you click on the text, it checks the box. A: The HTML <label> tag has one special feature: It allows you to provide a for attribute which links the label to an input field or other control, such that when the user clicks on the label, it is as if he clicked on the control. eg: <label for='mycontrol'>Label text</label> <input type='checkbox' name='mycontrol' id='mycontrol' value='1'> This would mean that when the user clicks on the 'Label text', the checkbox would be toggled. This is useful for accessibility, general usability, and also allows some tricks such as making a toggle control that doesn't look like a checkbox, but does contain one behind the scenes. But aside from this for feature, the <label> element is basically the same as any other HTML element. If you're not going to use the for attribute, it may still be correct to use a <label> element, for semantic reasons. A: HTML tags are meant to convey special meaning to users of various categories. Here is what label is meant for: * *For people with motor disabilities (also for general mouse users) Correctly used label tags can be clicked to access the associated form control. Eg. Instead of particularly clicking the checkbox, user can click on more easily clickable label and toggle the checkbox. *For visually-challenged users Visually challenged users use screen-readers that reads the associated label tag whenever a form control is focused. It helps users to know the label which was otherwise invisible to them. Read more about labelling here A: From HTML label tag: "The label element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the label element, it toggles the control. The for attribute of the tag should be equal to the id attribute of the related element to bind them together." A: Nothing from presentation point of view. Lable tag is used for defining label for an input element. From the semantic point of view, it should not be used for defining text. A: If you don't use tag then you will have to click on the exact tiny circular space to select an option. But,if you use tag then you will just have to click anywhere on the text(or the tiny circular blank space) to select an option. NOTE:-The tag just bound the small circular blank area with the text associated with it. Thats it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "58" }
Q: Java regex pattern Is there any way of excluding this characters: - \ _ to this pattern? I need especifically this pattern and no other Pattern pattern = Pattern.compile("[\\p{P}\\p{Z}]"); A: Use character class subtraction: Pattern.compile("[\\p{P}\\p{Z}&&[^-_\\\\]]"); A: Generally to exclude a character you prepend it with ^. for example to match any number of characters that do not containt character 'a' you write: [^a]*
{ "language": "en", "url": "https://stackoverflow.com/questions/7636504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: Can I have a string as a key and a function as value in a dictionary? In other words, is this giving me errors purely because it's impossible to actually do or am I just writing it wrong: class someClass: self.myString = "Hello" self.myMap = { 'someString' : self.functionInClass } So if functionInClass takes an argument, I want to call it like so from anywhere inside the class: self.myMap[self.myString](theArgument) This just yields: NameError: name 'self' is not defined Any help would be appreciated. A: Yes you can do that, since methods (or bound methods) are just objects themselves. In your code you forgot your function. I think you wanted to write somthing like this: class someClass: def __init__(self): self.myString = "Hello" self.myMap = { 'someString' : self.functionInClass } def functionInClass(self): pass A: This is perfectly valid. >>> def f(): ... print "test" ... >>> d = {'df':f} >>> d['df']() test >>> This test code does not use a class, but same thing can be done with a class too. The error shows that self is not defined, it has nothing to do with functions in dictionary. A: There's nothing impossible about what you're trying to do: class Test(object): def func1(self, arg): print 'func1, arg=%s' % arg def func2(self, arg, **kwargs): print 'func2, arg=%s, kwargs=%s' % (arg, kwargs) funcmap = {'func1': func1, 'func2': func2} def invoke(self, fname, *args, **kwargs): Test.funcmap[fname](self, *args, **kwargs) test = Test() test.invoke('func1', 0) test.invoke('func2', 42, kw=12) A: Your code should work. Probably you just forgot something. This works pretty well for me: class someClass: def __init__(self): self.myString = "someString" self.myMap = { 'someString' : self.functionInClass } def functionInClass(self, argument): print argument def someMethod(self): self.myMap[self.myString]("argument") cl = someClass() cl.someMethod() cl.myMap[cl.myString]("argument") A: If you wish for myMap to be a class attribute, make the dict values the string-name for the methods and use getattr to retrieve the actual method: class SomeClass(object): myMap = { 'someString' : 'methodInClass' } def methodInClass(self,argument): pass x = SomeClass() getattr(x,x.myMap['someString'])('argument')
{ "language": "en", "url": "https://stackoverflow.com/questions/7636508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How is this a nullpointerexception? I'm really confused: I'm simply trying to add the names of each object in an ArrayList to another ArrayList. for (int i = 0; i < availableParts.size(); i++) { for (int j = 0; j < namesOfIngredients.size(); j++){ if (availableParts.get(i).getName() != namesOfParts.get(j)){ namesOfParts.add(availableParts.get(i).getName()); } }//middle if statement makes sure there are no repeats } EDIT: I realize namesOfIngredients is null. However, I need it to start null -- this is how I am copying over the names. Can this just not be done this way? A: Make sure that * *both lists availableParts and namesOfIngredients are not null *The list that you're adding elements to (namesOfParts) has been properly initialized with a constructor (is not null). *All elements inside these lists are not null And remember that String comparison is done with String.equals(). Checking equality (==) on two String objects will only return true if they are the same instance. As a side note, you could consider using List.contains() in order to find out if a certain part's name is on the namesOfIngredients list. Also, maybe it's a typo, but you should be checking for an IndexOutOfBoundsException at namesOfParts.get(j) in that equality check. A: You're trying to look at namesOfParts in the loop itself, but in the definition of the loop you're going to the length of namesOfIngredients. Is one of them null? I bet one is. A: availableParts.get(i) is probably null and therefore a getName() call results in a NPE. A: We don't know: we can't see how availableParts and namesOfParts are initialized. But we can tell you how to find out. Add print statements like this: print "Before I try it" print availableParts.get(i) print namesOfParts(availableParts.get(i)) print "done" when it NPE's you'll see exactly which one did the deed. A: You seem to be invoking a number of methods within your loop, without checking that the object on which you are invoking it is NULL or not. It is ALWAYS advisable to do so (especially, if you are not sure about the contract of the object returned by a given method) So, basically, whenever you do something like object.method() and/or object.method1().method2(), ensure that object and/or object.method1() is NOT NULL before invoking follow-up methods on their return values. Also, you could break calls in the following manner, to better debug and catch NPEs at the exact location: Object returnObj = object.method1(); Object anotherReturn = returnObj.method2(); A: Given your edit - how do you declare namesOfIngredients? It should be Object namesOfIngredients = new Object(); not Object namesOfIngredients;
{ "language": "en", "url": "https://stackoverflow.com/questions/7636509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom ActionResult always returns empty string for "ContentType" I've got the following custom ActionResult. It works properly if I "Force" the ContentType, but the default behavior appears to be to retrieve an empty string as the ContentType C# Version public ActionResult Restful(Web.Mvc.Controller controller) { // Test code var contentType = controller.Request.ContentType; // Above always returns "" switch (ResultType(controller)) { case RestfulResultType.Html: ViewResult result = new ViewResult(); return result; case RestfulResultType.Json: JsonResult result = new JsonResult(); return result; case RestfulResultType.JsonP: JsonPResult result = new JsonPResult(); return result; case RestfulResultType.Xml: return new XmlResult(null); default: ViewResult result = new ViewResult(); return result; } } VB.NET Version <Extension()> Public Function Restful(controller As Web.Mvc.Controller) As ActionResult ''# Test code Dim contentType = controller.Request.ContentType ''# Above always returns "" Select Case ResultType(controller) Case RestfulResultType.Html Dim result As New ViewResult() Return result Case RestfulResultType.Json Dim result As New JsonResult() Return result Case RestfulResultType.JsonP Dim result As New JsonPResult() Return result Case RestfulResultType.Xml Return New XmlResult(Nothing) Case Else Dim result As New ViewResult() Return result End Select End Function Why wouldn't I be getting the appropriate contentType from this? PS: if you care what ResultType does, here it is. Private Function ResultType(controller As Web.Mvc.Controller) As RestfulResultType Select Case LCase(controller.HttpContext.Request.ContentType) Case "text/html" : Return RestfulResultType.Html Case "application/json" : Return RestfulResultType.Json Case "text/javascript" : Return RestfulResultType.JsonP Case "application/javascript" : Return RestfulResultType.JsonP Case "application/x-javascript" : Return RestfulResultType.JsonP Case "text/xml" : Return RestfulResultType.Xml Case "application/xml" : Return RestfulResultType.Xml Case Else : Return RestfulResultType.Html End Select End Function A: Request.ContentType is The mime type of the body of the request (used with POST and PUT requests) You should inspect HttpRequest.Accept header value Content-Types that are acceptable
{ "language": "en", "url": "https://stackoverflow.com/questions/7636516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: QT Creator easier "contexthelp" I just started using the QT Creator but there's some stuff that really annoys me... I like that i can show the coding window and the context help window next to each other. But the shortcut for showing the context help for the currently selected Symbol is F1, which is just terrible as Mac-User @_@ Now it would be nice if I could either put in on alt+"left mouse button". What would be even better is, if i select a word with the mouse and it's a QT-Object like QSlider, to automatically change the content of the help window to the selected word. Any help on that matter? :/ A: Yes, you can customise the Keyboard short-cuts in Qt Creator: * *Open the Options dialog (on Windows, it's via Tools->Options - I presume it'll be somewhere different on a Mca) *In the Environment page, select the Keyboard tab. *Scroll down to the Help section, and change the setting on the Context command from F1 to whatever you want it to be. This should go some way to making it easier for you to use. Edit If you want to make wider changes, you could always import a .kms QtCreator keyboard definitions file that someone else has created. For example, searching for 'qt creator kms' points to: * *TextMate key mapping scheme for Qt Creator *XCode Keyboard Mapping for Qt Creator
{ "language": "en", "url": "https://stackoverflow.com/questions/7636519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RangeValidator to revalidate when a new value is entered I have a asp RangeValidator of type money. When I enter a value that is below or above the min/max value I get an error message (onblur) as expected. However, when I re-enter a new value within the min/max, the error remains. The page does validate and lets me pass but I want the validator to reevaluate onblur. Is this possible without writing a custom solution? A: Just do this on the TextBox onblur='Page_ClientValidate();'
{ "language": "en", "url": "https://stackoverflow.com/questions/7636520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .Net remoting: Reversing the connection Ok so this is the first time I'm playing with .net remoting but seems fun so far. Creating a server that exposes a remoting object and then consuming it from a client is a piece of cake and works like a charm. (I'm using a TcpChannel btw) What I wanna do now is reverse the connection. Currently the server opens a port and listens for the client, the client connects and gets the reference of the object and has fun with it. The only thing I want changed is that the client will wait for the connection instead of the server. The object should be still created on the server and used from the client. Does this make sense to anyone?! And if so, is this possible? A: When working with Remoting, it's useful to agree on the meanings of the terms "server" and "client". The "server" is the machine that's listening for connections. The "client" is the machine that initiates the connection. Using those definitions, you want the client to initiate the connection and then have the server call methods on a client-created object. So what you want is: * *The client creates a MarshalByReferenceObject that contains the methods the server will call. *The client initiates a connection with the server and passes that object reference to the server. *The server stores that object reference, and calls methods on that object as necessary. All that said, I agree with the comment that says you should use WCF rather than remoting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any way/trick to pass std::set to a C API which expects C Array? Is there is a way/trick to pass std::set to a C API which expects C Array? A: No, but you could fill an array with your set contents pretty quickly. For example, assuming mySet is a set of the same type as YOUR_TYPENAME: YOUR_TYPENAME arr* = new YOUR_TYPENAME[mySet.size()]; std::copy(mySet.begin(), mySet.end(), arr); Then just pass arr into the C API. A: Not directly, but you can first convert the set to a vector (called, say, vec), and then pass &vec[0], which is a pointer to the first element of the internal vector array. With C++11, you can pass vec.data() instead of &vec[0]. A: For completeness, the vector alternative to the currently accepted answer would look like this: { std::vector<YOUR_TYPENAME> arr(mySet.begin(), mySet.end()); Your_C_API(&arr[0]); // memory implicitly freed on next line } I prefer this style because: * *It takes one fewer lines, and *It eliminates a class of mistakes that I often make (that is, forgetting to delete).
{ "language": "en", "url": "https://stackoverflow.com/questions/7636531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JNDI lookup gives "NullPointerException" when do lookup for a queue in LDAP I have successfully registered and retrieved the connection factory object from LDAP server.But when i try to look up for queue from LDAP server it gives NPE. I'm using OracleAQ with ApacheDS.. My code is; DirContext destctxQF = (DirContext) inictx.lookup("cn=OracleDBQueues"); System.out.println("OracleDBQueues look up success " + destctxQF.toString()); Queue queue = (Queue) destctxQF.lookup("cn=ratha.test"); And my LDIF definition for the queue is; dn: cn=ratha.test,cn=OracleDBQueues,cn=ORCL,cn=OracleContext,ou=Services,o=s gi,c=us objectClass: javaContainer objectClass: orclDBAQObject objectClass: javaNamingReference objectClass: javaObject objectClass: top cn: ratha.test javaClassName: oracle.jms.AQjmsDestination orcldbaqobjtype: Queue javaFactory: oracle.jms.AQjmsDestinationFactory orcldbaqobjname: test orcldbaqobjowner: ratha orcldbaqpointerattr: cn=ratha.test_table,cn=OracleDBQueuesTables,cn=ORCL,cn= OracleContext,ou=Services,o=sgi,c=us Any clue on this? Complete error stack is; javax.naming.NamingException: problem generating object using object factory [Root exception is java.lang.NullPointerException]; remaining name 'cn=ratha.test' at com.sun.jndi.ldap.LdapCtx.c_lookup(LdapCtx.java:1070) at com.sun.jndi.toolkit.ctx.ComponentContext.p_lookup(ComponentContext.java:526) at com.sun.jndi.toolkit.ctx.PartialCompositeContext.lookup(PartialCompositeContext.java:159) at com.sun.jndi.toolkit.ctx.PartialCompositeContext.lookup(PartialCompositeContext.java:148) at OracleAQJNDIClient.get_Factory_from_LDAP(OracleAQJNDIClient.java:93) at OracleAQJNDIClient.main(OracleAQJNDIClient.java:142) Caused by: java.lang.NullPointerException at oracle.jms.AQjmsDestinationFactory.getObjectInstance(AQjmsDestinationFactory.java:120) at javax.naming.spi.DirectoryManager.getObjectInstance(DirectoryManager.java:176) at com.sun.jndi.ldap.LdapCtx.c_lookup(LdapCtx.java:1063) ... 5 more Thanks, -Ratha
{ "language": "en", "url": "https://stackoverflow.com/questions/7636533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Maps V3 Geometry Library - Interpolate does not return expected Lat/Lng I have spent hours on a strange problem with the interpolate function of google maps' geometry library. (see: http://code.google.com/apis/maps/documentation/javascript/reference.html#spherical) I use the following javascript code to illustrate the problem: // be sure to include: https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false // this works just as expected var origin = new google.maps.LatLng(47.45732443, 8.570993570000041); var destination = new google.maps.LatLng(47.45733, 8.570889999999963); var distance = google.maps.geometry.spherical.computeDistanceBetween(origin, destination); console.log("origin:\r\nlat: " + origin.lat() + ", lng: " + origin.lng()); console.log("destination:\r\nlat: " + destination.lat() + ", lng: " + destination.lng()); console.log("distance between origin and destination: " + distance); console.log("interpolating 50 equal segments between origin and destination"); for (i=1; i <= 50; i++) { var step = (1/50); var interpolated = google.maps.geometry.spherical.interpolate(origin, destination, step * i); var distance = google.maps.geometry.spherical.computeDistanceBetween(origin, interpolated); console.log("lat: " + interpolated.lat() + ", lng: " + interpolated.lng() + ", dist: " + distance); } // the following does not work as expected // the "interpolated" location is always equal to the origin var origin = new google.maps.LatLng(47.45756, 8.572350000000029); var destination = new google.maps.LatLng(47.45753, 8.57233999999994); var distance = google.maps.geometry.spherical.computeDistanceBetween(origin, destination); console.log("origin:\r\nlat: " + origin.lat() + ", lng: " + origin.lng()); console.log("destination:\r\nlat: " + destination.lat() + ", lng: " + destination.lng()); console.log("distance between origin and destination: " + distance); console.log("interpolating 50 equal segments between origin and destination"); for (i=1; i <= 50; i++) { var step = (1/50); var interpolated = google.maps.geometry.spherical.interpolate(origin, destination, step * i); var distance = google.maps.geometry.spherical.computeDistanceBetween(origin, interpolated); console.log("lat: " + interpolated.lat() + ", lng: " + interpolated.lng() + ", dist: " + distance); } It appears that the interpolate function does NOT like the second set of lat/lng pairs. It always returns the origin lat/lng rather than the correctly interpolated location based on the fraction passed (1/50 * i). I tried reversing origin and destination, but the outcome is the same. Any ideas as to what I'm doing wrong are much appreciated! A: As it turns out, the interpolate function has a built in limitation that specifies that the distance between the two points must be larger than 1.0E-6. function (a,b,c){ var d=L(a.Ja),e=L(a.Ka),f=L(b.Ja),g=L(b.Ka),h=n.cos(d),o=n.cos(f),b=zx.se(a,b),r=n.sin(b); // here lies the problem: if(r<1.0E-6)return new Q(a.lat(),a.lng()); a=n.sin((1-c)*b)/r; c=n.sin(c*b)/r; b=a*h*n.cos(e)+c*o*n.cos(g); e=a*h*n.sin(e)+c*o*n.sin(g); return new Q(Fd(n[zb](a*n.sin(d)+c*n.sin(f),n[Db](b*b+e*e))),Fd(n[zb](e,b))) } This is still somewhat a mystery to me, as 1.0E-6 should be 0.000001 and not 6.0 as it is in my tests. Perhaps this is a bug that only shows when using google.maps.gjsload? I'll test a bit more and comment on my findings. I got around this by simply commenting out the if statement: google.maps.__gjsload__('geometry', 'var zx={computeHeading:function(a,b){var c=L(a.Ja),d=L(b.Ja),e=L(b.Ka)-L(a.Ka);return Dd(Fd(n[zb](n.sin(e)*n.cos(d),n.cos(c)*n.sin(d)-n.sin(c)*n.cos(d)*n.cos(e))),-180,180)},computeOffset:function(a,b,c,d){b/=d||6378137;var c=L(c),e=L(a.Ja),d=n.cos(b),b=n.sin(b),f=n.sin(e),e=n.cos(e),g=d*f+b*e*n.cos(c);return new Q(Fd(n[Dc](g)),Fd(L(a.Ka)+n[zb](b*e*n.sin(c),d-f*g)))},interpolate:function(a,b,c){var d=L(a.Ja),e=L(a.Ka),f=L(b.Ja),g=L(b.Ka),h=n.cos(d),o=n.cos(f),b=zx.se(a,b),r=n.sin(b);/*if(r<1.0E-6)return new Q(a.lat(),\na.lng());*/a=n.sin((1-c)*b)/r;c=n.sin(c*b)/r;b=a*h*n.cos(e)+c*o*n.cos(g);e=a*h*n.sin(e)+c*o*n.sin(g);return new Q(Fd(n[zb](a*n.sin(d)+c*n.sin(f),n[Db](b*b+e*e))),Fd(n[zb](e,b)))},se:function(a,b){var c=L(a.Ja),d=L(b.Ja);return 2*n[Dc](n[Db](n.pow(n.sin((c-d)/2),2)+n.cos(c)*n.cos(d)*n.pow(n.sin((L(a.Ka)-L(b.Ka))/2),2)))}};zx.computeDistanceBetween=function(a,b,c){return zx.se(a,b)*(c||6378137)};\nzx.computeLength=function(a,b){var c=b||6378137,d=0;a instanceof Lf&&(a=a[tc]());for(var e=0,f=a[B]-1;e<f;++e)d+=zx.computeDistanceBetween(a[e],a[e+1],c);return d};zx.computeArea=function(a,b){return n.abs(zx.computeSignedArea(a,b))};zx.computeSignedArea=function(a,b){var c=b||6378137;a instanceof Lf&&(a=a[tc]());for(var d=a[0],e=0,f=1,g=a[B]-1;f<g;++f)e+=zx.Hj(d,a[f],a[f+1]);return e*c*c};zx.Hj=function(a,b,c){return zx.xj(a,b,c)*zx.yj(a,b,c)};\nzx.xj=function(a,b,c){for(var d=[a,b,c,a],a=[],c=b=0;c<3;++c)a[c]=zx.se(d[c],d[c+1]),b+=a[c];b/=2;d=n.tan(b/2);for(c=0;c<3;++c)d*=n.tan((b-a[c])/2);return 4*n[pc](n[Db](n.abs(d)))};zx.yj=function(a,b,c){a=[a,b,c];b=[];for(c=0;c<3;++c){var d=a[c],e=L(d.Ja),d=L(d.Ka),f=b[c]=[];f[0]=n.cos(e)*n.cos(d);f[1]=n.cos(e)*n.sin(d);f[2]=n.sin(e)}return b[0][0]*b[1][1]*b[2][2]+b[1][0]*b[2][1]*b[0][2]+b[2][0]*b[0][1]*b[1][2]-b[0][0]*b[2][1]*b[1][2]-b[1][0]*b[0][1]*b[2][2]-b[2][0]*b[1][1]*b[0][2]>0?1:-1};var Ax={decodePath:function(a){for(var b=J(a),c=ga(n[jb](a[B]/2)),d=0,e=0,f=0,g=0;d<b;++g){var h=1,o=0,r;do r=a[sc](d++)-63-1,h+=r<<o,o+=5;while(r>=31);e+=h&1?~(h>>1):h>>1;h=1;o=0;do r=a[sc](d++)-63-1,h+=r<<o,o+=5;while(r>=31);f+=h&1?~(h>>1):h>>1;c[g]=new Q(e*1.0E-5,f*1.0E-5,i)}Ma(c,g);return c}};Ax.encodePath=function(a){a instanceof Lf&&(a=a[tc]());return Ax.Lj(a,function(a){return[rd(a.lat()*1E5),rd(a.lng()*1E5)]})};\nAx.Lj=function(a,b){for(var c=[],d=[0,0],e,f=0,g=J(a);f<g;++f)e=b?b(a[f]):a[f],Ax.mg(e[0]-d[0],c),Ax.mg(e[1]-d[1],c),d=e;return c[Hc]("")};Ax.$j=function(a){for(var b=J(a),c=ga(b),d=0;d<b;++d)c[d]=a[sc](d)-63;return c};Ax.mg=function(a,b){Ax.Mj(a<0?~(a<<1):a<<1,b)};Ax.Mj=function(a,b){for(;a>=32;)b[p](na.fromCharCode((32|a&31)+63)),a>>=5;b[p](na.fromCharCode(a+63))};function Bx(){}Bx[C].Jb=Ax;Bx[C].computeDistanceBetween=zx.computeDistanceBetween;var Cx=new Bx;df[se]=function(a){eval(a)};l.google.maps[se]={encoding:Ax,spherical:zx};gf(se,Cx);\n') I hope this will help someone else out there running into the same problem. A: I think you expect too much accuracy from the interpolation. The difference in the latitudes is 47.45756 - 47.45753 = 0.00003 deg ~ 3.3 meter. The difference in the longitudes is 8.57235- 8.57234 = 0.00001 deg ~ 0.5 meter (very appoximatively, see Wikipedia). Now you divide the approximative Euclidean distance 3m into 50 intervals, looking for points at a distance of ca. 6 cm. Compare this with the Earth equator whose length is about 4,003,020,000 cm. A: I have filed an issue concerning this problem: https://issuetracker.google.com/issues/260343763 For me the problem was that I am using this function to interpolate an animation. I ended up copying the function into my own source code and removing the if statement that checks for "r<1.0E-6" (as @davethebrave has pointed out)
{ "language": "en", "url": "https://stackoverflow.com/questions/7636546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Jenkins key-value variable or using a variable to define another I'm setting up a centralized build system where several projects get "packaged". The project can be selected using a choice parameter, and based on it I'm building the SVN checkout path. The repository is the same, but each app has a slightly different path, eg: * *app 1 resides in ../libs/App1.. *app 2 resides in ../tools/App2.. *etc My problem is that I need to somehow match the app name with its location. The first thought that came to mind was a key-value parameter but I have yet to find a plugin that permits it. The second one was to define some environmental variables within a file (there are 2-3 plugins that do it) and then use the value selected in the choice parameter to as the key for the env var. Is this achievable in any way? Kind regards A: You can use Conditional BuildStep Plugin together with EnvInject Plugin in order to set up an environment variable (say APP_PATH) that depends on your build parameters before any other build steps. You then use ${APP_PATH} whenever you need it in your build. A: After a few years :-) and on an unrelated topic, I found the Active choices plugin also known as / forked from uno choice plugin which allows to define parameters which dynamically update when changing other parameters: 1) define an active choice parameter named states with the following groovy-script content return[ 'Sao Paulo', 'Rio de Janeiro', 'Parana', 'Acre' ] 2) Define an active choice reactive parameter named cities which reacts to changes in the first parameter's value, with the following groovy-script content: if (States.equals("Sao Paulo")) { return ["Barretos", "Sao Paulo", "Itu"] } else if (States.equals("Rio de Janeiro")) { return ["Rio de Janeiro", "Mangaratiba"] } else if (States.equals("Parana")) { return ["Curitiba", "Ponta Grossa"] } else if (States.equals("Acre")) { return ["Rio Branco", "Acrelandia"] } else { return ["Unknown state"] } Thus, each time the state changes, then the list of selectable cities will be updated accordingly:
{ "language": "en", "url": "https://stackoverflow.com/questions/7636547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Wordpress : Multiple Columns on Homepage I am trying to create a Wordpress site. The design is Here I have created most of the outline of the site, barring the 3 regions "Follow Us", "Self Employment" & "Into Work Consortium". The client has told me he would like to make those 3 regions editable. My template contains an Index file, Header & Footer File as well as the obvious CSS files. I am using the "Multi Edit Plugin" Multi Edit Plugin but that guide, does it so that you create a CustomPage. I guess I could do that but what I want is my index.php file to be added to the admin side of the site and then point the template there or similar. As it's getting a little frustrating working with multiple WP plugins that just don't seem to do the job correctly. A: There are many ways to go about this: one being what was mentioned by Pekka and the other using Custom Page templates. The above mentioned methods are, in theory, quite similar with subtle differences in terms of execution and inclusion. Perhaps to better answer your question, I will provide a very brief sample outline below on Custom Post Templates. You may probably need to do a little more digging at Wordpress' Codex if you choose to further enhance anything else: Custom Post Template Method Referring to the wireframe provided in your image link, I propose that you use category filters to filter the associated posts to the right columns. So first up, you will need to create 4 categories for the method that I'm suggesting, namely: WELCOME, FOLLOW, SELF-EMPLOYMENT and CONSORTIUM. After doing so, your index.php should look something like this: INDEX.PHP <?php get_header();?> <!--container--> <div id="container"> <?php query_posts('category_name=welcome&showposts=1'); ?> <?php while (have_posts()) : the_post(); ?> <!--top-content--> <div class="top-content"> <h2><a href="<?php the_permalink();?>"><?php the_title();?></a></h2> <p><?php the_content();?></p> </div> <!--top-content--> <?php endwhile;?> <!--bottom-content--> <div class="bottom-content"> <!--follow--> <div class="follow"> <?php include(TEMPLATEPATH . '/follow.php');?> </div> <!--follow--> <!--self-employment--> <div class="self-employment"> <?php include(TEMPLATEPATH . '/self-employment.php');?> </div> <!--self-employment--> <!--consortium--> <div class="consortium"> <?php include(TEMPLATEPATH . '/consortium.php');?> </div> <!--consortium--> </div> <!--bottom-content--> </div> <!--container--> <?php get_footer();?> What is happening here is that I'm doing a post query for posts tagged to the category "WELCOME" and filter the posts into the top-content DIV. Note that my loop starts right before of the top-content DIV and ends immediately after it. This will means that the loop will only affect that particular DIV. I have also set the post limit to "1", thereby restricting the display of posts to just the latest post. Following on from there, you will notice that in the bottom-content DIV, I have included 3 different files for each column. These 3 files will be your custom post templates that you will need to create and have a post query to filter in the right post. An example of the custom post template will look something like this below: FOLLOW.PHP <?php query_posts('category_name=follow&showposts=1'); ?> <?php while (have_posts()) : the_post(); ?> <h2><a href="<?php the_permalink();?>"><?php the_title();?></a></h2> <?php the_post_thumbnail('bottom-content-thumb');?> <!--you will have to enable featured image thumbs in your functions.php file before you can do this--> <span class="read-more"><a href="<?php the_permalink();?>">Continue Reading</a></span> <!--there are other ways to do the read more link, but I'm just giving an example now so yeah--> <?php endwhile;?> The rest of the custom post templates for the bottom 3 columns should look something like the above. If there is any variation of style and all, you will probably have to shift things around and play around with the CSS. I want to stress that this is not the one and only way to do what you hope to achieve, but rather, that it is one of the many. What I've suggested is only an example that hopes to provide some insights on how you can utilize Custom Post templates for developing Wordpress based sites. My advice at the end of the day is to delve deeper into Codex and find out more about Custom Post/Page templates because eventually, they will come in very handy if you choose to make custom Wordpress templates. Hope my post had made things a little clearer for you =)
{ "language": "en", "url": "https://stackoverflow.com/questions/7636550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to make Visual Studio 2010 to run all tests on the same thread? Even when Visual Studio 2010 does not run tests in multiple parallel threads, it still uses different threads to run different test methods. It uses one thread to run one test, and then switches to other thread to run other test. It continues switching between threads for every test method. You can easily test it by querying thread IDs within different tests. I’m trying to write integration tests that initialize an actual application that uses COM objects. Those COM objects has to be using only in STA memory model and don’t have proxy/stub marshalers that can be used to call them from other thread. An application's COM objects get initialized during the first test on the thread that was used by the first test. Then any call to them from other tests fails because they are calling them from different threads. It throws InvalidComObjectException with the "COM object that has been separated from its underlying RCW can not be used", because it cannot reach a COM object that is in other STA apartment and does not have proxy/stub marshaler. Making Visual Studio to run all tests on the same thread will solve a problem, because all COM objects will be initialized and used on the same thread from within the same STA apartment. A: You could try using NUnit for this specific test, as it does run all tests on the same thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Require a library with configuration in CoffeeScript? I'd like to use CoffeeScript with Nano.js, a minimalistic CouchDB module. In JavaScript, the requirements are: var nano = require('nano')('http://127.0.0.1:5984'); However, there is no documentation on how to write this in CoffeeScript? nano = require 'nano', 'http://127.0.0.1:5984' Results in: nano = require('nano', 'http://127.0.0.1:5984'); Which doesn't work. A: Since you are calling a function which calls a function, doing what you tried is ambiguous. Parentheses are required in CoffeeScript to resolve ambiguity. Have you tried this: nano = require('nano')('http://127.0.0.1:5984') Or, if you really want to go without parens, you could do this: nano = require 'nano' nano = nano 'http://127.0.0.1:5984' Or just nano = require('nano') 'http://127.0.0.1:5984'
{ "language": "en", "url": "https://stackoverflow.com/questions/7636555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I call a Word Macro with parameters from JScript I have a Word template with a macro defined in the ThisDocument section: Sub Go(pID As Integer, pPassword As String) I am trying to execute this macro from JScript as follows: application.Run("Go", 1, "secret"); But this fails - what am I doing wrong? A: Ok, found one answer: * *remove the parameters *use document variables instead: document.Variables.Add("id", 1); document.Variables.Add("password", "secret"); application.Run("Go");
{ "language": "en", "url": "https://stackoverflow.com/questions/7636557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get all ids from a collection I got my collection items like this : hotels = Hotel.where('selection = ?', 1).limit(4) How can I get all ids of this items without a loop? Can i use something like : hotels.ids ? Thank you A: You can also pull just the id's. hotels.select(:id).where(selection: 1) A: What about trying hotels.map(&:id) or hotels.map{|h| h.id }? They both mean the same thing to Ruby, the first one is nicer to accustomed ruby-ists usually, whilst the second one is easier to understand for beginners. A: If you only need an array with all the ids you should use pluck as it makes the right query and you don't have to use any ruby. Besides it won't have to instantiate a Hotel object for each record returned from the DB. (way faster). Hotel.where(selection: 1).pluck(:id) # SELECT hotels.id FROM hotels WHERE hotels.selection = 1 # => [2, 3] A: If you are using Rails > 4, you can use the ids method: Person.ids # SELECT people.id from people More info: http://apidock.com/rails/ActiveRecord/Calculations/ids
{ "language": "en", "url": "https://stackoverflow.com/questions/7636563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: form Panel layout issue in extjs2 I am new to extjs layouts. I have a Form panel with default layout.I am adding a fieldset which contains a grid and two buttons. I am rendering a form Panel to div. Div in JSP <div id="mydiv"></div> FormPanel in JS var fp = new Ext.FormPanel( { standardSubmit :true, id :'panel', autoHeight :true, layout: 'border', bodyCfg: { cls: 'template' }, bodyPadding :10, margin :'0 0 20', frame :'true', renderTo :'mydiv', buttonAlign:'right', items : [topPanel , fieldset ] }); I want the form and grid to be resized as per window size (resizing of the window shold resize the element) Right now If try I to resize the window, fieldset is getting resized as per window but grid is not. I have given a fixed height and width to grid for now. As without that grid just expand horizontally. I dont want to give any height width to panel , grid. How can it be achieved? As I searched if we render panel to viewport , it will take care of resizing. If this is so , then should I create a viewport in extjs and reneder that to div? If yes then how to do that? Edit: Or I have to use css with div? Any pointers are appreciated. Thanks A: You can create a viewport and this will as you say, take care of the resizing. Within the viewport, you can then add your panel the 'items' collection. If you want the panel to fit the viewport, you should use the 'fit' layout. Something along these lines would be the right type of idea: var viewPort = new Ext.Viewport({ id: "blaa", items: [fp], layout: "fit" )}; I've not checked the syntax here, but you get the idea. A: Use anchor property. E.g.: anchor: '-10'on whichever components you want this feature on. This will automatically adjust the width of the component according to it's parents width. So if your formpanel is of width 100px, any child component which has anchor : '-10px' set, will have width widthOfParent - anchorWidth You can also set the layout to fit. This will automatically expand all child components to width of their parents.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: write information into Excel after each loop I have a 6x7 matrix(A) and some operation I'm doing on it for k=1:50 (number of loops). I know that in order to write a single matrix in an excel file I need: xlswrite('Filename.xls', A, 'A1') How is it possible to write the information after each loop, in that way that each loop starts at position A1+((k-1)*6+1) in Excel and I have all results of Matrix(A) listed one after each other. Thank you! A: When using the XLSWRITE function, you can avoid having to compute Excel cell ranges each time, by specifying both sheet number and range, where range only gives the first cell to start at. It is especially useful if the matrix changes size each iteration; we simply take the last cell used and shift it by the number of rows of the matrix. Example: offset = 1; for i=1:5 %# generate different size matrices each loop A = ones(randi(4),randi(4)).*i; %# insert matrix in Excel inside the 1st sheet, starting at cell specifed xlswrite('filename.xls', A, 1, sprintf('A%d',offset)); %# increment offset offset = offset + size(A,1); end this creates an Excel file with the following content: 1 1 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 Note that a connection is made to Excel then closed each time XLSWRITE is called. This has a significant overhead. A better approach would be to open Excel once, and reuse the same session to write all of your data, then close it once we are done. However, you will have to call the Office Interop functions yourself. Since the trick I mentioned above won't work now, I will be using the "Calculate Excel Range" function to compute the cell ranges (there are many other implementations of FEX). Here is the code (reusing some code from a previous answer): %# output file name fName = fullfile(pwd, 'file.xls'); %# create Excel COM Server Excel = actxserver('Excel.Application'); Excel.Visible = true; %# delete existing file if exist(fName, 'file'), delete(fName); end %# create new XLS file wb = Excel.Workbooks.Add(); wb.Sheets.Item(1).Activate(); %# iterations offset = 0; for i=1:50 %# generate different size matrices each loop A = ones(randi(4),randi(4)).*i; %# calculate cell range to fit matrix (placed below previous one) cellRange = xlcalcrange('A1', offset,0, size(A,1),size(A,2)); offset = offset + size(A,1); %# insert matrix in sheet Excel.Range(cellRange).Select(); Excel.Selection.Value = num2cell(A); end %# save XLS file wb.SaveAs(fName,1); wb.Close(false); %# close Excel Excel.Quit(); Excel.delete(); In fact, I ran both version with 50 iterations, and compared timings with TIC/TOC: Elapsed time is 68.965848 seconds. %# calling XLSWRITE Elapsed time is 2.221729 seconds. %# calling Excel COM directly A: I think that xlswrite will overwrite an existing file, so you're better off gathering all the data, then writing it in one go. Also, writing it all in one go will be faster since it involves opening and closing Excel only once. However, if you really want to write it in a loop, the following should work (assuming you mean going down): range = sprintf('A%i:G%i', (k-1)*6+[1 6]); xlswrite('Filename.xls', A, range); Note that this won't adjust automatically if A changes size.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to tell the compiler to put a block of code somewhere? I have a long method, and for reading clarity would like to put some of the code in a separate method. However, that can’t be done because that code uses the variables in the method. So I would like to put that code somewhere else and tell the compiler to insert that code in “this” place when compiling. Is there any way to do that? I’m using visual studio. A: Sounds like you're describing the Extract method and you can do this very easily, simply highlight the code you want to move and: Right click -> Refactor -> Extract method -> Enter method name Visual studio will deal with the rest for you. Read the docs here. A: As others have said, the fact that you have the problem in the first place is a symptom of a larger code organization problem. Ideally your methods should be so short, and have so few variables, that you don't need to move big parts of their code somewhere else. The right thing to do is probably to extract portions of the code into their own methods, each of which performs one task and does it well. As a stopgap measure, you could use code regions to help organize your code: void BigMethod() { #region Frobbing code FrobTheBlob(); // blah blah blah // blah blah blah #endregion ... And now in Visual Studio the editor will let you collapse that region down into just a single line that says "Frobbing code". A: If you have one long method that you can't split because you need to access the same locals, what you really have is another object that you haven't formally made into a class. Refactor your code, extracting the method and shared state into a class of its own, and then start refactoring the method to smaller, more manageable pieces. class SomeClass { // whatever shared state of the class // whatever methods of the class public void MethodThatsDoingTooMuch() { // long method // hard to split the method because of locals } } to class SomeClass { // whatever shared state of the class // whatever methods of the class public void MethodThatIsntDoingTooMuch() { bigSomethingDoer.Do(); } } class BigSomethingDoer { // shared locals are fields instead public void Do() { // refactor long method into smaller methods // shared locals are promoted to class fields // this smaller class only does this one thing // --> its state does not pollute another class } } A: well what you ask could be done with macros probably, but if the code is much and not readable you should consider to refactor it and create another method which accepts those variables you have in the main method as parameters. some Refactoring tools out there have features like extract-method where you select some code and this is moved to another method for you. I guess both ReSharper and DevExpress CodeRush have this feature but I am not 100% sure and I don't have any of them installed to try this right now. A: You can use anonymous methods/lambdas to create functions that can access the local variables of the containing method. But such long methods usually aren't necessary. Try decoupling different parts of the method so they don't need to share common local variables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt-webkit WebSocket protocol Which WebSocket protocol is supported by Qt-webkit? For example, the following list has the WebSocket protocol lists. The WebSocket protocol: draft-hixie-thewebsocketprotocol-76 A: Alright After some research I could find some details on this but I need some confirmation on this. As for qt 4.7 there are non. And for Qt 4.8 following mails provide some idea but again need to be confirmed. https://lists.webkit.org/pipermail/webkit-dev/2011-June/017102.html. also the comments of the following bug report might help you as well https://bugs.webkit.org/show_bug.cgi?id=50099
{ "language": "en", "url": "https://stackoverflow.com/questions/7636573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C# , Substring How to access last elements of an array/string using substring I am generating 35 strings which have the names ar15220110910, khwm20110910 and so on. The string contains the name of the Id (ar152,KHWM), and the date (20110910). I want to extract the Id, date from the string and store it in a textfile called StatSummary. My code statement is something like this for( int 1= 0;i< filestoextract.count;1++) { // The filestoextract contains 35 strings string extractname = filestoextract(i).ToString(); statSummary.writeline( extractname.substring(0,5) + "" + extractname.substring(5,4) + "" + extractname.substring(9,2) + "" + extractname.substring(11,2)); } When the station has Id containing 5 letters, then this code executes correctly but when the station Id is KHWM or any other 4 letter name then the insertion is all messed up. I am running this inside a loop. So I have tried keeping the code as dynamic as possible. Could anyone help me to find a way without hardcoding it. For instance accessing the last 8 elements to get the date??? I have searched but am not able to find a way to do that. A: For the last 8 digits, it's just: extractname.Substring(extractname.Length-8) oh, I'm sorry, and so for your code could be: int l = extractname.Length; statSummary.WriteLine(extractname.substring(0,l-8) + "" + extractname.Substring(l-8,4) + "" + extractname.Substring(l-4,2) + "" + extractname.Substring(l-2,2)); A: As your ID length isn't consistent, it would probably be a better option to extract the date (which is always going to be 8 chars) and then treat the remainder as your ID e.g. UPDATED - more robust by actually calculating the length of the date based on the format. Also validates against the format to make sure you have parsed the data correctly. var dateFormat = "yyyyMMdd"; // this could be pulled from app.config or some other config source foreach (var file in filestoextract) { var dateStr = file.Substring(file.Length-dateFormat.Length); if (ValidateDate(dateStr, dateFormat)) { var id = file.Substring(0, file.Length - (dateFormat.Length+1)); // do something with data } else { // handle invalid filename } } public bool ValidateDate(stirng date, string date_format) { try { DateTime.ParseExact(date, date_format, DateTimeFormatInfo.InvariantInfo); } catch { return false; } return true; } A: You could use a Regex : match = Regex.Match ("khwm20110910","(?<code>.*)(?<date>.{6})" ); Console.WriteLine (match.Groups["code"] ); Console.WriteLine (match.Groups["date"] ); To explain the regex pattern (?<code>.*)(?<date>.{6}) the brackets groups creates a group for each pattern. ?<code> names the group so you can reference it easily. The date group takes the last six characters of the string. . says take any character and {6} says do that six times. The code group takes all the remaining characters. * says take as many characters as possible. A: for each(string part in stringList) { int length = part.Length; int start = length - 8; string dateString = part.Substring(start, 8); } That should solve the variable length to get the date. The rest of the pull is most likely dependent on a pattern (suggested) or the length of string (when x then the call is 4 in length, etc) A: If you ID isn't always the same amount of letters you should seperate the ID and the Date using ',' or somthing then you use this: for( int 1= 0;i< filestoextract.count;1++) { string extractname = filestoextract[i].ToString(); string ID = extractname.substring(0, extractname.IndexOf(',')); string Date = extractname.substring(extractname.IndexOf(',')); Console.WriteLine(ID + Date); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Uninstall Sync Framework I'm trying to clean up my system a bit, and came across two entries related to either Visual Studio 2005, 2008, or 2010: Microsoft Sync Framework 2.0 Core Components Microsoft Sync Framework 2.0 Provider Services I do not currently, and will not in the future, be using the Sync Framework. Can they be safely uninstalled without affecting other Visual Studio components? If not, which components may be affected? A: looks like the same question as this one: Uninstalling Sync Framework without breaking Visual Studio Visual Studio's Local Database Cache project item uses Sync Framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: fatal: Unable to look up android.kernel.org (port 9418) (Name or service not known) repo sync fails with the following message: repo init -u git://android.kernel.org/platform/manifest.git Getting repo ... from git://android.kernel.org/tools/repo.git fatal: Unable to look up android.kernel.org (port 9418) (Name or service not known) I know that kernel.org has been hacked and the source is now under github at http://www.github.com/android, but I have the message reported above Anyone can help me? A: Whole kernel.org is down for maintenance. I hope it will be up and running soon. A: I've found instructions how to get sources from omapzoom.org mirror. It works for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java generics - parameters cannot be applied to method I can't seem to figure out why a method call I'm trying to make doesn't work. I've looked much around SO before asking this, and while there are (many) threads about similar problems, I couldn't find one that quite fits my problem.. I have the following code: (in file Processor.java:) public interface Processor { Runner<? extends Processor> getRunner(); } (in file Runner.java:) public interface Runner<P extends Processor> { int runProcessors(Collection<P> processors); } (in some other file, in some method:) Collection<? extends Processor> processorsCollection = ...; Runner<? extends Processor> runner = ...; runner.runProcessors(processorsCollection); IntelliJ marks the last line as an error: "RunProcessors (java.util.Collection>) in Runner cannot be applied to (java.util.Collection>)". I can't figure out whats wrong with what I did, especially since the error message is not quite clear.. any suggestions? thanks. A: Both your collection and your runner allow for anything that extend processor. But, you can't guarantee they're the same. Collection might be Collection<Processor1> and Runner be Runner<Processor2>. Whatever method you have that in needs to be typed (I forget the exact syntax, but I'm sure you can find it!) void <T extends Processor<T>> foo() { Collection<T> procColl = ... Runner<T> runner = ... runner.runProc(procColl); } Edit: @newAcct makes an excellent point: you need to genericize (is that a word?) your Processor. I've updated my code snippet above as to reflect this important change. public interface Processor<P extends Processor> { Runner<P> getRunner(); } public interface Runner<P extends Processor<P>> { int runProcessors(Collection<P> processors); } A: You have not made your situation clear and you're not showing us any of the code of the methods or of how you get the objects, so we don't really know what you're trying to do. Your code is not type-safe. As @glowcoder mentioned, there is no way of knowing that the parameter of Collection is the same as the parameter of Runner. If you believe they are indeed the same, then that is based on code that you're not showing us (i.e. what happens in "..."?) You have written Processor's getRunner() method with a return type that has a wildcard parameter. This says when run it will return a Runner with a mysterious parameter that it determines and we don't know. This doesn't make much sense and is probably not what you wanted. Also depending on what you are doing, the runProcessors method could possibly take a less strict bound. For example, perhaps <? extends P> or even <? extends Processor> if you don't need to modify the collection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to replace LSB of a byte with a LSB of another byte How to replace LSB of a byte with a LSB of another byte in c#. Something like this byte1 - 0 1 1 1 1 1 1 1 byte2 - 0 0 1 1 1 0 0 0 Now i want lsb of byte1 i.e "1" to be replaced by lsb of byte2 i.e "0" . So my final byte should be like this : byte3 - 0 1 1 1 1 1 1 0 A: Sounds like you want something like: byte x = ...; byte y = ...; // Only bits 1-7 of x, and only bit 0 of y (counting bit 0 = LSB) byte z = (byte) ((x & 0xfe) | (y & 1)); The cast is necessary because all of the operators are only defined for int and larger, so everything gets promoted to int.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Select multiple rows by max I have a simple table with a "versioning" scheme: Version | PartKey1 | PartKey2 | Value 1 | 0 | 0 | foo 2 | 0 | 0 | bar 1 | 1 | 0 | foobar This table is medium (~100 000 lines for a full version). At the start it is loaded with a version 1 which contains a full snapshot, and over time incremental updates are added, but we want to preserve the old versions, thus they are added with an incremented "Version" number (2 here). When reading the data, I want to be able to specify a maximum version, and I would like, if possible, to only retrieve the "rows" I am interested in. For example: specifying 2 as the maximum version, I would like a query that retrieve only 2 rows in the table above: Version | PartKey1 | PartKey2 | Value 2 | 0 | 0 | bar 1 | 1 | 0 | foobar The row: 1 | 0 | 0 | foo is discarded because the version 2 of this row is more recent. I was wondering if such a selection was possible / advisable in a SQL query. I can do the filtering on the application side, but obviously it means pulling in useless resources from the DB so if it's possible (and cheap on the DB side) I'd rather offload this work to the DB. A: You can do: SELECT v1.* FROM versioningscheme v1 LEFT JOIN versioningscheme v2 ON v2.partkey1 = v1.partkey1 AND v2.partkey2 = v1.partkey2 AND v2.version > v1.version WHERE v2.version IS NULL Left Join with NULL detection is very powerful and underused. Null values are returned when there is no match (and obviously, when you have the max row in v1, you can't get a row in v2 that satisfies the join condition). A: select t.* from MyTable t inner join ( select PartKey1, PartKey2, max(Version) as MaxVersion from MyTable where Version <= 2 group by PartKey1, PartKey2 ) tm on t.PartKey1 = tm.PartKey1 and t.PartKey2 = tm.PartKey2 and t.Version = tm.MaxVersion A: This is common with time varying data (Where you choose to find the most recent value within a specific window of time), and is completely reasonable. In your case, ROW_NUMBER() allows the data to be parsed just once, rather than multiple times. With an appropriate INDEX such as (PartKey1, PartKey2, Version), this should be exceptionally quick... SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY PartKey1, PartKey2 ORDER BY Version DESC) AS reversed_version FROM MyTable WHERE Version <= <MaxVersionParamter> ) AS data WHERE reversed_version = 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7636585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EJB 3.1 remove invocation context for security purpose (ThreadLocal, ...) I have a webapp on one Glassfish server (front-end) and an EJB 3.1 app (back-end) on another Glassfish server. The webapp communicates with the EJB 3.1 via remote invocation. I would like to pass context data (user data i.e.) without having to define it as an input parameter of each business operation. I have one idea, but not sure it will work: use a ThreadLocal to store data, but the ThreadLocal will only be available on one server (meaning JVM) => use the InvocationContext object and create interceptor to add user data to the ContextData Map. What do you think about it? Any other ideas are more than welcome! ;-) UPDATE After first answer, I googled it a little bit and found the annotation @CallerPrincipal. How can I set this object before the remote invocation? A: The container will already handle this so you don't have to code it yourself. In your EJB, you can access the EJBContext, which has a getCallerPrincipal() method which will give you the callers identity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: Limit supported devices in Android Market I have an application in the market that I want only Nexus S-users to be able to download. How can I do this? There is a "Supported Devices" in the publishing process, but I dont want to exclude devices 700times. Can I in the manifest support only the Nexus S? Dag A: I'm not sure why you would want to exclude all other devices instead of the filtering by features of the device, but I'd suggest following the directions for Market Filters in the Android Developer Documentation that is provided by Google. I'd suggest using the Nexus S specs as the minimum specs and go from there. EDIT: Google recently released a Device Availability Dialog in the Developer Console that allows you to understand which devices can run your application, as well as allowing you to filter out devices that you don't want to run your application. A: Try this in your manifest: <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" /> good luck
{ "language": "en", "url": "https://stackoverflow.com/questions/7636588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Removing Backstack Entry in WP7 Mango How we can implement back stack entry removal in WP7 Mango app effectively. A: You can use the NavigationService.RemoveBackEntry method to remove the most recent journal entry from the back history. However, to pass certification, you must make sure that pressing the back button takes the user back to where they expect to be.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculating time difference between 2 dates in minutes I have a field of time Timestamp in my MySQL database which is mapped to a DATE datatype in my bean. Now I want a query by which I can fetch all records in the database for which the difference between the current timestamp and the one stored in the database is > 20 minutes. How can I do it? What i want is: SELECT * FROM MyTab T WHERE T.runTime - now > 20 minutes Are there any MySQL functions for this, or any way to do this in SQL? A: Try this one: select * from MyTab T where date_add(T.runTime, INTERVAL 20 MINUTE) < NOW() NOTE: this should work if you're using MySQL DateTime format. If you're using Unix Timestamp (integer), then it would be even easier: select * from MyTab T where UNIX_TIMESTAMP() - T.runTime > 20*60 UNIX_TIMESTAMP() function returns you current unix timestamp. A: MySql version >=5.6 I am using below code for today and database date. TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20 According to the documentation, the first argument can be any of the following: MICROSECOND SECOND MINUTE HOUR DAY WEEK MONTH QUARTER YEAR A: ROUND(time_to_sec((TIMEDIFF(NOW(), "2015-06-10 20:15:00"))) / 60); A: If you have MySql version above 5.6 you could use TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2) something like select * from MyTab T where TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20 A: You can try this: SELECT * FROM MyTab T WHERE CURRENT_TIMESTAMP() > T.runTime + INTERVAL 20 MINUTE; The CURRENT_TIMESTAMP() is a function and returns the current date and time. This function works From MySQL 4.0 A: If you have MySql version prior than 5.6 you don't have TIMESTAMPDIFF. So,I wrote my own MySql function to do this. Accets %i or %m for minutes and %h for hours. You can extend it. Example of usage: SELECT MYTSDIFF('2001-01-01 10:44:32', '2001-01-01 09:50:00', '%h') Here goes the function. Enjoy: DROP FUNCTION IF EXISTS MYTSDIFF; DELIMITER $$ CREATE FUNCTION `MYTSDIFF`( date1 timestamp, date2 timestamp, fmt varchar(20)) returns varchar(20) DETERMINISTIC BEGIN declare secs smallint(2); declare mins smallint(2); declare hours int; declare total real default 0; declare str_total varchar(20); if date1 > DATE_ADD( date2, interval 30 day) then return '999999.999'; /* OUT OF RANGE TIMEDIFF */ end if; select cast( time_format( timediff(date1, date2), '%s') as signed) into secs; select cast( time_format( timediff(date1, date2), '%i') as signed) into mins; select cast( time_format( timediff(date1, date2), '%H') as signed) into hours; set total = hours * 3600 + mins * 60 + secs; set fmt = LOWER( fmt); if fmt = '%m' or fmt = '%i' then set total = total / 60; elseif fmt = '%h' then set total = total / 3600; else /* Do nothing, %s is the default: */ set total = total + 0; end if; select cast( total as char(20)) into str_total; return str_total; END$$ DELIMITER ;
{ "language": "en", "url": "https://stackoverflow.com/questions/7636599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "104" }
Q: Extracting and copying files to local folder from a zip archive stored in a blob storage I have stored my zip file in blob storage . I already read archive from blob to stream .Code is as follows string blobUrl = http://127.0.0.1:10000/devstoreaccount1/usercontrols/ucProfileViewSMSIS.zip"; string containerName = "usercontrols"; Storage.Blob blobHandler = new Storage.Blob(); Stream blobstream = blobHandler.GetBlob(blobUrl, containerName); I have three files in my archive . I want to write write those 3 files to my local folder . How do I do this ? A: You will need an unzip library like DotNetZip to unzip the files. Under the examples section, there is a method to unzip directly from a stream: Input from a stream. This example reads in zip archive content from an input stream, then extracts the content for one entry to a filesysten file. In this example, the filename "NameOfEntryInArchive.doc", refers only to the name of the entry within the zip archive. This name is used as the index in the string indexer on the ZipFile object. The return value is a ZipEntry. The ZipEntry.Extract() method is then called, which extracts the named entry to a filesystem file, using the current working directory as the base. A file by that name is created in the filesystem. using (ZipFile zip = ZipFile.Read(InputStream)) { ZipEntry entry = zip["NameOfEntryInArchive.doc"]; entry.Extract(); // create filesystem file here. }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AS3 Array pulling specific information I am using an array to keep information about 2 blocks that have landed. I then need to pull the spriteoffset from this array. How do I do this? My method below does not work. aryBlockRow[(elementbody.yp + elementbody.block[ii].yp)/BLOCKSIZE][(elementbody.xp + elementbody.block[ii].xp)/BLOCKSIZE] = new ElementBlock((elementbody.xp + elementbody.block[ii].xp), (elementbody.yp + elementbody.block[ii].yp), elementbody.block[ii].spriteoffset); trace("Block row: "+aryBlockRow.block[ii].spriteoffset) Alternatively, each block has a tag (block[ii].tag), is it possible to pull this information from aryBlockRow, or is it not as I'm not specifically adding it? Thanks -- To clarify: I am creating a tetris style game, however there are 4 different elements. In order to destroy the elements, I need to know when 4 of the same are in a line. The way I am planning to do this is having each of the elements having a variable ("tag") of either 0,1,2 or 3. I am calling the variable elementbody, and within it has an array "block". trace("Left tag is: "+elementbody.block[0].tag) trace("Right tag is: "+elementbody.block[1].tag) This returns: Left tag is: 3 Right tag is: 1 Which is correct. What I now need to do is be able to continue to trace the tags once the elements have landed. As such, I am placing them into a new Array: for(ii = 0; ii < elementbody.block.length; ii++) { aryBlockRow[(elementbody.yp + elementbody.block[ii].yp)/BLOCKSIZE][(elementbody.xp + elementbody.block[ii].xp)/BLOCKSIZE] = new ElementBlock((elementbody.xp + elementbody.block[ii].xp), (elementbody.yp + elementbody.block[ii].yp), elementbody.block[ii].spriteoffset); Spriteoffset for each of the blocks (block[0], block[1]) will return either 0, 30, 60 or 90. If I can get this returned, then I can work out whether it has 4 in a row. What I need to know is: Is it possible to pull "spriteoffset" from the aryBlockRow array, or do I need to somehow store this information elsewhere? Elementbody changes to the new element everytime it lands on the bottom, and the existing is saved in this array, which is why I can not use my current method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Area Chart is not taking value as int I'm using Google's Area Chart to dispaly a graph. For some reason I'm not ble to use values past into the function: I have the following code: function SetAreaChartData(valueString) { //This works AreaChartData.setValue(0, 0, 'SomeName'); AreaChartData.setValue(0, 1, 500); AreaChartData.setValue(0, 2, 500); AreaChartData.setValue(0, 3, 500); //This does not work // First I must "cast" the input to string in order to use the .split function var str = new String(valueString); // Then I split the string in order to get an array of string val = str.split(","); AreaChartData.setValue(0, 0, 'SomeName'); AreaChartData.setValue(0, 1, val[0]*1); //Multiply by one to cast it to integer AreaChartData.setValue(0, 2, val[1]*1); AreaChartData.setValue(0, 3, val[2]*1); } I've also tried using parseInt(val[0]), but that is not helping either. Why won't .setValue recognize val[0] as an integer?
{ "language": "en", "url": "https://stackoverflow.com/questions/7636607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }