text
stringlengths
8
267k
meta
dict
Q: Image for individual post/article using MySQL and PHP I have a member based website and what I have built a system where registered users can submit reviews. Those are submitted to a MySQL database using PHP and then queried out onto a review page, like review.php?id=246. However, I want users to be able to upload an image, store the image in a folder on the server, store the filename in the MySQL database then query it all out onto my review.php page for each individual one. How would I do this? Thanks in advance guys! A: Let's say you have table with columns id, review_id, img. Also id column must be autoincremented int. Create following folders: photos which includes folders named original and resized. Code below will resize image, save original and resized image, and set it's address into db table. I hope it will work for you <?php /* DB connection*/ require 'db.php'; /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /*registration sheck*/ $submit=$db->real_escape_string( $_POST['submit']); $review=$db->real_escape_string($_POST['review']); function createThumb($upfile, $dstfile, $max_width, $max_height){ $size = getimagesize($upfile); $width = $size[0]; $height = $size[1]; $x_ratio = $max_width / $width; $y_ratio = $max_height / $height; if( ($width <= $max_width) && ($height <= $max_height)) { $tn_width = $width; $tn_height = $height; } elseif (($x_ratio * $height) < $max_height) { $tn_height = ceil($x_ratio * $height); $tn_width = $max_width; } else { $tn_width = ceil($y_ratio * $width); $tn_height = $max_height; } if($size['mime'] == "image/jpeg"){ $src = ImageCreateFromJpeg($upfile); $dst = ImageCreateTrueColor($tn_width, $tn_height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height); imageinterlace( $dst, true); ImageJpeg($dst, $dstfile, 100); } else if ($size['mime'] == "image/png"){ $src = ImageCreateFrompng($upfile); $dst = ImageCreateTrueColor($tn_width, $tn_height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height); Imagepng($dst, $dstfile); } else { $src = ImageCreateFromGif($upfile); $dst = ImageCreateTrueColor($tn_width, $tn_height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height); imagegif($dst, $dstfile); } } if($submit){ $result = $db->query("INSERT INTO reviews (`review_id`) VALUE '$review'") or die($db->error)); $review_id = $db->insert_id; if(isset($_FILES['upload_Image']['name']) && $_FILES['upload_Image']['name']!=='') { $ext = substr($_FILES['upload_Image']['name'], strpos($_FILES['upload_Image']['name'],'.'), strlen($_FILES['upload_Image']['name'])-1); $imgNormal = 'img'.$new_user_id.$ext; $normalDestination = "photos/original/" . $imgNormal; $httprootmedium = "photos/resized/" . $imgNormal; move_uploaded_file($_FILES['upload_Image']['tmp_name'], $normalDestination); createThumb($normalDestination,$httprootmedium,200,300); #For 500x300 Image } $result = $db->query("UPDATE review SET img='$imgNormal' WHERE id='$review_id'") or ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7538068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IE8 is not accepting my privacy policy The development version of the site is at http://dev.blueankh.com userid: fix password: demo. The application is writen in php and the privacy policy is in a header created with the header() function. The site works with firefox but not IE. When I use fiddler2 it shows the privacy policy on the privacy tab. Since it sees it as a valid, parseable Privacy Policy, I feel it is going out correctly. It also shows the cookies. To me this says the privacy policy is going out correctly in a header. In IE when I use View -> Webpage Privacy Policy it tells me that based on privacy settings no cookies were blocked. The Cookies column is blank, acknowledging that no cookies were accepted.When I highlight the main page and click summary I get a blank box where the privacy policy should be displayed. Very frustrating A: The link to your privacy policy, Privacy.php, is broken.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Beautiful Soup line matching Im trying to build a html table that only contains the table header and the row that is relevant to me. The site I'm using is http://wolk.vlan77.be/~gerben. I'm trying to get the the table header and my the table entry so I do not have to look each time for my own name. What I want to do : * *get the html page *Parse it to get the header of the table *Parse it to get the line with table tags relevant to me (so the table row containing lucas) *Build a html page that shows the header and table entry relevant to me What I am doing now : * *get the header with beautifulsoup first *get my entry *add both to an array *pass this array to a method that generates a string that can be printed as html page def downloadURL(self): global input filehandle = self.urllib.urlopen('http://wolk.vlan77.be/~gerben') input = '' for line in filehandle.readlines(): input += line filehandle.close() def soupParserToTable(self,input): global header soup = self.BeautifulSoup(input) header = soup.first('tr') tableInput='0' table = soup.findAll('tr') for line in table: print line print '\n \n' if '''lucas''' in line: print 'true' else: print 'false' print '\n \n **************** \n \n' I want to get the line from the html file that contains lucas, however when I run it like this I get this in my output : **************** <tr><td>lucas.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> </tr> false Now I don't get why it doesn't match, the string lucas is clearly in there :/ ? A: It looks like you're over-complicating this. Here's a simpler version... >>> import BeautifulSoup >>> import urllib2 >>> html = urllib2.urlopen('http://wolk.vlan77.be/~gerben') >>> soup = BeautifulSoup.BeautifulSoup(html) >>> print soup.find('td', text=lambda data: data.string and 'lucas' in data.string) lucas.vlan77.be A: It's because line is not a string, but BeautifulSoup.Tag instance. Try to get td value instead: if '''lucas''' in line.td.string:
{ "language": "en", "url": "https://stackoverflow.com/questions/7538072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Aquamacs/emacs: focus-follows-mouse not working as expected I'm working with Aquamacs 2.3a [latest version] on Mac OS X 10.6.8. I would like to switch between frames/buffers by just moving the mouse. As far as I found out by searching for this problem, you can put the following code in Preferences.el to make it work: (setq focus-follows-mouse t) (setq mouse-autoselect-window t) See also here: Emacs sloppy focus no longer working - 2 second delay on changing focus and here: how to get focus-follows-mouse over buffers in emacs? I also found (setq mouse-autoselect-window t). The problem is that none of these entries in Preferences.el seems to have any impact on the behavior of Aquamacs. I can move the cursor over new buffers or frames, nothing is activated. So my questions are: 1) what is the expected behavior of theses settings? 2) if they (as I would guess) should have an impact on the way Aquamacs allows to change buffers/frames, why is it not working in my case? [I even tried with an empty Preferences.el, just putting in the above commands]. A: I think you've been bit by a typical confusion over what focus-follows-mouse does. It does not make the focus follow the mouse. Rather, it just tells Emacs that your OS/window manager does have a focus-follows-the-mouse behavior. AFAIK, there is no way for Emacs to make the focus follow the mouse -- that's an OS/window-mgr thing. A: Try M-x turn-on-follow-mouse or (turn-on-follow-mouse) assuming that https://www.emacswiki.org/emacs/follow-mouse.el is installed and correctly working.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error integrating simple GoogleMaps app with core app I'm doing my GPS app. Standalone app with GoogleMaps works smoothly (map intent is easy to invoke). I tried integrating it my core app (which has several other intents) and I'm having problem launching it. I've tried this: public class MapaG extends Activity { public class MapaG1 extends MapActivity { private static final int latitudeE6= 50656428; private static final int longitudeE6 = 17899562; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.widokmapy); MapView mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); List<Overlay> mapOverlays = mapView.getOverlays(); Drawable drawable = this.getResources().getDrawable(R.drawable.icon); NakladkaNaMape itemizedOverlay = new NakladkaNaMape(drawable, this); GeoPoint point = new GeoPoint(latitudeE6, longitudeE6); OverlayItem overlayitem = new OverlayItem(point, "Witaj w Opolu", "Polska"); itemizedOverlay.addOverlay(overlayitem); mapOverlays.add(itemizedOverlay); MapController mapController = mapView.getController(); mapController.animateTo(point); mapController.setZoom(12); } @Override protected boolean isRouteDisplayed() { return false; } } } LogCat perspective gives me info that no Activity was found: FATAL EXEPTION: main android.content.ActivityNotFoundException: No Activity found handle Intent {act=praca.dyp.k.d.MAPAG} A: Did you add your MapAcitivity in your AndroindManifest.xml file? You also need to include this in your manifest: <uses-library android:name="com.google.android.maps" /> <uses-permission android:name="android.permission.INTERNET" /> You can look here for a more detailed example: HelloWorld, MapActivity A: I'm wondering why you are creating a MapActivity class inside an Activity? Remove the outer activity class declaration. Keep the MapActivity class. Use proper permissions in Manifest.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using oracle sequences with jpa (toplink) I have a sequence object in my oracle db: create sequence BASE_SEQ minvalue 1 maxvalue 9999999999999999999999999999 start with 100 increment by 1 nocache; I use jpa(toplink) for my web application. I have base class for all my db objects: @MappedSuperclass @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class AbstractEntity implements Serializable { protected BigDecimal id; @javax.persistence.Column(name = "ID") @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "BASE_SEQ") @SequenceGenerator(name="BASE_SEQ",sequenceName="BASE_SEQ", catalog = "DOF") public BigDecimal getId() { return id; } This class is inherited by some entities. After I start my application, and persist/merge several entities to db, i can find, that theirs' PK starts with 51 (instead of expected 100). After that, I go to my db, view DDL of my sequence object and see, that it has been changed to: create sequence BASE_SEQ minvalue 1 maxvalue 9999999999999999999999999999 start with 101 increment by 1 nocache; Why so happens? I have some entities with PK 51, 52 ... etc, and sequence starting with 101. AS - GlassFish 3.1.1 A: The default preallocationSize on SequenceGenerator is 50, it must match your sequence increment, which you have set to 1. Either change your increment to 50 (recommended), or change your preallocationSize to 1 (this will result in poor insert performance).
{ "language": "en", "url": "https://stackoverflow.com/questions/7538086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What encryption do I have to use with openssl? I would like to create a SSL certificate for my server(apache), i'm following this tutorial: https://help.ubuntu.com/community/OpenSSL My question is: what is the stronger encryption to create a key with openssl? Thank you A: There's a whole section about creating self-signed certificates on the page you linked, just follow it. The guide uses RSA encryption. 2048-bit for the CA certificate and 1024-bit server certificate. I'd maybe use 2048-but for both. If it's a high traffic or commercial site, I'd definitely consider a commercial server certificate from an acknowledged CA, since using a self-signed certificate will generate those ugly red errors you might see in Chrome or Firefox sometimes. In no browser you will get that yellow or green lock icon in the URL bar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Are the .js files being cached? I recently made a website and I made a change to a .js file, but when I delete the .js file from the FTP server and upload the new one, the new file doesn't show up on the website. I checked the source code behind the .js file on the website and it's not right, it's showing the source for the old file, not the new one even though the old one is gone. Is that because my browser cached the .js file? Note: I have this source <meta http-equiv="cache-control" content="no-cache" /> on my page to stop the browser from caching my page, and I know that works on the HTML, but with that source there, do the resource files still get cached? I don't have that line of code on my other pages, just my home page, but the .js file is still referenced on the other pages so perhaps that is how it is getting cached? Furthermore, is there a way to check your browsers cache? I use chrome. Edit: I just cleared my browsers cache and reloaded the website and the file worked as it should now, so that means the file did get cached. So now my question becomes how to I prevent a resource file from being cached? A: Yes. The resources are still cached. In my opinion a good practice to avoid this is to version your resources files in a url?parameter=value way. For example you should set the ulr to your js or css file like this: < ... src="script.js?v=1" .../> < ... href="style.css?v=1 .. /> and when any changes occured just change v=1 to v=2 ... that will not affect your code but will make your browser/proxy etc to redownload the resource A: I am not positive that no-cache meta tag is the way to go. It negates all caching and kind defeats the purpose of quickly accessible pages. Also, AFAIK, meta tag works per page, so if you have a page without it that references your JS - it will be cached. The widely acceptable way of preventing JS files (and, again, CSS) from being cached is to differentiate the requests for them: Say, you have: <script type=”text/JavaScript” src=”somescript.js″></script> this one will cache it (unless the above meta-tag is present. What you want to have is that on each page load the above line looks different (URL-wise) like so: <script type=”text/JavaScript” src=”somescript.js?some-randomly-generated-string″></script> Same goes for CSS. If you were using some sort of JS network - it would take care of that for you had you given it some sort of "no-cache" configuration option. You, of course, can do it in pure JS too. Some sort of Date related string is an option. Now, normally, you would not want to negate all the caching, so the way to do so is to add a version parameter to your URL: <script type=”text/JavaScript” src=”somescript.js?version=1.0.0″></script> and manage your scripts from there. EDIT There is no need for any additional extension. Unless I am sorely mistaken, "Chrome Developer Tools" is built in in all Chrome versions (in beta and dev, for sure) and is accessible by pressing Ctrl-Shift-I. There, in "Network" tab, you can see all your requests, there content and headers. A: Use an incognito instance of chrome (ctrl+shift+n) to check the source, this mode won't use any cached files. With this you can check if your file is being cached on the client side. If it's on the client side make sure your server is not sending cache-control headers along with the JS file. If it's on the server then there's a ton of possibilities, maybe you have a reverse proxy, a physical load-balancer or some other type of caching mechanism. Edit (question changed): Use this chrome extension to check the headers being sent along with your .js files. There's probably a cache-control header set that instructs chrome to cache the resource. If you're on apache you can override this behaviour using an .htaccess file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: php oop call a class within a class I need help trying to call a class function within another class. Here's my setup: db.php class db { function connect(){ //db connection code here } function query($sql){ //perform query and return results } }//end db class main.php class main { function test(){ $sql = "select * from user"; $result = $db->query($sql);//does not work } }//end class index.php require_once './db.php'; $db=new database; $db->connect(); //so far so good require_once './main.php'; $main=new main; //rest of the code here The problem is that on index.php I can run $db->query($sql) without any problems, but I can't seem to run them inside the main class, more specifically inside the test function. So if I call $main->test() from index.php I get this error: Fatal error: Call to a member function query() on a non-object in /path/to/file A: Unlike C global variables in PHP are not in the visibility scope of functions/methods, see http://docs.php.net/language.variables.scope To access global variables you must either import them into the function's scope via global $var or acccess them through the superglobal $_GLOBAL But instead of using global variables you might be interested in dependency injection, e.g. (one of many possible ways to implement di): <?php $db = new db; $db->connect(); $main = new main($db); $result = $main->test(); class db { function connect(){ //db connection code here } function query($sql){ //perform query and return results } } class main { protected $db; public function __construct($db) { $this->db = $db; } public function test(){ $sql = "select * from user"; return $this->db->query($sql); } } A: I would add a static getInstance() method into the Db class. Then cou can call Db::getInstance()->query(...) from every scope. You can read more on this pattern on Wikipedia. A: Just put: global $db; in your test() function. But if you do this also make sure you check that $db exists and is what you think it is before you use it this way. A: I guess you should be using $db = new db; because $db is not defined in your main class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Return a value to external invoker C++ I am invoking a C/C++ program (exe) from C#, I want to return a float value from my C/C++ to the C# code, I have the exe code which writes file a for a single value, instead I want to return that value to C#. How can I do that? A: You could output the result of your C/C++ program to the standard output, and then parse it with C# after the invokation. Check this answer: Best Way to call external program in c# and parse output Or if your program is called a lot a time, maybe a better solution would be to let it run and communicate with your C# program through local sockets. C# program may send request by network and get the result back. A: If that code writes a float to a file, then all you can do is read the file afterwards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android setTypeface I have a simple main class public void onCreate(Bundle savedInstanceState) { databaseHelper = new wecDatabasesManager(this); databaseHelper.open(); super.onCreate(savedInstanceState); series = databaseHelper.getSeries(); startManagingCursor(series); setListAdapter(new SeriesListAdapter(this, series)); registerForContextMenu(getListView()); } I also have a simple adapter public class SeriesListAdapter extends SimpleCursorAdapter { public SeriesListAdapter(Context context, Cursor c) { super(context,R.layout.series_row, c, new String[] { wecSeriesTable.NAME }, new int[] {R.id.series_name}); } @Override public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); String SerieName = cursor.getString(cursor.getColumnIndex(wecSeriesTable.NAME)); } } Now my question: How can i change the fontface? i have found this code Typeface font = Typeface.createFromAsset(getAssets(), "whatelsecomicsfont.ttf"); TextView txt = (TextView) findViewById(R.id.series_name); txt.setTypeface(font); i had pasted it into getView method in my main class but it don't work Any idea? A: Change the font file (*.ttf file)
{ "language": "en", "url": "https://stackoverflow.com/questions/7538117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to know app was purchased in Android? I have to implement in app purchase in my application, so I used below link http://developer.android.com/guide/market/billing/billing_integrate.html Almost everything is working. But I have doubt that is how to know if in app product was purchased or not for particular device before purchase the app. Because of my requirement is to show my in app product to purchase. If particular device already purchased my in app product there is no need to show my in app product. How can I know app is purchased or not before purchase the in app product? A: The purchase information is stored in PurchaseDatabase class. From this class I am checking whether application was purchased or not. For more information see this link http://developer.android.com/guide/market/billing/billing_integrate.html#billing-implement
{ "language": "en", "url": "https://stackoverflow.com/questions/7538118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Insert query on page load, inserts twice? On my games page, I have a page where they play a game. On that page I have a query $insert_user_activity = mysql_query("INSERT INTO game_activity (user_id,user_full_name,game_id,game_name) values ('$user_id','$full_name','$browser_id','$game_title')"); Which will log it into my database, it's just sitting on its own and when I refresh the page, it is submitted to the database twice for some reason. A: The logic of your front controller is wrong. The page where you are executing this query is called on every request made to your site, no matter whether it's a proper request or a call to a non-existent resource. You must change the logic of the front controller so it wouldn't run the application for the invalid requests. Otherwise there will be not one but thousands false inserts when the site goes live. A: what's the conditions on the page for which the query execute or in other way how are values of the variable you are getting on the page to execute the query if it is so than first check the existence of variables if the variables are set than run the query. A: I was having problems with a query that was executed twice in Firefox but in other bowsers (Chrome and IE) did problem did not happen. I was searching for an answer and found this post. I discovered this: If i execute a simple insert query it gets inserted twice when i switch on the "net" functionality in Firebug this does not happen. Strange. Just wanted to add this to this post. Still trying to solve this. {edit} Update: I have found a solutions, although it is not a pretty one. I check first wicth an select count if such record exists, if not then it will be inserted otherwise it will not be. Did the trick for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do I need to use HeapLock and HeapUnlock functions in winapi whenever I want to use HeapAlloc or HeapFree? Do I need to use HeapLock and HeapUnlock functions in winapi whenever I want to use HeapAlloc or HeapFree in a multithreaded program which use the same handle to a heap? If yes, does HeapLock block until it gets the lock? A: No. HeapLock acquires the lock which is used by HeapAlloc which you can use to lock out other threads from performing allocation and deallocation function on the specified heap but you must not use HeapLock before calling HeapAlloc or HeapFree. So long as the heap was not created with HEAP_NO_SERIALIZATION, HeapAlloc and HeapFree are safe to use in a multithread environment. References: HeapAlloc HeapLock
{ "language": "en", "url": "https://stackoverflow.com/questions/7538122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: replacing non-alphanumeric characters within a text I want to put inside parentheses the non-alphanumeric characters within a text. For example: "I would like to add * parentheses % around certain text within cells*." I want to put inside parentheses via regex method the non-alphanumeric characters within above string. Result: "I would like to add (*) parentheses (%) around certain text within cells(*)." A: string s = Regex.Replace( @"I would like to add * parentheses % around certain text within cells*.", @"([^.\d\w\s])", "($1)"); or to be more selective: string s = Regex.Replace( @"I would like to add * parentheses % around certain text within cells*.", @"([*%])", "($1)"); A: In additio to Marc's "($1)" answer, you can also use a MatchEvaluator: Regex.Replace(test, "[^a-zA-z0-9 ]+", m => "(" + m.Value + ")"); Which would mainly be useful when you need to do more complicated manipulation of the found patterns. Edit: replacng single chars and not the '.' : Regex.Replace(test, @"[^a-zA-z0-9\. ]", m => "(" + m.Value + ")"); A: you can use string.replace or Regex.replace string replace = Regex.Replace("a*", "([^a-zA-Z0-9])", "($1)");
{ "language": "en", "url": "https://stackoverflow.com/questions/7538123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to integrate checkboxes with jquery to a custom html? I've a situation where i should integrate the check boxes with custom html and also in turn i need all the functions of normal checkbox. Can you guide me how to do that? I'm new to jquery.. A: I'd ignore the html checkbox altogether for this design. I'd build a graphics element (the blue overlay) which becomes visible when you click the image, and invisible if clicked again. For input, in every div like this, you should put an <input type="hidden" value="0">, and with jQuery set the relevant input's value to 1 when the overlay is on, and to 0 again when it's off. Let me know on which part exactly you're having a problem, I'll try to elaborate. Hope it helps. Here's a jsFiddle A: have following structure and when <a> is clicked changed the checkbox value using JavaScript. add the image and text to the span. <span> <a href="#"></a> <input type="checkbox" name="chbox"> </span>
{ "language": "en", "url": "https://stackoverflow.com/questions/7538124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dynamic web project creation option in eclipse helios I have installed eclipse helios from zip file with name 'eclipse-java-helios-SR1-win32' which means it is for win32 and SR1. But, after extracting these files and opening eclipse IDE I cannot create a dynamic web project from New->I cant find dynamic web project option. Can anyone help me on this ? Do I have to install any eclipse plugin for this? Thanks A: You should have gotten the eclipse-javaee-helios-SR1-win32 zip, or preferably the Indigo SR1 version You can also search the Help|Install New Software option for features related to Java EE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use accelerometer values to control FPS on PC? If I was running a FPS like counter-strike on my PC would it be possible to have the phone (connected to the PC via WiFi/Bluetooth) act as the mouse and control the character's looking direction? For example, the player stands up in front of his computer and points his phone up + down, and 360 degrees around him, and the character in the game follows the direction with its gun? A: Everything is possible.... Everything. Assume you can write a socket class that would connect to your PC app. I'm new to android so I don't know what it's got in it's native java - That would handle sending info to the desk... I don't think it would have to be significant amounts of data, but it would be a stream. With that in place, I'd create a way to capture the movements of the PDA and push them to the DESK. Okay now you've got the data from the PDA in the desk app's sphere.. --it's best to do as much processing on the desk as you can.. More power.. -- Record the values as you do things like turn around, and point the device up/down.. all the movements you can think of. Finally, take the recorded values and see if you can "mimic" the actual moves in the game. So; can it be done. Sure.. easily? That depends on your def of the word easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Mobile and iScroll Problem So I had found a good solution to solve the fixed header and footer problem in jquery mobile which is the iscoll library. To get the iscroll library to work with the jquery mobile, I'm using this third party script: https://github.com/yappo/javascript-jquery.mobile.iscroll Everything works just fine for my listing pages (using jquery mobile list view). My listing pages are loaded dynamically using ajax. But then, when I created a product detail page that is supposed to scroll, it didn't work at all. In some cases, I couldn't scroll at all. In some other cases, the scrolling behaves like rubber band effect, it always brings you back to the top again. But, the header and footer navigation bars are fixed as what I want it to be. So, here is the scenario. I have a listing page (with scrolling), when you click on any list item, you should see the product detail on a different page. The iscroll is triggered on pagebeforeshow event as you can see inside the yappo wrapper script. Here is the template of my product detail page. The content will be dynamically loaded and appended to the scroller div. <!-- PROMOTION DETAIL PAGE --> <div data-role="page" id="page-promotion-detail" data-iscroll="enable"> <div class="header" data-role="header"> <div class="sub-header-bg"> <div class="title"></div> <a href="#" id="Back" data-rel="back" class="btn-header-left btn-back"><span>Back</span></a> <a href="#" id="Edit" class="btn-header-right btn-edit hidden"><span>Edit</span></a> </div> </div> <div class="content" data-role="content" data-theme="anz"> <div data-iscroll="scroller" class="scroller"> <div data-iscroll="scroller"></div> </div> <input type="hidden" id="paramPromotionID" name="paramPromotionID" value="" /> </div> <div class="footer" data-id="footer" data-role="footer"> <div data-role="navbar"> <ul> <li><a id="menuHome" href="#page-home" class="footer-icon footer-icon-home">Home</a></li> <li><a id="menuMySpot" href="#page-myspot" class="footer-icon footer-icon-spot">My Spot</a></li> <li><a id="menuOtherCountries" href="#page-other-countries" class="footer-icon footer-icon-country">Others</a></li> <li><a id="menuSearch" href="#page-search" class="footer-icon footer-icon-search">Search</a></li> </ul> </div> </div> </div> Anyone here knows what i missed out or anyone of you guys managed to get iscroll to work perfectly with jQuery Mobile? I'm using jQuery Mobile beta 3 and iScroll 3.7.1. Cheers A: Without looking at the actual application is hard to tell what the solution might be. In the past I noticed the following issues when using iScroll and jQuery Mobile: * *If the content inside the scrollable area has the CSS rule 'float' iScroll will not be able to determine the height of the content. iScroll will think that there is nothing to scroll. So you may need to check the CSS rules applied to the scrollable content. *jQuery Mobile automatically binds touch event to some elements. When combining iScroll with jQuery Mobile it might be a good idea to bind a separate function to the 'touchmove' event and prevent the event from bubbling up ( event.preventDefault() ). By doing this jQuery Mobile will not be able to handle the touch event while users are interacting with the iScroll element. This are generic recommendation, but I hope they can help you. I wrote a little jQuery extension to integrate jQuery with iScroll. You can get it at: http://appcropolis.com/blog/jquery-wrapper-for-iscroll/ A: I dig deeper into the iScroll documentation and I found out that I need to refresh the iscroll object everytime the DOM changed. This is required because it needs to recalculate the actual height / width after the changes. I should've just learn Objective-C...trying to build apps using HTML is simply too much hassle..at least for now. A: In HTML5 based application, smooth scrolling is always challenging. There are third parties libraries available to implement smooth scroller but there implementation is very complex. In this scroller library, user only need to add scrollable=true attribute in the scrollable division, then that div will scroll like smooth native scroller. Please read readme.doc file first to start working on it library link http://github.com/ashvin777/html5 Advantages : 1 No need the manually create scroller object. 2 Scroller will automatically refreshed in case of any data being changed in the scroller. 3 So no need to refresh manually. 4 Nested Scrolling content also possible with no dual scrolling issue. 5 Works for all webkit engines. 6 In case if user wants to access that scroller object then he can access it by writing “SElement.scrollable_wrapper”. scrollable_wrapper is id of the scrollable division which is defined in the html page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery Mobile dialog fields clearing issue I'm new to jquery mobile and need some assistance in solving an issue. I have four links in a jsp page implemented through jquery mobile framework. Each link on click opens different jquery modal dialogs. Each link opens a new jsp in modal dialog. I have some common fields on all the dialogs and i used same ids for those fields in all the dialogs. The issue is when i open a dialog and enter values and submits the form and comeback to parent page and again open a new dialog, the values of the common fields are showing up in the new dialog. I want to show a form with empty fields whenever i open the modal dialog. Pls help me on how to acheive this. A: Sounds like you are using the same exact JSP for each modal view form. 2 options I see here: * *Clear the inputs on submit of the modal form $('#submit').click(function(){ //Empty fields here $('#name').val(''); }); *Clear inputs on pageinit $('#modalForm').on('pageinit', function(){ $('#name').val(''); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7538129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: javascript to select all checkbox in gridview i am searching for the javascript that performs select all - deselect all feature in asp.net gridview. So if a header checkbox is selected all the item templates checkbox should be selected. if any item template checbox is deselcted, the header checkbox should also be deselected. Thanks A: $('#GridView1 input[type=checkbox]').each(function(){ this.checked=!this.checked;}); Add this on 'select all' button click
{ "language": "en", "url": "https://stackoverflow.com/questions/7538132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change variable value using onchange I want to change the value of value using a change event listener. Is it possible? Here is my sample code: <select name="select1" onchange="updatevariable(this.value)"> <option value="2" >2</option> <option value="15" >15</option> </select> <script type="text/javascript"> value = "test"; function updatevariable(data) { value = data; } alert(value); // It should be 2/15 </script> A: You have alert() in wrong place <select name="select1" onchange="updatevariable(this.value)"> <option value="2" >2</option> <option value="15" >15</option> </select> <script type="text/javascript"> var value = "test"; function updatevariable(data) { value = data; alert(value); } </script> In your code it is loaded right after the script is loaded, you have to modify it to be called right after change
{ "language": "en", "url": "https://stackoverflow.com/questions/7538136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Undefined function or method 'Ei' for input arguments of type 'sym' syms x1 x2 x3 theta gamma beta rho miu sigma; f=-(exp(i*x1)-1)*Ei(1, x2)/(i*x1); Undefined function or method 'Ei' for input arguments of type 'sym' A: the function Ei does either not exist or is not in your matlab path. Edit: this function seems to be new in matlab 2011b, so if you are using an older version of matlab, the function won't be there -> error. Edit2: do you have the Symbolic Math Toolbox installed?
{ "language": "en", "url": "https://stackoverflow.com/questions/7538139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I create a custom token in Drupal 7? I need to create a custom token that can fetch a value from a mapping table based on nids. I need to know the hooks I should implement to create the custom token. A: You'll need to implement hook_token_info() and hook_tokens. The best thing you can do is download the Examples module, there's a module called token_example with well commented example code for how to implement tokens properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Mysql didn't get perfect result in Android Application First Image u can see List of college. When i clicked first college i got perfect result when i clicked last college i didn't get Result..plz help here 1)ListCollege.java//First Activity it's give me list of College//First Image collegelist=(ListView)findViewById(R.id.collegeList); InputStream is = null; String result = ""; //the year data to send ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("searchcollege",search_college)); nameValuePairs.add(new BasicNameValuePair("searchcity",search_city)); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.career4u.org/android/android_connection.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); String result1[]=result.split("\\}\\,\\{"); for(int i=0;i<=result1.length;i++) { result1[i]= result1[i].replace("[{", "").replace("institue_name", "").replace("\"", "").replace("}]", "").replace(":", ""); collegelist.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , result1)); collegelist.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(ListCollege.this,viewCollege.class); intent.putExtra("search_college", ((TextView) view).getText()); startActivity(intent); } }); } }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //parse json data } } 2)viewCollege.java//Second Activity it's give me information of college//second and Third Image String search_college =getIntent().getExtras().getString("search_college"); collegeName.setText(" "+search_college); InputStream is = null; String result = ""; //the year data to send ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("searchcollege",search_college)); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.career4u.org/android/android_collegeDetail.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); **collegeAddress.setText(result);//Display Mysql Result in JSON** //String result1[]=result.split("\\}\\,\\{"); //for(int i=0;i<result1.length;i++) //{ // result1[i]= result1[i].replace("[{", "").replace("institue_name", "").replace("\"", "").replace("}]", "").replace(":", ""); //} }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } } } A: Look at this part of yout code: for(int i=0;i<=result1.length;i++) { result1[i]= result1[i].replace("[{", "").replace("institue_name", "").replace("\"", "").replace("}]", "").replace(":", ""); collegelist.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , result1)); collegelist.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(ListCollege.this,viewCollege.class); intent.putExtra("search_college", ((TextView) view).getText()); startActivity(intent); } }); } You are Overriding the adapter and itemclicklistener of all items while looping collegelist.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , result1)); collegelist.setOnItemClickListener(new OnItemClickListener()... First what you need to do is save the result in result1 parsing it. After the loop Override the adapter , you must program the onclicklistener , using the arrayData to know which item is (with the position) are you clicking in . Maybe it can be easy for you to have an auxiliar array to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: new discovery of retain ,or my misunderstanding? @interface DataMode : NSObject { NSString * name; } @property (retain) NSString * name; - initWithName:(NSString * )name_; @end @implementation DataMode @synthesize name; - initWithName:(NSString * )name_ { if ([super init] != nil) { name = name_; return self; } return nil; } @end - (void) pressed:(id)sender { NSString * str = [NSString stringWithFormat:@"zhang"]; DataMode * a = [[DataMode alloc] initWithName:str]; a.name; a.name; a.name; a.name; a.name; NSLog(@"name count:%d",[a.name retainCount]); [ a release]; NSLog(@"str count:%d",[str retainCount]); } @end the output is name count:7 str count:7 but the code don't leak any memory. I get the result in leaks and Active monitor tools. begin I am surprise because SomeBody say "@property (retain) name;" eaual the below equal method. - getname { return name; } if that .it can't explain the above reslut of the output I think the method should so - getname { [name retain]; [name autorelease]; return name; } so this can explain the high number 7,and not leak any memory. this is my guess . it take me too much time .I am shamed. My understanding is right ??? welcome your post and comment. A: "SomeBody" is wrong. From The Objective-C Programming Language: If you specify retain or copy and do not specify nonatomic, then in a reference-counted environment, a synthesized get accessor for an object property uses a lock and retains and autoreleases the returned value—the implementation will be similar to the following: [_internal lock]; // lock using an object-level lock id result = [[value retain] autorelease]; [_internal unlock]; return result; If you specify nonatomic, a synthesized accessor for an object property simply returns the value directly. A: 1) retainCount is useless to you. 2) retainCount is useless to you. 3) yes, your properties should use retain+autorelease (there are a few cases where you can break this rule -- i'll not detail them here) - (NSString *)name { return [[name retain] autorelease]; (note that this also is not threadsafe, nor are properties) 4) your NSString properties should be declared copy (not retain) 5) your initWithName: should copy the argument name_ (assuming the property is copied) name = [name_ copy]; A: Given that you are new to the environment, you should most likely be using ARC and not worrying about this kind of stuff at all. retainCount is useless. Don't call it. To repeat: retainCount is useless. Don't call it. It is not useful for finding leaks as there are much better, more accurate, and less misleading tools available. There are several problems with your code (but leaking isn't one of them): * *NSString* properties should be copy *you don't use the property to set the string value in init, thus the DataMode instances are not retaining their strings. *there is no dealloc method Since you used stringWithFormat:, the constant string is turned into a non-constant string. If you had used the constant string or stringWithString:, it'd be abazillionsomething (unsigned -1... UINT_MAX...). In any case, you have: * *+1 for stringWithString: *+1 for calling a.name, every time it is called If Instruments is claiming a leak, post a screenshot. A: You shold type - initWithName:(NSString * )name_ { self = [super init]; if (self != nil) { name = name_; } return self; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7538151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSF h:panelGrid with ui:repeat My problem is ui:repeat inside a h:panelGrid. Its a big table from a list of objects.. All objects are saved in one list. I tried this: <h:panelGrid columns="1000"> <ui:repeat var="item" value="#{item.list}"> <h:outputText value="#{item.string}" /> </ui:repeat> </h:panelGrid> but inside a panelGrid the ui:repeat tag is one column for the grid. So all items are in one td tag. Is there a possibility to get the right column count? A: In that case you can use c:forEach instead of ui:repeat. c:forEach will cause a separate UIOutputText component in components tree for each item in the list. For more information on difference between c:forEach and ui:repeat refer here
{ "language": "en", "url": "https://stackoverflow.com/questions/7538154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trouble to open application on Blackberry Simulator I am trying to open my application on simulator 9800.i am using JDE 6.0.when i tried to debug my application i got some message on my console. [0.0] UIE: Foreground app package.MyApp@ has no screens. This should be corrected. [0.0] UIE: Foreground app package.MyApp@ ignoring touchscreen touch/click because it has no targ[0.0] et screen. My other applications are working fine.I have reinstalled my simulator but still probelm is occuring.need your suggestions. A: Sometimes clean and rebuild solves this problem, did you tried? A: Experiencing the same issue, with device B-9900. Re-installation of application helped me in solving the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Converting CvSeq to CvMat I have a sequence of CvPoint2D32f points in CvSeq and I want to convert it into a CvMat. How can I do that? A: Have a look at cvSeqToArray. It will dump the sequence to a contiguous array of any type (in your case, it will be float). You can then create a matrix header for that array by using cvCreateMatHeader.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Ruby, how can I remove numeric words from a phrase without splitting phrase into words and losing word delimiters? I am trying to remove numeric words from a phrase. I am writing the following: phrase = 'hello 234234 word' words = phrase.split(/\W/) words.reject!{ |w| w.match(/^\d+$/) } words.join(' ') or, one-liner: phrase = phrase.split(/\W/).reject{ |w| w.match(/^\d+$/) }.join(' ') Example: "hello 123 word" should end "hello word" "hello 123word" should end "hello 123word" "hello 123.word" should end "hello word" The problem with this solution is that it removes the word delimiters too. (See the 3rd example above) Is there a better, neater way to do that and save word delimiters at the same time? A: This regex does the job: phrase.gsub!(/\b\d+\b/, "") This gsub gets rid of the numeric words. A: I would do it like this: phrase.gsub!(/ \d+ /, " ") The brackets are required to prevent ruby thinking that you're trying a line-continuation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is wrong with the below PostgreSql insert function.. throwing error I have written a function in PostgreSQL which accepts two parameters viz varchar and int . The aim is to insert record CREATE OR REPLACE FUNCTION fnInsert(varchar,int) RETURNS void AS 'BEGIN Insert Into testtable(col1,col2) values ($1,$2) RETURN; END;' LANGUAGE plpgsql; But while trying to compile it is throwing error ERROR: syntax error at or near "RETURN" LINE 4: RETURN; ^ ********** Error ********** ERROR: syntax error at or near "RETURN" SQL state: 42601 Character: 173 If I take out the RETURN statement, I am getting the below error ERROR: syntax error at or near "END" LINE 4: END;' ^ ********** Error ********** ERROR: syntax error at or near "END" SQL state: 42601 Character: 173 Please help me in identifying what is wrong here? Thanks A: It's probably complaining about the lack of semicolon after Insert Into testtable(col1,col2) values ($1,$2)
{ "language": "en", "url": "https://stackoverflow.com/questions/7538164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating a value using jquery I have created a shortlist system, its like what is used on realestate websites so you can make a list of favorites (using a session arrray) which you can come back to. The system uses jquery to update the session array with a new shortlist item. What I am not sure how to do is update the 'shortlist/ array count' using jquery. I know how to change the HTML of an id, but how could I retrieve the session count and + 1 when something has been added a new item to the array. Here is how I display my 'shortlist count': Shortlist: " (view) A: Until you post code of element containing the html of the part of page you want to update, no one will be able to help you much, but lets say that you have something like this: <div id="shortlist"> You have <span id="itemCount">2</span> items in your cart. </div> You can update value from jQuery like this: var oldValue = $("div#shortlist").find("span#itemCount").text(); var newValue = parseInt(oldValue) + 1; $("div#shortlist").find("span#itemCount").text(newValue); Updating your html, which looks like: <div id="shortlist">3 (<a href="/shortlist">view</a>) </div> would be much simpler if you would change php to something like: <div id="shortlist"><span id="itemCount"><? echo count($_SESSION['shortlistArray']); ?></span>" (<a href="/shortlist">view</a>) </div> It is good to have value to update in html element you can identify through jQuery. If this is not option, then you need to update value using string.replace (probably searching for regex if you don't now old value?).
{ "language": "en", "url": "https://stackoverflow.com/questions/7538166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to get json data in jquery How can I get the comments from below json data? { "data": [ { "id":"123", "from":{"name":"name","id":"12"}, "message":"Message", "comments": { "data": [ { "id":"342", "from":{"name":"name","id":"32"}, "message":"comment message 1" }, { "id":"341", "from":{"name":"name","id":"21"}, "message":"comment message 2" } ], "count":2 } } ] } I know how to get id, from and message. but I do not know how can I get data inside comments. here is my jquery code $.getJSON(newsfeed_url,function(d) { $.each(d.data, function(i,res) { html += "<div class='container'>"; html += "<li>"+ res.from.name +"</li>"; html += "<li class='message'>" + res.message + "</li>"; html += "<li>Comments: " + res.comments.count + "</li>"; $.each(res.commments.data, function(i, comment) { html += "<li class=''>" + comment.message + "</li>"; }); html += "</div>"; }); html += "</ul>"; $("#contents").html(html); }); my current code does get res.from.name, res.comments.count but it does not get data inside comments i.e. res.comments.data. how can I achieve it? here is my actual json file. The above one I gave was example. here it goes { "data": [ { "id":"7234234234_32423432", "from":{"name":"name","id":"34534534534"}, "message":"Näyttelyn puoliväli/kolmas viikko.\n\nhttp://alastonkriitikko.blogspot.com/2011/09/nayttelykuvia-458-459-kadulla-ja.html", "picture":"http://external.ak.fbcdn.net/safe_image.php?d=AQAWGCUrr4QBEFXk&w=90&h=90&url=http%3A%2F%2F1.bp.blogspot.com%2F-pBAudI2423s%2FTm7y-ajz62I%2FAAAAAAAAE6g%2F-K4s1sfrYpI%2Fs72-c%2FIMG_1737.JPG", "link":"http://alastonkriitikko.blogspot.com/2011/09/nayttelykuvia-458-459-kadulla-ja.html", "name":"name: Näyttelykuvia 458 & 459: Kadulla ja studiossa", "caption":"alastonkriitikko.blogspot.com", "description":"Näyttelykuvia ja kritiikkejä sekä metakritiikkiä, päiväkirjamerkintöjä ja satunnaisia hajahuomioita taiteesta – sekä nähdystä että luetusta", "icon":"http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif", "actions": [ {"name":"Comment","link":"http://www.facebook.com/23432354/posts/324534543546565"}, {"name":"Like","link":"http://www.facebook.com/759688182/posts/274846375878348"} ], "type":"link", "created_time":"2011-09-13T09:47:23+0000", "updated_time":"2011-09-13T09:58:30+0000", "comments": { "data": [ { "id":"3242342343_345878348_4012650", "from":{"name":"name","id":"4534544"}, "message":"hitto. pitää ehtiä näkemään. Niin pitkä on matka kantsusta keskustaan...", "created_time":"2011-09-13T09:51:29+0000" }, { "id":"32453543534_34534534348_4012674", "from":{"name":"name","id":"54654654645"}, "message":"Ainakin verraten tähän matkaan Sörkästä keskustampaan, joka usein väittää itseään minulle liian pitkäksi.", "created_time":"2011-09-13T09:58:30+0000" } ], "count":2 } } ] } It is still not working. BTW I am not taking data from facebook or somewhere else. I have local .json file and from there I get data. The object which it says is undefined is "res.comments.data". here is my whole code $(function() { var newsfeed_url = "json_data/newsfeed.json"; var html = "<ul>"; $.getJSON(newsfeed_url,function(d) { $.each(d.data, function(i,res) { var userid = res.from.id; var username = res.from.name; var msg = res.message; var date_time = res.created_time; //var like = res.created_time; var url = "https://graph.facebook.com/" + userid + "/picture"; var pUrl = "http://www.facebook.com/profile.php?id=" + userid; html += "<div class='container'>"; html += "<li class='profile_image'><img src='" + url + "' /></li>"; html += "<li class='from_name'><a href='" + pUrl + "'>" + username + "</a></li>"; html += "<li class='message'>" + msg + "</li>"; html += "<li class='time_ago'>" + relative_time(date_time) + "</li>"; $.each(res.actions, function(i, action) { html += "<li class=''><a href='" + action.link + "'>" + action.name + "</a></li>"; //html += "<li class=''>Link: " + action.link + "</li>"; }); html += "<li>Comments: " + res.comments.count + "</li>"; //html += "<li>Likes: " + res.likes.count + "</li>"; //html += "<li>Comments: " + res.comments.data + "</li>"; alert(res.comments.data); $.each(res.comments.data, function(j, comment) { //alert(comment.message); html += "<li class=''>" + comment.message + "</li>"; }); //alert(res.comments.data); html += "<li class='no_float'></li>"; html += "</div>"; //newsfeed(userid, username, msg, date_time, like); }); html += "</ul>"; $("#contents").html(html); }); //display message short. function short_msg(msg, un) { var limit = 80; if(un) return msg.length > 30 ? msg.substring(0, 30) : msg; else return msg.length > limit ? msg.substring(0, limit) + "..." : msg; } //function which displays date and time in readable format function relative_time(date_str) { if (!date_str) {return;} var s = $.trim(date_str); s = s.replace(/\.\d\d\d+/,""); // remove milliseconds s = s.replace(/-/,"/").replace(/-/,"/"); s = s.replace(/T/," ").replace(/Z/," UTC"); s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400 var parsed_date = new Date(s); var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); //defines relative to what ..default is now var delta = parseInt((relative_to.getTime()-parsed_date)/1000); delta=(delta<2)?2:delta; var r = ""; if (delta < 60) r = delta + " seconds ago"; else if(delta < 120) r = " a minute ago"; else if(delta < (45*60)) r = (parseInt(delta / 60, 10)).toString() + " minutes ago"; else if(delta < (2*60*60)) r = " an hour ago"; else if(delta < (24*60*60)) r = "" + (parseInt(delta / 3600, 10)).toString() + " hours ago"; else if(delta < (48*60*60)) r = "a day ago"; else r = (parseInt(delta / 86400, 10)).toString() + " days ago"; return r; } }); A: Here is a working example, just replace with your app id: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <meta charset=utf-8 /> <title>Loop</title> <style> ul {list-style: none;} </style> </head> <body> <div id="content"></div> <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.init({ appId : 'APP_ID', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true, // parse XFBML oauth : true // enable OAuth 2.0 }); FB.login(function(response) { if (response.authResponse) { console.log('Welcome! Fetching your information.... '); FB.api('/me/posts', { limit: 3 }, function(d) { if(!d.data.length) return; var html = ""; $.each(d.data, function(idx, post) { html += "<div class='container'>"; html += "<ul>"; html += "<li>Name: "+ post.from.name +"</li>"; if(post.message) html += "<li class='message'>Message: " + post.message + "</li>"; if(post.comments) { if( post.comments.count > 1) html += "<li>There are " + post.comments.count + " comments</li>"; else html += "<li>There is one comment</li>"; html += "<li><ul>"; $.each(post.comments.data, function(i, comment) { html += "<li class=''>" + comment.message + "</li>"; }); html += "</ul></li>"; } html += "</ul>"; html += "</div>"; }); $('#content').html(html); }); } else { console.log('User cancelled login or did not fully authorize.'); } }, {scope: 'read_stream'}); }; (function(d){ var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; d.getElementsByTagName('head')[0].appendChild(js); }(document)); </script> </body> </html> Your code is fine you only have one typo in the comments loop: $.each(res.commments.data, function(i, comment) { If you know the structure of the response, which is the case, you don't need to use the first $.each: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <meta charset=utf-8 /> <title>Loop</title> </head> <body> <script> $(document).ready(function() { $.getJSON('json.php', function(d) { if(!d.data[0]) return; var html = ""; var result = d.data[0]; html += "<div class='container'>"; html += "<ul>"; html += "<li>"+ result.from.name +"</li>"; html += "<li class='message'>" + result.message + "</li>"; if(result.comments) { html += "<li>Comments: " + result.comments.count + "</li>"; $.each(result.comments.data, function(i, comment) { html += "<li class=''>" + comment.message + "</li>"; }); } html += "</ul>"; html += "</div>"; $('body').html(html); }); }); </script> </body> </html> json.php: <?php $var = <<<EOD { "data": [ { "id":"123", "from":{"name":"name","id":"12"}, "message":"Message", "comments": { "data": [ { "id":"342", "from":{"name":"name","id":"32"}, "message":"comment message 1" }, { "id":"341", "from":{"name":"name","id":"21"}, "message":"comment message 2" } ], "count":2 } } ] } EOD; echo $var; ?> A: That's because you're iterating comments.data already! What's the deal? Your d is a normal JS object (an array in this case), so you can do function (d) { alert(d[0].comments.data);} or function (d) { $.each(d, function (i, res) { alert(res.comments.data); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7538171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using const_iterator when overloading a const operator[] I really do not understand what I am doing wrong below. I have a class named Settings with the structure listed below, and two of the functions listed below as well. What I am having trouble with is specifically where to put the const modifiers when overloading a const operator[] within the overloading function. Do I need to use const_cast somewhere? What am I missing? class Settings { map<string, string> settingsMap; map<string, string>::const_iterator itc; const string getValue(string) const; public: const string operator[](string) const; }; const string Settings::operator[](string K) const { return getValue(K); } const string Settings::getValue(const string K) const { const map<string, string> m = settingsMap; itc = m.begin(); while(itc != m.end()) { if(itc->first==K) return itc->second; itc++; } return 0; } Thanks in advance. A: If your function getValue() modifies the member itc, then it can't be const (unless itc is mutable). I suggest you declare itc in the function getValue(): ... const map<string, string> m = settingsMap; imap<string, string>::const_iterator itc = m.begin(); ... A: the operator[] in c++ has two meanings: (1) a[i] = x; //store x into a in position i (2) x = a[i]; //load a in position i to x The first one must change the structure... and thus the structure cannot be const, so you should drop the last const for this: const string operator[](const string); [note that the parameter in here is const string and not string, since it should probably not be changed. in addition, since the output string shouldn't probably be changed, it should be defined as const as well. The 2nd one, should probably return a string, and not a const string, so you should probably drop the first const: string operator[](const string) const; [since the original structure for this op is not changed, the last const is good and should remain]. In addition note the parameter is a const string and not a string, since you do not want to cahnge the parameter. In your case: It seems you want the 2nd meaning for the operator[], thus you should declare it as: string operator[](const string) const; A: Your problem is not with the const but with references. Also your declarations in the class must match exactly the definitions you use when defining the functions. class Settings { map<string, string> settingsMap; map<string, string>::const_iterator itc; const& string getValue(const string& K) const; // ^^^^^ Added const to match definition below. // Also note the reference. This means you are referring // to the original value but because the reference is const // it cant be modified via this reference. // ^^^^^^ This const means the returned value is const. // unless you return a reference this is meaningless. // So also note the reference here are well. // ^^^^^^ The last const means the method will // NOT change the state of any members. public: const string& operator[](const string&) const; // ^^^^^^^^^^^^^ As above return a const reference. // ^^^^^ As above pass parameters by const reference // otherwise it makes a copy of the parameter. // ^^^^^ function will not change any members. }; const string& Settings::operator[](const string& K) const // Must match above definition. { return getValue(K); } const string& Settings::getValue(const string& K) const { const map<string, string> m = settingsMap; // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ As this is an object (not a reference) // You are making a copy of the object into a local variable. // This is probably not what you want. const map<string, string>& m = settingsMap; // This works. itc = m.begin(); while(itc != m.end()) { if(itc->first==K) return itc->second; itc++; } return 0; // ^^^^^^^^ This is not a good idea. // It is creating a string from a NULL pointer (0 is convertible to pointer). // What you really wanted to do is return a string. This is also why your // return type was not working as you expected. static const string emptyResult; // create a static object to use as the empty result return emptyResult; } A: In your declaration: const string operator[](string K) const; if you want just to read (and copy) the contents of the map, then the correct declaration should be: const string operator[](const string &k) const; The return type should be const, otherwise you may be able to modify a temporary value, and this is not correct. The argument can be passed by const reference, since you are not modifying it. With this declaration, the following two lines of code will give you an error: ... s["abc"] = "cde"; // cannot modify, the return type is const s["abc"] += "efg"; // cannot modify, the return type is const The const after the prototype declaration just tell you that operator[] does not modify the object, so it has to do with the code inside the method operator[], and not about its usage. For this reason, the const_iterator should be defined as local variable inside operator[] code. The const on the return type avoids the possibility that you modify a temporary value (the return type). For efficiency, you can obtain the same result by returning a const reference. const string& operator[](const string &k) const; Of course, if you want to modify the Settings container with operator[], then you should return a non const reference. string& operator[](const string &k);
{ "language": "en", "url": "https://stackoverflow.com/questions/7538174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: convert string to NSDate object I am getting string "2011-09-24T00:30:00.000-07:00" from webservice. I don't know the what is this format and want to convert in date object in objective-c. So any know how to convert this string to date. Thank you very much A: There is a small problem obtaining the date/time from this format, the ':' in the timezone, that will need to be removed, Apple does not handle this case nor it is a proper UTS format. Here is an example: NSString *dateString = @"2011-09-24T00:30:00.000-07:00"; dateString = [dateString stringByReplacingOccurrencesOfString:@":" withString:@"" options:0 range:NSMakeRange(dateString.length-3, 1)]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"]; NSDate *date = [formatter dateFromString:dateString]; NSLog(@"date: %@", date); NSLog output: date: 2011-09-24 07:30:00 +0000 As a test displaying the date just created: NSString *testDateString = [formatter stringFromDate:date]; NSLog(@"date: %@", testDateString); NSLog output: date: 2011-09-24T03:30:00.100-0400 Note that the time and time zone have been converted to my local time zone by NSLog, taking both changes into consideration the date/time are the same as the original. A: The string format typically used by web services for date/time representation is RFC 3339 It cannot be trivially converted to and from NSDate because it may include a variety of information not representable just by NSDate (such as time offset from UTC, and date with no time specified.) There are classes which map RFC 3339 strings to and from native Cocoa types, such as this. You may be able to get by with a simpler conversion that takes shortcuts, but for robust code, use a class written specifically to handle the representation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get rid of the xmlns declarations inserted by the XmlSerializer? I have this type: [Serializable, DataContract] public class A { [DataMember(Order = 1)] public int P1 { get; set; } [DataMember(Order = 2)] public XmlSerializableDictionary<string, string> P2 { get; set; } } Where XmlSerializableDictionary is borrowed from .NET XML serialization gotchas?. The XmlSerializer produces the following XML: <?xml version="1.0"?> <A xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <P1>17</P1> <P2> <item> <key> <string>Hello World!</string> </key> <value> <string>xo-xo</string> </value> </item> <item> <key> <string>Good Bye!</string> </key> <value> <string>xi-xi</string> </value> </item> </P2> </A> The only things that I wish to get rid of are the xmlns declarations on the root element. How do I do it? Thanks. A: Via XmlSerializerNamespaces: var ns = new XmlSerializerNamespaces(); ns.Add("", ""); // this line is important... honest! var ser = new XmlSerializer(type); ser.Serialize(destination, obj, ns);
{ "language": "en", "url": "https://stackoverflow.com/questions/7538179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: 2D php array into an HTML table How can I achieve with a PHP array, to have as result in an html table the following result: Server1 db_1 Server1 db_2 Server1 db_3 Server2 db_1 Server2 db_2 Server3 db_3 A: Like this? $servers = array( 'Server 1' => array( 'db_1', 'db_2', 'db_3' ), 'Server 2' => array( 'db_1', 'db_2' ), 'Server 3' => array( 'db_3' ) ); echo '<table>'; foreach($servers as $server=>$dbs) { foreach($dbs as $db) { echo '<tr><td>'.$server.'</td><td>'.$db.'</td></tr>'; } } echo '</table>';
{ "language": "en", "url": "https://stackoverflow.com/questions/7538184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I customize the position of a QuickAction? I have a clickable FrameLayout and I want to display a few quick actions on top of it after a long press. I can create a QuickAction to pop out of it like the old Twitter app, but I'm not sure how to display it like the current one. A: It's been a while but like I promised in the comment section: Here's the Twitter like feature you were asking for which works without a list view. You will find all information in my answer to Twitter for Android like swipe-to-side quick menu
{ "language": "en", "url": "https://stackoverflow.com/questions/7538188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading web user controls from blob storage in asp.net I am storing user control file in some other location may be in blob storage or some other place. ( not in my project work space ) and i store the url of the user control in database . Now how can load this usercontrol to my web page ? A: I'd used following approach to load .ascx controls. In fact I've saved .ascx files into "text" field. First of I've register a control in web.config file: <pages> <controls> <add tagPrefix="tab" src="~/pg.ascx" tagName="Test"/> </controls> </pages> In webform, I read .ascx content from the database and save it to pg.ascx under the root and load user control dynamically. Control t = LoadControl("~/pg.ascx"); PlaceHolder1.Controls.Add(t); EDIT: I'm adding a user control definition which I've stored into StringBuilder object. System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("<%@ Control Language=\"C#\" ClassName=\"m1\" %>"); sb.Append("<script runat=\"server\">"); sb.Append("int no=10;"); sb.Append("public void page_load(){ for(int i=1;i<=no;i++) { Response.Write(i);} }"); sb.Append("</script>"); sb.Append("<h1>Hello</h1>"); System.IO.File.WriteAllText(MapPath("~/pg.ascx"), sb.ToString()); Control t = LoadControl("~/pg.ascx"); PlaceHolder1.Controls.Add(t);
{ "language": "en", "url": "https://stackoverflow.com/questions/7538194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error in linq join query in MVC 4 I am trying this query: public ActionResult Index() { var topics = from t in db.Topics join subs in db.Subjects on t.SubID equals subs.SubID join mems in db.Members on t.MemberID equals mems.MemberID select new ViewModel { TopicID = t.TopicID, TDate = t.TDate, Title = t.Title, FileName = t.FileName, Displays = t.Displays, Description = t.Description, SubName = subs.SubName, FLName = mems.FLName }; return View(topics); } But it causes the following Error: The entity or complex type 'MySiteModel.ViewModel' cannot be constructed in a LINQ to Entities query. I have an Entitity Class with above fields. What is the problem? ???? A: Try convert it to List<> first. var topics = (from t in db.Topics join subs in db.Subjects on t.SubID equals subs.SubID join mems in db.Members on t.MemberID equals mems.MemberID select new ViewModel { TopicID = t.TopicID, TDate = t.TDate, Title = t.Title, FileName = t.FileName, Displays = t.Displays, Description = t.Description, SubName = subs.SubName, FLName = mems.FLName }).ToList(); Hope it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7538197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does rails 3.1 include the entire jQuery library? I have been really puzzled because I was trying to work out some jQuery tutorials in coffeescript for rails 3.1 and it seems like none of the animation functions of jquery work. For example, this does nothing: /assets/javascripts/my_controller.js.coffee: $(document).ready -> $('p:first').fadeIn() However, if I do this: $(document).ready -> alert($('p:first').text()) I do get the correct text. Can anyone tell me what is going on here? THANK YOU EVERYONE, and thanks Trevor for reading my mind. Thanks Benoit for helping me to properly use the site. My final answer below. A: I dug around a bit and found this: (from http://api.jquery.com/visible-selector/) Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout. During animations that hide an element, the element is considered to be visible until the end of the animation. During animations to show an element, the element is considered to be visible at the start at the animation. How :visible is calculated was changed in jQuery 1.3.2. The release notes outline the changes in more detail. So, using the correct style, or the toggle functions in jQuery are the right option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: chrome extension javascript problem I started trying to write chrome extension and I'm having problem with simple function: script inside "backgroound.html": chrome.tabs.onUpdated.addListener(function(tabId,changedInfo,tab){alert("a")}); manifest.json file: { "name": "ogys", "version": "1.0", "description": "description", "browser_action": { "default_icon": "icon.png", "background_page": "background.html" }, "permissions": ["tabs", "http://code.google.com/"] } I understand that an change on any tab would trigger the event but nothing happends. A: According with code.google.com, you've defined the backround_page in the wrong place. Move the background_page property definition outer from browser_action action in this way: { "name": "ogys", "version": "1.0", "description": "description", "browser_action": { "default_icon": "icon.png" }, "background_page": "background.html", "permissions": ["tabs", "http://code.google.com"] }
{ "language": "en", "url": "https://stackoverflow.com/questions/7538202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to store huge numbers in PHP I need to convert a number from 36-th base into an integer. The original number length is about 10 characters which seem to be bigger then PHP's limits for integers. In my case the original number looks like this: 9F02tq977. When converted I get the following result 8.46332972237E+12. How can I store huge numbers in PHP? A: Since BC Math doesn't work with arbitrary base numbers, you could try using GMP functions if you have them available. http://www.php.net/manual/en/ref.gmp.php Otherwise you'll probably have to rewrite your algorithm and write your own arbitrary precision arithemtic implementation of the validation algorithm. A: Use a math library like BC Math for big numbers :) http://be2.php.net/manual/en/book.bc.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7538207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: block reading in perl I need to read one block from file and then need to match the particular patterns and get the values for the matched pattern. > Call report:$VAR1 = { > 'service_status' => 'DIAL-IN-SEQUENTIAL', > 'called_id' => '761', > 'id' => '41298', > 'redirect_number' => undef, > 'profile_id' => '137', > 'not_answered_action' => '0', > 'call_landed_day' => '1', > 'call_end_status' => 'CALLER_HANGSUP', > 'announce_caller_type' => '0', > 'user_id' => '143', > 'follow_me_group' => '135', > 'call_end_time' => '29/11/2010 09:39:57', > 'findme_id' => '135', > 'fmsonenumber' => '43902761', > 'profile_cause' => 'IMMEDIATE_OVERRIDE', > 'fms_id' => '85dd3b2a-fb6e-11df-a0b0-a1f3d600a5a6', > 'caller_type' => 'UNKNOWN', > 'fms_type' => 'FOLLOWME', > 'profile_desc' => 'office', > 'caller_id' => '43902761', > 'call_landed_time' => '29/11/2010 09:39:55' > }; From the above block I need to read the block between two { } braces.After that I want to match the particular pattern like service_status and then after matching the service_status pattern should retrieve the value of the service_status as DIAL-IN-SEQUENTIAL.Likewise I need to match the patterns in some of the lines and get the values for that patterns. How can we achieve this?. If anyone know the way to solve this pls give me the solution. Thanks in advance. A: You can process the file so that it became a valid perl module that contains a definition of an array of hashes. Write a filter (or do it with emacs/vim or your favorite editor) to substitute the "Call report:$VAR1 = {" to a statement that pushes the hash into an array, something like "push @all_hashes, {". Then you can use the module and iterate through the variables as normal perl hashes. A: Well, given the constraints my solution is rather ugly, but you can get it as a regexp exercise ( but you can avoid it ): #!/usr/bin/env perl use v5.12; use strict; open my $fh, '<', 'block.txt'; while ( <$fh> ) { if ( /^[^}^{]++$/ .. /^[^}]++$/ ) { if ( /(?<='service_status' => )'([^']+)'/ ) { say $1 }; } } Just note how I used the flip-flop operator in the first conditional, and the positive lookbehind in the second conditional. The first conditional returns true when it finds a line without open or closed curly brace; it keeps returning true until it finds a line with a closed curly brace, when it returns false. With this kind of a filter you get only lines between those with braces.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ways to get location of the client from the browser? What i need is the lat/long of the client(via browser) Found some articles on the net,found some in stack overflow itself(an old article) Get GPS location from the web browser. it was answered almost 18months ago -- wondering if there's any other(more efficient) way of getting the information of the location of the user from the browser. Soo far,found 2 using Maxmind * *http://coding.smashingmagazine.com/2010/03/08/entering-the-wonderful-world-of-geo-location/ Other,using google's api * *http://briancray.com/2009/05/29/find-web-visitors-location-javascript-google-api/ w3c's geo api will have downward compatibility issues: http://dev.w3.org/geo/api/spec-source.html ,so not choosing that. Found a site, www.drumaroo.com -- requests for the location to be shared the 1st time when we drop into the site.Needed something similar A: The user can be located by using following ways:- * *Using the IP addr. easiest to achieve but most unreliable due to the uncertainty of network addresses / topologies. *Using the latitude, longitude pair most accurate solution, but most of the end users don’t know about their latitude, longitude value. *Using the zipcodes nice to think but quite difficult to achieve, although ZipCodes are being used for quite a long time but this is not a standard yet. (see link http://en.wikipedia.org/wiki/Postal_code ). ZipCode alone is not sufficient for calculation of distance we need to convert it to latitude, longitude pair which is an overhead. *Using user’s address most compelling thought since each user will have at least one geographic address. Address alone is not sufficient for calculation of distance we need to convert it to latitude, longitude pair which is an overhead. The Best option will be to use options 2,3.4 together, You can do that in two steps:- * *First determine the latitude, longitude from the address. *Then use this lat, long value for further processing i.e. storing in database etc. For various options available for this see the answer of this question A: Try HTML5 geolocation function init() { var mapOptions = { zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var infowindow = new google.maps.InfoWindow({ map: map, position: pos, content: 'Location found using HTML5.' }); map.setCenter(pos); } } else { alert('Geolocation not detected'); } } A: Here is geolocation described: http://www.w3schools.com/htmL/html5_geolocation.asp The lat/lng can then be reverse-geocoded to find the country, address. etc. https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse A: https://developers.google.com/maps/documentation/javascript/examples/map-geolocation . simply click on javascript+html and copy the code into an html file. A: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Reverse Geocoding</title> <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> var geocoder; if (navigator.geolocation) { var location_timeout = setTimeout("geolocFail()", 10000); navigator.geolocation.getCurrentPosition(function(position) { clearTimeout(location_timeout); var lat = position.coords.latitude; var lng = position.coords.longitude; geocodeLatLng(lat, lng); }, function(error) { alert("inside error "); clearTimeout(location_timeout); geolocFail(); }); } else { alert("Turn on the location service to make the deposit"); // Fallback for no geolocation geolocFail(); } function geolocFail(){ alert("Turn on the location service to make the deposit"); document.write("Turn on the location service to make the deposit"); } /*if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(successFunction, errorFunction); } //Get the latitude and the longitude; function successFunction(position) { var lat = position.coords.latitude; var lng = position.coords.longitude; codeLatLng(lat, lng) } function errorFunction(){ alert("Geocoder failed"); } */ function initialize() { geocoder = new google.maps.Geocoder(); } function geocodeLatLng(lat, lng) { var latlng = new google.maps.LatLng(lat, lng); geocoder.geocode({'latLng': latlng}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { console.log(results) if (results[1]) { //formatted address var add= results[0].formatted_address alert(add); //city data //alert(city.short_name + " " + city.long_name) } else { alert("No results found"); } } else { alert("Geocoder failed due to: " + status); } }); } </script> </head> <body onload="initialize()"> </body> </html> A: This is HTML code to trace the device(Browser/Mobile) location .Just save the above file as .html extension and browse it from any browser on your system or Mobile ,it will display the user current location.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: HTML5 Audio m4a Is it possible to play m4a music files using html5 audio? If that is not possible do you know of any flash player that can play m4a outside JWPlayer, I need a free one. A: Any Flash player should be able to play MP4 content - this capability is coded into Flash, not the player product built on top of it. JPlayer is a nice free player that uses HTML5 where it can, and falls back on Flash when it can't. A: You can use Soundmanager2 which can use Flash fallback if HTML5 does not natively support M4A. http://www.schillmania.com/projects/soundmanager2/ M4A should be supported by the browsers from companies who support MPEG-4 video and are the licensees of MPEG4-LA patents (Microsoft, Apple).
{ "language": "en", "url": "https://stackoverflow.com/questions/7538215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sass excluding application.css file for a page I just upgraded my project from Rails 3.0.7 to 3.1.0 and I see that I can use SASS now. I have a page in my application which is just a promotional page at /home/subscribe.html.erb and I would like it to not inherit the css declarations being used throughout the application like the scaffold.css. There is a separate subscribe.css file which I would like it to inherit ONLY. Even though I have gone inside my application.css.scss and changed it to have only: @import "scaffold.css.scss"; the application.css.scss still gets inherited as a part of the application in to the subscribe page. can you please suggest how to make the subscribe page ONLY use the subscribe.css file and no other css? A: Create a new layout that has a css tag that directly targets the css file you wish to import rather than application.css.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I find user by username rather than email in ruby on rails 3.1? I've tried a few things but can't seem to get my head round it. I've been practicing and know how to do this using email but how can I do it using username? def self.authenticate(username, password) user = find_by_name(username) if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) user else nil end end A: Change user = find_by_name(username) to user = find_by_username(username)
{ "language": "en", "url": "https://stackoverflow.com/questions/7538221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: show view count on rss feed in drupal i have a drupal site and i want to add to the RSS feed a view count what that i found that should do this is this code but so far i get a null value <?php print $node->links['statistics_counter']['title']; ?> and i can't run any SQL query because i can't match the nodes for it. i also tried to do: print_r($node->links['statistics_counter']); and also i get an empty array any help is appreciated A: This should work: <?php print $node->links['statistics_counter']['title']; ?>. Be sure that you print it in teaser mode, not in full view ($page == 1). If not, visit http://YOURSITE/admin/reports/settings and enable access log. p.s. Also Views module provide more powerfull feed page with any data and filters.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to covert a mdf into excel sheet i have installed SQL server Express Edition 2005 by using my application i am saving data in tables which is created in SQL Server so that i have to copy in that data in to excel file any please help me how to do this A: Read data from MsSql table and write each row into CSV file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I get the CPU and Memory useage I want to know the memory and CPU usage in php, because I'm using cronejobs sometimes the CPU is overloaded so in this case I don't wan to start more process, I just want to skip this cron. A: Take a look at this library http://phpsysinfo.sourceforge.net/ Demo: http://phpsysinfo.sourceforge.net/phpsysinfo/index.php?disp=dynamic Edit: This was taken from Stephen's comment. I put it here just so that it gets enough exposure for people to read. Just a note: this library isn't too snappy. I couldn't find a way to just return CPU or just ram, it returns EVERYTHING, hardware list, network stats, hd usage, os info, pretty much everything you can think of. This takes it about 4 seconds to complete so it may not be the best option if you want a constantly updating value using ajax or something of the sort. A: How to get Memory and CPU usage in PHP Perfect simple examples. -- Memory in procentage % ($mem[2]/1000 for used memory in MB) function get_server_memory_usage(){ $free = shell_exec('free'); $free = (string)trim($free); $free_arr = explode("\n", $free); $mem = explode(" ", $free_arr[1]); $mem = array_filter($mem); $mem = array_merge($mem); $memory_usage = $mem[2]/$mem[1]*100; return $memory_usage; } -- CPU in procentage % function get_server_cpu_usage(){ $load = sys_getloadavg(); return $load[0]; } A: I think better way is get load avarage, because it depends not only on CPU, but on HDD speed also. Here is a doc: http://php.net/manual/en/function.sys-getloadavg.php A: I recently have some issue to get CPU load and i feel like sharing it . Here was my solution witch help me out : My situation : I've use Zend Framework 1.2 to build monitoring application and i want to get cpu load and show it on the page . after doing some research i found out i could use COM Object and query the Win OS with wmi so i put these code to my init function : /* Initialize action controller here */ $this->wmi = new COM('winmgmts:{impersonationLevel=impersonate}//./root/cimv2'); if (!is_object($this->wmi)) { throw new GetInfoException('This needs access to WMI. Please enable DCOM in php.ini and allow the current user to access the WMI DCOM object.'); } * *You could use it anywhere you want , i have use it in the init function beacuse of Zend structure . And i added an Action and an function to use that wmi and get cpu load any time i want by calling that function . public function cpuloadAction() { echo json_encode($this->getLoad()); exit(); } private function getLoad() { // Time? if (!empty($this->settings['timer'])) $t = new LinfoTimerStart('Load Averages'); $load = array(); foreach ($this->wmi->ExecQuery("SELECT LoadPercentage FROM Win32_Processor") as $cpu) { $load[] = $cpu->LoadPercentage; } //return round(array_sum($load) / count($load), 2) . "%"; return (int)round(array_sum($load) / count($load), 2); } * *beacuse i what real time data i put these code in a function Otherwise you could write it in single non Object Oriented PHP file. Hope it help .
{ "language": "en", "url": "https://stackoverflow.com/questions/7538251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to covert a mySql DB into Drupal format tables Hi there i have some sql tables and i want to convert these in a "Drupal Node Format" but i don't know how to do it. Does someone knows at least which tables i have to write in order to have a full node with all the keys etc. ? I will give an example : I have theses Objects : Anime field animeID field animeName Producer field producerID field producerName AnimeProducers field animeID field producerID I have used the CCK module and i had created in my drupal a new Content Type Anime and a new Data Type Producer that exist in an Anime object. How can i insert all the data from my simple mysql db into drupal ? Sorry for the long post , i would like to give you the chance to understand my problem Thx in advance for your time to read my post A: You can use either the Feeds module to import flat CSV files, or there is a module called Migrate that seems promising (albiet pretty intense). Both work on Drupal 6 or 7. A: mmmmm.... i think you can export CVS from your sql database and then use http://drupal.org/project/node_import to import this cvs data to nodes.....mmmm i don know if there is another non-programmatically way A: The main tables for node property data are node and node_revision, have a look at the columns in those and it should be fairly obvious what needs to go in those. As far as fields go, their storage is predictable so you would be able automate an import (although I don't envy you having to write that!). If your field is called 'field_anime' it's data will live in two tables: field_data_field_anime and field_revision_field_anime which are keyed by the entity ID (in this case node ID), entity type (in the case 'node' itself) and bundle (in this case the name of your node type). You should keep both tables up to date to ensure the revision system functions correctly. The simplest way to do it though is with PHP and the node API functions: /* This is for a single node, obviously you'd want to loop through your custom SQL data here */ $node = new stdClass; $node->type = 'my_type'; $node->title = 'Title'; node_object_prepare($node); // Fields $node->field_anime[LANGUAGE_NONE] = array(0 => array('value' => $value_for_field)); $node->field_producer[LANGUAGE_NONE] = array(0 => array('value' => $value_for_field)); // And so on... // Finally save the node node_save($node); If you use this method Drupal will handle a lot of the messy stuff for you (for example updating the taxonomy_index table automatically when adding a taxonomy term field to a node)
{ "language": "en", "url": "https://stackoverflow.com/questions/7538252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: swf not showing up? I have a wordpress theme I'm adapting to a clients needs, but I can't make the sidebar ads, which are 125x125px, show a same sized swf instead of a image. If I insert a swf link, it show a broken image thumbnail. Please help me achieve this. If it helps you, the url of the website is http://infodrum.ro/inde2.php/ PHP code <?php if(get_theme_option('ads_125') != '') { ?> <div class="sidebaradbox"> <?php sidebar_ads_125(); ?> </div> <?php } ?> CSS .ad125 { margin: 10px; height: 125px; width: 125px; } A: You're usually inserting a path to an image in The backend, right? Like "http://somedomain.com/image.jpg" Most likely, The Code Inside The Plugin then Produces something like <img src="WHATEVER YOU ENTERED" /> Since an SWF is Not a valid image, everything ends up being terrible. I suggest you try The normal WP Text Widget instead!
{ "language": "en", "url": "https://stackoverflow.com/questions/7538254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reverse the display of a date using jQuery I have a date returned in this format YYYY-MM-DD, e.g. 2011-04-29. Using jQuery how can I make the date 29-04-2011? A: You can use .reverse() var pieces = '2011-07-27'.split('-'); pieces.reverse(); var reversed = pieces.join('-'); A: var parts = '2011-07-27'.split(/-/); parts.reverse(); alert(parts.join('-'));
{ "language": "en", "url": "https://stackoverflow.com/questions/7538255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can extract generic entities using Lingpipe other than People, Org and Loc? I have read through Lingpipe for NLP and found that we have a capability there to identify mentions of names of people, locations and organizations. My questions is that if I have a training set of documents that have mentions of let's say software projects inside the text, can I use this training set to train a named entity recognizer? Once the training is complete, I should be able to feed a test set of textual documents to the trained model and I should be able to identify mentions of software projects there. Is this generic NER possible using NER? If so, what features should I be using that I should feed? Thanks Abhishek S A: Provided that you have enough training data with tagged software projects that would be possible. If using Lingpipe, I would use character n-grams model as the first option for your task. They are simple and usually do the work. If results are not good enough some of the standard NER features are: * *tokens *part of speech (POS) *capitalization *punctuaction *character signatures: these are some ideas: ( LUCENE -> AAAAAA -> A) , (Lucene -> Aaaaaa -> Aa ), (Lucene-core --> Aaaaa-aaaa --> Aa-a) *it may also be useful to compose a gazzeteer (list of software projects) if you can obtain that from Wikipedia, sourceforge or any other internal resource. Finally, for each token you could add contextual features, tokens before the current one (t-1, t-2...), tokens after the current one (t+1,t+2...) as well as their bigram combinations (t-2^t-1), (t+1^t+2). A: Of course you can. Just get train data with all categories you need and follow tutorial http://alias-i.com/lingpipe/demos/tutorial/ne/read-me.html. No feature tuning is required since lingpipe uses only hardcoded one (shapes, sequnce word and ngramms)
{ "language": "en", "url": "https://stackoverflow.com/questions/7538256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IE7 & 8 add unwanted drop shadow to a table inside of another table I have the follwing jsfiddle http://jsfiddle.net/PrkUW/ There you will find a list-table which has a drop shadow filter applied to it. Inside one of it's rows I have another table, inner-table, which doesn't have any drop shadow declared on it. The problem is that both IE7 and 8 add drop shadow to the inner-table and to it's parent row, and I can't remove it using JS or CSS. I've tried $('.inner-table').css('filter', '') too but can't get it to work. And as you can see on IE7 the inner-table column's width are a total mess, and borders appear without any declaration. Does anybody have a suggestion on how to make it look right? Thanks! A: can u check with $('.inner-table').css('filter', null) or using .removeAttr('class'); jQuery remove attribute
{ "language": "en", "url": "https://stackoverflow.com/questions/7538263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using std::complex with iPhone's vDSP functions I've been working on some vDSP code and I have come up against an annoying problem. My code is cross platform and hence uses std::complex to store its complex values. Now I assumed that I would be able to set up an FFT as follows: DSPSplitComplex dspsc; dspsc.realp = &complexVector.front().real(); dspsc.imagp = &complexVector.front().imag(); And then use a stride of 2 in the appropriate vDSP_fft_* call. However this just doesn't seem to work. I can solve the issue by doing a vDSP_ztoc but this requires temporary buffers that I really don't want hanging around. Is there any way to use the vDSP_fft_* functions directly on interleaved complex data? Also can anyone explain why I can't do as I do above with a stride of 2? Thanks Edit: As pointed out by Bo Persson the real and imag functions don't actually return a reference. However it still doesn't work if I do the following instead DSPSplitComplex dspsc; dspsc.realp = ((float*)&complexVector.front()) + 0; dspsc.imagp = ((float*)&complexVector.front()) + 1; So my original question still does stand :( A: The std::complex functions real() and imag() return by value, they do not return a reference to the members of complex. This means that you cannot get their addresses this way. A: This is how you do it. const COMPLEX *in = reinterpret_cast<const COMPLEX*>(std::complex); Source: http://www.fftw.org/doc/Complex-numbers.html EDIT: To clarify the source; COMPLEX and fftw_complex use the same data layout (although fftw_complex uses double and COMPLEX float)
{ "language": "en", "url": "https://stackoverflow.com/questions/7538264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Reflection to Bind Business Objects to ASP.NET Form Controls This looks like a really useful way to simplify databinding ASP.NET controls to a generic business object. I've yet to use this in a fully fledged live project and so I'm not sure how accurate their performance metrics are. Off the top of my head I think I would implement these two methods 'BindControlsToObject' and 'BindObjectToControls' in a new class derived from the Page object, but whatever takes your fancy really. How I can accurate their performance? A: If performance is one of your concerns, then do not use reflection. At least not at every page call, so you could think about caching on demand or at application start. You could bind to a list or an object without using reflection and this would enable you to use Eval("...") in the markup, which is a commonly used pattern and other programmers new to your project would become faster productive. Besides this, doing this is a great way to learn reflection for something like a custom plugin system ( in the cases you cannot or do not want to use MEF or Unity or something like this ).
{ "language": "en", "url": "https://stackoverflow.com/questions/7538265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I run an ASP.NET website globally [or atleast in my LAN] I made a site using VS10 Ultimate [ASP.NET] and when I build & run it runs the severer locally, while I want to test it for security issues via Linux. How can I run it globally ? Thank you! A: Your development machine probably has IIS installed. Copy the code or the compiled code to the web root of this installation. If you want to put it on another computer, then that will need to have IIS, relevant version of .Net installed. It would also help if you can setup your local DNS to resolve the name for your computer within the LAN setup so that you can reache the machine using a name rather than the IP. This will allow you to test the security issues that are client side. For Server side security issues, you will need to create a server in your LAN that is configured similar to the actual server where you would be hosting your site. A: You need to set up the site in IIS Server installed in your Windows machine to run it locally See the links to learn more: http://www.beansoftware.com/ASP.NET-Tutorials/Set-Up-IIS-ASP.NET.aspx http://support.microsoft.com/kb/323972 A: You need an ASP.NET hosting service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OpenGL clipping I have been reading articles about clipping now for hours now but I dont seem to find a solution for my problem. This is my scenario: Within an OpenGL ES environment (IOS,Android) I am having a 2D scene graph consisting of drawable objects, forming a tree. Each tree node has its own spatial room with it's own transformation matrix, and each node inherits its coordinate space to its children. Each node has a rectangular bounding box, but these bounding boxes are not axis aligned. This setup works perfect to render a 2D scene graph, iterating through the tree, rendering each object and then it's children. Now comes my problem: I am looking for a way enable clipping on a node. With clipping enabled, children of a node should be clipped when leaving the area of the parent's bounding box. For example I wand to have a node containing a set of text nodes as children, which can be scrolled up and down withing it's parents bounding box, and should be clipped when leaving the area of the parent's bounding box. Since bounding boxes are not axis aligned, I cannot use glScissor, which would be the easiest way. I was thinking about using the stencil buffer and draw the filled bounding rectangle into it, when clipping is enabled and then enable the stencil buffer. This might workd but leads to another problem: What happens if a child inside a clipped node has clipping again ? - The stencil mask would have to be setup for the child, erasing the parents stencil mask. Another solution I was thinking of, is to do the clipping in software. This would be possible, because within each node, clipping could be done relative easily in it's own local coordinate space. The backdraw of this solution would be that clipping has to be implemented for each new node type that is implemented. Can anybody here point me into the right direction? What I am looking for is something like the functionality of glscissor for clipping non axis aligned rectangular areas. A: The scissor box is a simple tool for simple needs. If you have less simple needs, then you're going to have to use the less simple OpenGL mechanism for clipping: the stencil buffer. Assuming that you aren't using the stencil buffer for anything else at present, you have access to 8 stencil bits. By giving each level in your scene graph a higher number than the last, you can assign each level its own stencil mask. Of course, if two siblings at the same depth level overlap, or simply are too close, then you've got a problem. Another alternative is to assign each node a number from 1 to 255. Using a stencil test of GL_EQUAL, you will be able to prevent the overlap issue above. However, this means that you can have no more than 255 nodes in your entire scene graph. Depending on your particular needs, this may be too much of a restriction. You can of course clear the stencil (and depth. Don't try to clear just one of them) when you run out of bits via either method. But that can be somewhat costly, and it requires that you clear the depth, which you may not want to do. Another method is to use the increasing number and GL_EQUAL test only for non-axis-aligned nodes. You use the scissor box for most nodes, but if there is some rotation (whether on that node or inherited), then you use the stencil mask instead, bumping the mask counter as you process the graph. Again, you are limited to 256 nodes, but at least these are only for rotated nodes. Depending on your needs and how many rotated nodes there are, that may be sufficient.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Java if-statement currentTimeMillis, check if specific time has passed I've ran into an odd problem. I'm trying to check if the current time is greater than powertimer. When I run the method the if-statement returns true even though powerup.getPowertimer() - System.currentTimeMillis() is greater than 0 which I tested by printing out the result. this.powertimer = System.currentTimeMillis() + 10000; public long getPowertimer() { return this.powertimer; } if ((powerup.getPowertimer() - System.currentTimeMillis()) > 0) { System.out.println(powerup.getPowertimer() - System.currentTimeMillis()); powerup.reversePower(player); expired.add(powerup); } Does anyone know how to fix this? A: To check if current time has "passed" the powertimer timeout, you do if (System.currentTimeMillis() > powerup.getPowertimer()) { ... } Note that your line: if ((powerup.getPowertimer() - System.currentTimeMillis()) > 0) is equivalent to if (powerup.getPowertimer() > System.currentTimeMillis()) ^ | wrong direction of inequality A: You've got the subtraction around the wrong way. Do this: if (System.currentTimeMillis() - powerup.getPowertimer() > 0) Always remember this: delta = final - initial Thanks to my high school physics teacher Geoff Powell for this little gem I have used often in my life.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Facebook Request Dialog - Invite to External Website FB.init({ appId:'Application ID', cookie:true, status:true, xfbml:true }); FB.ui({ method: 'apprequests', message: 'Here is a new Requests dialog...'}); How to redirect the user to my external website rather than the Canvas Page inside facebook? A: There are a couple posts about this online that suggest making a dummy canvas page that sets window.location.top = 'yoursiteurl' ... but this does not seem satisfactory to me. Facebook docs are wildly unclear about whether external website ("Facebook Connect") devs are encouraged to use requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change Symbol Number to Upper Case... in the "richTextBox.Lines" array? How to change to Upper Case SymbolNumber... in the "richTextBox.Lines" array? I have a problem with "ToUpper()", because it is working only with the "String" data, but I need change the case to upper by number of the symbol. For example... I have a text... "qwerty \n asdfgh \n zxcvbn" ...in the "richTextBox.Text", and I need to change case of symbol #3 in each line (e, d, c) to Upper. A: I don't know what's exactly your situation, but you can expand bellow code for words , ...: I: var strs = richtextbox.Text.Split("\n".ToCharArray()); var items = ""; foreach(var item in strs) { items += new string(item.Select((x,index)=> index == 2?x.ToUpper():x) .ToArray()) + "\n"; } Edit: As I understand from your comment, this would work for you: indexUpper is input for example set it as 3: II: richTextBox1.Lines = richTextBox1.Lines .Where(x => x.Length > indexUpper + 1) .Select(s => s.Substring(0,indexUpper) + s[indexUpper].ToString().ToUpper() + s.Substring(indexUpper,s.Length - indexUpper - 1)) .ToArray(); and if you want to have all items: III: this.richTextBox1.Lines = richTextBox1.Lines //.Where(x => x.Length > indexUpper + 1) .Select(s => s.Length > indexUpper + 1? s.Substring(0,indexUpper) + s[indexUpper].ToString().ToUpper() + s.Substring(indexUpper + 1,s.Length - indexUpper - 1) : s.Length == indexUpper + 1? s.Substring(0,indexUpper) + s[indexUpper].ToString().ToUpper() :s).ToArray(); A: Try this code: public Form1() { InitializeComponent(); string text = "qwerty\nasdfgh\nzxcvbn"; richTextBox1.Text = text; } private void button1_Click(object sender, EventArgs e) { //change ever 3rd charater in each line: string[] words = richTextBox1.Text.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); richTextBox1.Text = ""; for (int i = 0; i < words.Length; i++) { char[] chars = words[i].ToCharArray(); chars[2] = Convert.ToChar(chars[2].ToString().ToUpper()); string newWord = new string(chars); richTextBox1.AppendText(newWord + "\n"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7538279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: python GUI frameworks / libraries suited for data analysis programs I'm looking for a good cross platform (mac, windows & linux) python GUI framework / library that will make my life easier while writing a data analysis program. Since my data is represented by custom data classes, it would be great if the GUI framework / library could take away the burden of having to code input checks, validation, etc (i.e., create input dialogs that take care of checking for the correct data range / data type based on the data model). The only library that I've found so far is TraitsUI. Are there more (similar) libraries / frameworks out there? A: Then Enthought Suite (not just TraitsUI) is the most complete as it provides everything from building the model to showing it including input validation. It plays nicely with numpy and scipy which is nice for a scientific app. Enthought UI can use Qt (via PySide or PyQt) or wx as backends. You can also use Qt directly via PyQt or Pyside and embed plots using matplotlib or PyQwt. QtDesigner allows you to generate nice UI with very little effort. You can achieve the type of initialization, validation as with Traits but with more effort. A: Have a look at http://qt.nokia.com/products/ A: When you said "Python", do you mean Python as a "language" irrespective of implementation (i.e. CPython)? If I take this question assuming "Python as a language, and I need a cross platform features, I would probably use Jython (Python on Java) that has good integration with Java Swift, thus our program should work on many different platforms. You may look at the GUI examples implemented in Jython in the DataMelt project
{ "language": "en", "url": "https://stackoverflow.com/questions/7538282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to embed a flash object on my website? Well, I must say this is embarrassing to ask, but to my defense I'll say that throughout my years of web development I've never encountered a case where embedding flash was absolutely necessary. The Question * *Simple, how do I embed a flash object of any kind (*.swf or if there any other options, them too) to my website? Some Points * *I don't need the code, I already have that, I just don't really understand it. *I'm looking for a good explanation on how to use the <embed> or <object> elements. *I've been searching around but couldn't find a clear explanation, even in the specs. I'd award any good answer with an upvote, a cookie, and an accepted answer to the best :) A: Definitions: http://www.w3.org/wiki/HTML/Elements/embed http://www.w3.org/wiki/HTML/Elements/object Explanation on how to embed a flash object from Adobe: http://kb2.adobe.com/cps/415/tn_4150.html "The HTML OBJECT tag directs the browser to load Adobe Flash Player and then use it to play your SWF file." A: Change "YOURFILENAMEHERE.swf" with your .swf file name. <OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="320" HEIGHT="240" id="Yourfilename" ALIGN=""> <PARAM NAME=movie VALUE="YOURFILENAMEHERE.swf"> <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#333399> <EMBED src="Yourfilename.swf" quality=high bgcolor=#333399 WIDTH="320" HEIGHT="240" NAME="Yourfilename" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED></OBJECT>
{ "language": "en", "url": "https://stackoverflow.com/questions/7538286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Dynamic page layouts with Smarty Templates I am a php student and i am also new to smarty.I know smarty syntax for some extent and I can use it for very basic needs.I am currently planning on a social networking project and as it will be a quite a complex project I don't have a clear understanding of following questions before starting to code : QUESTION 1: how to use different layouts for different sections of a web application. for example say facebook.com. It uses one layout for its index page and another for its login page and another different one for its profile page. How to do this with smarty templates? How to reuse templates and separate them and use them? QUESTION 2: How to display dynamic error messages on smarty templates based on various programming decisions. For example, again lets take a look at facebook.com. When you visit facebook.com with javascript disabled it displays a message asking to enable javascript. When you visit someone's profile without logged in it displays a different header and a sign up bar at the top. When you supplied wrong login credentials it displays an error message in the same template. When facebook.com needs to do some announcement to its users it gets displayed when we logged into our home page? How to do these things with smarty? QUESTION 3: How to handle the css styling of different templates. How to use javascript with different templates? These scenarios might sound like like ordinary but to me that information will be like gold. I greatly appreciate any help from anyone of you seeing this. If you can explain these stuff with some good example code it will be an enormous support for me. [A detailed explanation will be greatly appreciated] Thank you A: As you know smarty is a template engine, For your question 1: You can decide which template to show by calling the function display(); Example : $smarty->display("header1.tpl"); $smarty->display("header1.2pl"); etc.. or you can include the appropriate tpl files according to the conditions passed to the tpl. Example : $smarty->assign("type",$type); then in the tpl, you can include the appropriate tpl files as follows {if $type=='condition1'} {include file="file1.tpl"} {elseif $type=='condition2'} {include file="file2.tpl"} {/if} For your question 2: You can send the errors to the tpl and can display it as follows $smarty->assign("error",$errroMessage); Then in the tpl enter code here {$error}
{ "language": "en", "url": "https://stackoverflow.com/questions/7538287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Releasing recursive class module in VBA I've been playing around with a class module which contains multiple versions of itself to build up a tree structure. I've noticed the process of building the tree is very fast. Roughly 2 seconds for a 7 level tree with 6-8 branches per subtree. Unfortunately the program runs very slowly. This seems to be caused by the release of the memory used by the tree, which takes at least 60 seconds. Initially I did not release the class module, and allowed VB to do it at the end of the program, but replacing this with set myTree = nothing makes no difference to the speed. I also tried writing a sub routine to destroy the tree. This recursively went through each layer and set the sub trees to nothing. Oddly this seemed to save aroung 0.5 of a second, but nothing significant. Is there anything else I can do to reduce the unload time? The code is really long but the excert below gives the idea. I'm happy that the tree structure works, but the gap between the final two timer statements is very large Class treeNode private aCurrentDepth as integer private aNodeObject as myObject private aNodes(maxNodeCount) as treeNode end class public function creatreTree(m as myObject,depth as integer) as treeNode Dim x As Integer Set createTree = New treeNode createTree.initialise createTree.cNodeObject = m createTree.cCurrentDepth = depth If depth <> 1 Then For x = 0 To maxNodeCount createTree.tNode(x) = createTree(getObject(m,x), depth - 1) Next x End If end function sub testTree Dim t as treeNode dim g as myObject Set t = New treeNode g.initialise t.initialise set g = startObject Cells(1, "A") = Timer Set t = createTree(g, 7) Cells(1, "B") = Timer Set t = Nothing Cells(1, "C") = Timer end sub A: I just created a debugExcelLog class last week. You might find it helpful to track what is happening in your classes. I used it to locate a bug that was happening only occasionally. (Turned out UserRoutine2 was trying to use a global class that UserRoutine1 was in the middle of clearing.) '------------------------------------------------------------------------------ '| Class Name: debugExcelLog '| Programmer: Mischa Becker '| Date: 11/4/2011 '| Purpose: Creates an Excel Workbook log '------------------------------------------------------------------------------ '| Notes: '| + Add a DEBUG_PROJECT compiler constant to your project '| + Add Public Const g_PROJECT_NAME As String = "[ProjectName]" to a module. '| + sName and sCalledBy are expected to be in one of the following formats: '| Project.Class.Routine '| Class.Routine '| Routine '------------------------------------------------------------------------------ Option Explicit Private Const m_CLASS_NAME As String = g_PROJECT_NAME & ".debugExcelLog" Private Const m_OFFSET As Integer = 3 Private m_wbk As Workbook Private m_r As Range Private m_bLogged As Boolean Private m_iIndent As Integer Private m_bOkToLog As Boolean Private m_lInstanceID As Long '------------------------------------------------------------------------------ '------------------------------------------------------------------------------ Private Sub Class_Initialize() m_bOkToLog = False m_lInstanceID = CLng(Rnd * 10 ^ 6) #If DEBUG_PROJECT Then Debug.Print m_CLASS_NAME; ".Class_Initialize", "Id:"; m_lInstanceID Me.TurnOn #End If End Sub Private Sub Class_Terminate() If Not (m_bLogged Or m_wbk Is Nothing) Then m_wbk.Close False End If Set m_wbk = Nothing Set m_r = Nothing #If DEBUG_PROJECT Then Debug.Print m_CLASS_NAME; ".Class_Terminate", "Id:"; m_lInstanceID #End If End Sub '------------------------------------------------------------------------------ '------------------------------------------------------------------------------ Public Sub TurnOn() Set m_wbk = Application.Workbooks.Add Set m_r = m_wbk.Sheets(1).Range("A1") m_iIndent = 0 SetTitle m_bOkToLog = True End Sub Public Sub TurnOff() m_bOkToLog = False End Sub '------------------------------------------------------------------------------ '------------------------------------------------------------------------------ Public Sub Log_Start(sName As String, lInstance As Long _ , Optional sCalledBy As String = "" _ , Optional sComment As String = "") Const MY_NAME As String = m_CLASS_NAME & ".Log_Start" On Error GoTo ErrorHandler If Not m_bOkToLog Then Exit Sub m_bLogged = True m_iIndent = m_iIndent + 1 BreakApartAndLogName sName, ".Start" Instance = lInstance TimeStamp = Now CalledBy = sCalledBy Comment = sComment MoveNextRow Exit Sub ErrorHandler: Debug.Print MY_NAME, Err.Number; " - "; Err.Description Stop Resume End Sub Public Sub Log_End(sName As String, lInstance As Long _ , Optional sCalledBy As String = "" _ , Optional sComment As String = "") Const MY_NAME As String = m_CLASS_NAME & ".Log_End" On Error GoTo ErrorHandler If Not m_bOkToLog Then Exit Sub BreakApartAndLogName sName, ".End" Instance = lInstance TimeStamp = Now CalledBy = sCalledBy Comment = sComment MoveNextRow m_iIndent = m_iIndent - 1 Exit Sub ErrorHandler: Debug.Print MY_NAME, Err.Number; " - "; Err.Description Stop Resume End Sub Public Sub Log_Other(sName As String, lInstance As Long _ , Optional sCalledBy As String = "" _ , Optional sComment As String = "") Const MY_NAME As String = m_CLASS_NAME & ".Log_Other" On Error GoTo ErrorHandler If Not m_bOkToLog Then Exit Sub m_bLogged = True If m_iIndent < 0 Then m_iIndent = 0 BreakApartAndLogName sName Instance = lInstance TimeStamp = Now CalledBy = sCalledBy Comment = sComment MoveNextRow Exit Sub ErrorHandler: Debug.Print MY_NAME, Err.Number; " - "; Err.Description Stop Resume End Sub '------------------------------------------------------------------------------ '------------------------------------------------------------------------------ Private Sub SetTitle() Const MY_NAME As String = m_CLASS_NAME & ".SetTitle" On Error GoTo ErrorHandler m_r = "Debug Excel Log Created on " & Date MoveNextRow Project = "Project" Module = "Module" Routine = "Routine" Instance = "Instance" TimeStamp = "TimeStamp" CalledBy = "Called By" Comment = "Comment" With Range(m_r, m_r.End(xlToRight)) .Font.Bold = True .BorderAround XlLineStyle.xlContinuous, xlMedium End With MoveNextRow m_iIndent = -1 Exit Sub ErrorHandler: Debug.Print MY_NAME, Err.Number; " - "; Err.Description Stop Resume End Sub Private Sub MoveNextRow() Set m_r = m_r.Offset(1) End Sub Private Sub BreakApartAndLogName(ByVal sName As String _ , Optional sExtra As String = "") Const MY_NAME As String = m_CLASS_NAME & ".BreakApartAndLogName" On Error GoTo ErrorHandler Routine = SplitOffLastSection(sName) & sExtra If Len(sName) > 0 Then Module = SplitOffLastSection(sName) If Len(sName) > 0 Then Project = SplitOffLastSection(sName) End If End If Exit Sub ErrorHandler: Debug.Print MY_NAME, Err.Number; " - "; Err.Description Stop Resume End Sub Private Function SplitOffLastSection(ByRef sName As String) As String ' Passed sName is returned without the Last Section. Const MY_NAME As String = m_CLASS_NAME & ".SplitOffLastSection" Dim i As Integer i = InStrRev(sName, ".") If i > 0 Then SplitOffLastSection = Mid(sName, i + 1) sName = Left(sName, i - 1) Else SplitOffLastSection = sName sName = "" End If Exit Function ErrorHandler: Debug.Print MY_NAME, Err.Number; " - "; Err.Description Stop Resume End Function '------------------------------------------------------------------------------ '------------------------------------------------------------------------------ Private Property Let Project(sText As String) m_r = sText End Property Private Property Get Project() As String Project = m_r.Text End Property Private Property Let Module(sText As String) m_r.Offset(0, 1) = sText End Property Private Property Get Module() As String Module = m_r.Offset(0, 1).Text End Property Private Property Let Routine(sText As String) If m_iIndent < 0 Then m_r.Offset(0, 2) = sText Else m_r.Offset(0, 2) = Space(m_OFFSET * m_iIndent) & sText End If End Property Private Property Let Instance(lInstance As Variant) m_r.Offset(0, 3) = lInstance End Property Private Property Let TimeStamp(dTimeStamp As Variant) m_r.Offset(0, 4) = dTimeStamp End Property Private Property Let CalledBy(ByVal sText As String) ' remove Project and Module from sText if same as running Routine sText = Replace(sText, Project & "." & Module & ".", "") sText = Replace(sText, Project & ".", "") m_r.Offset(0, 5) = sText End Property Private Property Let Comment(sText As String) m_r.Offset(0, 6) = sText End Property '------------------------------------------------------------------------------ To use: * *Add the class to your project and name it debugExcelLog *Add DEBUG_PROJECT=-1 as a conditional compiler constant to your project *Create a global variable of the class. ie Public g_XlLog As debugExcelLog *Logging can be turned on and off with g_xlLog.TurnOn g_xlLog.TurnOff If DEBUG_PROJECT is True, you don't need to call TurnOn, the class will auto turn on when it initializes. *Use the following in any routine you want to track. g_XlLog.Log_Start "[Class.Routine]", m_lInstanceIdOrZero g_XlLog.Log_Other "[Class.Routine]", m_lInstanceIdOrZero, ,"Comment" g_XlLog.Log_End "[Class.Routine]", m_lInstanceIdOrZero *I suggest altering your testTree as follows. sub testTree Dim t as treeNode, g as myObject Dim iLevel as Integer iLevel = 7 Set g_XlLog = New debugExcelLog g_XlLog.Log_Start "testTree", 0, , "Initializing test variables" Set t = New treeNode g.initialise t.initialise set g = startObject g_XlLog.Log_Other "testTree", 0, , "Create a " & iLevel & " level tree" Set t = createTree(g, iLevel) g_XlLog.Log_Other "testTree", 0, , "Terminate a " & iLevel & " level tree" Set t = Nothing g_XlLog.Log_End "testTree", 0 set g_XlLog = Nothing end sub I would recommend adding logging to Class_Initialize and Class_Terminate for both treeNode and MyObject. If Class_Terminate is calling other routines you can either add logging to them, or use Log_Other to track when each one starts. If you haven't done so already, I really recommend adding some sort of instance id to treeNode so you will know which instance is being created\terminated. If you aren't worried about Rnd creating duplicate IDs it can be as simple as what I have in the above class. You will also notice the optional sCalledBy and sComment parameters. sComment should be obvious but sCalledBy is there because the Excel VBE's Call Stack leaves a lot to be desired. For debugging purposes, some of my methods require the routine calling them to pass their name in as a parameter. If you have this info, you can send it to the logger. Once you have a more precise idea of where the slow-down is happening, it will be a lot easier to figure out how to fix it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: CSS Box model width problem I am newbiew to css. Please have a look of this simple two column layout first. http://www.vanseodesign.com/blog/demo/2-col-css.html I want to ask why the width of content + width of sidebar =/= width of container? A: Width of content = 610px Width of padding in content = 5+5 = 10px Total width of content = 620px Similarly Total width of sidebar with padding = 340px So total content and sidebar = 620+340 = 960px which is equal to width of container ! A: The W3C specification says that the width of a box is: margin + border + padding + width. In this way you'll be able to determine the actual box width. If you sum the resulting box widths you will have a result equal to the container width. A: Without seeing your code it's hard to give you an answer. But some basic CSS and html is below which will give you a content area the same size as your header, see it in action here http://jsfiddle.net/peter/wZQNY/ The CSS .container{ margin:0 auto; width:960px; } .header{ width:100%; background:#eee; } .content{ width:100%; background:#ccc; } The HTML <div class="container"> <div class="header">header navigation</div> <div class="content">page content</div> </div> A: I can't see the problem. In your link, the content.width + sidebar.width == container.width What's your problem? what browser are you using? A possible solution is that you may have some weird behavior due to border or margins, for that, you should apply a CSS Reset.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to send mass emails from c# and check if they were delivered I need to implement the web application for sending marketing emails to the partners of the company. There are some requirements I have no idea how to solve it. * *The first one is how to check if the email was delivered? I'm sending emails through smtp server. *The second one is how to check if the email was readed by receipient. *the third one is how to ensure, that emails did not go to spam. I'm using .NET platform. I will apreciate any help to any of this questions. thanks A: * *The first one is how to check if the email was delivered? I'm sending emails through smtp server. *The second one is how to check if the email was readed by receipient. *the third one is how to ensure, that emails did not go to spam. TL;DR: You cannot do any of these using standard email protocols (ie. SMTP). There is no support in SMTP for acknowledgement or receipt or reading. There is no reliable mechanism to report failed to deliver: just ignoring is often done if determined to be spam. Closed systems (eg. MS Exchange) can offer this kind of functionality where one organisation can set policies for all parts of the system end to end. I suggest considering why The Evil Bit (RFC 3514) is not an effective security measure. A: The only option I can think of is using what's often called a tracking pixel or web bug in your emails. Wikipedia has a comprehensive explanation of this at http://en.wikipedia.org/wiki/Web_bug. However, it is easily bypassed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Placing a button inside a rendered partial that hides the partial <%= render :partial => "list" %> Inside this partial there is only one div. I would like to have a button in the top right corner of the div to close the div. I would like the button to "not render" the partial and just display the rest of the index.html. How should I code the button in rails? It will be a small png. Thanks A: in your layout <html> <head> <%= javascript_include_tag "https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js", "home.js" %> </head> home.js $(document).ready(function() { $('#close-it').live('click', function() { $('#list').hide(); }); }); _list.html.erb <div id="list"> <%= image_tag("button.png", :id => "close-it") %> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7538302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using dispose() method instead of close() method to a form What is happening when I close a form, which was opened using Show(), by using Dispose() instead of Close()? Can someone tell me in detail, what happening in the Dispose() method? A: The basic difference between Close() and Dispose() is, when a Close() method is called, any managed resource can be temporarily closed and can be opened once again. It means that, with the same object the resource can be reopened or used. Where as Dispose() method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing. Or just a general statement. With the connection object calling Close() will release the connection back into the pool. Calling Dispose() will call Close() and then set the connection string to null. Some objects such as a Stream implement IDisposable but the Dispose method is only available if you cast the object to an IDisposable first. It does expose a Close() method though. I would always argue that you should call Dispose() on any object that implements IDisposable when you are through with the object. Even if it does nothing. The jit compiler will optimize it out of the final code anyway. If the object contains a Close() but no Dispose() then call Close(). You can also use the using statement on IDispoable objects using(SqlConnection con = new SqlConnection()) { //code... } This will call Dispose() on the SqlConnection when the block is exited. A: Decompiling the two methods (Dispose and Close) it turns out that the latter performs two additional checks and then calls Dispose, just like this: object[] objArray; if (base.GetState(262144)) { throw new InvalidOperationException(SR.GetString("ClosingWhileCreatingHandle", new object[] { "Close" })); } if (base.IsHandleCreated) { this.closeReason = CloseReason.UserClosing; base.SendMessage(16, 0, 0); return; } base.Dispose(); From documentation: When a form is closed, all resources created within the object are closed and the form is disposed. [...] The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection. Hope it helps. A: Actually, in this case Close() and Dispose() is quite different: Close closes the form by sending the appropiate Windows message. You will be able to open the form again using Open() Dispose disposes the form resources altogether, and you won't be able to re-use the form instance again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: php & wordpress ASC / DESC using href AND sorting I have been battling with trying to get this code working on my site. I would like to have the ability for the user to sort posts in ascending or descending order from clicking href link. This option should be remembered when the user then chooses to sort the post list by another option e.g. title, votes, date. Here is what I have got far: <?php $sort= $_GET['sort']; if($sort == "A") { $order= "gdsr_sort=thumbs"; } if($sort == "B") { $order= "orderby=title"; } if($sort == "C") { $order= "orderby=date"; } ?> <?php $updown= $_GET['updown']; if($updown == "Y") {$ascend= "ASC";} //this orders in ascending if($updown == "Z") {$ascend= "DESC";} //this orders in descending ?> <a href="?sort=A&updown=<?php echo $updown?>">Thumbs</a> <a href="?sort=B&updown=<?php echo $updown?>">Author</a> <a href="?sort=C&updown=<?php echo $updown?>">Date</a> <?php $sort= isset($_GET['sort']) ? $_GET['sort'] : "B"; ?> <a href="?updown=Y&sort=<?php echo $sort?>">Ascending</a> <a href="?updown=Z&sort=<?php echo $sort?>">Descending</a> <?php query_posts($order.'&order=$.ascend.'); ?> <?php if ( have_posts() ) : ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> The href for sorting works just fine however the ASC / DESC do not do anything the whole thing just stays DESC. A: Instead of using confusing letters, I can suggest 2 better solutions: * *Use a base-3 number (1021021210) to determine which fields are not sorted (0), ASC (1) or DESC (2). *Use PHP's $_GET superglobal and create URLs such as example.com/index.php?fielda=asc&fieldb=desc. Then parse it to see what the user wanted to sort. Solution 2 is preferred. A: Way too complicated. Just store The user ASC/DESC preference in a Cookie (via JS, if you prefer a quick&dirty solution), use The Cookie Value for Setting Order when sorting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use Binding like proxy? <Setter Property="IsChecked"> <Setter.Value> <MultiBinding> <!-- Get value for property --> <Binding Path="IsPressed" RelativeSource="{RelativeSource Self}" Mode="OneWay"/> <!-- Set value to ViewModel's property --> <Binding Path="Shift" Mode="OneWayToSource"/> </MultiBinding> </Setter.Value> </Setter> I need to use 2 bindings for property: one to get value for property and one to set value to ViewModel's property. How I can realize this scenario? A: You can create a couple of attached properties. One will be the target of your binding, and second will contain binding for your proxy. Example: Then in ProxySource OnChange implementation you will get TextBox as UIElement, there you can read value from ProxySource and write it to ProxyTarget. This is not a very clean aproach, but it should work. If you can't get it working, I can write a complete sample later. Ok, I've implemented everything, here's complete source: public class ViewModel : ViewModelBase { string sourceText; public string SourceText { get { return sourceText; } set { if (sourceText == value) return; sourceText = value; System.Diagnostics.Debug.WriteLine("SourceText:" + value); RaisePropertyChanged("SourceText"); } } string targetText; public string TargetText { get { return targetText; } set { if (targetText == value) return; targetText = value; System.Diagnostics.Debug.WriteLine("TargetText:" + value); RaisePropertyChanged("TargetText"); } } } public static class AttachedPropertiesHost { public static object GetProxySource(DependencyObject obj) { return obj.GetValue(ProxySourceProperty); } public static void SetProxySource(DependencyObject obj, object value) { obj.SetValue(ProxySourceProperty, value); } public static readonly DependencyProperty ProxySourceProperty = DependencyProperty.RegisterAttached( "ProxySource", typeof(object), typeof(AttachedPropertiesHost), new UIPropertyMetadata(null, ProxySourcePropertyPropertyChanged) ); private static void ProxySourcePropertyPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { dependencyObject.Dispatcher.BeginInvoke( new { Dp = dependencyObject, NewValue = e.NewValue }, args => SetProxyTarget(args.Dp, args.NewValue) ); } public static object GetProxyTarget(DependencyObject obj) { return obj.GetValue(ProxyTargetProperty); } public static void SetProxyTarget(DependencyObject obj, object value) { obj.SetValue(ProxyTargetProperty, value); } public static readonly DependencyProperty ProxyTargetProperty = DependencyProperty.RegisterAttached("ProxyTarget", typeof(object), typeof(AttachedPropertiesHost)); } <TextBox Text="{Binding SourceText, UpdateSourceTrigger=PropertyChanged}" WpfDataGridLayout:AttachedPropertiesHost.ProxySource="{Binding RelativeSource={RelativeSource Self}, Path=Text, UpdateSourceTrigger=PropertyChanged}" WpfDataGridLayout:AttachedPropertiesHost.ProxyTarget="{Binding TargetText, Mode=OneWayToSource}" /> And the output from console while editing textbox: SourceText:f TargetText:f SourceText:fh TargetText:fh SourceText:fhh TargetText:fhh A: Please dont design your solution around IsPressed, thats actually what some call a flash data which means it changes back to a default value (false) sooner. Also contextually Binding will have dedicated target, source and mode. In MultiBinding acheiving one way IsPressed (from a Source) and other way saving back to another Target is not supported. For two way update to occur, all bindings have to be TowWay. Although a Hack to this could be using MultiConverter having a Target itself as one of the values. <MultiBinding Converter="MyMultiBindingConverter"> <!-- Get value for property --> <Binding Path="IsPressed" RelativeSource="{RelativeSource Self}" Mode="OneWay"/> <!-- Set value to ViewModel's property --> <Binding BindsDirectlyToSource="True"/> </MultiBinding> MyMultiBindingConverter.Convert() { var myViewModel = values[1] as MyViewModel; var isPressed = bool.Parse(values[0].ToString()); if (isPressed) { myViewModel.Shift = !myViewModel.Shift; } } But this is strongly NOT recommended.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Vkontakte Audio Search with HTTP API Sorry for my English. I know very little English. I am trying pull data from here : http://api.vk.com/api.php?api_id=2539386&count=200&v=2.0&method=audio.search&sig=c2b83d95d3d5914de0aa6ae7ca1c1007&test_mode=1&q=beatles c2b83d95d3d5914de0aa6ae7ca1c1007 = md5->141080534api_id=2539386count=200method=audio.searchq=beatlestest_mode=1v=2.0mysecretkey But return to me : "Incorrect signature: ifame/flash authorization" Where is error ? A: Should've read the API documentation first, the solution to your problem gets explained in pretty much the first line about the Audio Search method. You're getting an error because you're not authorized yet. You need to authorize your app first with rights with bitmask 8. More info about the Audio Search method | More info about the application rights bitmasks A: You are using old method my dear :) Use like this: https://api.vk.com/method/audio.search.xml?access_token=TOKEN&q=QUERY Replace TOKEN with your access token... Replace QUERY with your search term More info
{ "language": "en", "url": "https://stackoverflow.com/questions/7538315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to solve the vm budget memory heap error in lazy loading bitmaps? I have been using Image loader class for lazy loading in list view. It works fine but I have been dealing with lots of bitmap that will be downloaded from web service. so now I get bitmap size exceeds VM budget. Increased bitmapfactory size to be 32*1024 but if it reaches 32mb again it will throw a the error. It being breaking my head for the past one week. so some one please help me out of this problem. I here by post my image loader class as well please let me know where and how should I solve this problem. public class ImageLoader { private HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>(); Bitmap bitmap = null; private Activity activity; PhotosLoader photoLoaderThread=new PhotosLoader(); public ImageLoader(Activity activity){ this.activity = activity; photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1); clearCache(); } public void DisplayImage(String url, Activity activity, ImageView imageView, String[] imageUrl){ this.activity = activity; if(cache.containsKey(url)){ imageView.setImageBitmap(cache.get(url)); } else{ imageView.setImageResource(R.drawable.icon); queuePhoto(url, activity, imageView); } } private void queuePhoto(String url, Activity activity, ImageView imageView){ this.activity = activity; photosQueue.Clean(imageView); PhotoToLoad p=new PhotoToLoad(url, imageView); synchronized(photosQueue.photosToLoad){ photosQueue.photosToLoad.push(p); photosQueue.photosToLoad.notifyAll(); } if(photoLoaderThread.getState()==Thread.State.NEW) photoLoaderThread.start(); } public Bitmap getBitmap(String url, int sampleSize) throws Exception{ Bitmap bm = null; try { URL request = new URL(url); InputStream is = (InputStream) request.getContent(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inDither = true; options.inPurgeable = true; options.inInputShareable = true; options.inSampleSize = sampleSize; options.inTempStorage = new byte[32 * 1024]; bm = BitmapFactory.decodeStream(is, null, options); if (bm!=null) bm = Bitmap.createScaledBitmap(bm, 115,100, true); is.close(); is = null; } catch (IOException e) { throw new Exception(); } catch (OutOfMemoryError e) { bm.recycle(); bm = null; System.gc(); throw new Exception(); } return bm; } private class PhotoToLoad{ public String url; public ImageView imageView; public PhotoToLoad(String u, ImageView i){ url=u; imageView=i; } } PhotosQueue photosQueue=new PhotosQueue(); public void stopThread(){ photoLoaderThread.interrupt(); } static class PhotosQueue{ private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>(); public void Clean(ImageView image){ for(int j=0 ;j<photosToLoad.size();){ try{ if(photosToLoad.get(j).imageView==image) photosToLoad.remove(j); else ++j; }catch (Exception e) { } } } } class PhotosLoader extends Thread { public void run() { try { while(true){ if(photosQueue.photosToLoad.size()==0) synchronized(photosQueue.photosToLoad){ photosQueue.photosToLoad.wait(); } if(photosQueue.photosToLoad.size()!=0){ PhotoToLoad photoToLoad; synchronized(photosQueue.photosToLoad){ photoToLoad=photosQueue.photosToLoad.pop(); } Bitmap bmp = null; bmp = getBitmap(photoToLoad.url, 1); cache.put(photoToLoad.url, bmp); if(((String)photoToLoad.imageView.getTag()).equals(photoToLoad.url)){ BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView); Activity a=(Activity)photoToLoad.imageView.getContext(); a.runOnUiThread(bd); } } if(Thread.interrupted()) break; } } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } class BitmapDisplayer implements Runnable{ ImageView imageView; public BitmapDisplayer(Bitmap b, ImageView i){ bitmap = null; bitmap=b; imageView=i; } public void run(){ if(bitmap!=null){ imageView.setImageBitmap(bitmap); imageView.setScaleType(ScaleType.FIT_XY); } else{ imageView.setImageResource(R.drawable.icon); } } } public void clearCache() { try{ cache.clear(); cache = new HashMap<String, Bitmap>(); bitmap.recycle(); System.gc(); }catch (Exception e) { } } A: Quite simply you're trying to use more memory than the Android VM gives you. So you need to use less. You either: (1) need to manually clear your in-memory cache - i.e. once you reach a certain size or number of images or alternatively (2) use a HashMap of type <String, SoftReference<Bitmap>> so that the garbage collector can automatically reclaim the memory when the images are no longer being displayed. With either of these methods your in-memory cache should not get as large as before (which is good), so you may want to save your files to disk so they do not have to be downloaded again should they be cleared from the in-memory cache. A: Try like this.. try { HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection(); conn.setDoInput(true); conn.connect(); int length = conn.getContentLength(); InputStream is = conn.getInputStream(); bmImg = BitmapFactory.decodeStream(is); proImage.setImageBitmap(bmImg); // Bind image here on UI thread clearBitMap(bmImg); // Call to clear cache } catch (IOException e) { e.printStackTrace(); } private void clearBitMap(Bitmap bitMap) { bitMap = null; System.gc(); } A: verify below links..u can get idea about that... http://negativeprobability.blogspot.com/2011/08/lazy-loading-of-images-in-listview.html http://stackoverflow.com/questions/5082703/android-out-of-memory-error-with-lazy-load-images http://blog.jteam.nl/2009/09/17/exploring-the-world-of-android-part-2/ http://groups.google.com/group/android-developers/browse_thread/thread/bb3c57cab27e0d91?fwc=1
{ "language": "en", "url": "https://stackoverflow.com/questions/7538317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Visual C++ can't write into exe after I compiled my project in C++ (VisualStudio) around 3-4 times, I can do it anymore due to LNK1168 that stands for "VisualStudio can't write into the exe". I've looked up in my TaskManager, the exe is NOT running. Normally I have to wait for like 5 minutes but that isn't a real solution. Any ideas? ProcessExplorer just tells me, that the handle is invalid and though can't be closed. It remains open all the time... A: First thing that comes to mind is to use ProcessExplorer to figure out what process is keeping the file open. Download and start up the tool en select Find from the menu. Enter the (partial) file name and it should show up in the search results. Double click to jump to the process and file handle in the main application window. I'm guessing Visual Studio is the culprit. Fortunately, you can also use Process Explorer to close the handle. Right-click and choose Close Handle. Note that it's not a good idea to go around closing file handles on a regular basis. However, whenever you're in a pickle it can really help solve annoying problems. If I recall correctly, a similar problem existed way back in VS 6. It had to do with incremental compilation. For a more structural solution, try doing a full rebuild from time to time or disabling incremental compilation all together. A: I have been experiencing exactly the same problem (For C# and C++). I have just discovered that having the Application Experience Service disabled seems to cause EXPLORER.EXE To keep .exe files hanging around (locked by the SYSTEM) for several minutes after running that executable. The solution to this problem, for me at least, was to re-enable the Application Experience service. (I had originally disabled it since it seemed unnecessary - Apparently I was wrong!) A: Your exe might still be running. Stop it before recompiling it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Importing a existing Web Application , into Eclipse I need to import a existing Web Application , into Eclipse . Please see the Structure of my Web Application as shown in the below figure . http://imageshack.us/f/220/structurek.jpg/ From Eclipse IDE , while using import What option i need to select that is should i use * *Existing projects into Eclipse *Archive File *File System please see this image http://imageshack.us/f/850/eclipseo.jpg/ A: Import existing projects into Eclipse works only for projects that were created in Eclipse. And you're definitely not dealing with an Archive File here. Import from the File System just copies the resources but does not actually create an Eclipse project for you. What I would advise you, is to create a new Dynamic Web Project, configuring all the required facets, and then just copy all the contents of your existing app to the WebContent folder, either by drag'n'dropping it into the Project Explorer or by using Import from the File System, overwriting all the contents. So far, there seems to be no other way to do it in Eclipse. However you may check out the similar post. The user @RC recommends using ant task for this process, but I'm more than sure that it won't configure all the required facets for you. It may work for some simple Java projects, but surely not enough for Java EE projects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jquery slider and jquery kwicks issue I am using the jquery slider from http://www.gmarwaha.com/jquery/jcarousellite/ and the jquery kwciks as shown here http://mottie.github.com/Kwicks/. The problem is when click the first element it expands perfectly, and also the second. but if I click the third element it is not fully displayed. I want to element to be displayed fully. how to achieve this. any ideas will be great A: I just picked the expanded element's id and used it as trigger to move forward/backward on the slider. that worked. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7538327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3.1 on heroku worth it? I just upgraded my project to rails 3.1 since I saw the sass feature and the moving of public folder files to the assets folder and considered these major changes I should adjust to, especially the sass feature which is pretty cool. however, when looking at heroku, i came across this post detailing what to do to get rails 3.1 working on heroku: http://devcenter.heroku.com/articles/rails31_heroku_cedar#getting_started my app hasn't launched yet but I do intend to be on heroku and from the looks of that document, getting rails 3.1 to run on heroku sounds a little messy, where the assets folder is being created in the public folder.. when it has its own place now in 3.1. what are everyone else's thoughts on this? i like to keep my code clean and am thinking if I should go back to rails 3.0. maybe I missed something or a useful reason for doing this here, or am not interpreting this right, because this public folder precompile thing sounds so redundant to me. In short, is having Rails 3.1 on Heroku good? Or should I go back to Rails 3.0 A: The asset pipeline is not required, and you can simply not use it if you don't want to. Definitely keep Rails 3.1 for your app. You will have a much easier time upgrading for things you like in the future, and will have better security updates as the older versions eventually won't be maintained. I'd recommend using the asset pipeline, and you can read more about it in the guide. http://guides.rubyonrails.org/asset_pipeline.html If you don't want to use it though in your config/application.rb file change: config.assets.enabled = true to config.assets.enabled = false You'll probably also want to remove the assets gem group from your Gemfile as well. A: Having your assets compiled into public is nothing to worry about. This is a sensible idea as you don't want to have to recompile your assets for every request. Rails 3.1 has a number of advantages, however ultimately it's your decision, but I certainly wouldn't be fretting about asset compilation. A: If youre app if using Jquery-UI (jquery being the new default in 3.1) then for sure just disable the asset pipeline and use 3.1. asset pipeline breaks jquery-ui anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Scrollview problem In an activity, I have list of buttons and a listview. For every category I have a button and on click of that it shows corresponding data.Here is my xml code. <?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" > <Button android:layout_width="fill_parent" android:layout_height="60dp" android:id="@+id/button_1" android:text="first" /> <Button android:layout_width="fill_parent" android:layout_height="60dp" android:id="@+id/button_2" android:text="second" /> <Button android:layout_width="fill_parent" android:layout_height="60dp" android:id="@+id/button_3" android:text="three" /> <Button android:layout_width="fill_parent" android:layout_height="60dp" android:id="@+id/button_4" android:text="four" /> <Button android:layout_width="fill_parent" android:layout_height="60dp" android:id="@+id/button_5" android:text="five" /> <Button android:layout_width="fill_parent" android:layout_height="60dp" android:id="@+id/button_6" android:text="six" /> <Button android:layout_width="fill_parent" android:layout_height="60dp" android:id="@+id/button_7" android:text="seven" /> <Button android:layout_width="fill_parent" android:layout_height="60dp" android:id="@+id/button_8" android:text="eight" /> <ListView android:id="@+id/list" android:visibility="gone" android:layout_width="wrap_content" android:layout_height="fill_parent"/> </LinearLayout> In this activity, first buttons are visible. Then on click of button, all buttons will be invisible and only list view is there. Problem is If I am using scroll view, I can scroll button but only half of list view can be seen means I cannot scroll it. If I am not using scroll view, I can scroll the list view but not buttons. Can anybody please help me, where I am wrong? Thank you.. A: My suggestion is to just put the buttons as a listview header. This way you can scroll everything without the need for a ScrollView. see ListView.addHeaderView A: Do NOT put a ListView inside a ScrollView. ListView already handles scrolling, you're only going to run into trouble. In you case you can keep all the Button in a seperate xml layout with scroll and ListView in a seperate layout and use the addHeaderView property of ListView and add the layout of button's. Example of addHeaderView in ListView
{ "language": "en", "url": "https://stackoverflow.com/questions/7538335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: save the data of custom metabox to database I want to save the data of my custom meta box to the corresponding table in a field. my custom metabox.. add_action( 'admin_init', 'blc_add_custom_link_box', 1 ); add_action( 'save_post', 'blc_save_linkdata' ); function blc_add_custom_link_box() { add_meta_box( 'backlinkdiv', 'Backlink URL', 'blc_backlink_url_input', 'link', 'normal', 'high' ); } function blc_backlink_url_input( $post ) { // Use nonce for verification wp_nonce_field( plugin_basename( __FILE__ ), 'blc_noncename' ); // The actual fields for data entry echo '<input type="text" id="backlink-url" name="backlink_url" value="put your backlink here" size="60" />'; function blc_save_linkdata( $link_id ) { if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; if ( !wp_verify_nonce( $_POST['blc_noncename'], plugin_basename( __FILE__ ) ) ) return; if ( 'link' == $_POST['link_type'] ) { if ( ! current_user_can( 'edit_page', $link_id ) ) return; } else { if ( !current_user_can( 'edit_post', $link_id ) ) return; } $blc_linkdata = $_POST['blc_link']; ?> now i want to store the data in to the database table WP_link in a custom field. i got meta box in the link edit admin page . but it cant save the data in database. how it can be save in database table wp_link. I want know how to save the $blc_linkdata from custom metafield from the link edit page. Plz help.. A: You should find this page on the Wordpress Codex useful: http://codex.wordpress.org/Function_Reference/add_post_meta A: I would simply use the Meta Box Script from DeluxeBlogTips. I'm also working on a (huge) site that requires (many) metabox/custom field integrations. Trust me, this will save you lots of time and is well written and thoroughly tested ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7538337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom Sorting in Linq to Entities based on QueryString Spent all day trying to find ready to use solution for "Sort data in LINQ bases on Query String" without any results. SO, I have a LINQ query in action: public AcrionResult MyAction(int perPage = 10, string orderBy = "DESC", sting sortBy = "id") { var some = from m in db.Some select new ExampleModel {id = m.id, some = m.some}; return View(some); } From exmaple above: 1. perPage describe how many items we should show in page 2. orderBy DESC or ASC order 3. sortBy can be some field from ViewModel I need to make somethisng like this: var query = some.OrderFilter(...).AmountFilter(...).SortByFilter(...) Can somebody help me? Thanks a lot! A: You could use dynamic LINQ. Here's another example of implementing dynamic queries. A: The page size is best handled by Take and Skip – LINQ to Entities will translate that in to SQL. The parametrised sort can be done either by creating an expression tree based on the selected property and passing it to OrderBy or OrderByDescending as needed. Or by using Entity-LINQ building the SQL from the name of the field. The latter apporoach needs to white-list the column names to avoid SQL Injection..
{ "language": "en", "url": "https://stackoverflow.com/questions/7538341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prompt an alert box in cakephp? <?php $this->redirect(array('controller' => 'Users', 'action' => 'login', )); I would like to redirect and prompt and alert box saying your registration was successfully. How should I modify this code? A: You can use $session->setFlash("message");. In your Layout/View use $session->flash(); to get the output. Example: // Controller $session->setFlash("message"); // View print $session->flash("flash", array("element" => "alert")); // views/Elements/alert.ctp <script type="text/javascript"> alert("<?php print $message; ?>"); </script> For more details see this Page A: You can't display content and redirect using $this->redirect() at the same time because it uses http headers to do the redirect. You have to display the message either on the target page or use JavaScript for the redirection instead. You could save a session variable at the same time you save the user data ($this->Session->write( 'newUser', 1 )) and check the variable in the login form. If the variable is set, show the alert box and clear the variable. The other way is to use an extra parameter in the link that tells the login page that it should show the alert (users/login/newUser:1). The downside is that if the user bookmarks the page right after registering they'll see the message every time they visit the page. If you show the alert and then redirect using JavaScript instead of headers, it of course works only if the user has JS enabled so in this case you should also provide a clickable link that leads to the login page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flex Spark tabbar : initialize hidden tabs problem is I have a spark Tabbar, with many forms in each tab. But I have a single global save button. Problem is, if I don't open a Tab, it doesn't get initialized and therefore the forms it contains do not exist.. How Can I make it as if the user had clicked on every tab? A: The best way to handle this is to have a data model that each tab is displaying and editing, rather than trying to go in and read the values out of the controls in each tab, and save those. This is at the heart of MVC. However, if you're too invested in your current architecture to be able to change it and you are using a ViewStack with your TabBar, you may find that setting creationPolicy to "all" does what you want. If you're using States, I don't think you can force all of them to be instantiated without putting your application into each State at least once.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: return more then one JSON object in the same response and parsing it i have the following code: (simplified for readability) C# foreach(DataRow dRow in myDS.Tables[0].Rows){ Company myCompany = new Company(); myCompany.id = int.Parse(dRow["id"].ToString()); Companies.Add(myCompany); } JavaScriptSerializer serializer = new JavaScriptSerializer(); Response.Write(serializer.Serialize(Companies)); Response.End(); jQuery $.getJSON('ajax.aspx?what=' + $('input[name="what"]').val() + '&where=' + $('input[name="what"]').val(), function (data) { $.each(data, function (key, val) { var myCompany = new function () { this.id = val.id; } Companies.push(myCompany); }); }); Now, i have another object in the C# code, which is named Cities and i would like to return it in the same request. something like Response.Write(serializer.Serialize(Companies)); Response.Write(serializer.Serialize(Cities)); Response.End() and offcourse parse it on the Client side. how can i do something like that? A: You could wrap the two properties into an anonymous object: var result = new { Cities = Cities, Companies = Companies }; Response.Write(serializer.Serialize(result); Response.End(); Or if you are using some old .NET version which doesn't support anonymous objects you could define a wrapper class: public class Wrapper { public IEnumerable<Cities> Cities { get; set; } public IEnumerable<Company> Companies { get; set; } } and then: Wrapper result = new Wrapper(); wrapper.Cities = Cities; wrapper.Companies = Companies; Response.Write(serializer.Serialize(wrapper); Response.End(); Also fix your AJAX call as you are not properly url encoding your parameters: var data = { what: $('input[name="what"]').val(), where: $('input[name="what"]').val() }; $.getJSON('ajax.aspx', data, function (data) { $.each(data.Companies, function (index, val) { var myCompany = new function () { this.id = val.id; } Companies.push(myCompany); }); }); A: You need to create Object containing both collections like this: { "Cities": { ... Cities Collection ... }, "Companies": { ... Companies Collection ... } } So create one Object like [Serializable] public class Output { Collection<City> cities; Collection<Company> companies; } then will this object with data and output it
{ "language": "en", "url": "https://stackoverflow.com/questions/7538345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Help with overriding python import In application no.1 I have a settings.py file, and a utils.py, which contains the following: from application_one import settings def someFunction(): // do some logic here based on imported settings Then in application no.2 I do: from application_one.utils import someFunction In application no.2 I have a local settings.py and when I import 'someFunction()' I want to use the local settings.py not the file from application no.1. So how would one overide the import in application no.2? A: You can do the following: def someFunction(settings=settings): … # Unmodified code ('settings' refers to the local 'settings' variable) (this lets someFunction() use the Application 1 settings by default) and then call it from Application 2 by sending the local settings: someFunction(application2_settings) # Explicit settings sent by Application 2 One advantage of this approach is that your code in both Application 1 and 2 explicitly shows that someFunction() gives results that are setting-dependent. A: Simply ensure that you import your settings after you have loaded the function you wish to overload. However it seems that you'd be better of loading with namespaces intact, as this would prevent this entire issue from occurring.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using dconf watch callback I'm trying to use the dconf api to capture the background change event, in an Ubuntu 11.04. I've created a client and can read the background value, but when I change a dconf value (through dconf-editor), the callback function is not called. How should I use the callback technique? Thanks. Here is the code: #include <glib-2.0/glib.h> #include <glib-2.0/glib-object.h> #include <glib-2.0/gio/gio.h> #include </usr/include/dconf/dconf.h> #include <iostream> void WatchBackground (DConfClient *client, const gchar* path, const gchar* const *items, gint n_items, const gchar* tag, gpointer user_data){ if (g_strcasecmp(path, (gchar*)"/org/gnome/desktop/background/picture_uri") == 0){ std::cout << "filename Ok" << std::endl; } std::cout << "Call callback" << std::endl; } int main(int argc, char** argv) { g_type_init(); DConfClient *dcfc = dconf_client_new(NULL, WatchBackground, NULL, NULL); if (dcfc != NULL){ std::cout << "DConfClient created." << std::endl; GVariant *res = dconf_client_read(dcfc, (gchar*)"/org/gnome/desktop/background/picture-uri"); if (res != NULL){ gsize s = 0; std::cout << "/org/gnome/desktop/background/picture-uri: " << g_variant_get_string(res, &s) << std::endl; } else { std::cout << "NULL read" << std::endl; } } while(true){ sleep(1000); } return 0; } And here's the result of executing this program: (process:6889): GLib-WARNING **: XDG_RUNTIME_DIR variable not set. Falling back to XDG cache dir. DConfClient created. /org/gnome/desktop/background/picture-uri: /usr/share/backgrounds/space-02.png A: You must use GMainLoop to wait. Here is a simple code to demonstrate. #include <dconf.h> void watch(DConfClient *c, const gchar *p, const gchar * const *i, gint n, const gchar *t, gpointer unused) { g_message("%s", p); } int main(int argc, char *argv[]) { DConfClient *c; GMainLoop *l; g_type_init(); c = dconf_client_new(NULL, watch, NULL, NULL); dconf_client_watch(c, "/", NULL, NULL); l = g_main_loop_new(NULL, FALSE); g_main_loop_run(l); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7538366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change field in model metadata to read only in runtime based on criteria I'm creating a generic interface for editing pages and on some pages eg the start page I need to disable or remove some fields. The form is rendered with Html.EditorFor. What is the best way of doing this? A: You could write a custom editor template for the given type (string, decimal, object, ...): @model string @Html.TextBox( "", ViewData.TemplateInfo.FormattedModelValue, ViewData ) and then: @Html.EditorFor(x => x.Foo) or in views where you want it to be disabled: @Html.EditorFor(x => x.Foo, new { disabled = "disabled" })
{ "language": "en", "url": "https://stackoverflow.com/questions/7538367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to start sound after sound in soundmanager2 How can i start sound after sound in soundmanager2, i mean when the first sound ends, second sound to start and when the second end the third start and etc and etc.. A: var soundArray = ['sound1', 'sound2', ...]; var chain = function (sound) { soundManager.play(sound, { multiShotEvents: true, onfinish: function () { var index = soundArray.indexOf(sound); if (soundArray[index + 1] !== undefined) { chain(soundArray[index + 1]); } }}); }; chain(soundArray[0]) tray use recursion, the only problem can occur, when in array you put same sound twice(chain be infinity) A: There is an example of how to do this in the documentation (see Demo 4a). The play method takes an object as an argument. That object contains a set of options. One of those options is an onfinish callback function: soundManager.play('firstSound',{ multiShotEvents: true, onfinish:function() { soundManager.play('secondSound'); } }); The multiShotEvents option has to be set to true to cause the onfinish event to fire upon completion of each sound. By default it will only fire once sounds have finished. You could queue up as many sounds as you wanted to this way really. A: It took me like 3 hours to figure out.. but here it is: soundManager.play('sound1',{ multiShotEvents: true, onfinish:function() { soundManager.play('sound2',{ multiShotEvents: true, onfinish:function() { soundManager.play('sound3'); } }); } }); A: In addition to Ashot's answer and all the others, you can set the onfinish function when you create the sound, not only when you play it, for example: var demo2Sound = soundManager.createSound({ url: '../mpc/audio/CHINA_1.mp3', onfinish: function() { soundManager._writeDebug(this.id + ' finished playing'); } }); ...and if you need to change the onfinish function once the sound is already playing, you can do so like this: demo2Sound._onfinish = function(){ //now this function will override the previous handler };
{ "language": "en", "url": "https://stackoverflow.com/questions/7538372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Adding an indexed table view with sections from SQLite I have a table view which is populated from data from an SQLite database. I would like to make the table an indexed table view with sections. Can anybody suggest the best way to do this ? All the examples I can find use a plist which I am not using. Thanks ! A: this link may be helpful to you. You have to store the values in an array like the above link
{ "language": "en", "url": "https://stackoverflow.com/questions/7538373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change default folder So I'm developing with my team and we are using Github for that. Now, default folder is usually in C:\Documents and Settings\username\.ssh\somefolder now when I want to commit&push changes I MUST commit from this folder, but its annoying because I'm editing and testing files on my wamp which is located on D:\wamp\www now my question is, how to change default folder so I can pull repo and commit/push directly from my wamp? A: Simply move your local repository (the folder containing the .git subfolder and everything it contains) into the location you'd like to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Magento 1.6, changes to login.phtml don’t reflect I customized the file app\design\frontend\base\default\template\checkout\onepage\login.phtml to hide the login fields in onepage checkout. It works well in 1.5 version. When I do the same modifications in 1.6 version, nothing changes in the frontend. I observed that in 1.6 version, onepage.phtml is not using onepage\login.phtml unlike in 1.5. I did the basic checks of file location mistake(base\default and default\default) and cache refresh. I am having trouble figuring out which login.phtml is being picked up in onepage.phtml in the line getChildHTML(’login’) [to display the login fields in checkout step 1]. Thanks in advance. A: a) Do Not ever edit anything in Base, man! b) Configuration -> Developer, Switch to Website or store or store view scope, turn on Template path hints, Look into your Frontend, you'll See The path! A: Your problem may be related to the following Thread http://www.magentocommerce.com/boards/viewthread/243571/ about Persistent Shopping Cart. I encoutered a similar issue because of the template override name: * *before 1.6, my template override was: frontend/default//template/customer/form/login.phtml * 1.6: frontend/default//template/persistent/customer/form/login.phtml Elsewhere you can find the default template path from 1.6 : frontend/base/default/template/persistent/customer/form/login.phtml For more information about Persistent Shopping Cart, please refer to http://www.magentocommerce.com/blog/comments/persistent-shopping-cart-customer-segmentation-just-getting-better/
{ "language": "en", "url": "https://stackoverflow.com/questions/7538376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Martin Odersky's ScalaDay's 2011 Example: Yielding a Map? I was working through Odersky's ScalaDays 2011 keynote talk, where he constructs a phone number synonym generator in remarkably few lines of code, when I got to this particular line (assigning charCode): val mnem: Map[Char, String] = // phone digits to mnemonic chars (e.g. '2' -> "ABC") val charCode: Map[Char, Char] = for ((digit, str) <- mnem; letter <- str) yield (letter -> digit) // gives ('A', '2'), ('B', '2') etc Why is charCode of type Map? When I yield tuples in other examples, I merely obtain a sequence of tuples -- not a map. For example: scala> for (i <- 1 to 3) yield (i -> (i+1)) res16: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,2), (2,3), (3,4)) One can easily convert that to a map with toMap(), like so... scala> (for (i <- 1 to 3) yield (i -> (i+1))).toMap res17: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 2 -> 3, 3 -> 4) ... but somehow, Odersky's example avoids this. What Scala magic, if any, am I overlooking here? Addendum 1: Implicit conversion? I'd like to add some detail pertaining to Oxbow Lake's comment (NB: my comment there may be partially in error, having misunderstood slightly, perhaps, what he was getting at). I suspected that some kind of implicit conversion was happening because a map was required. So I tried Odersky's iterator in the interpreter, with no hints as to what it should produce: scala> val mnem = Map('2' -> "ABC", '3' -> "DEF", '4' -> "GHI") // leaving as a map, still scala> for ((digit, str) <- mnem; letter <- str) yield (letter, digit) res18: scala.collection.immutable.Map[Char,Char] = Map(E -> 3, F -> 3, A -> 2, I -> 4, G -> 4, B -> 2, C -> 2, H -> 4, D -> 3) (Note that I'm leaving mnem as a map here.) Likewise, telling the compiler I wanted a map didn't change my own result: scala> val x: Map[Int,Int] = for (i <- 1 to 3) yield (i -> (i+1)) <console>:7: error: type mismatch; found : scala.collection.immutable.IndexedSeq[(Int, Int)] required: Map[Int,Int] val x: Map[Int,Int] = for (i <- 1 to 3) yield (i -> (i+1)) On the other hand, following Eastsun's hints (and this seems to be what OL was saying, too), the following (dorky) modification does produce a map: scala> for ((i,j) <- Map(1 -> 2, 2 -> 2)) yield (i -> (i+1)) res20: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 2 -> 3) So if the iterated value comes from a map, somehow a map is produced? I expect the answer is to be understood by (a) converting the "for" loop to its longhand equivalents (a call/calls to map) and (b) understanding what implicits are being magically invoked. Addendum 2: Uniform Return Type: (huynhjl:) That seems to be it. My first example converts to (1 to 3).map(i => (i, i+1)) // IndexedSeq[(Int, Int)] Whereas the second becomes something akin to this: Map(1 -> 2, 2 -> 2).map(i => (i._1, i._1+1)) // Map[Int,Int] The type of "Map.map" is, then def map [B, That] (f: ((A, B)) ⇒ B)(implicit bf: CanBuildFrom[Map[A, B], B, That]): That Ah, trivial. ;-) Addendum 3: Well, okay, that was too simple, still. Miles Sabin provides a/the more correct desugaring, below. Even more trivial. ;-) A: charCode is a Map because mnem is a Map. You got a sequece because 1 to 3 is a sequence Some interesting examples: EDIT: I add a link to show how the magic of breakOut works. Scala 2.8 breakOut Welcome to Scala version 2.10.0.r25713-b20110924020351 (Java HotSpot(TM) Client VM, Java 1.6.0_26). Type in expressions to have them evaluated. Type :help for more information. scala> val seq = 1 to 3 seq: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3) scala> val seq2 = for(i <- seq) yield (i -> (i+1)) seq2: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,2), (2,3), (3,4)) scala> import collection.breakOut import collection.breakOut scala> val map2: Map[Int,Int] = (for(i<-seq) yield(i->(i+1)))(breakOut) map2: Map[Int,Int] = Map(1 -> 2, 2 -> 3, 3 -> 4) scala> val list2: List[(Int,Int)] = (for(i<-seq) yield(i->(i+1)))(breakOut) list2: List[(Int, Int)] = List((1,2), (2,3), (3,4)) scala> val set2: Set[(Int,Int)] = (for(i<-seq) yield(i->(i+1)))(breakOut) set2: Set[(Int, Int)] = Set((1,2), (2,3), (3,4)) scala> val map = (1 to 3).zipWithIndex.toMap map: scala.collection.immutable.Map[Int,Int] = Map(1 -> 0, 2 -> 1, 3 -> 2) scala> val map3 = for((x,y) <- map) yield(x,"H"+y) map3: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -> H0, 2 -> H1, 3 -> H2) scala> val list3: List[(Int,String)] = (for((x,y) <- map) yield(x,"H"+y))(breakOut) list3: List[(Int, String)] = List((1,H0), (2,H1), (3,H2)) scala> val set3: Set[(Int,String)] = (for((x,y) <- map) yield(x,"H"+y))(breakOut) set3: Set[(Int, String)] = Set((1,H0), (2,H1), (3,H2)) scala> val array3: Array[(Int,String)] = (for((x,y) <- map) yield(x,"H"+y))(breakOut) array3: Array[(Int, String)] = Array((1,H0), (2,H1), (3,H2)) scala> A: The magic you are overlooking is called the uniform return type principle. See An Overview of the Collections API section in http://www.scala-lang.org/docu/files/collections-api/collections.html. The collection library tries very hard to return the most specialized type based on the type of collection you start with. It's true for map and flatMap and for loops. The magic is explained in http://www.scala-lang.org/docu/files/collections-api/collections-impl.html, see Factoring out common operations. A: It's easier to understand why you get a Map back if you desugar the for comprehension, val charCode: Map[Char, Char] = for ((digit, str) <- mnem; letter <- str) yield (letter -> digit) is equivalent to, val charCode = mnem.flatMap { case (digit, str) => str.map { letter => (letter -> digit) } } So the type inferred for charCode here will be the result type of flatMap applied to a Map. flatMap's signature is quite complex, def flatMap [B, That] (f: ((A, B)) => GenTraversableOnce[B]) (implicit bf: CanBuildFrom[Map[A, B], B, That]): That because it's providing the infrastructure that the Scala compiler needs to compute the appropriate result type given the type of the Map and the type of the function being (flat)Map'd across it. As has been mentioned elsewhere, the collections framework has been designed in such a way that containers will be (flat)Map'd to containers of the same shape where possible. In this case we're mapping across a Map[Char, String], so its elements are equivalent to pairs (Char, String). And the function we're mapping is producing pairs (Char, Char), which concatenated can give us back a Map[Char, Char]. We can verify that the compiler believes this too by looking up the corresponding CanBuildFrom instance, scala> import scala.collection.generic.CanBuildFrom import scala.collection.generic.CanBuildFrom scala> implicitly[CanBuildFrom[Map[Char, String], (Char, Char), Map[Char, Char]]] res0: scala.collection.generic.CanBuildFrom[Map[Char,String],(Char, Char),Map[Char,Char]] = scala.collection.generic.GenMapFactory$MapCanBuildFrom@1d7bd99 Notice that the CanBuildFrom's last type argument is Map[Char, Char]. This fixes the "That" type parameter in flatMap's signature, and that gives us the result type for this flatMap, and hence the inferred type of charCode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Python group by array a, and summarize array b - Performance Given two unordered arrays of same lengths a and b: a = [7,3,5,7,5,7] b = [0.2,0.1,0.3,0.1,0.1,0.2] I'd like to group by the elements in a: aResult = [7,3,5] summing over the elements in b (Example used to summarize a probability density function): bResult = [0.2 + 0.1 + 0.2, 0.1, 0.3 + 0.1] = [0.5, 0.1, 0.4] Alternatively, random a and b in python: import numpy as np a = np.random.randint(1,10,10000) b = np.array([1./len(a)]*len(a)) I have two approaches, which for sure are far from the lower performance boundary. Approach 1 (at least nice and short): Time: 0.769315958023 def approach_2(a,b): bResult = [sum(b[i == a]) for i in np.unique(a)] aResult = np.unique(a) Approach 2 (numpy.groupby, horribly slow) Time: 4.65299129486 def approach_2(a,b): tmp = [(a[i],b[i]) for i in range(len(a))] tmp2 = np.array(tmp, dtype = [('a', float),('b', float)]) tmp2 = np.sort(tmp2, order='a') bResult = [] aResult = [] for key, group in groupby(tmp2, lambda x: x[0]): aResult.append(key) bResult.append(sum([i[1] for i in group])) Update: Approach3, by Pablo. Time: 1.0265750885 def approach_Pablo(a,b): pdf = defaultdict(int); for x,y in zip(a,b): pdf[x] += y Update: Approach 4, by Unutbu. Time: 0.184849023819 [WINNER SO FAR, but a as integer only] def unique_Unutbu(a,b): x=np.bincount(a,weights=b) aResult = np.unique(a) bResult = x[aResult] Maybe someone finds a smarter solution to this problem than me :) A: Here's approach similar to @unutbu's one: import numpy as np def f(a, b): result_a, inv_ndx = np.unique(a, return_inverse=True) result_b = np.bincount(inv_ndx, weights=b) return result_a, result_b It allows non-integer type for a array. It allows large values in a array. It returns a elements in a sorted order. If it is desirable it easy to restore original order usingreturn_index argument of np.unique() function. It performance worsens as the number of unique elements in a rises. It 4 times slower than @unutbu's version on the data from your question. I've made performance comparison with additional three methods. The leaders are: for integer arrays -- hash-based implementation in Cython; for double arrays (for input size 10000) -- sort-based impl. also in Cython. A: If a is composed of ints < 2**31-1 (that is, if a has values that can fit in dtype int32), then you could use np.bincount with weights: import numpy as np a = [7,3,5,7,5,7] b = [0.2,0.1,0.3,0.1,0.1,0.2] x=np.bincount(a,weights=b) print(x) # [ 0. 0. 0. 0.1 0. 0.4 0. 0.5] print(x[[7,3,5]]) # [ 0.5 0.1 0.4] np.unique(a) returns [3 5 7], so the result appears in a different order: print(x[np.unique(a)]) # [ 0.1 0.4 0.5] One potential problem with using np.bincount is that it returns an array whose length is equal to the maximum value in a. If a contains even one element with value near 2**31-1, then bincount would have to allocate an array of size 8*(2**31-1) bytes (or 16GiB). So np.bincount might be the fastest solution for arrays a which have big length, but not big values. For arrays a which have small length (and big or small values), using a collections.defaultdict would probably be faster. Edit: See J.F. Sebastian's solution for a way around the integer-values-only restriction and big-values problem. A: How about this approach: from collections import defaultdict pdf = defaultdict(int) a = [7,3,5,7,5,7] b = [0.2,0.1,0.3,0.1,0.1,0.2] for x,y in zip(a,b): pdf[x] += y You only iterate over each element once and use a dictionary for fast lookup. If you really want two separate arrays as results in the end you can ask for them: aResult = pdf.keys() bResult = pdf.values()
{ "language": "en", "url": "https://stackoverflow.com/questions/7538382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: "JSR-303 Provider is on the classpath" Means I am using Spring MVC 3. Here is the my model, public class MarketPlace { @NotNull(message="This Template Name is required") @Size(max=50) private String templateName; public String getTemplateName() { return templateName; } public void setTemplateName(String templateName) { this.templateName = templateName; } } and here is the controller method, public String PublishForm(@Valid MarketPlace m, BindingResult result) { if (result.hasErrors()) { return "Error"; } return "Sucess"; } But hasErrors is always false. Then I put these lines in dispather-servelet, xmlns:mvc="http://www.springframework.org/schema/mvc" ................ mvc:annotation-driven / But now now, NetBean showing me this error, The matching wildcard is strict, but no declaration can be found for element 'mvc:annotation-driven. Some people suggests me to "Set JSR-303 Provider is on the classpath" What does this means. I have these jars in my application, lib\slf4j-api-1.6.2.jar, build/web/Resources/validation-api-1.0.0.GA.jar, build/web/Resources/hibernate-validator-4.2.0.Final.jar Edit: <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="demo.htm">DemoAppMarketController ................................. <bean name="indexController" class="Controller.IndexControler" A: You have to be sure that the following xsi:schemaLocation entries exist: http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd In addition look at this tutorial it explains how to work JSR-303 Providers. http://www.openscope.net/2010/02/08/spring-mvc-3-0-and-jsr-303-aka-javax-validation/ Update: Frankly, I prefer another way for URL mapping: all jsp requested are mapped to *.html URLS. Now your Dispatcher servlet looks like that: <display-name>MyServlet</display-name> <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> Than your Spring URL mapping looks like that: <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean>
{ "language": "en", "url": "https://stackoverflow.com/questions/7538383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In Python, how to catch the exception you've just raised? I've got this piece of code: jabberid = xmpp.protocol.JID(jid = jid) self.client = xmpp.Client(server = jabberid.getDomain(), debug = []) if not self.client.connect(): raise IOError('Cannot connect to Jabber server') else: if not self.client.auth(user = jabberid.getNode(), password = password, resource = jabberid.getResource()): raise IOError('Cannot authenticate on Jabber server') It's using xmpppy. Since xmpppy does not throw any exceptions if it could not connect or authenticate, I need to throw them myself. The question is, how do I catch those exceptions I throw to output only the error message, but not the full traceback, and keep the code running despite them? EDIT Is this construction appropriate? def raise_error(): raise IOError('Error ...') if not self.client.connect(): try: self.raise_error() except IOError, error: print error A: Try/except like with all exceptions in python. Here is an example: def raise_error(): raise IOError('Error Message') print('Before Call.') try: raise_error() except IOError as error: print(error) print('After Call.') Edit: To make a more realistic example: def connect_to_client(): ... if time_since_client_responded > 5000: raise ClientTimeoutError(client_name+" timed out.") ... try: connect_to_client("server:22") except ClientTimeoutError as error: print(error) sys.exit(1) A: Use try: ... except: .... The Python tutorial explains the use of this construct here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: cancan and enums only on "show" action I'm using cancan in my rails 3 application with mysql DB. When i create a rule based on an enum column i always get AccessDenied only for "show" action. Any idea why? I use enumerated_attribute to enforce enums in the models and an actual ENUM type column in the database. Example: I have a Post that has an enum field privacy with ['PUBLIC','PRIVATE','LOCAL']. I always get AccessDenied when i use this rule: can :read, Post, :privacy => 'PUBLIC' Every other rule works perfectly. The above rule also works great on "index" action. UPDATE 1: My ability.rb: class Ability include CanCan::Ability def initialize(user) can :read, Post, :privacy => 'PUBLIC' end end A: The question was answered here: https://github.com/ryanb/cancan/issues/479
{ "language": "en", "url": "https://stackoverflow.com/questions/7538387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Face Detection on Camera video input on iPhone I am working on a project that needs to do face detection on a camera video input (like security camera). I managed to open Video input via AVFoundation framework. I managed to capture a UIImage from the video input, then feed into opencv library to do face detection. But the process of capturing requires at least 2 to 3 seconds. Is there anyone who got some experience to share ? A: If you can work with the limitation if iOS 5, you can get this to work pretty well with the new CIFaceDetector baked into the OS. That should help address performance concerns and simplify the code if you're not worried about implementing your own version of face detection. Apple has some sample code projects up on the developer forums here. There are some details on the kind of data available using their face detection here and some basic docs for the detector here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to delete firefox cookies in C#? I delete firefox cookies by this code: if(Environment.SpecialFolder.ApplicationData + @"\Mozilla\Firefox\Profiles\cookies.sqlite") { File.Delete(Environment.SpecialFolder.ApplicationData + @"\Mozilla\Firefox\Profiles\cookies.sqlite"); } but when I run firefox, deleted file restored again. Can one help me? A: Why you dont use "DELETE" sql command insted of deleting sql file? You can use sqlite file in your C# application. http://www.codeproject.com/KB/cs/SQLiteCSharp.aspx http://www.dreamincode.net/forums/topic/157830-using-sqlite-with-c%23/
{ "language": "en", "url": "https://stackoverflow.com/questions/7538394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can I wait for results in javascript? I have a bit of javascript code that is getting loading in some data from an RSS feed. I then need to process that data and then get some more data from another RSS feed, but it is dependant on the results of the first feed. When I run my app, it processes both feeds at the same time, how can I make the second feed wait for the first to finish? A: You can use the setTimeout function which postpones a function call for the number of milliseconds specified as explained at http://www.w3schools.com/js/js_timing.asp A: The trick is to treat the loading of the rss feeds like what they are: asynchronous events. Do something like this: var success1=false, success2 = false; function onRssFeed1Success() { //lets pretend this gets called when rss feed 1 is loaded success1 = true; doStuffDependentOnBothFeeds() } function onRssFeed2Success() { //lets pretend this gets called when rss feed 2 is loaded success2 = true; doStuffDependentOnBothFeeds() } function doStuffDependentOnBothFeeds() { if(success1 && success2) { //do stuff } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7538400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }