text
stringlengths
8
267k
meta
dict
Q: PostgreSQL: How to optimize this query I am developing a small application in C++ and using PostgreSQL as back-end database. Along with other tables in my database in have a "projects" table. Based on each primary key of this table a new table is dynamically added in my Database. Example: Suppose the projects table contains following 3 rows: -------------------------------- | Id |Other Columns Goes here | -------------------------------- | 1 | | -------------------------------- | 2 | | -------------------------------- | 3 | | -------------------------------- So in this case i also have following three more table Table1, Table2, Table3 Now you might notice that the table names are generated by appending projects.Id at the end of fixed string i.e "Table". It might also be possible that for some projects no table is generated. Example: Suppose the projects table contains following 3 rows: -------------------------------- | Id |Other Columns Goes here | -------------------------------- | 1 | | -------------------------------- | 2 | | -------------------------------- | 3 | | -------------------------------- So in this i might found only following two tables in my database: Table1, Table3 Now i simply need to get all the valid projects. For this currently i am using following algo: //part1 SELECT * FROM Projects Table get the projects info one by one from the results of above query and store them in new instance of my Custom Class Project Store the above instance in some contianer e.g Vector say vProjects //part 2 For each Project p in vProject if (TableExist(p.Id)) Store p in a new container say vValidatedProjects Note: The TableExist() method execute the following query: SELECT COUNT(*) FROM pg_tables WHERE tablename = 'Table"+ p.Id + "'" Now every thing is working fine as expected but !!! the program executes very slow just because of the second part of above algo, if we have one thousand projects the TableExist() method is also called thousand time and each time this method is called a new query is executed which slow downs the program :( The solution in my mind is some such thing //part1 SELECT * FROM Projects Table WHERE a table exist angainst projets.Id get only those projects info for whom a dynamic table exist. From the results of above query and store them in new instance of my Custom Class Project Store the above instance in some contianer e.g Vector say vProjects. Now in this way only one query did the job for us rather than N+1 Queries (Where N is no of rows in Projects Table) But i don't know how do i write such a query that returns the above results. Please help me in acheiving this. A: Changing the design would be the best solution. If that is not an option, then you could change the second part: //part 2 For each Project p in vProject if (TableExist(p.Id)) Store p in a new container say vValidatedProjects Note: The TableExist() method execute the following query: SELECT COUNT(*) FROM pg_tables WHERE tablename = 'Table"+ p.Id + "'" by, first adding a new boolean column in projects table (lets name it projects.TableExists ) Then, run your current TableExist() function one and populate that column. In addition, chnage the code that creates table for a project, to also update that column and the code that deletes a table to also update the column accordingly. Then your second part would be: //part 2 For each Project p in vProject if (p.TableExists) Store p in a new container say vValidatedProjects Note: The TableExist() method will not be used any more A: I would rather have one table with project_id in it and do all selects with where project_id = .... That would result in better table statistics and the table optimizer will make a better job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get altitude in Android I use the Location class to get altitude, but it always returns 0. Please tell me how to get altitude? Location.getAltitude(); A: Initially I used location.getAltitude() and it always retuned 0.0 . Then I came across https://groups.google.com/forum/#!topic/android-beginners/KNeLh905ip0 it helped me solve my problem. It works on actual real device. private LocationProvider _locationProvider; private LocationManager _locationManager; _locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); _locationProvider = _locationManager .getProvider(LocationManager.GPS_PROVIDER); location = _locationManager.getLastKnownLocation (LocationManager.GPS_PROVIDER); _locationProvider.supportsAltitude(); hasaltitude = location.hasAltitude(); double altitude = location.getAltitude(); System.out.println("HasAltitude" + hasaltitude+"-"+altitude); The value of "altitude" is will be in meters. A: Altitude is typically only available with GPS provider. You can check with available location provider if the support altitude: locationProvider.hasAltitude(); A: You need to obtain the user Location : http://developer.android.com/guide/topics/location/obtaining-user-location.html The locationListener will give you a Location object, on which you can use the getAltitude() function. A: With all the different methods to get location, while request a location for high accuracy it requires permission ACCESS_FINE_LOCATION
{ "language": "en", "url": "https://stackoverflow.com/questions/7594221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get every 100th "Like" for Facebook page We would like to reward every 100th Like of a Facebook page. I've seen other pages doing this, but all of them seem to be operating manually. Is it possible to get this information using the current Facebook APIs? The fan count could probably be polled using a cronjob, but if too many people like the page between polls the count may go from 199 to 201 and we won't know who was the 200th. A: You cannot get data about who likes your page via the Facebook API, and probably never will be able to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to block free shipping method in frontend only in magento I am in a tensed situation. I am behind this for more than 1 day. Is there anyway to block showing free shipping method in checkout page, but showing it on admin panel page. For eg: i purchased a product paying shipping charges for shipping method. But it is not delivered , In that case, through admin Panel, admin may able to reorder the same quote, free of cost and shipping charges, so free shipping method should show in admin panel. But When I enable that, this is shown on frontend also, so how can I block free shipping in frontend(customer checkout), but keeping it enable in admin panel. I am sorry for poor English. I think, the example that i provided you make the question clear. Thanks in advance. A: Sure it is , just edit the shipping methods template and make a if condition by shipping method code or extend the shipping method and set the isActive method to distinct front and backend
{ "language": "en", "url": "https://stackoverflow.com/questions/7594224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what is wrong with this jquery drop down I have trying to create this jquery dropdown, but it doesn't work, Does anybody know If I am missing something in jquery or CSS <style type="text/css"> body{padding:0px;margin:0px;} ul li{list-style-type:none;} #cssdropdown{padding:0px;margin:0px;} a{text-decoration:none;padding:0px;margin:0px;} .headLink{ display: inline-block; padding:10px;margin:10px;text-align:right;background-color:#999999;cursor:pointer;} .headLink ul{display:none;} </style> <script type="text/javascript" src="jquery-1.6.2.min.js"></script> <script type="text/javascript"> $(function() { $(".headLink").hover(function() { $('ul',this).css("display","block"); $('ul',this).css("display","none"); }) }) </script> <ul id="cssdropdown"> <li class="headLink">Home <ul> <li><a href="#">Home1</a></li> <li><a href="#">Home4</a></li> <li><a href="#">Home2</a></li> <li><a href="#">Home3</a></li> <li><a href="#">Home5</a></li> </ul> </li> <li class="headLink">About <ul> <li><a href="#">About1</a></li> <li><a href="#">About2</a></li> <li><a href="#">About</a></li> <li><a href="#">About3</a></li> <li><a href="#">About5</a></li> </ul> </li> <li class="headLink">Contact <ul> <li><a href="#">Contact1</a></li> <li><a href="#">Contact2</a></li> <li><a href="#">Contact3</a></li> <li><a href="#">Contact4</a></li> <li><a href="#">Contact5</a></li> </ul> </li> <li class="headLink">Links <ul> <li><a href="#">Links1</a></li> <li><a href="#">Links2</a></li> <li><a href="#">Links3</a></li> <li><a href="#">Links4</a></li> <li><a href="#">Links5</a></li> </ul> </li> </ul> I am also not sure how this works with ul as a parameter. for function inside jquery Thanks A: For starters you are showing and hiding the ul on hover. Change $(function() { $(".headLink").hover(function() { $('ul',this).css("display","block"); $('ul',this).css("display","none"); }) }) To $(function() { $(".headLink").hover(function() { $('ul',this).css("display","block"); }, function(){ $('ul',this).css("display","none"); }) }) Demo A: There's a way to do this with pure CSS. Remove the <script> tag, and replace your styles with these. No change to the HTML structure. <style> *{padding:0;margin:0} ul{list-style:none} a{text-decoration:none} a:hover{color:red} .headLink{float:left;height:30px;line-height:30px;padding:0 10px;cursor:pointer} .headLink ul{display:none;position:absolute} .headLink:hover ul{display:block} </style>
{ "language": "en", "url": "https://stackoverflow.com/questions/7594225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: find all method invocations How can I using eclipse Java search find all calls of methods that are declared in specific class? I tried p1.p2.p3.MyClass.* but this search string finds equals, getClass calls which is not necessary. I only need to find methods that are declared explicitly in p1.p2.p3.MyClass. A: If you select the method pressing CRTL ALT H you can see the call hierarchy and configure its view. In the outline view you can select multiple methods, then right button and open in call hierarchy. Again CRTL ALT H . You can find references to a class by selecting the class name and CRTL SHIFT G (references). A: Select the method name and hit CTRL-SHIFT-G, which searches for all references to this method. If you want to find all of the usages of all of the methods, you can't do that, but you can find all usages of the class, by selecting the class name and doing CTRL-SHIFT-G. A: Go to the method that you want to find. Right click and select the option to see all references. Eclipse is amazing for this. It should show all references in a panel of results A: I have found how it can be done using Java search. I have filtered out overrode methods from search result and got only methods defined in type. Thank you all for your time spent on this question nevertheless :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7594233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error in connecting with Php app in Android Here is my code to send the data from android app to php app which is running in my localhost. It is showing "Connection to http:// localhost refused" . Please help me public void postData() throws JSONException { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost/xampp/FeelSafeSecurity/connectiondemo.php"); JSONObject json = new JSONObject(); try { // prepare JSON data: json.put("name", "santhosh"); json.put("age", "24"); JSONArray postjson=new JSONArray(); postjson.put(json); // Post the data: httppost.setHeader("json", json.toString()); httppost.getParams().setParameter("jsonpost",postjson); // Execute HTTP Post Request System.out.print(json); HttpResponse response = httpclient.execute(httppost); // for JSON: if(response != null) { InputStream is = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } text = sb.toString(); } tv.setText(text); } catch (ClientProtocolException e) { System.out.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } And here is my php code to receive the data. I'am new to PHP. <?php $json = $_SERVER['HTTP_JSON']; echo "JSON: \n"; echo "--------------\n"; var_dump($json); echo "\n\n"; $data = json_decode($json); echo "Array: \n"; echo "--------------\n"; var_dump($data); echo "\n\n"; echo "Result: \n"; echo "--------------\n"; echo "\n\nName : ".$data->name."\n\n Age : ".$data->age; ?> A: Don't use localhost use your IP address. Localhost is only for the LOCAL server A: localhost means the local machine on which the app executes. In your case either amdroid device or the emulator virtual machine. Neither of which is running your php server. So, if you run this on device you must use the IP of the machine where php code is running. If you are trying this on emulator and you host machine runs the php code then you might try 10.0.2.2 as described in emulator network addressing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do i align a view in RelativeLayout to top-right corner Im trying to figure out how to align a view in relative layout to its top right corner. Currently it is aligned in top left corner. A simple problem, yet I dont know how to do it. Here is the code: RelativeLayout.LayoutParams gpsViewLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT ); gpsViewLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); gpsViewLayoutParams.addRule(RelativeLayout.ALIGN_RIGHT); this.relativeLayout.addView(gpsView,gpsViewLayoutParams); A: It is ALIGN_PARENT_RIGHT instead of ALIGN_RIGHT http://developer.android.com/reference/android/widget/RelativeLayout.html#ALIGN_PARENT_RIGHT A: Use this: gpsViewLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); instead of gpsViewLayoutParams.addRule(RelativeLayout.ALIGN_RIGHT); You may get in this way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Open access database (mdb) in sharing (among multiple users) I have an access database (mdb) and I want to open create an "automatic system" that a third party user (I would say a stupid-user) could run a macro automatically. So I created a batch file and I run the command: INOPENSPACE.mdb /nostartup /x MyMacro The problem is that Access cannot open because it needs the exclusive rights. If I try to open it by myself I open without exclusive rights and run the same macro without problems. Is there any way to do this by a command line or same, or is there any way to open an access database without exclusive rights and run my macro? A: The way I would approach this is to split the data into a separate database (data-db), and then create links to the tables in the database housing the macro (app-db). The user would then have their own copy of the app-db, and not have to work if another user has opened it or not - they can always have exclusive access.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Identifying the entity in sentiment analysis using Lingpipe I have implemented sentiment analysis using the sentiment analysis module of Lingpipe. I know that they use a Dynamic LR model for this. It just tells me if the test string is a positive sentiment or negative sentiment. What ideas could I use to determine the object for which the sentiment has been expressed? If the text is categorized as positive sentiment, I would like to get the object for which the sentiment has been expressed - this could be a movie name, product name or others. A: Although this question is really old but I would like to answer it for others' benefit. What you want here is concept level sentiment analysis. For a very basic version, I would recommend following these steps: * *Apply sentence splitter. You can either use Lingpipe's Sentence Splitter or the OpenNLP Sentence Detector. *Apply part-of-spech tagging. Again you can either use Lingpipe's POS tagger or OpenNLP POS Tagger. *You then need to identify tokens(s) identified as 'Nouns' by the POS tagger. These token(s) have the potential of being the targeted entity in the sentence. *Then you need to find sentiment words in the sentence. The easiest way to do this is by using a dictionary of sentiment bearing words. You can find many such dictionaries online. *The next step will be find out dependency relations in sentences. This can be achieved by using the Stanford Dependency Parser. For example, if you try out the sentence - "This phone is good." in their online demo, you can see the following 'Typed Dependencies': det(phone-2, This-1), nsubj(good-4, phone-2), cop(good-4, is-3), root(ROOT-0, good-4) The dependency nsubj(good-4, phone-2) here indicates that phone is the nominal subject of the token good, implying that the word good is expressed for phone. I am sure that your sentiment dictionary will contain the word good and phone would have been identified as a noun by the POS tagger. Thus, you can conclude that the sentiment good was expressed for the entity phone. This was a very basic example. You can go a step further and create rules around the dependency relations to extract more complex sentiment-entity pairs. You can also assign scores to your sentiment terms and come up with a total score for the sentence depending upon the number of occurrences of sentiment words in that sentence. A: Usually sentiment sentence means that the main entity of such sentence is the object of that sentiment. So basic heuristic is to NER and get first object. Otherwise you should use deep parsing NLP toolkits and write some rules to link sentiment to object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django and tests in docfiles I'm having a small problem with my test suite with Django. I'm working on a Python package that can run in both Django and Plone (http://pypi.python.org/pypi/jquery.pyproxy). All the tests are written as doctests, either in the Python code or in separate docfiles (for example the README.txt). I can have those tests running fine but Django just do not count them: [vincent ~/buildouts/tests/django_pyproxy]> bin/django test pyproxy ... Creating test database for alias 'default'... ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK But if I had some failing test, it will appear correctly: [vincent ~/buildouts/tests/django_pyproxy]> bin/django test pyproxy ... Failed example: 1+1 Expected nothing Got: 2 ********************************************************************** 1 items had failures: 1 of 44 in README.rst ***Test Failed*** 1 failures. Creating test database for alias 'default'... ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK This is how my test suite is declared right now: import os import doctest from unittest import TestSuite from jquery.pyproxy import base, utils OPTIONFLAGS = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE) __test__ = { 'base': doctest.testmod( m=base, optionflags=OPTIONFLAGS), 'utils': doctest.testmod( m=utils, optionflags=OPTIONFLAGS), 'readme': doctest.testfile( "../../../README.rst", optionflags=OPTIONFLAGS), 'django': doctest.testfile( "django.txt", optionflags=OPTIONFLAGS), } I guess I'm doing something wrong when declaring the test suite but I don't have a clue what it is exactly. Thanks for your help, Vincent A: I finally solved the problem with the suite() method: import os import doctest from django.utils import unittest from jquery.pyproxy import base, utils OPTIONFLAGS = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE) testmods = {'base': base, 'utils': utils} testfiles = {'readme': '../../../README.rst', 'django': 'django.txt'} def suite(): return unittest.TestSuite( [doctest.DocTestSuite(mod, optionflags = OPTIONFLAGS) for mod in testmods.values()] + \ [doctest.DocFileSuite(f, optionflags = OPTIONFLAGS) for f in testfiles.values()]) Apparently the problem when calling doctest.testfile or doctest.testmod is that the tests are directly ran. Using DocTestSuite/DocFileSuite builds the list and then the test runner runs them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Image download - image cannot open I tried to create some code so that a user can download an image in opencart without right clicking and using Save as... but after I created this code and download the image, trying to open the image says the image was damage. <form action="download.php" method="post" > <input type="text" name="file" value="<?php echo $image['popup']; ?>" /> <input type="submit" value="download" /> </form> download.php <?php $file= $_POST["file"]; header ("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header ("Content-Type: application/octet-stream"); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-type: application/pdf'); header('Content-type: image/jpg'); header('Content-type: image/gif'); header('Content-type: image/png'); readfile('$file'); ?> A: Your current problem is that when in single quotes, $file will not be parsed but taken literally. Use double or no quotes: readfile($file); Other observations: * *Why are you sending five different content-types? That doesn't make sense. You should detect the file's type and send the appropriate image header (or just application/octet-stream if you just want to offer a downloadable resource, and not try and display it in the browser). *You should check that $file actually points to one of the files you want to allow to download. Without that check, an attacker could get any file from your site this way, including configuration files. A: There is no way you can define the content type multiple times. Determine what the content type is by file extension and include the correct one. Besides that, use this: readfile($file); No quotes needed. edit: with quotes it doesn't even work, but it will try to open a filename named $file A: You send multiple Content-Type headers? This is wrong. You have to determine the Content-Type via the extension (.jpg, .pdf, ...) of the file, and then send the appropriate headers. Here is a snippet of a download script I've done lately. $fileName = $_POST['file']; // or whatever $file = 'someDirectory/' . $fileName; // full path of the file, could also be absolute $fileLen = filesize($file); $ext = strtolower(substr(strrchr($fileName, '.'), 1)); switch($ext) { case 'txt': $cType = 'text/plain'; break; case 'pdf': $cType = 'application/pdf'; break; case 'exe': $cType = 'application/octet-stream'; break; case 'zip': $cType = 'application/zip'; break; case 'doc': $cType = 'application/msword'; break; case 'xls': $cType = 'application/vnd.ms-excel'; break; case 'ppt': $cType = 'application/vnd.ms-powerpoint'; break; case 'gif': $cType = 'image/gif'; break; case 'png': $cType = 'image/png'; break; case 'jpeg': case 'jpg': $cType = 'image/jpg'; break; case 'mp3': $cType = 'audio/mpeg'; break; case 'wav': $cType = 'audio/x-wav'; break; case 'mpeg': case 'mpg': case 'mpe': $cType = 'video/mpeg'; break; case 'mov': $cType = 'video/quicktime'; break; case 'avi': $cType = 'video/x-msvideo'; break; //forbidden filetypes case 'inc': case 'conf': case 'sql': case 'cgi': case 'htaccess': case 'php': case 'php3': case 'php4': case 'php5': exit; default: $cType = 'application/force-download'; break; } $headers = array( 'Pragma' => 'public', 'Expires' => 0, 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Cache-Control' => 'public', 'Content-Description' => 'File Transfer', 'Content-Type' => $cType, 'Content-Disposition' => 'attachment; filename="'. $fileName .'"', 'Content-Transfer-Encoding' => 'binary', 'Content-Length' => $fileLen ); foreach($headers as $header => $data) header($header . ': ' . $data); @readfile($file); A: $mimeInfo = finfo_open(FILEINFO_MIME_TYPE); $mime_type = finfo_file($mimeInfo, $_FILES['files']['tmp_name']); that will help you detect what mimetype to use with header('Content-Type: '.$this->_mime_type); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file));
{ "language": "en", "url": "https://stackoverflow.com/questions/7594255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image Compression Algorithm - Breaking an Image Into Squares By Color I'm trying to develop a mobile application, and I'm wondering the easiest way to convert an image into a text file, and then be able to recreate it later in memory said text. The image(s) in question will contain no more than 16 or so colors, so it would work out fine. Basically, brute-forcing this solution would require me saving each individual's pixel color data into a file. However, this would result in a HUGE file. I know there's a better way - like, if there's a huge portion of the image that consists of the same color, breaking up the area into smaller squares and rectangles and saving their coordinates and size to file. Here's an example. The image is supposed to be just black/white. The big color boxes represent theoretical 'data points' in the outputted text file. These boxes would really state their origin, size, and what color they should be. E.g., top box has an origin of 0,0, a size of 359,48, and it represents the color black. Saved in a text file, the data would be 0,0,359,48,0. What kind of algorithm would this be? NOTE: The SDK that I am using cannot return a pixel's color from an X,Y coordinate. However, I can load external information into the program from a text file and manipulate it that way. This data that I need to export to a text file will be from a different utility that will have the capability to get a pixel's color from X,Y coordinates. EDIT: Added a picture EDIT2: Added constraints A: Could you elaborate on why you want to save an image (or its parts) as plain text? Can't you use a binary representation instead? Also, if images typically have lots of contiguous runs of pixels of same color, you may want to use the so-called run-length encoding (RLE). Alternatively, one of Lempel-Ziv-something compression algorithms could be used (LZ77, LZ78, LZW). A: Compress the image into a compressed format (e.g. JPEG, PNG, GIF, etc) and then save it as a .txt file or whatever. To recreate the image, just read in the file into your program using whatever library function suits your particular needs. If it's necessary that the .txt file have some textual meaning, then you may be in some trouble. A: In cs there is an algorithm like spatial index to recursivley subdivide a plane into 4 tiles. If the cell has the same size it looks like a quadtree. If want you to subdivide a plane into pattern (of colors) you can use this tiling idea to dynamically change the size of the cell. A good start to look at is a z-curve or a hilbert curve.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I create elements with trigger invoke method in SilverLight? This question is a continuation of the pregoing one.( How can I combine some UserControls in SilverLight?) I have 3 view models with different colour properties. How can I create elements of User Control with trigger invoke method after pressing the button on the element. Here is a code of this element that I have upgrade with the trigger action. <UserControl x:Class="SilverlightApplication14.NodePicture" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:SilverlightApplication14" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"> <Grid x:Name="LayoutRootNodePicture" Height="100" Width="100" HorizontalAlignment="Center"> <Canvas x:Name="ParentCanvas" Background="{Binding NodeColor}" Width="100" Height="100" > </Canvas> <Image HorizontalAlignment="Center" Source="add.png" Stretch="Fill" Width="16" VerticalAlignment="Top" Margin="0,0,2,2" Height="16" > <i:Interaction.Triggers> <i:EventTrigger EventName="MouseLeftButtonDown"> <local:Add /> </i:EventTrigger> </i:Interaction.Triggers> </Image> </Grid> </UserControl> And the code with the trigger action namespace SilverlightApplication14 { public class Add : TriggerAction<FrameworkElement> { protected override void Invoke(object parameter) { var vm = AssociatedObject.DataContext as NodeViewModel; if (vm != null) { if (vm.Nodes == null) { vm.Nodes = new ObservableCollection<NodeViewModel>(); } var child = new NodeViewModel { NodeColor = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0)) }; vm.Nodes.Add(child); } } } } Updated code: <Grid> <Grid.Resources> <Style x:Key="myStyle" TargetType="ListBoxItem"> <Setter Property="Background" Value="Khaki" /> <Setter Property="Foreground" Value="DarkSlateGray" /> <Setter Property="Margin" Value="5" /> <Setter Property="FontStyle" Value="Italic" /> <Setter Property="FontSize" Value="14" /> <Setter Property="BorderBrush" Value="DarkGray" /> </Style> </Grid.Resources> <ListBox ItemsSource="{Binding Nodes}" ItemContainerStyle="{StaticResource myStyle}"> <ListBox.ItemTemplate> <DataTemplate> <local:NodePicture DataContext="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ItemsPanel> <ItemsPanelTemplate> <StackPanel /> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox> </Grid> Is there a simple (or a right way ) way of doing this? A: It is preferable to work with business-logic in view models, whereas triggers are intended for working with UI. I would change the trigger to a command: <Button Command="{Binding AddCommand}"> <Button.Template> <ControlTemplate TargetType="Button"> <Image ... /> </ControlTemplate> </Button.Template> </Button> When a user clicks the button, the AddCommand is invoked. It can be implemented in the view model so: public class NodeViewModel { public NodeViewModel() { this.AddCommand = new RelayCommand(obj => { /* do something */ }); } public RelayCommand AddCommand { get; private set; } //... } The RelayCommand class is one of the possible implementations and it can be downloaded with the MVVM Light framework here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binding interface via ToMethod to a method with a parameter I think what I'm looking for is something very simple, yet I am unable to find any examples. I'd like to use Ninject to create an object by having Ninject call a factory method with a parameter specified and not injected during the actual request to instantiate the object: Request for an object here: StandardKernel.Get<ISomeInteface>(new Ninject.Parameters.Parameter("dataContext", dataContext, true)); And I'd like to map the ISomeInterface to a method that is expecting a value to be passed to it at runtime. Mapping an interface here: Kernel.Bind<ISomeInterface>().ToMethod(SomeObject.Create(--> `what do I put here?`)); Is this possible? If so, how do I properly map my interface? Thanks! A: ToMethod(ctx => SomeObject.Create( (IDataContext)ctx.Parameters.Single(p =>p.Name == "dataContext") .GetValue(ctx, null)) But you should rethink your design to avoid calling Get from anywhere else than your composite root.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Background worker update progress freezes datagridview I am trying to write an application to get a list a users in various AD groups and display them in a datagrid on a form. When a button on my form is clicked it fires a background worker which calls a method to get the user list for an AD group. The background worker returns a data table and the background worker completed method sets the data grid data source to the data table and everything works OK. The problem comes when I try to use the background worker progress changed method to update the data grid as each data table column is filled in. It works OK while the background worker is running but when it finishes the grid and the form becomes unresponsive for several minutes. I'm struggling to figure out why this is. code example: backroundWorker_DoWork(.........) { DataTable dt = new DataTable(); DataRow dr; //Get datatable from argument DataTable dt2 = e.Argument as DataTable //get list of AD groups to check for (int i = 0; i > dt2.Rows.Count; i++) { columnName = dt2.Rows[i][0].ToString(); groupName = dt2.Rows[i][1].ToString(); //Call Method to get users from nested AD groups GetADUsers(groupName) //Add users returned from above method to DataTable dt //.......... //Send DataTable to Report Progress backgroundWorker.ReportProgress(0, dt); } e.Result = dt; } backroundWorker_ProgressChanged(..........) { DataTable dt = e.UserState as DataTable; dataGridView1.DataSource = dt; } backroundWorker_RunWorkerCompleted(..........) { DataTable dt = e.UserState as DataTable; dataGridView1.DataSource = dt; } A: In RunWorkerCompled() event handler, you should use e.Result instead of e.UserState i.e. your code should be like: DataTable dt = e.Result as DataTable, As a practice before reading the result in RunWorkerCompleted event, you should also check for error using e.Error != null syntax, see the complete ComputeFibonacci example using background worker component in the below MSDN link: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7594264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android AsyncTask onPostExecute method EDIT: If I do not use the progress at all, just showing the dialog, then everything works without any problems. But if i add progress, then dialog doesn't close(method onPostExecute() is not fired). onPostExecute method is not executed. Where do I have a mistake? (Same result on emulator and on the device) I am also not sure if I should use Override notation for these methods This is the rough solution for now. It works every time, but is not the proper and not the nice one. What I am doing: * I start a child activity using tabgroupactivity * Then i navigate to another activity in the child activity, so it is a current child of a parent * There is a webview, where I display information about one comment.. whatever * There is a link in the content displayed by the webView * when i click it, i start downloading the PDF file. When the file is downloaded: while ((current = bis.read()) != -1) { read = read + current; baf.append((byte) current); Dialog.setProgress(read); if(Dialog.isShowing() && read+2*current>file_size){ Dialog.dismiss(); Dialog.cancel(); } } My Dialog object is disapeared, so if I try to call Dialog after the While loop, i just don't get it. So what I did is that every time i get new buffer from website, i check if the dialog is still visible and if the current byte together with the amount of bytes read up to now are greater than the full size of the file, then I close the dialog in the while loop. I tried using fileSize == read(amount of bytes), but it did not work, maybe they are not precisely mach each other when the file is downloaded private class DownloadPDFFile extends AsyncTask<String, Integer, Void> { private ProgressDialog Dialog = new ProgressDialog(getParent()); protected void onPreExecute() { Dialog.setMessage("Downloading PDF file.."); Dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); Dialog.setCancelable(false); // Dialog.setMax(1000); Dialog.setProgress(0); Dialog.show(); } protected Void doInBackground(String... urls) { File file=null; int file_size = 0; try { URL url = new URL(urls[0]); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); file_size = urlConnection.getContentLength(); Dialog.setMax(file_size); } catch (IOException e) { } try { URL url1 = new URL(urls[0]); // you can // link file = new File("skm_intern_pdf.pdf"); URLConnection ucon = url1.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(5000); int read = 0; int current = 0; while ((current = bis.read()) != -1) { read = read + current; baf.append((byte) current); Dialog.setProgress(read); if(Dialog.isShowing() && read+2*current>file_size){ Dialog.dismiss(); Dialog.cancel(); } } FileOutputStream fos = openFileOutput("skm_pdf.pdf", Context.MODE_WORLD_WRITEABLE); fos.write(baf.toByteArray()); fos.flush(); fos.close(); } catch (IOException e) { } return null; } A: Is the parent of the AsyncTask cancelled/paused/destroyed before the AsyncTask finishes? If yes, the AsyncTask might recieve a cancel() which results in onPostExecute() never to be run. To verify this, try overriding onCancelled()-method and check if it is run. A: Funny how you can post 3 times the same answer because people does not search before they post... You are NOT allowed to access the UI thread from anywhere but the UI Thread... That means that your Dialog.dismiss and Dialog.cancel can't be executed since it is not Thread safe... To fix your problem you have several ways. First way : do NOT use AsyncTask as you will have 5 tasks (at max) running at every time... I send you to the Android Doc of AsyncTask, and the guidelines to Processes and Threads attached for further info. Second way : Move all of your UI Thread-related methods in the onPostExecute(). This is thread-safe, and the result of doInBackground() is automatically transmitted to it. Third way : use on of the following Activity.runOnUiThread(Runnable) View.post(Runnable) View.postDelayed(Runnable, long) The Runnable will be executed inside the UI Thread. So again. Thread-safe. I recommend the second solution if you really do not need your app to be thoroughly optimized. If it does, use tasks manually added to a manually created ThreadPoolExecutor (again, see the doc of ThreadPoolExecutor). While searching through the doc I found This : There are a few threading rules that must be followed for this class to work properly: The task instance must be created on the UI thread. execute(Params...) must be invoked on the UI thread. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. The task can be executed only once (an exception will be thrown if a second execution is attempted.) If not on UI Thread, do not use AsyncTask but Task instead, with a ThreadPoolExecutor to wrap them. This is why you should NOT use Asynctask : How can I make asynchronous URL connections on Android? look for my name in the answers. A: I found this thread searching for the same problem. After much trial and error, I found two issues: * *I was sometimes canceling my Task in doInBackground instead of letting the method complete normally, causing onCancelled() to fire instead of onPostExecute(). Thanks for the tip, Kasper! *I was apparently using the wrong method signature for onPostExecute. If you do not have a return type, it needs to be: protected void onPostExecute(Void v) Not very intuitive, and not shown in the API, but once I did this that did the trick. A: IMHO, you just need to remove super call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Does robots.txt apply to files/directories only, or URLs too? I can use robots.txt to stop a folder of images/html files getting indexed. But what about dynamic pages, e.g. preventing indexing of certain WordPress pages? A: The robots.txt syntax doesn't care about whether a page is dynamic or not: All that matters for it is the directory structure. If you are using a permalink structure like example.com/blog/year/month/slug you should be able to exclude single pages like so: user-agent: * disallow: /blog/2011/09/this-is-a-test-entry you could use Google's webmaster tools to verify whether that happens properly. Remember that Wordpress stores static content like images and PDF documents in /wp-content - you can't block those this way unless you want to block all resources in that directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to validate user input a number and the number greater than 0 I'm trying to validate user input that user must enter number and it must be greater than 0, the validation of only numbers I got it working; however, I can't seem to incorporate the validation of greater than 0 float income; cout << "How much did you earn last year: "; //validating imput for income while(!(cin >> income)) { char ch; cin.clear(); cout << "Sorry, number must be biger than \"0\" \n" << "How much did you make last year: "; while(cin.get(ch) && ch != '\n'); } A: Just add the condition to the while, and handle it in the loop: while ( !(cin >> income) || income < 0.0 ) { if ( !cin ) // Clean up input stream... else // Must be negative number... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7594273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: facebook comments words expanding I created an app and installed it on a page. In this app, I installed the comments plugin specifying the data-href parameters as follows: http://www.facebook.com/{my_page_username}?sk=app_{my_app_id} It seems that facebook enabled the grammar filter by default and is erroneously expanding some words. How can I disable the grammar filter? A: There's a setting in the 'settings' section of the plugin. The real question is how to get to that section. The only way I know of, is when actually posting a comment (so, you're at a comment box at the end of your article now), and you're a moderator, in the upper-right cornet you have a 'settings' link. http://www.ivanlistes.com/facebook-social-plugins-comments-problem-with-grammar-filter/
{ "language": "en", "url": "https://stackoverflow.com/questions/7594279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to register interop .net asssembly per user Without Administrator Privileges using InstallShield I am working on a task not to prompt a normal user a popup(UAC) for approval to install windows Addin application while registering a .net assembly during installation using instalshield. On windows xp, its working fine but during installation on vista and windows 7, a popup comes up for approval. As per the requirement, it shouldnt come. Is there any way to bypass this pop up on vista and windows 7 if UAC is on and registered the assembly per user without administrator privileges? Kindly help? Thank You. A: Actually, COM can be registered per-user or per-machine as HKEY_CLASSES_ROOT is a view derived from both HKEY_CURRENT_USER\Software\Classes and HKEY_LOCAL_MACHINE\Software\Classes. If you run regasm /regfile:foo.dll you can generate a regfile and then change all the references in the key names to make it local to the current user. In the .reg file that gets generated, all the reg key additions will be to HKEY_CLASSES_ROOT. You need to replace these with "HKEY_CURRENT_USER\Software\Classes". Also if you need the COM registration to work with 32 bit applications and you're running x64, then for additions to HKEY_CLASSES_ROOT\CLSID, you'll need to insert "\Wow6432Node" before the CLSID token like. To be clear, additions to "HKEY_CLASSES_ROOT\CLSID" become "HKEY_CURRENT_USER\Software\Classes\Wow6432Node\CLSID". To make it work on x86 you only need to make this change for CLSID entries. Also, in certain situations, you can consider making use of Registration Free COM Interop by creating a manifest file for the EXE that consumes the COM server to make the ProgID/ClassID's available to the EXE without actually writing the registration information to the registry. A: This is a common mistake among developers which are not familiar with elevation and user privileges. The assembly you are installing is registered per-machine. This is why it requires elevation for its registration process. It's also elevated on XP, but you don't see if because its automatic. If you would run the installation under a normal user account, it would fail because of insufficient privileges. Since this assembly was designed to be registered per-machine, why are you trying to change its behavior? It's like trying to modify Windows to support your application. You adapt to the environment, not the other way around. So the correct solution would be to use a per-machine installer. This way your installation process will be installed for all users and will always require Administrator privileges. Per-user installations are designed for products which use only per-user locations. If you are installing resources in a per-machine location, then you should use a per-machine installation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google feed api integration with iPhone/Objective C I am building an RSS Reader. Some of the existing ones out there (for example, Pulse News for iPhone/iPad) have a search box where you can search for some term (example - "sports") and it will return a list of feeds that match your search criteria. So in this example, you type in "sports", and it searches and then comes back with ESPN.com's news feed, Yahoo! Sports' news feed, etc. etc. After initial research, I found out that Google feed API does the same. https://code.google.com/intl/fr/apis/ajaxfeeds/documentation/reference.html#findFeeds However, I cant figure out how to use the google feed api. It returns the xml that i need to parse but the part I am confused is how to call the API and where to catch the xml response. Can some one post a tutorial or some help on how to integrate it. A: Found a suitable solution with "Google Feed API" itself. They also have a JSON API(wow!!) which returns the JSON file for any query fired.. Here is the link: https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q= e.g: https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q=News
{ "language": "en", "url": "https://stackoverflow.com/questions/7594292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: asp.net mvc 3 double level authentication suppose i have a forms authentication in my application. once authenticated, it can access certain folders / controllers in my website auth level 1 -> profile,history,change password but, certain users can access another part of site if they pass level 2 . this type of users are like resellers (like sellers of accounts, etc) auth level 2 -> sell accounts, view online users the question is, how can i implement this another forms authentication in mvc 3 app? can these 2 form authentication coexist? tnx A: Surely you only need the one auth method. What you are describing sounds like you want to implement "roles". I dont understand why you need 2 form authentication processes. http://www.asp.net/mvc/tutorials/authenticating-users-with-forms-authentication-cs https://web.archive.org/web/20211029043732/https://www.4guysfromrolla.com/articles/082703-1.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7594293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issues with JFrame and JPanel Separation? I cant tell If I'm just not getting what these 2 things are but from what I gathered, the JFrame is just a big open box, So what I am trying to do is have that big box that opens will be say Red, then after that I'm making a JPanel which I assume is something that sits on top of the JFRAME, I'm trying to get this to be GRAY, So How can I get a red frame, with a gray strip on the left. I'm also trying to put these buttons vertically along the gray JPanel, and if at all possible them all to be stretched to the width of the JPanel. import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; public class Board extends JFrame implements MouseListener,ActionListener { public int x1, y1, x2, y2; public Board() { JFrame frame = new JFrame(); frame.setSize(1200, 800); Container con = frame.getContentPane(); con.setBackground(Color.RED); addMouseListener(this); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton clear = new JButton("Clear"); clear.addActionListener(this); JButton emptyR = new JButton("Empty Rectangle"); emptyR.addActionListener(this); JPanel menu = new JPanel(); menu.setSize(200, 500); BoxLayout layout = new BoxLayout(menu, BoxLayout.Y_AXIS); menu.setLayout(layout); menu.add(clear); menu.add(emptyR); //menu.setBackground(Color.black); frame.add(menu); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu help = new JMenu("Help"); menuBar.add(help); JMenuItem about = new JMenuItem("About"); help.add(about); about.addActionListener(this); } public void mouseExited(MouseEvent evt){} public void mouseEntered(MouseEvent evt){} public void mouseClicked(MouseEvent evt){} public void mousePressed(MouseEvent evt) { x1 = evt.getX(); y1= evt.getY(); } public void mouseReleased(MouseEvent evt) { x2 =evt.getX(); y2=evt.getY(); } public void actionPerformed(ActionEvent e) { } } A: On a first look, you have automatically a JFrame as soon as you extend JFrame. Board is a JFrame and frame is not necessary. Study the tutorial, especially the Swing section. public class Board extends JFrame implements MouseListener,ActionListener { public int x1, y1, x2, y2; public Board() { JFrame frame = new JFrame(); frame.setSize(1200, 800); Container con = frame.getContentPane(); con.setBackground(Color.RED); addMouseListener(this); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ... should rather be: public class Board extends JFrame implements MouseListener,ActionListener { public int x1, y1, x2, y2; public Board() { setSize(1200, 800); Container con = getContentPane(); con.setBackground(Color.RED); addMouseListener(this); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ... Here is a generic JSplitPane approach fresh from NetBeans: public class NewJFrame1 extends javax.swing.JFrame { /** Creates new form NewJFrame1 */ public NewJFrame1() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jSplitPane1.setBorder(null); jSplitPane1.setDividerLocation(100); jSplitPane1.setDividerSize(1); jSplitPane1.setEnabled(false); jPanel1.setBackground(new java.awt.Color(153, 153, 153)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); jSplitPane1.setLeftComponent(jPanel1); jPanel2.setBackground(new java.awt.Color(255, 0, 0)); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 299, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); jSplitPane1.setRightComponent(jPanel2); getContentPane().add(jSplitPane1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold> /** * @param args the command line arguments */ public static void main(String args[]) { /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame1().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JSplitPane jSplitPane1; // End of variables declaration } You should configure the setDividerLocation(n) to be 1/3 of your JFrame width. The jSplitPane1.setEnabled(false) makes the division fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Designing Animation using jQuery - Need Samples I need to design small (and simple-looking) animations which would suit a board game. For example, I need to coins which appear when points are won. The coins glide in a certain way towards the score-board. Are there sample implementations for simple animations or some useful links that I could refer to for this purpose? (I have a feeling I am not too good with design.) Thanks. A: docs about the available animation effects http://docs.jquery.com/UI/Effects/ http://blarnee.com/wp/jquery-ui-animation-effects/ tuitorials on how they are implemented. http://webdesignledger.com/tutorials/13-excellent-jquery-animation-techniques http://vandelaydesign.com/blog/web-development/jquery-animation-tutorials/ http://sixrevisions.com/javascript/10-awesome-techniques-and-examples-of-animation-with-jquery/ A: Try out the jQuery docs at http://jquery.com . Here is a link to the animate function of jQuery http://api.jquery.com/animate/ . With this function you can preform animations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Simple deterministic primality testing for small numbers I am aware that there are a number of primality testing algorithms used in practice (Sieve of Eratosthenes, Fermat's test, Miller-Rabin, AKS, etc). However, they are either slow (e.g. sieve), probabalistic (Fermat and Miller-Rabin), or relatively difficult to implement (AKS). What is the best deterministic solution to determine whether or not a number is prime? Note that I am primarily (pun intended) interested in testing against numbers on the order of 32 (and maybe 64) bits. So a robust solution (applicable to larger numbers) is not necessary. A: If I didn't care about space, I would try precomputing all the primes below 2^32 (~4e9/ln(4e9)*4 bytes, which is less than 1GB), store them in the memory and use a binary search. You can also play with memory mapping of the file containing these precomputed primes (pros: faster program start, cons: will be slow until all the needed data is actually in the memory). A: If you can factor n-1 it is easy to prove that n is prime, using a method developed by Edouard Lucas in the 19th century. You can read about the algorithm at Wikipedia, or look at my implementation of the algorithm at my blog. There are variants of the algorithm that require only a partial factorization. If the factorization of n-1 is difficult, the best method is the elliptic curve primality proving algorithm, but that requires more math, and more code, than you may be willing to write. That would be much faster than AKS, in any case. Are you sure that you need an absolute proof of primality? The Baillie-Wagstaff algorithm is faster than any deterministic primality prover, and there are no known counter-examples. If you know that n will never exceed 2^64 then strong pseudo-prime tests using the first twelve primes as bases are sufficient to prove n prime. For 32-bit integers, strong pseudo-prime tests to the three bases 2, 7 and 61 are sufficient to prove primality. A: Up to ~2^30 you could brute force with trial-division. Up to 3.4*10^14, Rabin-Miller with the first 7 primes has been proven to be deterministic. Above that, you're on your own. There's no known sub-cubic deterministic algorithm. EDIT : I remembered this, but I didn't find the reference until now: http://reference.wolfram.com/legacy/v5_2/book/section-A.9.4 PrimeQ first tests for divisibility using small primes, then uses the Miller-Rabin strong pseudoprime test base 2 and base 3, and then uses a Lucas test. As of 1997, this procedure is known to be correct only for n < 10^16, and it is conceivable that for larger n it could claim a composite number to be prime. So if you implement Rabin-Miller and Lucas, you're good up to 10^16. A: * *Use the Sieve of Eratosthenes to pre-calculate as many primes as you have space for. You can fit in a lot at one bit per number and halve the space by only sieving odd numbers (treating 2 as a special case). *For numbers from Sieve.MAX_NUM up to the square of Sieve.MAX_NUM you can use trial division because you already have the required primes listed. Judicious use of Miller-Rabin on larger unfactored residues can speed up the process a lot. *For numbers larger than that I would use one of the probabilistic tests, Miller-Rabin is good and if repeated a few times can give results that are less likely to be wrong than a hardware failure in the computer you are running.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: I'm using Facebook PHP-sdk v3.1.1 ... Do I still need to set cookie to "true"? I just upgraded my php-sdk to the latest version (v3.1.1) .. Do I still need to set cookie to true like I used to do when using php-sdk v2.0 ? or should I just remove this line? $facebook = new Facebook(array( 'appId' => 'MyappId', 'secret' => 'Mysecret', 'cookie' => true )); A: NO, not anymore. Have you checked the Library (base_facebook.php)? /** * Initialize a Facebook Application. * * The configuration: * - appId: the application ID * - secret: the application secret * - fileUpload: (optional) boolean indicating if file uploads are enabled * * @param array $config The application configuration */ public function __construct($config) { $this->setAppId($config['appId']); $this->setApiSecret($config['secret']); if (isset($config['fileUpload'])) { $this->setFileUploadSupport($config['fileUpload']); } $state = $this->getPersistentData('state'); if (!empty($state)) { $this->state = $this->getPersistentData('state'); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7594310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Switching to use a background image from no background image via a multi-part post to the Twitter API with Ruby and OAuth I would like to change my profile background from no background image to a background image that I upload via the Twitter API using Ruby. I have no problems uploading new background images when my profile is already set to use an image as the background. When my profile is set to not use an image as the background, however, and I try to upload an image with the added param "use=1" to tell Twitter I want to use the background image I'm uploading, Twitter replies with this: {"error":"You tried to turn on your background, but don't have one selected.", "request":"\/1\/account\/update_profile_background_image.json"} suggesting Twitter's not recognizing that I'm uploading an image. In every other case, however, image uploading works perfectly. Adding the "tile" param with the request works too, so the problem doesn't seem to be with mixing file params and non-file params. I can even try to turn my background image off from being on while uploading a new image and Twitter gives me this: {"error":"You tried to turn off your background while also uploading a new one.", "request":"\/1\/account\/update_profile_background_image.json"} showing that Twitter is totally able to detect that I'm uploading an image. Am I missing something? Here's the code: require 'oauth' require 'net/http/post/multipart' consumer = OAuth::Consumer.new(APP_CONSUMER_KEY, APP_CONSUMER_SECRET, {:site => "http://api.twitter.com", :scheme => :header}) access_token = OAuth::AccessToken.from_hash(consumer, {:oauth_token => OAUTH_TOKEN, :oauth_token_secret => OAUTH_TOKEN_SECRET}) image_file = File.new(image_file_path) url = URI.parse('http://api.twitter.com/1/account/update_profile_background_image.json') req = Net::HTTP::Post::Multipart.new url.path, { "use" => "1", "image" => UploadIO.new(image_file, image_mime_type, image_file_name) } consumer.sign!(req, access_token) Net::HTTP.new(url.host, url.port).start do |http| puts http.request(req) end
{ "language": "en", "url": "https://stackoverflow.com/questions/7594311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Nginx rewrite omitting port I've got a an nginx setup that's proxying all requests to a rails app. I would like to have a some kind of "maintenance-mode", so that if I use a different nginx-config, all incoming requests should return a local maintenance.html page. Here's what I've come up with: server { listen 3000; server_name localhost; root html/; #maintenance.html resides here location / { # redirect everything not already going to maintenance.html if ($request_uri !~ ^.*/maintenance.html$ ) { rewrite ^(.*)$ /maintenance.html break; } } } With this setup, I am able to directly access http://localhost:3000/maintenance.html. However, if I trigger the rewrite rule, the new URL results in localhost/maintenance.html instead of http://localhost:3000/maintenance.html. This results in a completely empty page being rendered. nginx version: nginx/1.0.6 on Windows 7 thx for any help UPDATE: I just noticed, it works fine with Internet Explorer and also with Chrome. Only Firefox seems to have that problem. A: location / { try_files /maintenance.html $uri =404; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7594314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: writing java testng test cases I am beginning with Java and testng test cases. I need to write a class, which reads data from a file and makes an in-memory data structure and uses this data structure for further processing. I would like to test, if this DS is being populated correctly. This would call for dumping the DS into a file and then comparing the input file with the dumped file. Is there any testNG assert available for file matching? Is this a common practice? A: I think it would be better to compare the data itself not the written out data. So I would write a method in the class to return this data structure (let's call it getDataStructure()) and then write a unit test to compare with the correct data. This only needs a correct equals() method in your data structure class and do: Assert.assertEquals(yourClass.getDataStructure(), correctData); Of course if you need to write out the data structure to a file, then you can test the serialization and deserialization separately. A: File compare/matching can be extracted to a utility method or something like that. If you need it only for testing there are addons for jUnit http://junit-addons.sourceforge.net/junitx/framework/FileAssert.html If you need file compare outside the testing environment you can use this simple function public static boolean fileContentEquals(String filePathA, String filePathB) throws Exception { if (!compareFilesLength(filePathA, filePathB)) return false; BufferedInputStream streamA = null; BufferedInputStream streamB = null; try { File fileA = new File(filePathA); File fileB = new File(filePathB); streamA = new BufferedInputStream(new FileInputStream(fileA)); streamB = new BufferedInputStream(new FileInputStream(fileB)); int chunkSizeInBytes = 16384; byte[] bufferA = new byte[chunkSizeInBytes]; byte[] bufferB = new byte[chunkSizeInBytes]; int totalReadBytes = 0; while (totalReadBytes < fileA.length()) { int readBytes = streamA.read(bufferA); streamB.read(bufferB); if (readBytes == 0) break; MessageDigest digestA = MessageDigest.getInstance(CHECKSUM_ALGORITHM); MessageDigest digestB = MessageDigest.getInstance(CHECKSUM_ALGORITHM); digestA.update(bufferA, 0, readBytes); digestB.update(bufferB, 0, readBytes); if (!MessageDigest.isEqual(digestA.digest(), digestB.digest())) { closeStreams(streamA, streamB); return false; } totalReadBytes += readBytes; } closeStreams(streamA, streamB); return true; } finally { closeStreams(streamA, streamB); } } public static void closeStreams(Closeable ...streams) { for (int i = 0; i < streams.length; i++) { Closeable stream = streams[i]; closeStream(stream); } } public static boolean compareFilesLength(String filePathA, String filePathB) { File fileA = new File(filePathA); File fileB = new File(filePathB); return fileA.length() == fileB.length(); } private static void closeStream(Closeable stream) { try { stream.close(); } catch (IOException e) { // ignore exception } } Your choice, but having an utility class with that functionality that can be reused is better imho. Good luck and have fun. A: Personally I would do the opposite. Surely you need a way to compare two of these data structure in the Java world - so the test would read from the file, build the DS, do its processing, and then assert it's equal to an "expected" DS you set up in your test. (using JUnit4) @Test public void testProcessingDoesWhatItShould() { final DataStructure original = readFromFile(filename); final DataStructure actual = doTheProcessingYouNeedToDo(original); final DataStructure expected = generateMyExpectedResult(); Assert.assertEquals("data structure", expected, actual); } A: If this DS is a simple Java Bean. then you can use EqualsBuilder from Apache Commons to compare 2 objects. A: compare bytes loaded from file system and bytes you are going to write file system pseudo code byte[] loadedBytes = loadFileContentFromFile(file) // maybe apache commons IOUtils.toByteArray(InputStream input) byte[] writeBytes = constructBytesFromDataStructure(dataStructure) Assert.assertTrue(java.util.Arrays.equals(writeBytes ,loadedBytes));
{ "language": "en", "url": "https://stackoverflow.com/questions/7594316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: converting image name extension from .PNG to .png in Python I have large set of images with .PNG extension (say image00.PNG). I want to convert it into .png (lower case). I got a script from internet, but am unable to process. Here's the script: files = os.listdir(cur_dir) for filename in files: file_ext = os.path.splitext(filename)[1] if old_ext == file_ext: newfile = filename.replace(old_ext, new_ext) os.rename(filename, newfile) When I try to run it on the terminal, I get the error: NameError: name 'filename' is not defined What could be the problem? A: Try this, it works for real (and not rename PNGX.PNG into pngX.png ;) ) : import os files = os.listdir(".") for filename in files: file_wo_ext, file_ext = os.path.splitext(filename) if file_ext == ".PNG": newfile = file_wo_ext + ".png" os.rename(filename, newfile) A: If the current working directory is not cur_dir, it fails. That's because os.listdir() returns only the list of filenames, without path. You should change to os.rename(os.path.join(cur_dir, filename), os.path.join(cur_dir, newfile)) . A: You should define old_ext to .PNG and new_ext to .png. A: lets do it this way: import os for filename in os.listdir(cur_dir): file_ext = os.path.splitext(filename)[1] if file_ext == '.PNG': newfile = filename.replace(file_ext, '.png') os.rename(cur_dir+'/'+filename, cur_dir+'/'+newfile) A: I use that when I want to lower all files extensions: for filename in os.listdir(directory): file_ext = os.path.splitext(filename)[1] file_ext_low = file_ext.lower() newfile = filename.replace(file_ext, file_ext_low) os.rename(directory+'/'+filename, directory+'/'+newfile) A: This is a python script. Do the following if you want to use python $ python > import os > old_ext = "PNG" > new_ext = "png" > files = os.listdir(cur_dir) > for filename in files: > file_ext = os.path.splitext(filename)[1] > if old_ext == file_ext: > newfile = filename.replace(old_ext, new_ext) > os.rename(filename, newfile) > > >exit() But this hawkish and probably won't work. I'd do this $ rename .PNG .png *.PNG via here
{ "language": "en", "url": "https://stackoverflow.com/questions/7594318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extending System.String for custom EditTemplate (Ajax) implementation This is the following. Normally, when i have a city, i'm using some javascript to autocomplete the cities as the user type. Now i want it to make it automaticly, using the edittemplate. So i would change : Public String City{get;set;} to Public City City {get;set;} But i can't inherit the System.String class, so i would like the best alternative to do this. I would create a new view of the City class and add javascript in my EditorTemplate, so i wouldn't ever have to add it anymore :) . Thanks in advance. A: I assume that what you want is to use the Html.EditorFor<City>() method and its siblings, which doesn't work very well with simple types. You can make the City class implicitly cast to and from System.String and it should be indistinguishable from an actual string: public class City { private readonly string city; public City(string city) { if (city == null) throw new ArgumentNullException("city"); this.city = city; } public override bool Equals(object obj) { City other = obj as City; return (other != null) && this.city.Equals(other.city); } public override int GetHashCode() { return this.city.GetHashCode(); } public override string ToString() { return this.city; } public static implicit operator string(City city) { return city.city; } public static implicit operator City(string city) { return new City(city); } } This class can now be passed to methods that expect System.String and vice versa: string city = new City("Washington"); City city = "Washington"; A: I would not bother with a new type but use metadata on your models to change the editor. The [UIHint("MyCityTemplate")] attribute on the property will make EditorFor and DisplayFor use MyCityTemplate rather than the default editor template for string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: for-loop & ArrayList This is a simple exercise from Chapter 2 of the Sun Certified Java Associate Study Guide that i'm having trouble with. When I try to compile the class below, I get the following error message: "error: type ArrayList does not take parameters ArrayList hookSizesList = new ArrayList<>;" import java.lang.Iterable; public class ArrayList { public static void main(String[] args) { Integer hookSizeList; ArrayList<Integer> hookSizesList = new ArrayList<Integer>(); hookSizesList.add(1); hookSizesList.add(4); hookSizesList.add(5); for (Integer hook: hookSizesList) System.out.print(hook + " "); } } I'd really appreciate any help in advance, thanks! A: you have numerous errors, here is a updated snippet import java.util.*; public class Numbers { public static void main(String[] args) { List<Integer> hookSizesList = new ArrayList<Integer>(); hookSizesList.add(1); hookSizesList.add(4); hookSizesList.add(5); for (Integer hook: hookSizesList) { System.out.print(hook + " "); } } } A: You probably want to use the class java.util.ArrayList. But since you named your own class ArrayList, this is the class your program uses instead, and your ArrayList class doesn't take any generic parameter. Change the name of your class and import java.util.ArrayList. A: Well there are some strange things: * *First you are not importing java.util.ArrayList. *You don't need to import java.lang.Iterable because classes from java.lang are imported automatically. *Your class has the same name of ArrayList, and this is not a good idea. When you write "ArrayList hookSizesList = new ArrayList();" you are initializing a java.util.ArrayList but your own class, that is not a generic class. Try doing: import java.util.ArrayList; public class MyArrayList { public static void main(String[] args) { Integer hookSizeList; //<--looks useless ArrayList<Integer> hookSizesList = new ArrayList<Integer>(); hookSizesList.add(1); hookSizesList.add(4); hookSizesList.add(5); for (Integer hook: hookSizesList) System.out.print(hook + " "); } } A: The class you create is named ArrayList. public class ArrayList { The class the example is about is java.util.ArrayList. Change the name of your class and import java.util.ArrayList. A: Your class doesn't use generics so you can't parameterize ArrayList with <Integer>. Above that, it doesn't seem like you implemented the add() method or implemented Iterable or anything else for that matter. But to solve the generics problem, you would have to have a class declaration like: public class ArrayList<E> Perhaps you were trying to import java.lang.ArrayList; ? In that case, you might want to consider renaming your class to something else. A: The ArrayList class defined in your code (not java.util.ArrayList<E>) does not define any generic type parameter, so you cannot use new ArrayList<Integer>(), but only new ArrayList() (same for variable declaration). A: You should use a different name for your class. Rename your class from ArrayList to something else.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Excel 2003 protected worksheet, not allowing Excel 2000 users to use autofilter I have created a spreadsheet for work and am trying to protect the sheet so that nobody except myself can edit the document. I have set it up so that I can edit the full range of the document. In the protection setting I have ticked the box that says that any users can use auto-filter. I have the auto-filter set before applying the security so this is not the issue as many forums would suggest. However I am using Excel 2003 whereas the majority of the organization is using Office 2000. I can't help thinking that there is some incompatibility between the two systems. Can anyone advise? VBA macro's aren't really an option as the default setting within the organization is that only signed macros can run but even then they have to be verified by the end user (very annoying for users with a low IT knowledge). Does anyone know of a way to make this work? A: It's not possible without VBA. See http://office.microsoft.com/en-us/excel-help/enable-autofilter-functionality-for-a-protected-worksheet-HA001098270.aspx By default, the AutoFilter functionality in Excel becomes unavailable when you protect part or all of a spreadsheet. If you use Microsoft Office Excel 2003 or Excel 2002, you can restore that functionality manually. If you use Excel 2000, you need to use a few lines of Microsoft Visual Basic® for Applications (VBA) code. Use VBA code to protect a worksheet and enable the AutoFilter functionality in Excel 2000 The sample code shown here protects a worksheet (not a workbook) and enables the AutoFilter functionality for that worksheet. The code works only with Excel 2000. This particular sample runs automatically when you open the workbook that contains the protected worksheet. The code also contains a password that you use to unprotect the worksheet. If you haven't already, start Excel 2000, open the desired workbook, and note the name of the worksheet that you want to protect. On the Tools menu, point to Macro, and then click Visual Basic Editor. In the Project Explorer, double-click ThisWorkbook. A new, blank code module opens in the code window. Copy the following sample code and paste it into the code window: Private Sub Workbook_Open() Sheet1.Protect password:="test", DrawingObjects:=True, _ contents:=True, Scenarios:=True, _ userinterfaceonly:=True Sheet1.EnableAutoFilter = True End Sub A: Does the organisation allow to change the default security settings within Excel for yourself and your users? If not you can easily create your own macro signature. I think its an optional install component to Excel that allows you to create the signature based on your PC or username? This will not have the same standing as a full Microsoft verified signature but depending on the organisation's settings it might allow all your macros to be accepted. This worked for me a few years ago on Excel 2000 but I still had to have each user change their security settings. I think I also made a macro to automate this change in security settings for each user? If I remember correctly. A: This is solved now. we are all working on Office 2010.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Learning Haskell with a view to learning Scala I've read a few questions such as Scala vs Haskell discussing the merits of both languages or which to learn, but I already know that I'd like to learn Scala. I was a Java programmer at uni and now mainly use PHP. I want to learn Scala as it looks like an improvement on Java for personal projects and I'd also like to learn a functional language to improve my knowledge as a programmer. I am wondering if it would be a good idea to learn Haskell as an introduction to functional programming as it is purely functional so I'd properly learn it rather than haphazard using bits of functional in Scala without knowing why? I'd also like to use Haskell for personal projects etc as it looks great, but I don't really see many real world applications of it, seems more used for academic stuff hence wanting to learn it to get the functional understanding then move on to Scala. A: Speaking as someone who came from Java, and for whom Scala was a gateway drug to Haskell, I happen to think this is a great idea (learn Haskell first)! Haskell is conceptually a much simpler language than Scala, and if your goal is to learn how to program functionally, you can't help but do so if you start with Haskell. By design, Scala supports a kind of "legacy mode" of coding in which you don't really have to change your Java (or PHP) habits too much if you don't want to. I think this is a strategic decision--and a good one!--meant to increase adoption amongst crusty Java stalwarts. But that's not you! You're actually interested in learning something new... so why not go all-out? Learning functional programming in a pure setting, without the clutter and the temptation to regress into old habits, will crystallize the concepts in your brain. Then by all means return to Scala and learn how it differs from Haskell; it is both weaker in some respects and stronger in others, but you will then be on a much better foundation to appreciate these differences. A: The risk of starting directly from Scala, without having played any purely functional programming language first, is that you'll probably be drawn to the procedural solutions a bit too often. I wouldn't try Haskell as an intro to functional programming, though: not that it's particularly hard - its syntax is amazingly terse - but it's definitely very peculiar (even in the peculiar world of functional programming) and I think you should try with a language you can port more easily to Scala, like Racket or plain Scheme. To better understand what I mean, look at list comprehensions in Haskell, Scala and Scheme. A: I learned Haskell first and then Scala and never regretted. You will gain a much deeper appreciation of FP if you learn Haskell first. Your understanding of the concepts behind FP and why they are important will be seared in. Much of Scala is taken from Haskell (IMHO). It will make more sense when you have the Haskell background. Don't shy away! Your efforts will be rewarded. A: I wouldn't do that. If you go straight to Scala (your final aim) you save time. You'll learn functional programming anyway, but as Scala is "less pure" you'll be able to start writing programs in Scala usign some Java-like constructs, which will make the transition simpler. Even if you go into Haskell, your first programs will be of less "functional quality" than later ones, as only practice improves that. Starting Scala your first programs will be of "less quality" as your first programs in Java or PHP were, but with practice you'll improve. Spending time in unrelated tasks hoping they MAY help, it can result in you wasting that time. Focus on your aim. If that's Scala, go for it. UPDATE: I believe this may be relevant to the question. It raises a point on productivity (deliver software) vs seeking "pure knowledge". A: I came to Scala from a Java background. Initially I just focused on Scala as a better Java. As time went on I started to use more and more functional concepts in Scala. Eventually I reached a point where I felt I needed a purer understanding of functional programming. It was at this point that I went away and learnt Haskell. When I cam back to Scala I found it much easier to use a functional style and some of the the concepts I struggled with previously made much more sense. You don't have to learn Haskell to become a good Scala developers, but I think once you get to a certain level in Scala that having a deeper understanding of functional programming concepts really helps. A: For me, I want to learn Scala and functional programming; and, thus simply, I am learning Scala. My study material is Programming Scala. After I have read the early chapter on syntx and stuff, I have skipped chapter covering OO stuff and jumped to Chapter 8 which cover the functional programming stuff. There I let myself struggle with FP. I read this scala code, which is written in FP way and analyze it. You want to learn Scala for "...an improvement on Java for personal projects." and Haskell for FP intro. So, it seems that first of all, you want to be productive with your java project and then grasp FP as a side effect. To be productive, you have to master the language. There are much to learn and master the language and the only way to master the language is that you have to write the code in that language. As you learn/use Scala, you can't avoid FP out right even if you want to. I have been reading the Scala blogs(the book too) and the authors always go out of their way to do explanation when it comes to FP concept. You don't have to worry about not grasping FP by going Scala route. Yes, you can draw inspiration from Haskell like this when you are learning Scala. Or as Chris Turner above have pointed out, you can delve into more FP when you are already productive with Scala. You wanna go to point A, why not go to point A directly? If you go via the route of point B (Haskell), you will have to postpone your productivity as Pere Villega mentioned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "45" }
Q: How to create named autoresetevent in C#? I need to synchronize two applications by using a named event. But neither AutoResetEvent nor ManualResetEvent contains constructor with a name for event (only initial state). I can open existing named event through static method OpenExisting in AutoResetEvent or ManualResetEvent class, but can't create It! I don't want to use native WinAPI CreateEvent function for It, unless I know precisely of not existing of other ways. A: I found a solution by myself. That is: EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset, "testRemoteServer");
{ "language": "en", "url": "https://stackoverflow.com/questions/7594338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Checksum of a loop device file exactly reproducible? how can I mount and unmount a file as loop device and have exactly the same MD5 checksum afterwards? (Linux) Here's the workflow: * *I take a fresh copy of a fixed template file which contains a prepared ext2 root file system. *The file is mounted with mount -t ext2 <file> <mountpoint> -o loop,sync,noatime,nodiratime *( Here, some files will be added in future--but ignore this for a moment and focus on mount / umount ) *umount *Take the MD5 sum of the file. *I expect the same, reproducible checksum every time I perform exactly the same steps. However, when I repeat the process (remember: taking a fresh copy of the template file), I always get a different checksum. I assume on the one hand that still some timestamps are set internally (I tried to avoid this with the noatime option) or, on the other hand, Linux manages the file system on its own way where I have no influence. That means: the files and timestamps inside might might be the same, but the way the file system is arranged inside the file might be differnt and therefore kind of random. In comparison, when I create a zip file of a file tree, and I touched all files with a defined timestamp, the checksum of the zip file is reproducible. Is there a way to keep the mount or file access that controlled as I need at all? A: it depends on the file system on disk format. I believe ext2 keep sat the least the mount count counter - how many time the file system was mounted. I don't remember any mount option to tell it not to write that counter (and perhaps other data items) but you can: a. mount the file system read only. Then the checksum will not change of course. b. Change the ext2 file system kernel driver to add an option to not change the counter and possible other data bits. The more interesting question is why you are interested is such an option. I think there is probably a better way to achieve what you are trying to do - whatever it is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to port an iOS game to WP7 Does exist any tool or procedure to easily port a iOS game (made with cocos2d for example) to Windows Phone 7 (XNA)? Thanks! A: You can use Cocos2D-XNA which is a good port of the cocos2d-x project to XNA and C#. You can find the source for Cocos2D-XNA at https://github.com/Cocos2DXNA/cocos2d-xna A: Not any I know, but if you know C++ it is easy to learn C#. I found this link; http://i2w.codeplex.com/ I dont know if it is any help at all but still.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Making a Composite Component in JSF2 I have a problem with my composite component in JSF2. I implement a list using ui and li. But if I use my component nothing happens. My list-tag is not replaced in code generated by facelet. So whats wrong with this. The composite component is stored under /resources/util/list.xhtml. Here is the code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:composite="http://java.sun.com/jsf/composite" xmlns:ui="http://java.sun.com/jsf/facelets"> <head><title>(For validation only)</title></head> <body> <composite:interface> <composite:attribute name="values"/> <composite:attribute name="listStyle"/> <composite:attribute name="elementStyle"/> </composite:interface> <composite:implementation> <ul class="#{cc.attrs.listStyle}"> <ui:repeat var="element" value="#{cc.attrs.values}"> <li class="#{cc.attrs.elementStyle}">#{element}</li> </ui:repeat> </ul> </composite:implementation> </body></html> I use my tag this way <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:core="http://java.sun.com/jsf/core" xmlns:utils="http://http://java.sun.com/jsf/composite/utils"> <h:head> <title>Show user Color</title> <style type="text/css"> .elements { font-style: italic; } .list { margin: 0px; padding:0px;} </style> </h:head> <h:body> <h1>Show Color</h1> <p>User selected: #{ColorBean.selectedColor}</p> <p>User set hex: #{ColorBean.showHex == true? "yes": "no"}</p> <p><h:outputFormat value="#{msgs.hexNotification}" rendered="#{ColorBean.showHex}"> <core:param value='#{ColorBean.showHex == true? "yes": "no"}' /> </h:outputFormat> </p> <fieldset><legend>Colors</legend> <utils:list values="#{ColorBean.colors}" listStyle="list" elementStyle="elements"/> </fieldset> </h:body> </html> Here is the generated code. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" > <html xmlns="http://www.w3.org/1999/xhtml" xmlns:utils="http://http://java.sun.com/jsf/composite/utils"><head> <title>Show user Color</title> <style type="text/css"> .elements { font-style: italic; } .list { margin: 0px; padding:0px;} </style></head><body> <h1>Show Color</h1> <p>User selected: green</p> <p>User set hex: no</p> <p> </p> <fieldset><legend>Colors</legend> <utils:list values="[Ljava.lang.String;@13e86ec" listStyle="list" elementStyle="elements"></utils:list> </fieldset><div id="javax_faces_developmentstage_messages"></div></body> </html> What is wrong here. I use an tutorial to build this code. http://courses.coreservlets.com/Course-Materials/pdf/jsf/jsf2/JSF2-Looping.pdf They did a similar example on the last pages. I hope you can help me Thanks A: Change your xmlns:utils="http://http://java.sun.com/jsf/composite/utils"> to xmlns:utils="http://java.sun.com/jsf/composite/utils"> Regs, Rob
{ "language": "en", "url": "https://stackoverflow.com/questions/7594342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I add addresses to a person from the add person form? I have a (rails 3/jquery) application where a user comes across a new person form. In the form, one of the things he can do is to add addresses as he is constructing the person. I want the addresses to be added, and displayed (either through Ajax, or on the page itself), but the addresses should be committed only once the person is saved (if the user cancels the person creation, the addresses should also not be saved). The person form has fields for a person name, and a button to add addresses. On clicking on add address, a dialog pops up to enter addresses. As each address is added, it is shown inline with the form. What is the best way to do this? I am currently populating a div within the person using jquery to enter addresses: <%= form_tag ... do %> <%= text_field_tag :person_name%> <%= link_to 'Add address', nil, :id => 'add_address_link', :remote => true%> <%= submit_tag%> <%end%> $('#add_address_link').click(function(){ $('#addresses').append(...); }); I could handle the submit, and read the address elements into a series of hidden fields (not shown here), or use ajax instead of direct jquery click handler, and populate the hidden fields in an erb. Not sure what is the best way to achieve this? Thanks Anand A: What does your database look like? If Persons and Addresses are separate tables, I would recommend using Ryanb's nested_form gem. The gem uses jQuery and makes adding dynamic nested forms very easy and fast. The gem supports has_many relationships, so you could allow a person to have multiple addresses. https://github.com/ryanb/nested_form A: Rails 3 supports nested forms with the fields_for form helper. Check out http://guides.rubyonrails.org/form_helpers.html#binding-a-form-to-an-object. You should show the model associations in your question, but I'll assume you have: class Person < ActiveRecord::Base has_many :addresses end class Address < ActiveRecord::Base belongs_to :person end Now, you want to dynamically add duplicate fields for each address. While I don't think ryanb's nested_form gem is necessary, you should look at his railscast http://railscasts.com/episodes/197-nested-model-form-part-2 The railscast demonstrates dynamically adding a row to a table where each row is a nested form using fields_for There is a companion project on github that includes the code to do that. Finally, you want to adapt ryanb's code to use hidden fields instead of table rows. I'm actually in the process of doing exactly this. Another option is to restructure your form workflow. I had another use case which sounds even more like what you've described and the easiest thing for me to do was, using the same _form partial for Person, only show the child objects (Address in your case) if there are any. Naturally, on a "new" action, there aren't (unless you have done something in a Person callback). Then, on the Person "create" action, rather than redirect to a Person index page (typical), redirect back to the edit_person_path. Then, you can use remote/ajax to add addresses to the person, since the person will exist. A: I am assuming that you have a separate model - Address. In this case, just pass the params used for creating a new user into the address controller, and in the create action for the Address controller, call @address.save only if a Person with the params exists (if Person.find is successful).
{ "language": "en", "url": "https://stackoverflow.com/questions/7594347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want a button on my website that will execute a python script I am currently making a website using django. Now I want to execute a python script from my template/view with a button on the website. It should be possible but to be honest I don't know how. An example would be best. Thanks for any help at all. A: If you are using Django - best way, IMHO, is just to create the view that will handle your python code, and then access it at onclick event via ajax request. yourapp/views.py def your_python_script(request): if request.is_ajax: # do your stuff here ... else: return HttpRequest(status=400) If you are using django also you should have jQuery, and in your template add javascript code, something like this: $("#<your_button_id>").click( function() { $.post("your_python_script_url", {<dict with any args you need>}, function () { // What to do when request successfully completed }); }); And not to forget about CRSF token if your are using it. How to handle it you can find in offical django documentation. UPDATE You can add csrf token to page template like: <script> var csrf_token = '{% csrf_token %}'; ... </script> Next, you need to bind to the global jquery ajaxSend event, and add the token to any POST request. $("body").bind("ajaxSend", function(elm, xhr, s) { if (s.type == "POST") { xhr.setRequestHeader('X-CSRF-Token', csrf_token); } }); Something like this should work. A: Well got it working now and just thought I would write my answer: view.py: import script as gh def get_hostname(request): gh.main() return HttpResponseRedirect('/') urls.py: ... url(r'^get_hostname/$', 'thinco.views.get_hostname'), ... somewhere in template: ... <form action="/get_hostname/" method="GET"> <input type="submit" value="Liste der Thin Clients laden"> </form> ... A: Create a view function and do an @dajaxice_register decorator for it: A silly example follows: models.py: class Funkyness(models.Model): funktasm = models.CharField(max_length=128) funfasticness = models.TextField() urls.py: url(r'^funk$', 'views.myFunkyView'), views.py: def myFunkyView(request) render_to_request('index.htm', {'where': 'home'}, context_instance=RequestContext(request)) index.htm: {% if where %} You are {{ where }} {% endif %} When you go to http://yoursite.com/funk, you will get index.htm rendered and you will get a page that says "You are home." Now, the dynamic part... Write a view method as such: from django.utils import simplejson def getHowFunky(request, v): html = """ <div class="my_message"> This is really funky, almost stinky... <br /> """ + str(v) + """ </div> """ return simplejson.dumps({'message': html}) back in index.htm: <script type="text/javascript> /* first argument is return JS function, the second is the dictionary of data to sent to the python method. */ function init(){ Dajaxice.package.getHowFunky(showFunky, {'v': "Your's Truly... Fubar"}); } function showFunky(data){ /* This is the data returned back from the AJAX (Dajaxice) call. */ document.write(data.message) } </script> So, you build a python method that takes inputs and returns something. You register it with Dajaxice, you call it, passing a callback method. It runs and when it succeeds, it send the python return (possibly JSON object) to the callback method as an argument. That method then writes to the screen what it got from the Dajaxice call. For more info on Dajaxice, go to: http://dajaxproject.com/ Props to Jorge Bastida, the sole developer of Dajax/Dajaxice! A: What I could think of for an answer is to use: Django + Dajax Django link: https://docs.djangoproject.com/en/1.4/ Dajax is actually ajax for django: Visit their website and refer to their examples for quick start http://www.dajaxproject.com/ You can create your button in django view and upon triggering your button, you can use run a python snippet, not script. If you want to run a standalone script, you could probably check out djcelery. http://pypi.python.org/pypi/django-celery
{ "language": "en", "url": "https://stackoverflow.com/questions/7594348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Cocos2d App is Freezing I'm creating a game app using cocos2d Chipmunk. The app is working normally but after 30 to 40 seconds the app becomes unresponsive(app freezes) without any error log. Can any tell me why this is happening and how to overcome this problem. Please tell me the code also. Thanks in advance.. A: i got the solution. i was using timers but was not unscheduling them that's why app was freezing. now it is working fine after unscheduling that timers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing an async method call Below is a simplified setup of my application. It has a class Foobar which calls on a facade method for fetching data. The facade then calls on a web service to actually get the data and then manipulates the data a bit and then returns it to Foobar. Now because the web service might take a good while to run, the method call to the facade needs to be asynchronous. Hence the facade's method doesn't have a return value, but instead, the method uses a callback object. Look at the example and continue reading below. public class Foobar { private List<DTO> dtos; @Autowired private Facade facade; public void refresh() { facade.refreshFoobar(new CallBack() { public void dataFetched(List<DTO> dtos) { setDtos(dtos); } }); } public void setDtos(List<DTO> dtos) { this.dtos = dtos; } } public class Facade { ... public void refreshFoorbar(CallBack cb) { // Fetch data from a web service List<DTO> dtos = webService.getData(); // Manipulate DTOs .... // call on the callback method cb.dataFecthed(dtos); } } I have two ways of making the facade's method asynchronous, either by creating a thread manually or by using springs @Async annotation. public class Facade { public void refreshFoorbar(CallBack cb) { new Thread() { @Override public void run() { .... } }.start(); } } // ... OR ... public class Facade { @Async public void refreshFoorbar(CallBack cb) { .... } } My problem is that I now need to write an integration test for this chain of method calls. I think I need to force the async facade call to be synchronous when the integration test is ran, otherwise I won't know for sure when I can do the appropriate asserts. The only idea for making the method call synchronous is to use manually handled threads AND making the threading conditional (so, for testing purposes, I have an if clause which determines if the facade method should be ran in a separate thread or not). However, I have a feeling that there could be a better solution to my problem, whether it be a better way of forcing the method to me synchronous, eg with spring, or by testing the multithreading on some way. This is where I need your suggestions, how would you solve my problem? Note, I'm using junit for both unit and integration tests. A: When JUnit testing stuff like this, I use a testing callback with a CountDownLatch that gets counted down by the callback and await()ed by the test method. private static class TestingCallback implements Callback { private final CountDownLatch latch; public TestingCallback(CountDownLatch latch) { this.latch = latch; } @Override public void onEvent() { this.latch.countDown(); } } @Test public void testCallback() { final CountDownLatch latch = new CountDownLatch(1); classUnderTest.execute( new TestCallback(latch) ); assertTrue(latch.await(30, TimeUnit.SECONDS)); } If the callback is invoked (asynchronously) by the code under test, the latch returns true and the test passes. If the callback doesn't get invoked, the test times out after thirty seconds and the assertion fails. A: Simple solution would be to return a Future object like this, @Async public Future<String> refreshFoorbar(CallBack cb) { yourHeavyLifting(); //asynchronous call return new AsyncResult<String>("yourJobNameMaybe"); } And in your test, take the future reference and call the get() method. future.get(); // if its not already complete, waits for it to complete assertTrue(yourTestCondition) This blog post shows a sample.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Reason for not requiring numbers in a username I've come across a system that requires you to include a number in your username. I feel this is pointless, as the username should be easy to remember, and not be subject to requirements that may be applied to passwords. However I can't find a good write up of the reasons for this. Can anyone reference a good source for this, and/or explain it in better words than I can? Edit: I'm getting answers explaining why they do this, which are certainly of value, but there must be a write up somewhere of how to make a secure login system, that advocates a simple, easy to remember username. A: I would say it could be because if you force a number in an username, you will most likely never receive a dublicate name problem. There wont be someone having for example the name 'peter' and then there is a 'peter95' and a 'peter112'. No one will have the original one. This is just what I think is the most reasonable answer. A: Having no clue about the specific system mentioned, if one can call support and say something like "My username is John and I forgot my password" - adding a number may add just a bit of security. Also, if the system is not protected against brute-force attacks, one can try common usernames together with common passwords. I agree with Xavjer: the reason for this is most likely not security-related. I agree with you: If the requirement is security-related - the security scheme is probably wrong. Edit: Another idea - Maybe they want to force you to use a username which is different than the one you use on other sites. Since many users tend to select the same username and password for different sites, and in case the password is compromised on one of these sites - this may help (but again, just a bit).
{ "language": "en", "url": "https://stackoverflow.com/questions/7594362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Resolve generic types with IXamlTypeResolver I'd written a new TypeExtension class that replace the default System.Windows.Markup.TypeExtension to handle generic types. It allows the Xaml to work with generic types in many different ways, like : <DataTemplate DataType="{ck:Type [here a generic type name]}"> This is how it works : * *I'd written TypeExtention class, that inherit of MarkupExtension (it's the ck:Type in the example) *I'd override the ProvideValue method to call Resolve on IXamlTypeResolver IXamlTypeResolver service = p.GetService( true ); _type = service.Resolve( _typeName ); So, in .NET 3.5, I can resolve types like "local:IConfigItemProperty`1". But now in .NET 4 (with WPF 4) the resolve method throws an exception : Character '' was unexpected in string 'local:IConfigItemProperty1'. Invalid XAML type name. Do you think .NET 4.0 does not support '`' anymore ? A: While the post is a bit old, i put the answer for any other dev looking for solution. It's seem from 4.0 they change the way the Reader deal with generic. The lack of support to '`' by the IXamlTypeResolver service seem to be a bug while the regression is not documented at all. If u want to use generic, you might want to switch with x:TypeArguments which is list the argument for the generic. C# public class GraphBase<N,L,P> : IGraph<N,L,P> { ... } XAML <?xml version="1.0" encoding="utf-8" ?> <GraphBase xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="clr-namespace:MyGeoLive.Topology;assembly=MyGeoLive.Topology" xmlns:System="clr-namespace:System;assembly=mscorlib" x:TypeArguments="System:String,System:String,System:String" > </GraphBase>
{ "language": "en", "url": "https://stackoverflow.com/questions/7594363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I do a MSBuild Condition testing if an ItemGroup contains an item? This should be simple, but I can't find how to do this (or maybe it's not possible). In MSBuild I have an ItemGroup that is a list of files. I want to execute a task only if a particular file is in that ItemGroup Something like: <Copy Condition="@(Files) <contains> C:\MyFile.txt" .... /> Any way to do this? Preferably without writing a custom task. Edit: The list of files is only to do with the condition. Otherwise it has no relation to the task. A: Try <Copy Condition="'%(Files.Identity)' == 'C:\MyFile.txt'" .. />
{ "language": "en", "url": "https://stackoverflow.com/questions/7594366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: listview and round corner doesn't work What I want: I'am using a Listview and I want to use this view with round corners. Situation: A listview without round corners :-( . I use different examples to define a customShape <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="30dp"/> <stroke android:width="1dp" android:color="#000000" /> </shape> If I apply this customShape to the listview items(Textview) every entry in Listview have round corners. It is crazy!!! So the customShape.xml works but not with the border of the listview. Any idea??? regard marcel A: Get view by id for the list view. ListView.setBackgroundResource(R.drawable.custom_shape); Remove the background settings in the xml . Put the custom_shape.xml in drawable folder. Remove the stroke component from it as it is not needed to round the corners
{ "language": "en", "url": "https://stackoverflow.com/questions/7594368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I add an image column to a table in wicket framework? I want to add a column containing images in each cell of a table in wicket framework. I make the table in a java class and have a createColumns() method as the following: private List<IColumn> createColumns() { List<IColumn> columns = new ArrayList<IColumn>(); // Create the columns that will be displayed, second param is the sort // order // Use column position for aggregate functions // Otherwise the query uses column aliases so these need to match here columns.add(new PropertyColumn(new Model("Status"), "code") { private static final long serialVersionUID = 1L; @Override public void populateItem(Item item, String componentId, IModel model) { Object[] values = ((ArrayWrapper) model.getObject()).getArray(); setStatus((Integer) values[0]); item.add(new Image(componentId, new ResourceReference(this.getClass(), getStatus()))); } }); columns.add(new PropertyColumn(new Model("First"), "2", "array[1]")); columns.add(new PropertyColumn(new Model("Last"), "3", "array[2]")); columns.add(new PropertyColumn(new Model("Sender"), "sender", "array[4]")); columns.add(new PropertyColumn(new Model("Receiver"), "receiver", "array[5]")); columns.add(new HeaderlessColumn() { private static final long serialVersionUID = 1L; public void populateItem(Item cellItem, String componentId, IModel rowModel) { cellItem.add(new ActionPanel(componentId, rowModel)); }; }); return columns; } The html file is simply as the following: <html xmlns:wicket="http://wicket.sourceforge.net/"> <body> <wicket:extend> <table align="center" wicket:id="results"></table> </wicket:extend> </body> </html> But I get an exception which is: org.apache.wicket.markup.MarkupException: Component cell must be applied to a tag of type 'img', not '' (line 0, column 0) And it's related to the lines that I make the column for image. Can anyone help me how I can make it? A: Use an AbstractColumn instead of a PropertyColumn. PropertyColumn is suitable if you only need to specify a property name, as you would do with a PropertyModel. From this discussion in the Wicket users list, DataTable outputs this markup: <tbody> <tr wicket:id="rows"> <td wicket:id="cells"> <span wicket:id="cell">[cell]</span> </td> </tr> </tbody> Note that IColumn implements ICellPopulator, and it is ICellPopulator#populateItem() that is overriden in AbstractColumn. So, whatever you come up with in populateItem should be ok if associated with a <span> in markup. PropertyColumn might be doing it with a Label, and you should be fine adding a custom Panel or WebMarkupContainer which will contain your Image. This is a slightly related question: How do you make a link inside a PropertyColumn in Wicket? A: The code in CreateColumns method is as the following: columns.add(new PropertyColumn(new Model("Status"), "code") { private static final long serialVersionUID = 1L; @Override public void populateItem(Item item, String componentId, IModel model) { Object[] values = ((ArrayWrapper) model.getObject()).getArray(); setStatus((Integer) values[0]); item.add(new ImagePanel(componentId, new ResourceReference(SearchResults.class, getStatus()))); } }); And this is the ImagePanel: public class ImagePanel extends Panel { private static final long serialVersionUID = 1L; /** * @param id */ public ImagePanel(String id, ResourceReference image) { super(id); add(new Image("status", image)); } } The html code for the panel is: <html xmlns:wicket="http://wicket.sourceforge.net/"> <body> <wicket:panel> <img wicket:id="status"/> </wicket:panel> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7594371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: sort Gridview doesn't work I have asp.net page contain gridview as following <asp:GridView ID="GridView1" runat="server" AllowPaging="True" OnPageIndexChanging="gridView_PageIndexChanging" OnSorting="TaskGridView_Sorting" AllowSorting="True" AutoGenerateColumns="False" onselectedindexchanged="GridView1_SelectedIndexChanged" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"> <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" /> <Columns> <asp:boundfield datafield="name_english" convertemptystringtonull="true" headertext="Name"/> <asp:BoundField DataField="Inc_ID" convertemptystringtonull="true" HeaderText="Inc_ID" SortExpression="Inc_ID"/> <asp:BoundField DataField="UID" HeaderText="Study_UID" SortExpression= "UID"/> </Columns> <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" /> <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> </asp:GridView> I fill and sort it using the following code protected void Button1_Click(object sender, EventArgs e) { //connection to database string connection = System.Configuration.ConfigurationManager.ConnectionStrings["NorthindConnectionString"].ConnectionString; SqlConnection myConn = new SqlConnection(connection); myConn.Open(); SqlCommand cmd = new SqlCommand(" WorkList", myConn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@Name", TextBox1.Text)); cmd.Parameters.Add(new SqlParameter("@ID", TextBox2.Text)); cmd.Parameters.Add(new SqlParameter("@AccNo", TextBox4.Text)); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); Session["TaskTable"] = ds.Tables[0]; ds.Dispose(); da.Dispose(); GridView1.Visible = true; myConn.Close(); } protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e) { //Retrieve the table from the session object. DataTable dt = Session["TaskTable"] as DataTable; if (dt != null) { //Sort the data. dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression); GridView1.DataSource = Session["TaskTable"]; GridView1.DataBind(); } } private string GetSortDirection(string column) { // By default, set the sort direction to ascending. string sortDirection = "ASC"; // Retrieve the last column that was sorted. string sortExpression = ViewState["SortExpression"] as string; if (sortExpression != null) { // Check if the same column is being sorted. // Otherwise, the default value can be returned. if (sortExpression == column) { string lastDirection = ViewState["SortDirection"] as string; if ((lastDirection != null) && (lastDirection == "ASC")) { sortDirection = "DESC"; } } } // Save new values in ViewState. ViewState["SortDirection"] = sortDirection; ViewState["SortExpression"] = column; return sortDirection; } } the problem when click on any header for sorting raise error System.IndexOutOfRangeException: Cannot find column name .. , any idea to solve that , I am sure from the columns name in database , A: private string ConvertSortDirectionToSql(SortDirection sortDirection) { string newSortDirection = String.Empty; switch (sortDirection) { case SortDirection.Ascending: newSortDirection = "ASC"; break; case SortDirection.Descending: newSortDirection = "DESC"; break; } return newSortDirection; } protected void gridView_Sorting(object sender, GridViewSortEventArgs e) { DataTable dataTable = gridView.DataSource as DataTable; if (dataTable != null) { DataView dataView = new DataView(dataTable); dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection); gridView.DataSource = dataView; gridView.DataBind(); } } try this code.. A: You need to bind your grid to the sorted view (and not the original table) for sorting to work. protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e) { //Retrieve the table from the session object. DataTable dt = Session["TaskTable"] as DataTable; if (dt != null) { //Sort the data. dt.DefaultView.Sort = e.SortExpression; GridView1.DataSource = dt.DefaultView; GridView1.DataBind(); } } I am not sure if you need GetSortDirection method. Also note that SortExpression property consists of sort direction (e.g. "UID DESC") so base your logic on that. Your code could have set sort expression such as "UID DESC ASC" which is obviously a wrong expression. A: In order to have the code work in asp.net or a web environment, you need to put your gridview in Session a session object, and your sorting in a view state. In order to get the sorting to work with paging, do the following. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Session["SearchTable"] = gv_GridView.DataSource; LoadSearchGrid("Select * from WF_Search); } private void LoadSearchGrid(string query) { DataTable dsp = new DataTable(); conn = new SqlConnection(ConnectionString); SqlDataAdapter sda = new SqlDataAdapter(query, conn); conn.Open(); sda.Fill(dsp); Session["SearchTable"] = dsp; gv_GridView.DataSource = Session["SearchTable"]; gv_GridView.DataBind(); conn.Close(); sda.Dispose(); } protected void gv_GridView_Sorting(object sender, GridViewSortEventArgs e) { ViewState["SortDirection"] = e.SortDirection; DataTable dtr = Session["SearchTable"] as DataTable; if (dtr != null) { dtr.DefaultView.Sort = e.SortExpression + " " + getSortDirection(e.SortExpression); gv_GridView.DataSource = Session["SearchTable"]; gv_GridView.DataBind(); Session["SearchTable"] = gv_GridView.DataSource; } } private string getSortDirection(string column) { string sortDirection = "ASC"; string sortExpression = ViewState["SortDirection"] as string; if (sortExpression != null) { if (sortExpression == column) { string lastDirection = ViewState["SortDirection"] as string; if (lastDirection != null && lastDirection == "ASC") { sortDirection = "DESC"; } } } ViewState["SortDirection"] = sortDirection; ViewState["SortExpression"] = column; return sortDirection; } protected void gv_GridView_PageIndexChanging(object sender, GridViewPageEventArgs e) { gv_GridView.DataSource = Session["SearchTable"]; gv_GridView.DataBind(); gv_GridView.PageIndex = e.NewPageIndex; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7594375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use HTC opensenseSDK? I downloaded and test HTC opensense SDK . But I can't test any sample application . The main.xml file in the layout show like this The following classes could not be found: * *com.htc.painting.engine.HTCPaintingView (Fix Build Path, Edit XML, Create Class) *com.htc.painting.penmenu.PenMenu (Fix Build Path, Edit XML, Create Class) How can I solve this problem ? I see log cat error like this 10-04 12:02:05.001: ERROR/dalvikvm(580): Could not find class 'com.htc.painting.penmenu.PenMenu', referenced from method com.htc.demo.penmenu.MainActivity.init 10-04 12:02:05.510: ERROR/AndroidRuntime(580): FATAL EXCEPTION: main 10-04 12:02:05.510: ERROR/AndroidRuntime(580): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.htc.demo.penmenu/com.htc.demo.penmenu.MainActivity}: android.view.InflateException: Binary XML file line #55: Error inflating class com.htc.painting.engine.HtcPaintingView 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1748) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1764) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.app.ActivityThread.access$1500(ActivityThread.java:122) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1002) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.os.Handler.dispatchMessage(Handler.java:99) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.os.Looper.loop(Looper.java:132) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.app.ActivityThread.main(ActivityThread.java:4025) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at java.lang.reflect.Method.invokeNative(Native Method) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at java.lang.reflect.Method.invoke(Method.java:491) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at dalvik.system.NativeStart.main(Native Method) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): Caused by: android.view.InflateException: Binary XML file line #55: Error inflating class com.htc.painting.engine.HtcPaintingView 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:682) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.view.LayoutInflater.rInflate(LayoutInflater.java:724) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.view.LayoutInflater.rInflate(LayoutInflater.java:727) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.view.LayoutInflater.inflate(LayoutInflater.java:479) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.view.LayoutInflater.inflate(LayoutInflater.java:391) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.view.LayoutInflater.inflate(LayoutInflater.java:347) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:223) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.app.Activity.setContentView(Activity.java:1780) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at com.htc.demo.penmenu.MainActivity.onCreate(MainActivity.java:42) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): ... 11 more 10-04 12:02:05.510: ERROR/AndroidRuntime(580): Caused by: java.lang.ClassNotFoundException: com.htc.painting.engine.HtcPaintingView in loader dalvik.system.PathClassLoader[/data/app/com.htc.demo.penmenu-1.apk] 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:251) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at java.lang.ClassLoader.loadClass(ClassLoader.java:540) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at java.lang.ClassLoader.loadClass(ClassLoader.java:500) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.view.LayoutInflater.createView(LayoutInflater.java:542) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:671) 10-04 12:02:05.510: ERROR/AndroidRuntime(580): ... 21 more A: I speak with a person from HTC,in samples only one example is working there will be update in few weeks and whole functions will be supported other A: * *Make sure to install HTC SKD properly as written on this page. *When opening project from sample, make sure to check Build Target to HTC Tablet Extension This problem is that main.xml references custom View, which is in this case in HTCExtension.jar archive, so you must have HTCExtension.jar on build path. But I didn't have any problem opening sample project, everything was set up correctly and could be built. Try to reinstall whole SDK and open sample again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to preload my nav bar's graphics I created and coded my own css navigation bar (inspired by apple, if that helps you visualize), that means i have dynamic buttons with 4 states that i manage with a css stylesheet. I only have two graphics, one with the button states, and another with the stylized "text". However, i'de like to make it so that the nab bar's graphics are preloaded in my webpages. 1) is this possible ? 2) is it useful ? 3) if yes to both questions what would be the code ? A: I don't really see the point in preloading those images. If the images are static and always refer to the same file without parameters, they will be cached anyway by the browser and only loaded the first time a visitor comes to your site (unless you prevent caching with some fancy http header settings), and served out of the clients browser cache on further requests. Do you have an example of your navigation to look at? if you are concerned about loading times your could quite easy have a navigation similar to apple.com by using css3-gradients for the background, border radius for the outer container and only declare a background-image in you IE stylesheet as fallback option, so modern browsers wont requests the IE background pattern. Add some 1px offset text-shadow to give your navigation some 3d look. A: You can preload images either by using JavaScript, or by inserting img tags early on in the page with styling to hide them. JavaScript example: <script> image = new Image(); image.src = '/path/to/image.png'; </script> You'll need to do the "image = ...", "image.src = ..." for each image you want to preload. This code will load the image into the browser's cache. HTML/CSS example: <img src="/path/to/image.png" style="display: none;" /> The above will load the image, but won't display it on the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to write Unobtrusive Ajax calls in jquery with rails I am currently in rails 3.1. I wanna achieve ajax call in jquery with out the use of form_for method. My current page is localhost:3000/posts/show/2 and I have a button in the page and it does not belong under any form. On click of that button, I have to send an ajax call to the create action in the Comments controller and this is the jquery code $(function(){ $('#add_button').click(function(){ $.post('comments/create', function(data) { $('.result').html(data); }); return false; }); }); but this didnt end in an ajax call but it was a browser call and got an error saying could not find the method in Posts controller. I even tried changing the url in $.post to Comments.create (fyi, I have added necessary changes in routes.rb) but still i end up getting a browser call and an error. How can i restrict it to pure ajax call and how to access the correct url(i.e. to access action of a comments controller inside the view of a Posts controller)? A: If you want to do it 'the rails way' I would suggest you read this excellent post: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/ That way you'll be able to bind your code to rail's remote link code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing a boolean value on the server WordPress has this thing that examines whether it has been set up (installed) on the server and if it's not, it takes the visitor to a "install" page. I need to have something like that in a system I'm building. I need to store a boolean value on the server. What would be the most elegant / lightweight approach? A: You could create a semaphore, where you just create an empty file, and then you just check if the file exists as your TRUE value. A: Most of the packages that require installation or configuration have different ways. Some can check if a file exists then return true or false, write to a database, or have a configuration file included in all its scripts. Most go with the if(file_exists) method. EDIT : Dabr has a config_bla.php file (with all the needed constants defined in the file) which should be renamed to config.php after installation. A: This should do it: function was_here_before() { $file="/some/writable/file.txt"; if (file_exists($file)) return true; else { touch($file) return false; } } There are many ways however, YMMV.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why a STUN Server Needs Two Different Public IP addresses I have took a look to STUN Server settings in openfire, and this statement from there: "In order to act as a STUN server, two different public IP addresses on the same machine are required, as well as two different port numbers for each IP." I have researched on google, and generally stun servers need two public IPs, what is reason for that? A: For attempting to establish P2P connectivity, the STUN binding request and response to/from the STUN service's primary address (IP and port) is all that really matters. The mapped address returned in the response body of this request is passed (via XMPP or other service) to the remote node that the local client is attempting to establish directly communication with. The second IP and port that the STUN service listens on are useful for determining NAT port mapping behavior and NAT filtering behavior. By making binding requests to the alternate IP:port on the service, a client can discover if his NAT has consistent mapping semantics for local ports. In the event he gets different port mapping values for each test, the client can conclude it is behind a "symmetric NAT" - which are the most difficult to traverse for P2P. By sending up a bind request with a "change request" attribute that asks the service to respond from the other IP or port, a client can detect if his NAT just filters datagrams from remote hosts based on IP and port, or allows for datagrams from alternate ports on hosts it has sent outbound datagrams to. The mapping behavior and filtering tests only provide limited information for subsequent P2P connections. In the case of determining a symmetric NAT is between the host and the Internet, some implementations may observe the NAT to have a consistent incremental value of the port value in each binding response. (e.g. the external port observed by the STUN service increases by one). As such, the client can offer an IP and guessed port number for the remote client to try to send to instead of the one mapped back from the first binding request. Or the client may use this behavior/filtering test for logging. Or to automatically allocate a relay in the event of symmetric NAT. A: Because in some rare cases, the behavior of NAT translation is a function of the target IP address. Meaning, you must 'ping' two different IP addresses to find the precise behavior of the NAT (does it depend of the target IP address or not?) If you 'pinged' twice the same server with two distinct ports, that would not cover this case properly (i.e., you would not be covering all your bases). P.S.: The two IP addresses don't need be on the same server, it could be different servers. A: I'm guessing that it is required to identify the type of NAT being performed - some NAT will use the same source IP address and encode the session id via the port number (I think it's called cone NAT but not sure), some NAT will use a combination of source IP and port to encode the session ID. The answer the STUN server needs to give the client is different based on NAT type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Android LogCat displaying messages multiple times instead of once I'm working on a project which is connecting to web server and gets data stream from it. For testing purposes I'm showing all the data in LogCat so I can be sure that everything is right. I'm testing my application in 2 devices: * *HTC EVO 3D *HTC DESIRE. At one point I noticed something strange: when I'm testing on EVO 3D I saw that I'm getting all packets of data stream twice, which is really strange because server cannot send me one packet two times. I thought it's because of EVO's dual core processor. But after that I noticed the same problem with HTC Desire and in emulator too. On emulator I'm getting all packets even three times. The problem is that it's not always happening. I looked closer at that problem and I saw that LogCat is showing all running processes on my devices and emulator twice or more and actually I started thinking that it's LogCat bug and have nothing to do with my application. So my question: is anybody else getting the same strange behaviour of LogCat? Is it an SDK bug, or the problem is in my application code? (I just tried with other applications, and the result is the same). A: As I noticed it's probably some kind of LogCat bug, because I debug my code maybe 50 times and find that there is nothing which can reproduce that problem. And I did check the request to the server which I am sending. It was only one request, not more. So that's why I started of thinking that it's probably an LogCat bug.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HQL CASE statement usage I'm using HQL and have this query <query name="rule.myRule.query.by.name"> <![CDATA[ FROM rule.myRule as cr WHERE cr.name LIKE :name AND cr.type = 'myType' CASE WHEN COUNT(cr.childRules) > 0 THEN cr.childRules LIKE :name ]]> </query> I need some help making this query correct. What I want is to have the condition cr.childeRule LIKE :name execute only when the count of cr.childRules >0 . Where am I wrong ? A: FROM rule.myRule as cr left join cr.childRules childRule WHERE cr.name LIKE :name AND cr.type = 'myType' and childRule.id is null or childRule.name = :name should do what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to hide literals in code What are the main existing approaches to hide the value of literals in code, so that they are not easily traced with just an hexdumper or a decompiler? For example, instead of coding this: static final int MY_VALUE = 100; We could have: static final int MY_VALUE = myFunction1(); private int myFunction1(){ int i = 23; i += 8 << 4; for(int j = 0; j < 3; j++){ i-= (j<<1); } return myFunction2(i); } private int myFunction2(int i){ return i + 19; } That was just an example of what we're trying to do. (Yes, I know, the compiler may optimize it and precalculate the constant). Disclaimer: I know this will not provide any aditional security at all, but it makes the code more obscure (or interesting) to reverse-engineer. The purpose of this is just to force the attacker to debug the program, and waste time on it. Keep in mind that we're doing it just for fun. A: Since you're trying to hide text, which will be visible in the simple dump of the program, you can use some kind of simple encryption to obfuscate your program and hide that text from prying eyes. Detailed instuctions: * *Visit ROT47.com and encode your text online. You can also use this web site for a more generic ROTn encoding. *Replace contents of your string constants with the encoded text. *Use the decoder in your code to transform the text back into its original form when you need it. ROT13 Wikipedia article contains some notes about implementation, and here is Javascript implementation of ROTn on StackOverflow. It is trivial to adapt it to whatever language you're using. Why use ROT47 which is notoriously weak encryption? In the end, your code will look something like this: decryptedData = decryptStr(MY_ENCRYPTED_CONSTANT) useDecrypted(decryptedData) No matter how strong your cypher, anybody equipped with a debugger can set a breakpoint on useDecrypted() and recover the plaintext. So, strength of the cypher does not matter. However, using something like Rot47 has two distinct advantages: * *You can encode your text online, no need to write a specialized program to encode your text. *Decryption is very easy to implement, so you don't waste your time on something that does not add any value to your customers. *Anybody reading your code (your coworker or yourself after 5 years) will know immediately this is not a real security, but security by obscurity. *Your text will still appear as gibberish to anyone just prying inside your compiled program, so mission accomplished. A: Run some game of life variant for a large number of iterations, and then make control flow decisions based on the final state vector. If your program is meant to actually do something useful, you could have your desired branches planned ahead of time and choose bits of the state vector to suit ("I want a true here, bit 17 is on, so make that the condition..") A: You could also use some part of compiled code as data, then modify it a little. This would be hard to do in a program executed by virtual machine, but is doable in languages like asm or c.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: C program through mysql pull I have this code to find the mean and standard deviation of some input values. But it's a static program. I want to pull this through a MySQL database and use it. Can you help me out? int main[] [ /* 2-dimensional array is used to store the height,lenght and the width attributes of the nose. indian array represents the indian data and the china array represents the chinese data */ /* Mean variable represents the mean values. The subscripts are used to identify indian and chinese attributes */ float indian[MAX][3],china[MAX] [3],mean_ih=0,mean_il=0,mean_iw=0,mean_ch=0,mean_cl=0,mean_cw=0; /* Following float variables store the standard deviation values */ float sd_ih=0,sd_il=0,sd_iw=0,sd_ch=0,sd_cl=0,sd_cw=0; int i,j; float test_h,test_l,test_w; /* POPULATING THE INDIAN DATABASE */ indian[i][j]=random[]/DIV; /POPULATING THE CHINESE DATABASE/ china[i][j]=random[]/DIS; Finding the MEAN of the Indian and the Chinese Data mean_ih+=indian[i][0]; mean_il+=indian[i][1]; mean_iw+=indian[i][2]; mean_ch+=china[i][0]; mean_cl+=china[i][1]; mean_cw+=china[i][2]; mean_ih=mean_ih/MAX; mean_il=mean_il/MAX; mean_iw=mean_iw/MAX; mean_ch=mean_ch/MAX; mean_cl=mean_cl/MAX; mean_cw=mean_cw/MAX; To find the Standard Deviation of the entries sd_ih+=pow[[indian[i][0]-mean_ih],2]; sd_il+=pow[[indian[i][1]-mean_il],2]; sd_iw+=pow[[indian[i][2]-mean_iw],2]; sd_ch+=pow[[china[i][0]-mean_ch],2]; sd_cl+=pow[[china[i][1]-mean_cl],2]; sd_cw+=pow[[china[i][2]-mean_cw],2]; sd_ih=sqrt[sd_ih/MAX]; sd_il=sqrt[sd_il/MAX]; sd_iw=sqrt[sd_iw/MAX]; sd_ch=sqrt[sd_ch/MAX]; sd_cl=sqrt[sd_cl/MAX]; sd_cw=sqrt[sd_cw/MAX]; Prompting the user to enter data to verify printf [" \n ============================================================\n"]; printf[" \n Enter the Height \n"]; scanf[" %f",&test_h]; printf [" \n ============================================================\n"]; printf[" \n Enter the length \n"]; scanf["%f",&test_l]; printf [" \n ============================================================\n"]; printf[" \n Enter the width \n "]; scanf ["%f",&test_w]; printf [" \n ============================================================\n"]; if [[abs[mean_ih-test_h] A: You will need to look at the mySQL C API documentation here for how to connect to a MySQL database through a C program. For a tutorial, you can also take a look at this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to replace word/words with url/urls using jQuery? I want to replace specific words (laptop, asus, acer) with links (test.com/l12, test.com/13, test.com/14) using jQuery. I found this function <script type="text/javascript"> (function($) { var thePage = $("body"); thePage.text(thePage.html().replace(/laptop/ig, '<a href="http://test.com/laptop">laptop</a>')); })(jQuery) </script> but the problem is that it replaces laptop word in existing urls (creating urls like test.com/test.com/laptop-review if the url was test.com/laptop-review) and all the laptop html (html ids, classes, urls etc) on the page is destroyed. Thank you A: You could do: $('body *').each(function(){ var txt = $(this).text(); txt = txt.replace('laptop', '<a href="http://test.com/laptop">laptop</a>'); $(this).html(txt); }); fiddle http://jsfiddle.net/LXw6P/ EDIT of course you could make this a function and reuse it: var updateTxt = function(stringToReplace){ var replaceText = '<a href="http://test.com/'+stringToReplace'+">'+stringToReplace+'</a>'; $('body *').each(function(){ var txt = $(this).text(); txt = txt.replace(stringToReplace, replaceText); $(this).html(txt); }); } use it: updateTxt('laptop'); A: You could try using the jQuery text replace plug-in - http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/ The plug-in should ignore HTML mark-up and only change 'text' values. Further details are given in this question - How do I do a case insensitive search for a word and convert it to a hyperlink using jquery?
{ "language": "en", "url": "https://stackoverflow.com/questions/7594405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Media Object in C# WebBrowser control with Custom DirectShow Filter in Windows 7 I have a Windows Media Object in a C# WebBrowser control. We've got what are basically .AVI files, and the files have been given a custom header. In order to play these we have a custom DirectShow filter. The videos can be played back inside Windows Media Player, and inside a Windows Media Player Object in IE9 on Windows 7, and in IE8 on Windows XP. The video playback also succeeds inside the C# embedded WebBrowser control in XP, but not on Windows 7. When trying to use the Windows Media Player Object in the C# WebBrowser control in Windows 7 we receive a message stating: "Windows Media Player cannot play the file. The player might not support the file type or might not support the codec that was used to compress the file." It's exactly the same code each time, so does anyone have any idea why the specific combination of Windows 7, the WebBrowser Control, and Custom DirectShow filters fails to playback the video, when everywhere else it functions correctly? A: You need to do more debugging to get an idea what is going on. First of all, you need to check out if playback at all picks up your DirectShow filter, what kind of methods are called, are there any errors involved, in what way this is different from other systems where playback takes place successfully. A: The problem was that our DirectShow Filter was only built as an x86 DLL. For some reason the WebBrowser control in C# defaults to using a 64 bit IE backend if available, and that version wouldn't work with the x86 DLL we built, because the WMP Object only looked into registry entries for 64-bit versions of Filters. By setting your build configuration in Visual Studio to target an "x86" CPU rather than "Any CPU" for the application that runs the WebBrowser control, you can ensure that even on a 64-bit version of Windows that the WebBrowser control uses the 32-bit back end. Seems quite a few people had the same problem with Flash before a 64-bit build was available for it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to send to a jsp page from a rest call I've written a rest interface (with jersey), a browser will be calling this rest interface. I would like show some html/jsp to the user as a response to this rest call... Is this possible? How do I do it? A: Yes, that is possible. This post as well as this one gives a hint how to use Viewables to return JSPs as a response.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: use validateRequired through composite component I'm trying to forward "f:validateRequired" validator through a composite component without using required attribute. How to get its value inside of my component ? <aa:myComponent id="specificNotice" value="#{edit.specificNotice}"> <f:validateRequired for="specificNotice" disabled="#{empty param['form:save']}" /> </aa:myComponent> Thanks. A: The for attribute should refer the id of the input component inside the composite component implementation. The input component in turn should be declared as <cc:editableValueHolder> inside the composite component interface. So, <my:input value="#{bean.input}"> <f:validateRequired for="input" /> </my:input> with <cc:interface> <cc:editableValueHolder name="input" /> </cc:interface> <cc:implementation> <h:inputText id="input" value="#{cc.attrs.value}" /> </cc:implementation> should do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ajax push system In my own system, I have a PHP page which displays all the goods I have sold through my online webshops, from the latest transaction to the first. I would like this page to automatically update, whenever people buy something from me. I could make AJAX call every 5 seconds to check the orders in my databases, but that seems 1980? or is it that way people do it? How can I go about pushing a notification to my php page whenever my php newOrder() function (lets call it that) is called? A: You could simulate a push effect by doing the following (pseudo code!) // This would go on for 60-90 seconds, unless there is new data for($i = 1; $i <= 60; $i++) { // Check in the database what the last timestamp is // Compare this to the timestamp that has been posted by the AJAX-call // If there is something new, show the data and then exit // If not, sleep for 1-3 seconds } Your javascript: function pollForNewProducts() { // Check if there is a timestamp // Make an AJAX-request to the script that has the first code in it // If there is a response (JSON?) than evaluate that // If not, then run the script again pollForNewProducts(); } It is a simple yet effective way to let the server do all the hard work, instead of timeouts on the client side which will cause the browser to eat memory. More about this on: Simple “Long Polling” example code? Client notification, should I use an AJAX Push or Poll? PHP or Javascript poll code ExtJS 3.0: Ext.Direct with PHP: Polling:ok and Pushing ? Comet Programming: Using Ajax to Simulate Server Push A: You can achieve push within PHP but it won't be the most efficient solution because to achieve push you need to maintain long running connections between your client and your server (HTTP or WebSocket connections). See: * *Long Polling/HTTP Streaming General Questions *phpwebsocket *php-websocket on github *Ratchet *how to implement comet in PHP - frequently linked to guide General best practice when building a realtime infrastructure has been to decouple the push solution from your web application (Note: node.js and socket.io has changed this a bit, but personally I still think it should be decoupled). But, assuming that the latter is still the best solution you would need to write/host/install this push solution. Decoupling also means that the technology doesn't have to be PHP but you can access/use it from PHP. Maybe a bit of overkill? And especially if you don't have too many users on your site? For simplicity I would recommend looking at using a 3rd party hosted service. I work for one such company called Pusher. Using a service such as ours lets you remove the need to install and maintain the realtime part of your application. It also makes it really easy to add the push functionality you are looking for. All you need to do is add a few lines of PHP code to your existing app to trigger the push notifications and add a few lines of JavaScript to your front-end. Resources: * *Most commonly use PHP library for this: https://github.com/pusher/pusher-php-server *Quickstart guide If you'd like to investigate the alternatives or some of the technologies I've mentioned above I'm maintaining a list of realtime technologies which you might also be interested in. A: Apart from the excellent suggestion about nodejs ..if you want to still use php to achieve this, you want to look for the COMET method, not ajax. Howto with php here : http://www.zeitoun.net/articles/comet%5Fand%5Fphp/start
{ "language": "en", "url": "https://stackoverflow.com/questions/7594425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: parse youtube input links and get youtube ID using jquery ? I know lots of people asked this sort of question alot but unfortunetly I couldn't sort out my problem . I have this code in my textarea editor to input a youtube link : {name:'youtube', key:'Y', replaceWith:'[youtube][![Youtube video Url]!][/youtube]'}, It will ask for youtube video url in a popup window and after that it will put the url between [youtube] and [/youtube]. I would like to have a youtube parser added to it then if member puts youtube url , it will parse the url and get the youtube video ID and input it in the text area like this : [youtube] ID [/youtube] Thanks in advance for your help . A: function getVideoId(url){ if(url.indexOf('?') === -1) return null; var query = decodeURI(url).split('?')[1]; var params = query.split('&'); for(var i=0,l = params.length;i<l;i++) if(params[i].indexOf('v=') === 0) return params[i].replace('v=',''); return null; } var url = "http://www.youtube.com/watch?v=yV3i6OoiR4w&feature=BFa&list=PL4A312BE02BA06BB7&lf=bf_play"; alert(getVideoId(url)); update : another solution is to use regex : var url = "http://www.youtube.com/watch?v=yV3i6OoiR4w&feature=BFa&list=PL4A312BE02BA06BB7&lf=bf_play"; var videoUrl = url.replace(/^.*?(\?|&)(v=([^&]+)).*$/i,'$3'); A: There is a new shortened URL format for youtube URL's... here's an updated script to accomodate both types. function getVideoId(url){ if(url.indexOf('?') != -1 ) { var query = decodeURI(url).split('?')[1]; var params = query.split('&'); for(var i=0,l = params.length;i<l;i++) if(params[i].indexOf('v=') === 0) return params[i].replace('v=',''); } else if (url.indexOf('youtu.be') != -1) { return decodeURI(url).split('youtu.be/')[1]; } return null; } var urlLONG = "http://www.youtube.com/watch?v=UF8uR6Z6KLc&feature=feedlik"; var urlSHORT = "http://youtu.be/UF8uR6Z6KLc"; alert(getVideoId(urlLONG)); alert(getVideoId(urlSHORT)); P.S. I am a flash developer and have only tested this in AS3, but simple stuff like this is identical in both languages. if you want to use it in AS3 just swap the alert() with a trace(). Happy coding! A: function getYoutubeId(str){ if(str.indexOf('youtube.com/') != -1 || str.indexOf('youtu.be/') != -1){ var idStr = str.match(/([\&|\?]v\=|youtu\.be\/)([^\&\/\?]*)/); if(typeof(idStr[2]) != 'undefined'){ return idStr[2]; }; }; return null; };
{ "language": "en", "url": "https://stackoverflow.com/questions/7594427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: I want to display buttons at the bottom of the screen and the buttons are inside linearLayout4,can someone pls tell me in this, am frustated now Problem with last linear layout containing buttons,I want to display my last linear layout i.e. of id-linearlayout4 at the bottom of the screen,so that my buttons should come at the bottom... <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/pic5"> <LinearLayout android:orientation="vertical" android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="60dip"></LinearLayout> <LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout5" android:layout_height="wrap_content"> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/textView2" android:layout_marginLeft="19dp" android:id="@+id/quesname" android:textSize="20dip" android:textColor="#000000"></TextView> </LinearLayout> <LinearLayout android:id="@+id/linearLayout3" android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="match_parent"> <ScrollView android:id="@+id/ScrollView01" android:layout_width="fill_parent" android:layout_height="wrap_content"> <LinearLayout android:id="@+id/linearLayout2" android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="match_parent"> <LinearLayout android:id="@+id/optionslayout" android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="match_parent"> </LinearLayout> </LinearLayout> </ScrollView> <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout4" android:layout_width="match_parent" android:gravity="bottom"> <Button android:id="@+id/prev" android:layout_width="100dip" android:text="Previous" android:layout_height="wrap_content"></Button> <Button android:id="@+id/next" android:layout_marginLeft="120dip" android:layout_width="100dip" android:text="Next" android:layout_height="wrap_content"> </Button> </LinearLayout> </LinearLayout> </LinearLayout> A: you can insert a <View android:layout_height="0dp" android:layout_width="0dp" android:layout_weight="1"/> right before your buttons. Or use a relative layout with alignParentBottom="true" A: You need a RelativeLayout instead of a LinearLayout as parent; then simply drag the buttons in the layout-GUI to the bottom and they should stick there. When i am at home i am able to post "real" example code. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout …> <!-- your posted code --> Dragging the button's layout parent to the bottom will produce: alignParentBottom="true"
{ "language": "en", "url": "https://stackoverflow.com/questions/7594428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android service not found (contact change detection) I am trying to get my Android app to respond to changes in the local address book and sync with it on a need basis. I understand that in order to do that, I need to create a service to run in the background. I did. But it isn't working... when my app runs and I try to initiate the service, it fails with : [exec] [DEBUG] I/ActivityManager( 60): Starting activity: Intent { cmp=ti.test/my.Activity (has extras) } [exec] [DEBUG] E/aas ( 1812): (main) [490639,495460] people uri:content://contacts/people [exec] [DEBUG] W/ActivityManager( 60): Unable to start service Intent { cmp=ti.test/.MyService }: not found this is how I try to run it: startService(new Intent(activity, MyService.class)); this is part of my manifest.xml fie: <android xmlns:android="http://schemas.android.com/apk/res/android"> <manifest android:versionCode="1" android:versionName="1"> <uses-sdk android:minSdkVersion="4"/> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true"/> <application> <service android:name="ti.test.MyService"/> </application> </manifest> </android> this is the service class: package ti.test; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import android.database.ContentObserver; import android.provider.Contacts.People; public class MyService extends Service { private static final String TAG = "MyService"; private class MyContentObserver extends ContentObserver { public MyContentObserver() { super(null); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); Log.e ("DatabaseTable" , "****************************** contact database change detected *************************************"); } @Override public boolean deliverSelfNotifications() { return true; } } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { Log.d("MyService", "starting........"); MyContentObserver contentObserver = new MyContentObserver(); getContentResolver().registerContentObserver (People.CONTENT_URI, true, contentObserver); } @Override public void onDestroy() { Log.d("MyService", "stopping........"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("LocalService", "Received start id " + startId + ": " + intent); // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } @Override public void onStart(Intent intent, int startid) { Log.d("MyService", "onStart........"); } } thanks! A: you should not create class in service. you should define a contectResolver class and register it in an activity or where you want to use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bind to parent DataContext within DataTemplate I'm trying to bind MenuItem's Command to command contained in UserControl.DataContext. I've found couple of similar question, but solution according to them is failing to me: <UserControl ...> <UserControl.Resources> <DataTemplate x:Key="TileItemStye"> <Grid Width="100" Height="100"> <Grid.ContextMenu> <ContextMenu> <MenuItem Header="Remove" Command="{Binding DataContext.RemoveItem, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"> </MenuItem> </ContextMenu> </Grid.ContextMenu> </Grid> </DataTemplate> </UserControl.Resources> <Grid> <ListView ItemsSource="{Binding Path=Files}" ItemTemplate="{DynamicResource TileItemStye}" > <ListView.ItemsPanel> <ItemsPanelTemplate> <WrapPanel /> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView> </Grid> UserControl's DataContext is ViewModel with ICommand RemoveItem and ObservableCollection<FileViewModel> Files. A: Menus are not drawn in the same Visual Tree as your Controls, which is why the RelativeSource binding does not work You need to bind to the PlacementTarget of your ContextMenu to access the main Visual Tree <MenuItem Header="Remove" Command="{Binding PlacementTarget.DataContext.RemoveItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}" /> A: If you are on .NET 4 there indeed is a more elegant solution: <UserControl Name="uc" ...> <!-- ... --> <MenuItem Header="Remove" Command="{Binding DataContext.RemoveItem, Source={x:Reference uc}}"/> (This requires that the template stays in the Resources, otherwise there will be a cyclical dependency error)
{ "language": "en", "url": "https://stackoverflow.com/questions/7594438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Session getting cleared with Authorize attribute? I am trying to customize my Authorize attribute so that it redirects the user to appropriate page if he is not authorized. This is my code till now: public class CustomAuthorizationAttribute : AuthorizeAttribute { public string ErrorMessage { get; set; } public string WebConfigKey { get; set; } private const string UnauthorizedAccessMessage = "UnauthorizedAccessMessage"; protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { HttpContext.Current.Session["foo"] = "bar"; base.HandleUnauthorizedRequest(filterContext); if (string.IsNullOrEmpty(WebConfigKey)) throw new ArgumentNullException("WebConfigKey parameter is missing. WebConfigKey should give the actual page/url"); string configValue = ConfigurationManager.AppSettings[WebConfigKey]; if (string.IsNullOrEmpty(configValue)) throw new Exception(WebConfigKey + "'s value is null or empty"); if (!configValue.StartsWith("http")) HttpContext.Current.Response.Redirect(WebUIUtils.GetSiteUrl() + configValue); else HttpContext.Current.Response.Redirect(configValue); filterContext.Controller.TempData[UnauthorizedAccessMessage] = ErrorMessage; HttpContext.Current.Session[UnauthorizedAccessMessage] = ErrorMessage; } } Problem is whatever I store in Session or TempData in this method gets lost when the user arrives in some action method in controller after redirect is done from this method. I checked Session.Keys/TempData.Keys etc. But all values are lost. Probably something is happening in base.HandleUnauthorizedRequest(filterContext);. But I guess that calling to base is important. Can anybody tell me the exact reason of this behavior and how do I prevent it from happening? A: Form authorization and Session are distinct concepts for IIS. You can be authorized but your session can be not valid (for example try to restart the application pool). Try with this custom attribute: public class CustomAuthorizationAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); if (filterContext.Result == null) { if (filterContext.HttpContext.Session != null ) { //add checks for your configuration //add session data // if you have a url you can use RedirectResult // in this example I use RedirectToRouteResult RouteValueDictionary rd = new RouteValueDictionary(); rd.Add("controller", "Account"); rd.Add("action", "LogOn"); filterContext.Result = new RedirectToRouteResult("Default", rd); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7594439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHPExcel modify existing .xlsx file with multiple worksheet require_once '../Classes/PHPExcel/IOFactory.php'; /** PHPExcel */require_once '../Classes/PHPExcel.php'; $excel2 = PHPExcel_IOFactory::createReader('Excel2007'); $excel2 = $excel2->load('dentkey.xlsx'); $excel2->setLoadAllSheets(); $excel2->setActiveSheetIndex(0); $excel2->getActiveSheet()->setCellValue('C6', '4') ->setCellValue('C7', '5') ->setCellValue('C8', '6') ->setCellValue('C9', '7'); $excel2->setActiveSheetIndex(1); $excel2->getActiveSheet()->setCellValue('A7', '4') ->setCellValue('C7', '5'); $objWriter = PHPExcel_IOFactory::createWriter($excel2, 'Excel2007'); $objWriter->save('dentkey1.xlsx'); here, i am able to load (.xlsx) file and i also able to modify (dentkey.xlsx). But After generating new .xlsx file (dentkey1.xlsx)..all worksheets data which was in (dentkey.xlsx) is not loading and also i cannot set value for 2nd worksheet. you can fine $excel2->setActiveSheetIndex(1); $excel2->getActiveSheet()->setCellValue('A7', '4') ->setCellValue('C7', '5'); is not setting value 5 to 'C7' column of generated (dentkey.xlsx) file please help me... thanks a lot in advance A: This code seems working, Tested in local Environment WampServer Version 2.1 Download latest version of PHPExcel from here PHPExcel 1.7.6 Working Code. <?php error_reporting(E_ALL); date_default_timezone_set('Europe/London'); require_once '../Classes/PHPExcel/IOFactory.php'; require_once '../Classes/PHPExcel.php'; $excel2 = PHPExcel_IOFactory::createReader('Excel2007'); $excel2 = $excel2->load('nTest.xlsx'); // Empty Sheet $excel2->setActiveSheetIndex(0); $excel2->getActiveSheet()->setCellValue('C6', '4') ->setCellValue('C7', '5') ->setCellValue('C8', '6') ->setCellValue('C9', '7'); $excel2->setActiveSheetIndex(1); $excel2->getActiveSheet()->setCellValue('A7', '4') ->setCellValue('C7', '5'); $objWriter = PHPExcel_IOFactory::createWriter($excel2, 'Excel2007'); $objWriter->save('Nimit New.xlsx'); ?> Remove this line from your code: $excel2->setLoadAllSheets();. Hope this will help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Alfresco web service authentication I'm trying to connect to a remote Alfresco webservice using this java instrunction: WebServiceFactory.setEndpointAddress(configFile.getProperty("WebServiceFactory")); AuthenticationServiceSoapBindingStub authenticationService = (AuthenticationServiceSoapBindingStub) new AuthenticationServiceLocator().getAuthenticationService(); The authentication fails because the authority properties of AuthenticationServiceSoapBindingStub it's not remote URL but it's localhost:8080. How can I fix that? the stack trace is: AxisFault faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.generalException faultSubcode: faultString: faultActor: faultNode: faultDetail: {http://www.alfresco.org/ws/service/authentication/1.0}AuthenticationFault:<ns1:errorCode>100</ns1:errorCode><ns1:message>08290021 Failed to authenticate</ns1:message> {http://xml.apache.org/axis/}exceptionName:org.alfresco.repo.webservice.authentication.AuthenticationFault {http://xml.apache.org/axis/}stackTrace: at org.alfresco.repo.webservice.authentication.AuthenticationWebService.startSession(AuthenticationWebService.java:90) at sun.reflect.GeneratedMethodAccessor1310.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:397) at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:186) at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:323) at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32) at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118) at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83) at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:454) at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281) at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.alfresco.web.app.servlet.GlobalLocalizationFilter.doFilter(GlobalLocalizationFilter.java:58) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Thread.java:680) {http://xml.apache.org/axis/}hostname:heisenberg.local at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:308) at org.apache.axis.encoding.ser.BeanDeserializer.<init>(BeanDeserializer.java:104) at org.apache.axis.encoding.ser.BeanDeserializer.<init>(BeanDeserializer.java:90) at org.alfresco.webservice.authentication.AuthenticationFault.getDeserializer(AuthenticationFault.java:146) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.axis.encoding.ser.BaseDeserializerFactory.getSpecialized(BaseDeserializerFactory.java:154) at org.apache.axis.encoding.ser.BaseDeserializerFactory.getDeserializerAs(BaseDeserializerFactory.java:84) at org.apache.axis.encoding.DeserializationContext.getDeserializer(DeserializationContext.java:464) at org.apache.axis.encoding.DeserializationContext.getDeserializerForType(DeserializationContext.java:547) at org.apache.axis.message.SOAPFaultDetailsBuilder.onStartChild(SOAPFaultDetailsBuilder.java:157) at org.apache.axis.encoding.DeserializationContext.startElement(DeserializationContext.java:1035) at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source) at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source) at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source) at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source) at org.apache.xerces.jaxp.SAXParserImpl.parse(Unknown Source) at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227) at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696) at org.apache.axis.Message.getSOAPEnvelope(Message.java:435) at org.apache.axis.handlers.soap.MustUnderstandChecker.invoke(MustUnderstandChecker.java:62) at org.apache.axis.client.AxisClient.invoke(AxisClient.java:206) at org.apache.axis.client.Call.invokeEngine(Call.java:2784) at org.apache.axis.client.Call.invoke(Call.java:2767) at org.apache.axis.client.Call.invoke(Call.java:2443) at org.apache.axis.client.Call.invoke(Call.java:2366) at org.apache.axis.client.Call.invoke(Call.java:1812) at org.alfresco.webservice.authentication.AuthenticationServiceSoapBindingStub.startSession(AuthenticationServiceSoapBindingStub.java:187) at com.kipcast.health.Caller.main(Caller.java:60) thanks, Andrea A: just put the webserviceclient.properties in the alfresco folder. Check the SDK for webservice client samples. Alfresco reads the following propertie: repository.location=http://localhost:8080/alfresco/api Hence this is the remote Alfresco location. A: You have to write like following - For Login - WebServiceFactory.setEndpointAddress("http://" + remoteHostIp + ":" + port + "/alfresco/api"); AuthenticationUtils.startSession(strUserName, strPassword); For Logout - AuthenticationUtils.endSession();
{ "language": "en", "url": "https://stackoverflow.com/questions/7594448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't my likebox doesn't show any faces? I have a likebox generated with this code: <fb:like-box href="http://www.facebook.com/pages/Browser-Games/260061187354628" width="250" show_faces="true" stream="false" header="true"></fb:like-box> The SDK is loaded like this: FB.init({appId: '111929132246901', status: true, cookie: true, xfbml: true}); (website is ibrowsergame.it if you want to see the full code) * *When I'm logged in with the page's admin account, I can see the facepile being correctly filled with photos. *If I login with another account, there are just 2 faces. Is this just a problem of mine, or is everyone experiencing this due to privacy settings? It's strange that there just 2 people willing to display their profile photo (out of 180). Isn't it? The result is pretty awful, because I have around 50px of unusued white space, if no faces are displayed. A: First, are you using facepile (as stated in your text) or like-box (as stated in the code example)? If you're using the facepile plugin, this behavior is as designed . The plugin will only show the faces of friends who've liked the page/ or app. If none of your friends like it, then it will be completely blank.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DB client shows only date without time component..how can I convert? I am saving date with time into DB and using SQL Developer which by default shows just date. I know its matter of client config but I have seen query in Oracle that returned time component of date when one was present. Something like convert (HH:MM:SS). I am just interested in this one. A: To show the time element of all dates as a one-off exercise use this DDL statement. ALTER SESSION set nls_date_format = 'DD-MON-YYYY HH24:MI:SS' / or whatever date mask takes your fancy. To set this permanently in SQL Developer, set parameters in Tools -> Preferences -> Database -> NLS Parameters A: I you understand that it's a matter of client config and want to see time portion of date for some special purpose you can query it converting to char like this: select to_char(sysdate, 'yyyy.mm.dd hh24:mi:ss') from dual; More info on date format can be found here or in official docs
{ "language": "en", "url": "https://stackoverflow.com/questions/7594460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Looking for .net logger that would save output as html page Is there any .net logger that would log events and write logs to html page or maybe any logger that stores logs to database or to file and then generates html page from it? A: I am not aware of any complete solution as you ask for; log parsing can be very specific because in logging frameworks like Log4Net or NLog you can define what you log and how your logs look like. I would use Log4Net and store to database then make your ASP.NET application which loads most recent entries from that database into a gridView, just to start, then if you imagine to add paging, sorting and filtering to that asp.net application you have another whole project to take care of :) there are also Log4Net appenders which send out HTML emails, see here for an example: http://modelus.com/Products/Log4NetExtensions.aspx you can have a look at the sources and imagine to write your own HTML publisher appender if you really want to go this way...
{ "language": "en", "url": "https://stackoverflow.com/questions/7594461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: to add a last row in listview i have a custom listview i want to add one lat row to it which will calculate total of all the list when i scroll the last row gets added again and again if(position==searchResult.size() && searchResult.size()!=1) { holder.checkImg.setVisibility(ImageView.GONE); holder.fvtImg.setVisibility(ImageView.GONE); holder.type.setVisibility(TextView.GONE); holder.name.setVisibility(TextView.GONE); holder.offer_price.setVisibility(TextView.GONE); holder.real_price.setVisibility(TextView.GONE); holder.total.setVisibility(TextView.VISIBLE); holder.total_price.setVisibility(TextView.VISIBLE); //DecimalFormat df = new DecimalFormat("0.00"); //holder.txt_distance.setText(df.format(mData.get(position).get("distance")).toString()+"..."); DecimalFormat twoDForm = new DecimalFormat("0.00"); String totalPrice = (twoDForm.format(mTotalPrice)+"").replace('.',','); holder.total.setText("Total"); holder.total_price.setText("Kr. "+totalPrice); } else { holder.total.setVisibility(TextView.GONE); holder.total_price.setVisibility(TextView.GONE); if(isEdit){ /*LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.leftMargin=30; holder.fvtImg.setLayoutParams(lp);*/ /* TranslateAnimation anim = new TranslateAnimation(0,35,0,0); holder.fvtImg.setAnimation(anim); anim.setFillAfter(true);*/ holder.fvtImg.setVisibility(ImageView.GONE); holder.name.setPadding(10,0, 0, 0); holder.type.setPadding(10,0, 0, 0); holder.checkImg.setVisibility(ImageView.VISIBLE); Layout file : <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/list_background" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/price_list_background" /> <CheckBox android:id="@+id/checkBox" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_centerVertical="true" android:layout_alignParentLeft="true" android:visibility="gone"> </CheckBox> <ImageView android:id="@+id/img_pol" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/pol_icon_tag" android:layout_centerVertical="true" android:layout_marginLeft="5dp" /> <TextView android:id="@+id/txt_name" android:layout_width="wrap_content" android:layout_height="15dp" android:textSize="16dp" android:textColor="#000000" android:layout_marginTop="5dp" android:layout_marginLeft="35dp" /> <TextView android:id="@+id/txt_type" android:layout_width="200dp" android:layout_height="13dp" android:textSize="12dp" android:textColor="#464647" android:layout_marginTop="35dp" android:layout_marginLeft="35dp" /> <TextView android:id="@+id/txt_real_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12dp" android:textColor="#464647" android:layout_marginTop="35dp" android:layout_marginLeft="90dp" /> <TextView android:id="@+id/txt_offer_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16dp" android:textColor="#464647" android:layout_marginTop="31dp" android:layout_marginLeft="190dp" /> <TextView android:id="@+id/txt_total" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15dp" android:textColor="#464647" android:layout_centerVertical="true" android:layout_marginLeft="100dp" android:text="Total" android:visibility="gone" /> <TextView android:id="@+id/txt_total_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16dp" android:textColor="#464647" android:layout_centerVertical="true" android:layout_marginLeft="230dp" android:text="kr. 222.22" android:visibility="gone" /> </RelativeLayout> A: Have you considered using a footer instead of placing the last item inside the ListView? What you do is, before you set the adapter of the ListView, you inflate a footer layout (or perhaps just a TextView, if that's all you need). Store a reference to it, and then add it to the ListView: TextView myFooter = new TextView( context ); myListView.addFooterView( myFooter ); Then when you add items to the list or when the calculation needs to occur, you just calculate and set the text of myFooter. myFooter.setText( myCalculatedValue ); Setting the text of the footer must ofcourse happen on the UI-thread so if you use a background thread or a AsyncTask to add to your listview, be sure you update stuff the right place.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Group-wise Maximum of a Certain Column I've got the table: SELECT * FROM shop; +---------+--------+------ | article | dealer | price +---------+--------+------ | 0001 | A | 3.45 | 0001 | B | 3.99 | 0002 | A | 10.99 | 0003 | B | 1.45 | 0003 | C | 1.69 | 0003 | D | 1.25 | 0004 | D | 19.95 +---------+--------+------ 7 rows in set (0.20 sec) And I want to get - for each article - the dealer or dealers with the most expensive price. Could anyone tell me why this doesn’t work? SELECT article, dealer, MAX(price) FROM shop GROUP BY(article); For this query, I get the following result-set; +---------+--------+------------+ | article | dealer | MAX(price) | +---------+--------+------------+ | 0001 | A | 3.99 | | 0002 | A | 10.99 | | 0003 | B | 1.69 | | 0004 | D | 19.95 | +---------+--------+------------+ 4 rows in set (0.03 sec) Although the max prices are correct, I got the wrong dealers for some articles. A: According to your question it seems that you have already read the article about group-wise maximum of a certain column, however you just don't understand why the method you mentioned does not work as you expect. Let's imagine a query like this: SELECT article, dealer, MAX(price), MIN(price) FROM shop GROUP BY article What value of a dealer do you expect? I think this answers your question. A: Standard SQL would reject your query because you can not SELECT non-aggregate fields that are not part of the GROUP BY clause in an aggregate query. You're using a MySQL extension of SQL described here: MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. This means that the preceding query is legal in MySQL. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. A: This does not work, because if you use group by, you can not use the individual fields of the original rows (except for the field you are grouping on). The correct way to do this, is to make an inner/nested query to select the dealer, suck as this (I haven't tested it, so it might be slightly off): SELECT article, MAX(price) as maxPrice, (SELECT dealer FROM shop AS s2 WHERE s2.article = s1.article AND s2.price = maxPrice) AS expensiveDealer FROM shop AS s1 GROUP BY(article); A: Here you go: SELECT article, dealer, price FROM (SELECT article, dealer, price FROM shop ORDER BY price DESC) AS h GROUP BY article This solution doesn't even require a MAX() function. :) Note: This solution doesn't work with ONLY_FULL_GROUP_BY active and only works in MySQL. This solution is to a certain extent unsupported due to lack of documentation confirming this behavior. It works well for me and has always worked well for me however. This method still works on the latest MySQL on sqlfiddle. A: I just tumbled over this question and wonder why noone comes to idea to join the table with itself as described in certain tutorials (see links below). So I'd suggest the following solution: Select A.* From shop As A Left Join shop As B On A.article = B.Article AND A.price < B.price Where B.price Is Null; The magic is obvious: join the table with itself and link any records in it to any other record having a higher price. From those, grab only those having NO linked record with a higher price (for these records are the ones with the highest price). As far as I have experienced, this solution is even the best regarding its performance. This part of the MySQL documentation and/or this very interesting article by Jan Kneschke might be helpful — enjoy!
{ "language": "en", "url": "https://stackoverflow.com/questions/7594465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Does a decision on what services to use and in which order consitute logic in an MVC controller method? I am near the end of a new ASP.NET MVC application I have been developing, and I have realised that I am not 100% on what should be goning on in my controller methods. Is it better for an action method to decide which services/methods are called and in what order like so: AccountService _accountService; BillingService _billingService; InvoiceService _invoiceService; ... public ActionResult UpgradeAccountPackage(PackageType packageType, int accountId) { _accountService.UpgradeAccountPackage(packageType, accountId); _billingService.BillForAccountUpgrade(packageType, accountId); _invoiceService.CreateAccountUpgradeInvoice(packageType, accountId); } Or is it better to stick to a single method call to one service and allow this method to call the other services/support method it needs? public ActionResult UpgradeAccountPackage(PackageType packageType, int accountId) { // account service upgrades account then calls the BillingService and InvoicService // methods called above within this method _accountService.UpgradeAccountPackage(packageType, accountId); } I have tended to go for the second example here, as it seemed originally like the first method would constitute logic in some way, and means the acion method would have to intrinsically know about how the account upgrade process works within my application, which seems like a bad thing. However, now my application is almost finished it has a large service layer and this approach has led to almost every service having a strong dependency on numerous other services, and there is no centralised place which decides the flow of business transactions such as the one mentioned above, you have to dig around a bit in service methods to discover the processes. I am considering refactoring to more closesly resemble the second method above, or introducing a new layer in between the controller and service layer which controls the flow of processes. Do people tend to use the first or second method? What are peoples opinions? A: I prefer the second method - much easier to test (using mocks), and the logic is there for reuse. You end up with Facades to your actual business logic, but that's not bad thing. I don't understand why your service layer is full of concrete dependencies though... The thing to remember is that you want classes to rely on interfaces, not implementation. (and then string it all together with a Dependancy Injection tool) In C#, we can have one class implement many interfaces. So your service implementations can implement many interface, and yet the caller need only know about the part they need. For example, you might have an AccountTransactionService that imlpements IDepositor and IWithdrawer. If you implement double-entry accounting, then that could depend on IDepositor and IWithdrawer, which, in actual fact, just uses the same instance of AccountTransactionService, but it doesn't have to, and the implementation details could be changed afterwards. In general, the less one class knows about the other classes in the system, the better. A: I more closely use the first method. Let the controller control what happens. Let the services decide how that happens. If you add a second layer to control the flow of processes would that leave your ActionMethods only making the one call? If so, it seems unnecessary at that point. A: You could have a service layer which depends on multiple repositories (not other services) and which defines the business operations: public class MyService: IMyService { private readonly IAccountRepository _accountRepository; private readonly IInvoiceRepository _invoiceRepository; private readonly IBillingRepository _billingRepository; public MyService(IAccountRepository accountRepository, IInvoiceRepository invoiceRepository, IBillingRepository billingRepository) { _accountRepository = accountRepository; _invoiceRepository = invoiceRepository; _billingRepository = billingRepository; } public void UpgradeAccountPackage(PackageType packageType, int accountId) { ... } } and then have your controller take IMyService as dependency: public class HomeController: Controller { private readonly IMyService _service; public HomeController(IMyService service) { _service = service; } public ActionResult UpgradeAccountPackage(PackageType packageType, int accountId) { _service.UpgradeAccountPackage(packageType, accountId); ... } } I define simple CRUD operations with the entities on the repositories and the service aggregates those multiple operations into one business transaction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Lion Resume when Closing Docs without Quitting App I'm dipping my feet into Cocoa for the first time. Here's a simple question. OS X Lion supports Resuming of window state when an app is terminated and relaunched. Okay, good and fine. But for document-based apps, can the same Resume feature also manage saving of window state when a document is closed and reopened later but without any quitting of the app? (In other words, can it manage each file's state persistently regardless of whether the app quits or not? Or do I have to manage it myself by saving the information in the documents' files?) For instance, iWork '09 apps do do this sort of thing: if you close a saved document and reopen it, it will restore the window size, location, and scroller position. I don't know if it does this using Lion's Resume per se. But, in contrast, OS X Lion's TextEdit restores windows when it is quit and restarted, but it does not remember window states when you close a document and reopen it. This makes me suspicious that using Resume without quitting might not be possible automatically (since maybe Pages keeps window states in its proprietary file format, but TextEdit doesn't since it uses plain text, RTF, HTML, etc. files). I don't have access to the WWDC 2011 videos yet, and neither the OS X release notes, the OS X Application Programming Guide, nor the NSWindowRestoration API docs talk about this specifically. So the question again: automatically remembering the state of a document window after closing and reopening it without quitting the app (like iWork does)...does Lion's Restore support this? Thanks a lot! A: But for document-based apps, can the same Resume feature also manage saving of window state when a document is closed and reopened later but without any quitting of the app? (In other words, can it manage each file's state persistently regardless of whether the app quits or not? Not unassisted, no. Or do I have to manage it myself by saving the information in the documents' files?) Or somewhere else, yes. My untested suggestion is to try using the window-restoration protocol yourself. When closing, send yourself encodeRestorableStateWithCoder:, then stash that data in your document (or wherever you want). When opening a document, if it has restorable state information, pass it to restoreStateWithCoder:.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Webdriver : how to set IE in virtual environment? I am setting up the Virtual Environment for my grid-based Webdriver tests. And sure enough, there are problems with IE driver. First of all, Internet Options → Security should have the same Protected Mode setting. It's an easy fix if you have an access to the browser, but in my case, I won't have physical access to the browser. In Webdriver's FAQ it says you can do the following: DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer(); capabilities.set(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true); WebDriver driver = new InternetExplorerDriver(capabilities); Ruby bindings have no reference to setting up this capability in IE. It there a way to code it out in Ruby? The other thing is what can be done against "unsecure connection" pop-ups? Again, they are easy to deal with manually after the first run, but what about running "clean" IE instance each time? There are probably more concerns, I'd like to hear your opinion. Thank you!
{ "language": "en", "url": "https://stackoverflow.com/questions/7594471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replacement for Prototype.js Class system We have a set of classes created that depend on Prototype's Class implementation (and some Object.extend). The problem is prototype is creating trouble when integrating with the rest of our applications (even with "noconflict" adapters and the such). Does anybody know of a compatible Class implementation that does not mess with the global scope? Or has anybody been able to "extract" Prototype's to use it alone? A: I wrote one a couple of years back (I should go revisit it, and give it a proper name) because I didn't like Prototype's handling of calling methods on the "superclass", which involves creating a function every time an overridden method is called (yes, really). It's very similar to Prototype's except for how you make supercalls; you can readily drop it in and search for super in your code and change it up. My implementation also makes it a bit easier to use named functions rather than anonymous ones, which is useful for many reasons, not least because it helps your tools help you. It also makes private "class" methods trivial. Details below. But you don't have to use mine. There are other options that will require slightly more work to migrate your code to, but probably not a lot more: * *John Resig's simple inheritance *Dean Edwards' mechanism My issue with both of them is that they use function decompilation (so does Prototype's Class stuff), and function decompilation (e.g., calling toString on a function) has never been standardized and does not work on some mobile browsers. Resig's mechanism continues to work if function decompilation doesn't work, but it adds overhead to every method in that case (rather than only ones that make supercalls). My mechanism doesn't use function decompilation at all, adds no overhead to method calls, and even makes supercalls highly-efficient. If you use my mechanism and your Prototype code looks like this: var SuperThingy = Class.create({ foo: function(arg) { console.log("SuperThingy: " + arg); this._pseudoPrivate(); }, _pseudoPrivate: function() { console.log("I'm not really private."); } }); var Thingy = Class.create(SuperThingy, { foo: function(super, arg) { console.log("Thingy: " + arg); super(arg); } }); You can make minimal changes: var SuperThingy = Helper.makeClass({ foo: function(arg) { console.log("SuperThingy: " + arg); this._pseudoPrivate(); }, _pseudoPrivate: function() { console.log("I'm not really private."); } }); var Thingy = Helper.makeClass(SuperThingy, { foo: function(arg) { console.log("Thingy: " + arg); this.callSuper(arguments, arg); } }); ...or you can make slightly larger changes and get the benefit of a speed increase (callSuper uses arguments.callee, which is slow), properly-named functions (for debugging and such), and truly private functions: var SuperThingy = Helper.makeClass(function() { function SuperThingy_foo(arg) { console.log("SuperThingy: " + arg); trulyPrivate.call(this); } function trulyPrivate() { console.log("I'm truly private."); } return {foo: SuperThingy_foo}; }); var Thingy = Helper.makeClass(SuperThingy, function() { function Thingy_foo(arg) { console.log("Thingy: " + arg); foo.$super.call(this, arg); } return {foo: Thingy_foo}; }); A: The Prototype source tries to be modular so you can download lang/class.js separately. However a quick glance at the code shows it depends on functions from lang/array.js, lang/object.js, lang/function.js - it would be safer to grab prototype.js and all of the lang directory. That gives you the core of Prototype without the conflicting DOM stuff. I too find the Class class too useful to do without. I was recommended to try Sugar which is nice but still has no inheritence. It seems the only real alternative currently is MooTools' class. A: You should have a look at : MyJS class system I think you will enjoy ! A: After trying out ComposeJS, I couldn't find a way to invoke superclass constructors explicitly (they are invoked automatically), so I had to abandon it. I finally settled on JsFace which has many features (inheritance, mixins, static properties, AOP), although a slightly weird syntax to invoke the super class constructor: this.$class.$super.call(args). It also seems to be the fastest implementation, according to its website and also this benchmark, totally blowing away the Resig implementation, which is quite slow. The caveat to watch out for is is that this.$class.$super is always the super class of the final child class, so you may need to do something like this: var C = Class(A, { constructor: function (x) { C.$super.call(this, x); }, ... } instead of var C = Class(A, { constructor: function (x) { this.$class.$super.call(this, x); }, ... } which is like the examples, if you have multiple levels of inheritance, otherwise you'll get an infinite recursion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does the message contract provide interoperability across different languages? I am reading about WCF services. I am new to the WCF services. I read that WCF provides interoperability. I want to know in which context it provides the interoperability. Is it providing the interoperability in the context of consuming the .net wcf web services from any other language (e.g. php) or for any different purpose. I have read the following article. http://blogs.msdn.com/b/drnick/archive/2006/11/27/mixing-message-contract-attributes.aspx In this way if we provide the OperationContract for all the methods in wcf web service by passing or returning MessageContract for some method and DataContract for some method then what will happen in php or any other language ? *Whether the method having DataContract as parameter or return type are available in php or any other language ? or Whether the method having MessageContract as parameter or return type are available in php or any other language ? or Both are available in php or any other language * A: Is it providing the interoperability in the context of consuming the .net wcf web services from any other language (e.g. php) or for any different purpose. Interoperability means being able to call your WCF service from a non-.NET platform, as long as the client uses the same web service protocol as your service. Note that you can use many type of bindings for your WCF service, but only BasicHttpBinding, WSHttpBinding and WSDualHttpBinding support interoperability. For more information, refer to the MSDN article Web Services Protocols Supported by System-Provided Interoperability Bindings. Whether the method having DataContract as parameter or return type are available in php or any other language ? or Whether the method having MessageContract as parameter or return type are available in php or any other language ? or Both are available in php or any other language The short answer is yes. If you use BasicHttpBinding for example, it all becomes XML, and it's up to the libraries available to that language to convert the XML to something native to the language. For example, the PHP SoapClient translates a DataContract return type to the built-in stdClass object (see Echo xml result from wcf service in php?). A: At least messagecontract should provide a workable solution consuming with PHP, according to https://github.com/geersch/WcfServicesWithPhp5. And I can find a similar post for DataContracts at http://www.rizalalmashoor.com/blog/calling-a-wcf-service-from-php/. And comparing the way these two contract types are consumed from PHP, I think it would not give a problem combining the two in the same WCF service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to give an asp button a specific shortcut Q: Is there some way to capture (specific key(keyboard stroke)) ,when the user clicks it as he clicks the specific button i want. I want to do that , because i have a grid view with an insert button in the gridview footer (to create a new row),and for facilitation, instead of using the mouse every time to add a new row, i wanna to capture a specific key as an equivalent to this button. A: Yes you can create specific combinations of keyboard strokes to give you shortcuts. A typical example would be to use Ctrl + S to save some data on the page. Here is a good tutorial on how to do it with javascript and jQuery http://www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/ Here's an excerpt of the code: var isCtrl = false; document.onkeyup=function(e){ if(e.which == 17) isCtrl=false; } document.onkeydown=function(e){ if(e.which == 17) isCtrl=true; if(e.which == 83 && isCtrl == true) { //run code for CTRL+S -- ie, save! return false; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7594475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How using usemap in div background url i missed you can you help me? i have such style .lorry{ background: url(../img/lorry.png);background-repeat:no-repeat; _background: none; _filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='img/lorry.png'); height: 143px; width: 385px; float: left; margin: 39px 0 0 0; } I want to add usemap on image, is it possible? A: You can't put an imagemap in a background. If you need this functionality you will have to layer objects to achieve the same thing: * *First layer: just your image (not bound to imagemap) *Second layer: the contents of the container that you want to appear over the "background" *Third layer: another copy of the image bound to the image map, but transparent. Here's an example: http://jsfiddle.net/jamietre/fgeee/1/ Below is the general construct to achieve this effect. It works by having an imagemap on the topmost layer (so it will be active), but bound to a transparent image. The actual image you see is behind everything, and is not transparent. You can also do this with two layers by skipping the first image, and assigning it as a background to the layer2 div. This will only work if you are going to display the image at its native resolution, so may be fine, but this answer is more general purpose. <div id="wrapper"> <img id="layer1" src="some/image.jpg"> <div id="layer2" style="position: absolute; top: 0; left: 0;"> Your content here </div> <img id="layer3" style="position: absolute; top: 0; left: 0; opacity:0; *filter: Alpha(opacity=0);" usemap="#your-map" src="some/image.jpg"> </div> Notes: * *The wrapper is required to make the absolute positioning work *the *filter: .. css is to supporter IE <8 which doesn't understand opacity. A: I just come up here because I was trying do the same, and I found one one to use "map" without image. As the other folks said, isn't possible use maps without image, but we can use DIV instead. What you do is, you place a div over the main image and create a link for that DIV, below follows my code: HTML <div id="progress"> <a id="link1" title="Symbol Link" href="#">Symbol Link</a> <a id="link2" title="Stack Link" href="#">Stack Link</a> <a id="link3" title="Overflow Link" href="#">Overflow Link</a> </div> CSS #progress { width: 257px; height: 84px; background:url(http://upload.wikimedia.org/wikipedia/en/9/95/Stack_Overflow_website_logo.png); position:relative; } a#link1, a#link2, a#link3 { display: block; overflow: hidden; position: absolute; background: transparent; text-indent: -9999px; } #link1 { left: 10px; width: 45px; height: 84px; } #link2 { left: 55px; top: 45px; width: 70px; height: 39px; } #link3 { top: 45px; left: 124px; width: 130px; height: 39px; } jsFiddle of my example. Reference: CSS image maps A: Using an imagemap on an object with a background-image is not possible. The usemap attribute requires an image (img tag). Reference: http://www.w3schools.com/tags/att_img_usemap.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7594479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Issue with ViewPager in application I know we can flip pages horizontally using ViewPager.But is there any function which i can override which can catch the action when i will flip pages left and right.I mean any function which will be called when i will flip left and any function which will be called when i will flip right.Anyone having any idea please share. thanks in advance A: You can detect the page transition by calling setOnPageChangeListener() and specifying your own OnPageChangeListener.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I change the circle picture of a radio button in both cases checked and unchecked? I want to customize the radio buttons so instead of being like this "empty circle in case unchecked and green on in case checked" I want to make the picture in case it's unchecked like this and in case it's checked like this How can I achieve that by xml or java?? A: Use a state list to define different drawables for different Button states. Here is an example: Is it possible to change the radio button icon in an android radio button group A: Use state list drawables. There's a tutorial on them here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I reorder the tab order of two elements in the middle of the page? I have a dynamic web page, and I need to reorder the tab order of two elements some place in the content. I really don't want to set the tab index for every preceding element to achieve this. Is it possible to assign a tab index to an element relative to it's position in the DOM, thus keep the natural tab order for the rest of the elements? Give the following elements: <a>Link1</a> <a>Link2</a> <a>Link3</a> <a>Link4</a> <a>Link5</a> The natural tab order here is Link 1, 2, 3, 4, 5. Is it possible to change the tab order to 1, 2, 3, 5, 4 without setting the tab index for 1, 2 and 3 also? In the real context, I need to rearrange two elements following an expanding menu, so I don't know the numeric value of the tab index. Solutions based on javascript/jquery are also welcome. A: You can't work your way around this without changing the tabindex stack. However, you can pretty easily write a small plugin that takes focus and change it to something else. It's messy, though, and I'd strongly recommend against it. What you can do, however, is have a tabindex-stack above and below. Say all objects above these items in the DOM could have tabindex 10, and all objects below could have tabindex 30. For the items you're listing, you could force tab index between 20 and 29. Like this: Over: <div></div> <div></div> <div></div> <div></div> Your range: <a tabindex="20">Link1</a> <a tabindex="20">Link2</a> <a tabindex="20">Link3</a> <a tabindex="20">Link4</a> <a tabindex="20">Link5</a> Under: <domobject tabindex="30"/> <domobject tabindex="30"/> <domobject tabindex="30"/> <domobject tabindex="30"/> This would force tabbing to go through the DOM in the correct order. However, if you include untabindex'ed objects along the way, they'll get the same tab index as the first block - making everything odd and strange. If you want to switch the tab index of your range, you can change it accordingly, within the 'buffer range' that you have (20-29 in the example): <a tabindex="25">Link1</a> <a tabindex="24">Link2</a> <a tabindex="23">Link3</a> <a tabindex="22">Link4</a> <a tabindex="21">Link5</a> It's messy as hell. The jQuery option is messy also, but it's a lot cleaner (and easier to maintain). A: The correct solution to this, in my opinion, is to order the elements in your HTML/DOM so that the tab-order is the one you want. Then, you can use CSS and flex-box to reorder the elements the way you want them to display visually. Depending on how you want to re-order things, you can do that with for example flex-direction: column-reverse, to reverse the order of all elements in a container, or you can use the order attribute to mess with the order of single elements. Here's an example of doing the latter, where giving the 4th element order: 1 makes it show up after all the other elements (which I believe has a default order of 0). nav { display: flex; flex-direction: column; } <nav> <a href="#">Link1</a> <a href="#">Link2</a> <a href="#">Link3</a> <a href="#" style="order: 1">Link5</a> <a href="#">Link4</a> </nav>
{ "language": "en", "url": "https://stackoverflow.com/questions/7594489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TinyMce wiht AtD spell check not work correctly in Chrome, please guide? In my asp.net site I have TinyMce editor and for spell checking I have included AtD (after the deadline) spellcheck plugin in it. In Chrome there is a problem this AtD spell check plug in has damaged TinyMce controls functionality. I can not use TinyMce features (like font size family change etc.) in Chrome but it works fine in other browsers. Any guidance will be highly appreciated. A: Why don't you use the regular spellcheck plugin together with either google spellchecker or Aspell/Ispell? Edit (added): Here is a linkt o a HOWTO. It describes well how the spellchecker plugin can be configured and what needs to be done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Could not load file or assembly 'System.Windows.Controls' in silverlight 5 using prism4 I'm creating an application silverlight 5 using prism 4 and when I'm running the bootstrapper using UnityBootstrapper then I have the next error: Could not load file or assembly 'System.Windows.Controls, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. This error in the ConfigureRegionAdapterMappings method: protected override RegionAdapterMappings ConfigureRegionAdapterMappings() { // Call base method var mappings = base.ConfigureRegionAdapterMappings(); <-- I get the error here! if (mappings == null) return null; // Add custom mappings // Set return value return mappings; } The strange thing is if I change my project to silverlight 4 then it is working fine (?). Could you please help me? Thanks! A: this is because prism 4 libraries are targeting silverlight 4. you have to download the source code of prism and have to change all silverlight project references to silverlight5 and the recompile it and then set references to new binaries
{ "language": "en", "url": "https://stackoverflow.com/questions/7594491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: CRM 2011 Workflow Condition Issue I have created a simple workflow in CRM 2011 which checks a field value in one entity and creates a new record in a different entity. Sometimes however, the creation doesn't occur, it just seems that the condition is not met when it should be. Consider an entity called "Car" which has a text field called "Task". This Task field will always be saved with 1 of 4 possible values: "", "Add", "Change", "Delete". This value is used to determine how the workflow should process. The workflow is set to fire when a different field is changed - "Driver". The workflow is setup like this... - Condition - If "Task" == "Add" - create new record - Else if "Task" == "Change" - create new record - Else if "Task" == "Delete" - create new record - Reset "Task" to "" NOTE: the created record is using different values depending on "Task" I can see that the workflow is always fired when expected, and both the "Condition" and the "Reset" are processed. The problem is that sometimes (although, not so far today) no record is created - this suggests that none of the IF conditions are met. However, I have no reason to explain why. I can see that the field "Task" is always set as expected prior to the save (exact spelling/casing and all) So, are there any known issues with CRM workflows that could explain this? Is there a more indepth way to debug these issues? (i.e. check the value of "Task" at time on "Condition" checks) I am wondering is it possible that the "Reset" part of the workflow is somehow being processed before the condition? and there for the condition is checking a blank field. Any help will be greatly appreciated, Thanks A: Unfortunately, I have not experienced this issue again since the first time when I created the workflow. However, some good techniques where offered in comments as to how this sort of issue could be debugged - thanks to those people! Firstly, you can turn on Entity Auditing which will help you track down what is going wrong. Another option would be to send an email from the workflow with the current data values for debugging, or add a final "else" clause to send emails when none of the conditions have been met (perhaps a good fail safe addition to have even when it does seem to all be working) - I like this second option as it is more "out of the box" thinking ;) Anyway here you can find information on sending emails from within a CRM workflow
{ "language": "en", "url": "https://stackoverflow.com/questions/7594493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: XmlReader and InvalidCharacter I am using SqlCommand.ExecuteXmlReader() to Execute an SqlCommand with FOR XML AUTO, ELEMENTS Now, there is a column which contains for xml invalid characters (like 0x1F). When I read now the result of the XmlReader with using (var xmlReader = command.ExecuteXmlReader()) { xmlReader.Read(); while (xmlReader.ReadState != ReadState.EndOfFile) { try { sb.Append(xmlReader.ReadOuterXml()); } catch(Exception e) { log.Error("Error in xmlReader.ReadOuterXml()", e); } } } I get the Exception "Invalid Character" at xmlreader.ReadOuterXml() when It read the Invalid Character. Does anybody know a Workaround how I can solve this problem? A: You could surround your XML data with <![CDATA[Data]]>, like this <SomeNode><![CDATA[0x1F]]></SomeNode> OR you can use XmlConvert to Encode/Decode the XML data. Look here for mor info: http://msdn.microsoft.com/en-us/library/35577sxd%28v=VS.100%29.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7594494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WEbResponse throws 500 Internal server error I have many times successfully implemented reading data from web pages using technique like this: WebRequest req = (WebRequest)WebRequest.Create(path); WebResponse resp = (WebResponse)req.GetResponse(); etc. ......... However, this time the WebResponse throws an internal error. Otherwise, I can browse the parameter path. What could be the reason? A: I think it could be any number of reasons. You should try to catch the error and see if you can get any further details from the response. Perhaps try adding the code below and see if that provides any further details: catch (WebException webex) { Console.WriteLine("Unable to perform command: " + req); String data = String.Empty; if (webex.Response != null) { StreamReader r = new StreamReader(webex.Response.GetResponseStream()); data = r.ReadToEnd(); r.Close(); } Console.WriteLine(webex.Message); Console.WriteLine(data); A: Probably its not creating the request, WebRequest.Create, there can be a proxy issue if you are behind any proxy, i got the same problem that my code was unable to connect to any path but it was browsing fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: get a list of listItem.fieldValues Client object model Sharepoint 2010 I'm building a Sharepoint 2010 export tool for back up reasons (a bit like the filemanager from Metavis). When downloading a file to local disk I need to back up the metadata associated with the document. Which I will store in a csv-file. My first approach was to iterate all listItem.fieldvalues, but that doesn't really work because some fieldvalues are complex types, which would needlessly complicate the backup file. Some values even have line endings, for example "MetaInfo". Furthermore not all values are needed to restore the content when that might be necessary. So my idea is to only get the values from the Fieldvalues collection which are needed to do a functional restore, supplemented with all the user added metadata. To do this I want to check all fieldvalues against an exclusion list to see if it is present. If it is present don't back up. If it is it is either user generated metadata or a value I need like for instance "author", "created". So my question is, does anyone know of a list of all fieldvalues keys? Or is there a better approach to my problem? Thanks Update: Well, as I was iterating through the FieldValues collection any way. It was easy to do a dump of all the values to a CSV. Running it once was enough to get all the values. Now all I need to write is an xml file for configuration. This leaves the question: is there a better way of doing this? A: Filter the list fields by writing following code using System; using Microsoft.SharePoint.Client; clientContext.Load( listItems, items => items .Include( item => item["Title"], item => item["Category"], item => item["Estimate"])); Source: http://msdn.microsoft.com/en-us/library/ee857094.aspx#SP2010ClientOM_Creating_Windows_Console_Application You can create an view with all fields, get the view using sharepoint object model and and get its column name from collection and filter them as per your requirement. A: I have finished the application. As I wrote in my update I have made a list of all fieldValues by exporting them to a CSV file. After that I made a configuration-file with a boolean 'Backup'. This makes it possible to control which values are to be used when a backup is made. I retrospect I think a configuration file was not needed. The values used when backing up are so much part of the whole workings of the program that a configuration file gives an administrator or casual future developer the impression that a simple reconfiguring will fulfill there needs. I can now see that if the program needs to change due to new requirements the code has to be changed anyway. So even though setting a value to 'True' will change the output. Some other code has to be written as well. If I were to write it again I would probably use constants. This makes it all less dynamic, but still fulfill the needs of the program. (BTW a list of all the names off the standard fieldValues would have been nice to start with. I would publish it here, but I don't have access to the file anymore, because I switched jobs recently.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7594502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to close the current form in a SplitContainer? I have a user control in my SplitContainer's right panel. A form opens below the user control. Now if i click a button in the user control, that current form should close and a new form should open. How to do this? A: You can implement below logic in your app easily: splitContainer.Panel2.Controls.Remove(myPanel); splitContainer.Panel2.Controls.Add(myOtherPanel); which will remove the existing panel from the container and place the other panel. You can extend the same logic to place forms, or separate controls on the container easily.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get video resolution on Mac via .NET I can get informations about video-files like resolution by using the Shell32.dll under windows. Is there some way to do this (in C# - running under the mono framework) that will work on Mac? A: Use MonoMac and look at MonoMac.AppKit.NSScreen. It should have all the properties you need to retrieve the resolution of any (if multiple) screen(s). If you need more documentation or samples you simply have to browser Apple doc on NSScreen. The properties names will closely match what MonoMac provides. A: Since the question is unclear to me, here are two part answer: 1. if you want to check the resolution of your screen (desktop): Check if this is implemented: System.Windows.Forms.Screen.AllScreens. For now, there is some code for it but it's marked with [MonoTODO] attribute. AllScreens: http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.allscreens.aspx Source for the library: http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System.Windows.Forms/System/Windows/Forms/Screen.cs.htm 2. if you want to check video file resolution For that, I would seek ffmpeg built for Mac and using command line parameters extract resolution information from the file. http://jungels.net/articles/ffmpeg-howto.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7594505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Refresh only a specified spot in asp.net website (Updated code) not working I want to do page load every 5 sec so I have this in my head content <meta http-equiv="refresh" content="5" /> Because of this the whole page refreshes. I just want to refresh the gridview and the graph that I have in the page. How can I do that without refreshing the whole page. <asp:ToolkitScriptManager ID="ToolkitScriptManager1" EnablePageMethods="true" EnablePartialRendering="True" runat="server"> </asp:ToolkitScriptManager> <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <ContentTemplate> <div id="pie"> <canvas width="125" height="450" id="progress1">[No canvas support]</canvas> <canvas id="pie1" position="relative" width="400" height="400">[No canvas support]</canvas> </div> <asp:Panel runat="server" ID="Panel_Users"> <asp:GridView ID="Grid_UserTable" runat="server" OnRowDataBound="MyGrid_RowDataBound"> <Columns> </Columns> </asp:GridView> </asp:Panel> <asp:Timer ID="TimerClickEvent" runat="server" Interval="4000" ontick="TimerClickEvent_Tick"></asp:Timer> </ContentTemplate> </asp:UpdatePanel> protected DateTime LastUpdate { get { return (DateTime)(ViewState["LastUpdate"] ?? DateTime.Now); } set { ViewState["LastUpdate"] = value; } } protected void TimerClickEvent_Tick(object sender, EventArgs e) { if (LastUpdate.AddSeconds(5.0) < DateTime.Now) { UpdatePanel1.Update(); LastUpdate = DateTime.Now; } } protected void Page_Load(object sender, EventArgs e) { ToolkitScriptManager1.RegisterAsyncPostBackControl(TimerClickEvent); if (!IsPostBack) { LastUpdate = DateTime.Now; }} Doesn't reload. where am I going wrong A: Place the panel inside an UpdatePanel and use method updatePanelID.Update() to update the update the Panel containing GridView. See this for more details Instead of button click event you can use a timer for that. A: If you only want to refresh a region, there are 2 options: * *load that into an <iframe> and let it do whatever it wants (via meta-refresh on the document inside the <iframe> *reload the implacted region via javascript, perhaps jQuery's .load() method, i.e. $('#id').load(url); A meta-refresh on the entire page will, by necessity, reload the entire page. A: For a built in asp.net solution, use an <asp:UpdatePanel> along with an <asp:Timer> control. Set the update panel to update based on the Timers Tick event. This will then only update the content within the update panel. HOWEVER, this is a quick and dirty solution (in my opinion) because even though the content on the page only updates within the update panel, the whole page is actually posted back each time, and anything within the Page_Load method will be processed again. Another solution would be to use some javascript ajax, and only update what you need to update. A great javascript library which will help you with this is jQuery, and then use the AJAX features of this. This will allow you to reload on the areas that you need, and give you far greater control over what is happening. I would forget about the AJAX Control Toolkit, and look more into jQuery Ajax and jQuery UI.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Modulo operator with negative values Why do such operations: std::cout << (-7 % 3) << std::endl; std::cout << (7 % -3) << std::endl; give different results? -1 1 A: a % b in c++ default: (-7 / 3) => -2 -2 * 3 => -6 so a % b => -1 (7 / -3) => -2 -2 * -3 => 6 so a % b => 1 in python: -7 % 3 => 2 7 % -3 => -2 in c++ to python: (b + (a % b)) % b A: The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03), The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined. That is all the language has to say, as far as C++03 is concerned. A: From ISO14882:2011(e) 5.6-4: The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a. The rest is basic math: (-7 / 3) => -2 -2 * 3 => -6 so a % b => -1 (7 / -3) => -2 -2 * -3 => 6 so a % b => 1 Note that If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined. from ISO14882:2003(e) is no longer present in ISO14882:2011(e)
{ "language": "en", "url": "https://stackoverflow.com/questions/7594508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "194" }
Q: Mocking HttpContext to retrieve item form contexts item dictionary We use MVC3, for our unit tests we use RhinoMocks in our unit tests. When the a request starts we check the domain from which it came and match that to a customer. This customer is stored in the HttpContext.Items. Most controllers need this info to do their thing. var mocks = new MockRepository(); using (var controller = new TestController()) { HttpContext context = MockRepository.GenerateStub<HttpContext>(); Customer customer = new Customer { Key = "testKey" }; context.Items["Customer"] = customer; controller.ControllerContext = new ControllerContext { Controller = controller, RequestContext = new RequestContext( new HttpContextWrapper(context), new RouteData() ) }; ... This code sample shows basically what is needed, however the stub is not allowed as HttpContext is a "sealed" class. The controller accepts a HttpContextBase (there is lot about mocking this one), but it does not expose the Items property. Thoughts anyone? Or even better a solution ;-) A: Creating a HttpContextBase stub and stubbing its Items property will allow you to use the Items dictionary: HttpContextBase context = MockRepository.GenerateStub<HttpContextBase>(); Customer customer = new Customer { Key = "testKey" }; context.Stub(c => c.Items).Return(new Dictionary<string, object>()); context.Items["Customer"] = customer;
{ "language": "en", "url": "https://stackoverflow.com/questions/7594510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gstreamer video to opengl texture I'm trying to render AV frames grabbed and converted from a MPEG4 video using Gstreamer to an Android (2.2)-opengl texture. I've pretty much exhausted google and not found an answer. Basically, I am using Gstreamer uridecodebin to decode the frame, and then convert the frame to RGB, and then glTexSubImage2D() to create an openGL texture from it, but can't seem to get anything to work.The texture is getting colored when I get the decoded data (RGB) from Gstreamer. I am getting the video size as 320 * 256 and my Texture size is 512 * 256 & I am using glDrawTexiOES(0,0,videowidth,videoheight), I am not getting any errors related to opengl, but the texture is blank( different color frames), though the Audio works fine. Here is my code:Native OnDraw: if (theGStPixelBuffer != 0) { glBindTexture (GL_TEXTURE_2D, s_texture); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glPixelStorei( GL_UNPACK_ALIGNMENT, 2); glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, theTexWidth, theTexHeight, GL_RGB, GL_UNSIGNED_BYTE, GST_BUFFER_DATA(theGStPixelBuffer)); check_gl_error("glTexSubImage2D"); theGStPixelBuffer = 0; } glDrawTexiOES(0, 0, 0, theTexWidth, theTexHeight); check_gl_error("glDrawTexiOES") A: I have encounter the same problem ;you can get the bitmap and use martix class to resize the bitmap.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: IIS 7 Session timeout frequently I prepared my website in visual studio 2008 with ajax control kit and working well in the local machine. My website is hosted on Windows 2008 R23 Server with II7 But it is frequently loosing its session with in 30 secs. Please provide me a solution to increase my session timeout. my web.config is as follows: Asp.Net Configuration option in Visual Studio. A full list of settings and comments can be found in machine.config.comments usually located in \Windows\Microsoft.Net\Framework\v2.x\Config --> section enables configuration of the security authentication mode used by ASP.NET to identify an incoming user. --> section enables configuration of what to do if/when an unhandled error occurs during the execution of a request. Specifically, it enables developers to configure html error pages to be displayed in place of a error stack trace. <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors> --> <customErrors mode="Off"></customErrors> <pages enableViewStateMac="false" viewStateEncryptionMode="Never" enableEventValidation="false"> <namespaces> <clear/> <add namespace="System"/> <add namespace="System.Collections"/> <add namespace="System.Collections.Generic"/> <add namespace="System.Collections.Specialized"/> <add namespace="System.Configuration"/> <add namespace="System.Text"/> <add namespace="System.Text.RegularExpressions"/> <add namespace="System.Linq"/> <add namespace="System.Xml.Linq"/> <add namespace="System.Web"/> <add namespace="System.Web.Caching"/> <add namespace="System.Web.SessionState"/> <add namespace="System.Web.Security"/> <add namespace="System.Web.Profile"/> <add namespace="System.Web.UI"/> <add namespace="System.Web.UI.WebControls"/> <add namespace="System.Web.UI.WebControls.WebParts"/> <add namespace="System.Web.UI.HtmlControls"/> </namespaces> <controls> <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </controls> </pages> <sessionState mode="StateServer" cookieless="true" timeout="30"/> <httpRuntime executionTimeout="43200" maxRequestLength="104856" enable="true" /> <httpHandlers> <remove path="*.asmx" verb="*"/> <add path="*.asmx" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/> <add path="*_AppService.axd" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/> <add path="ScriptResource.axd" verb="GET,HEAD" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/> <add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false"/> </httpHandlers> <httpModules> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </httpModules> </system.web> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <providerOption name="CompilerVersion" value="v3.5"/> <providerOption name="WarnAsError" value="false"/> </compiler> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <providerOption name="CompilerVersion" value="v3.5"/> <providerOption name="OptionInfer" value="true"/> <providerOption name="WarnAsError" value="false"/> </compiler> </compilers> </system.codedom> <!-- The system.webServer section is required for running ASP.NET AJAX under Internet Information Services 7.0. It is not necessary for previous version of IIS. --> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <remove name="ScriptModule"/> <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </modules> <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <remove name="ScriptHandlerFactory"/> <remove name="ScriptHandlerFactoryAppServices"/> <remove name="ScriptResource"/> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="Reserved-ReportViewerWebControl-axd" path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler" resourceType="Unspecified"/> </handlers> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> Thanks in advance chandu A: I think you have set the session time out to 30 in your web.config file. <sessionstate timeout="required no of minutes" /> In here you can set the time that you need the session to be time out. This ASP.NET Session State will give you a better idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7594518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to obtain the exact dpi value of android device? we can use DisplayMetrics.densityDpi to obtain a approximate dpi value of the device,but i eager to know how to obtain the exact dpi value? A: I think you can accesss this through the class DisplayMetrics and the field densityDpi. A: Use DisplayMatrics.xdpi and DisplayMatrics.ydpi xdpi The exact physical pixels per inch of the screen in the X dimension. ydpi The exact physical pixels per inch of the screen in the Y dimension. getResources().getDisplayMetrics().xdpi getResources().getDisplayMetrics().ydpi
{ "language": "en", "url": "https://stackoverflow.com/questions/7594527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Internet Explorer 6 Mobile Scrollbar Rendering Problems I have a web application running on internet explorer 6 mobile, and I've noticed that the rendering of scroll bars is inconsistent. For example, if you take a regular html select (with lots of entries) and expand it, the scroll bar renders in a slim, black-colored way, but if you have an overflowing div, you get a wide, old windows-style scroll. Do you know of a way to force the rendering to the select-style one? (screenshots follow)
{ "language": "en", "url": "https://stackoverflow.com/questions/7594530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }