text
stringlengths
8
267k
meta
dict
Q: Switch databases in CodeIgniter Sorry if this is a real newbie question (also a php newbie), but I can't figure it out from the docs: I want to be able to use a default database, if I don't speficy anything else, and that works fine using $this->db with the following configuration: $active_group = 'default'; $active_record = TRUE; $db['default']['hostname'] = 'localhost'; $db['default']['username'] = 'root'; $db['default']['password'] = 'root'; $db['default']['database'] = 'ion_auth'; $db['default']['dbdriver'] = 'mysql'; $db['default']['dbprefix'] = ''; $db['default']['pconnect'] = TRUE; $db['default']['db_debug'] = TRUE; $db['default']['cache_on'] = FALSE; $db['default']['cachedir'] = ''; $db['default']['char_set'] = 'utf8'; $db['default']['dbcollat'] = 'utf8_general_ci'; $db['default']['swap_pre'] = ''; $db['default']['autoinit'] = TRUE; $db['default']['stricton'] = FALSE; $db['visitorsDB']['hostname'] = 'localhost'; $db['visitorsDB']['username'] = 'root'; $db['visitorsDB']['password'] = 'root'; $db['visitorsDB']['database'] = 'visitorsDB'; $db['visitorsDB']['dbdriver'] = 'mysql'; $db['visitorsDB']['dbprefix'] = ''; $db['visitorsDB']['pconnect'] = TRUE; $db['visitorsDB']['db_debug'] = TRUE; $db['visitorsDB']['cache_on'] = FALSE; $db['visitorsDB']['cachedir'] = ''; $db['visitorsDB']['char_set'] = 'utf8'; $db['visitorsDB']['dbcollat'] = 'utf8_general_ci'; $db['visitorsDB']['swap_pre'] = ''; $db['visitorsDB']['autoinit'] = TRUE; $db['visitorsDB']['stricton'] = FALSE; But then I want to use the second database in one of my models, so I tried this: function __contruct() { parent::__construct(); $this->db = $this->load->database('visitorsDB', TRUE); } public function getAllVisitors($paramArr) { //$this->db = $this->load->database('visitorsDB', TRUE); But that doesn't work. Only if I uncomment the last line so that I load the database in the method itself will it work. I don't understand why. I also tried declaring a new class variable at the beginning of the class - private $myDB; - and then instantiating it in the constructor - $myDB = $this->load->database('visitorsDB', TRUE); But that didn't work either. So how can I switch database for the entire model? A: when login user with database changed private $db; function __construct() { parent::__construct(); if($this->session->userdata('username') == "swaroop") $this->db = $this->load->database('visitorsDB', TRUE); else $this->db = $this->load->database('default', TRUE); } A: I wouldn't recommend selecting a second database by overwriting $this->db. Just add a property for your other database in the model you need it and access it through that. In your model do this: private $myDB; function __construct() { parent::__construct(); $this->myDB = $this->load->database('visitorsDB', TRUE); } function getAllVisitors() { return $this->myDB->someMethod(); // Or use active record, etc... } I know in your question you said that you did something similar but I'm not sure if you did it correctly. This would be the correct way of doing so and I don't see why it wouldn't work if it was done this way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: while switching between android phone modes the video runs from the beginning In my application while playing a video if i change the phone's mode the video does not continue to play but it starts from the beginning. all i understand is the activity is recreated when the mode is changed,how do i fix this i have no idea please someone help me fix this. thanks in advance A: Follow these links: http://android-developers.blogspot.com/2009/04/updating-applications-for-on-screen.html http://davidwparker.com/2011/08/30/android-how-to-float-a-row-above-keyboard/ A: Add the following thing in EditText and remove android:windowSoftInputMode="stateHidden|adjustResize" from manifest file <EditText android:id="@+id/edtInput" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_weight="1" android:inputType="textShortMessage|textAutoCorrect|textCapSentences|textMultiLine" android:imeOptions="actionSend|flagNoEnterAction" android:maxLines="4" android:maxLength="2000"/> for more detail follow this link http://developer.android.com/resources/articles/on-screen-inputs.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7596138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i setup this layout? I would like to make a rather complex layout. Can someone help me, as how to do my layout.xml ? Layout image No. 1 is a Layout (Table, Linear etc) No. 2 is my listview, containing a row of list_details.xml Edit: so far I managed to do the first part <TableLayout android:layout_height="wrap_content" android:layout_width="fill_parent"> <TableRow android:layout_width="wrap_content" android:stretchColumns="0,2" android:layout_marginTop="2sp" android:layout_height="wrap_content" > <TextView android:id="@+id/homeTeam" android:layout_weight="2" android:paddingRight="4sp"/> <TextView android:text="Vs" android:layout_weight="0" /> <TextView android:id="@+id/awayTeam" android:layout_weight="2" android:gravity="right" android:paddingLeft="4sp"/> </TableRow> </TableLayout> <ListView android:id="@id/android:list" android:layout_width="wrap_content" android:layout_height="wrap_content"> </ListView> EDIT: Well i probably didn't explain well what i want to do. Here is a screenshot of my app My current layout I want the columns to align. So far i am using this xml <?xml version="1.0" encoding="utf-8"?> <TableLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:stretchColumns="0,4" xmlns:android="http://schemas.android.com/apk/res/android"> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/ll_playerHome" android:layout_weight="0.5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12sp"/> <ImageView android:id="@+id/ll_eventHome" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:id="@+id/ll_minute" android:layout_weight="0" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <ImageView android:id="@+id/ll_eventAway" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:id="@+id/ll_playerAway" android:layout_weight="0.5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:textSize="12sp"/> </TableRow> </TableLayout> A: This might do the trick: <?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"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout1"> <TextView android:layout_width="wrap_content" android:text="TextView" android:id="@+id/textView1" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_horizontal"></TextView> <TextView android:text="TextView" android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal"></TextView> <TextView android:layout_width="wrap_content" android:text="TextView" android:id="@+id/textView3" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_horizontal"></TextView> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout2"> <ListView android:layout_height="wrap_content" android:id="@+id/listView1" android:layout_weight="1" android:layout_width="fill_parent"></ListView> <TextView android:text="TextView" android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal"></TextView> <ListView android:layout_height="wrap_content" android:id="@+id/listView1" android:layout_weight="1" android:layout_width="fill_parent"></ListView> </LinearLayout> </LinearLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/7596139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compare tables and identify new or changed fields New to SQL, would like to compare fields between a stg and src table. The identify any differences between the tables and assign transaction status of 'C' for change. Any new records will be set with 'A' for add. STG_DM_CLIENT and SRC_DM_CLIENT What is the best way to do it, would it be best to do a some form of union all. Unsure how to proceed, any assistance welcomed. A: You can identify new records by using NOT IN or NOT EXISTS update STG_DM_CLIENT SET TransactionStatus = 'A' WHERE ID IN (select Id from STG_DM_CLIENT where Id not in (select Id from SRC_DM_CLIENT)) Then, you can identify changed records by comparing fields: update STG_DM_CLIENT SET TransactionStatus = 'C' WHERE ID IN (select STG_DM_CLIENT.Id from STG_DM_CLIENT join SRC_DM_CLIENT on SRC_DM_CLIENT.Id = STG_DM_CLIENT.Id where (SRC_DM_CLIENT.Field1 != STG_DM_CLIENT.Field1 OR SRC_DM_CLIENT.Field2 != STG_DM_CLIENT.Field2 ...)) A: update [STG] set TransactionStatus = CASE WHEN [SRC].id IS NULL THEN 'A' ELSE 'C' END from STG_DM_CLIENT AS [STG] left join SRC_DM_CLIENT AS [SRC] ON [STG].id = [SRC].id -- Or whatever relates the records 1:1 WHERE [SRC].id IS NULL OR [STG].field1 <> [SRC].field1 OR [STG].field2 <> [SRC].field2 OR [STG].field3 <> [SRC].field3 ... OR [STG].fieldn <> [SRC].fieldn
{ "language": "en", "url": "https://stackoverflow.com/questions/7596144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not able to load properties file in Java I am trying to load a properties file. The properites file is in the class path of the application. Properties p = new Properties(); p.load(new FileInputStream("classpath:mail.properties")); System.out.println(p.get("hi")); Now I say classpath, because another file called x.properties is referred in an xml file like this <property name="x"> <util:properties location="classpath:x.properties" /> </property> I placed my mail.properties in the same folder as x.properties, but my Java program is not able to find it ? Any idea what I am missing ? A: Just because some program processing that XML file likes the syntax classpath:x.properties doesn't mean that it is a universally accepted syntax in Java! If you provide "classpath:x.properties" to a FileInputStream it will look for a file named classpath:x.properties. (Check the documentation of that particular constructor.) Try providing the full path to that file. If the file happens to be on your class path, you could use something like p.load(getClass().getResourceAsStream("mail.properties")); A: if mail.properties is indeed on your classpath, you will have better luck loading it via a class loader: Properties p = new Properties(); InputStream is = getClass().getClassLoader().getResourceAsStream("mail.properties"); p.load(is);
{ "language": "en", "url": "https://stackoverflow.com/questions/7596155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get a user email from Facebook Graph Api? I'm confused here, I'm trying to get user data using Facebook Api, I'm requesting email permission using scope=email like this: https://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&redirect_uri=MY_URI&scope=email In Facebook access confirmation window I see that my application requests access to the email, but even after that when I do request to Graph Api it doesn't return the email (it does return all other fields) If I do a request like this: https://graph.facebook.com/me?fields=id,name,email&access_token=MY_TOKEN it only returns id and name. A: Thank you all guys for your time. It started to work by itself after I deleted the app access from My account in Facebook and then tried to get access again. A: Try using c# sdk it's to easy with it. There are some examples in this link. Hope it helps. A: Use the FQL API for this: query: select contact_email from user where uid=me() Call: https://api.facebook.com/method/fql.query?format=json&query=select+contact_email+from+user+where+uid%3Dme%28%29&access_token=[access_token] A: Check whether you have the permission of email or user have unchecked it while approving the request you raised from the URL : facebook.com/dialog/oauth?client_id=MY_APP_ID&redirect_uri=MY_URI&scope=email. You can check using https://graph.facebook.com/me?fields=permissions&access_token=[TOKEN]. It should give you response notifying whether email permission is granted or not like below: { "permissions":{ "data": [ { "permission": "user_friends", "status": "granted" }, { "permission": "email", "status": "granted" }, { "permission": "public_profile", "status": "granted" } ] }, "id": "10207905751235096" } check facebook tool explorer for more: https://developers.facebook.com/tools/explorer/ A: I'm not sure if this is for an app, if so, I had the same problem until I published my app. Check the documentation to see if it applies to you: https://developers.facebook.com/apps/{your app id}/review-status/ After approved, the email and other sensitive info will show...
{ "language": "en", "url": "https://stackoverflow.com/questions/7596157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Show the complete sections of rows in my table view after scrolling is done i have table view(it has sections). at a time it will show only 4 images/rows(the height of table View is set according to that). when the scrolling is done, it will display 5th row half section,6th row full, 7th row full ,8th row full , 9th row half section as usual. however i don't want to show the half section of any rows. i need to show the complete sections of rows in my table view(it may be Rows 5,6,7,8 or Rows 6,7,8,9) after my scroll function is done. is any way to do it?any property for tableView to do it? A: I think you should combine next methods: * *scrollToRowAtIndexPath:atScrollPosition:animated: Scrolls the receiver until a row identified by index path is at a particular location on the screen. - (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated *scrollViewDidEndDragging:willDecelerate: Tells the delegate when dragging ended in the scroll view. - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate *scrollViewDidEndDecelerating: Tells the delegate that the scroll view has ended decelerating the scrolling movement. - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{ "language": "en", "url": "https://stackoverflow.com/questions/7596158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multithreaded FTP download I'm trying to process a certain FTP directory which holds several directories and in turn those directories have an arbitrary number of files. So what I'm trying to do is to have 1 thread for each of the subdirectories and each thread to be concerned with the respective sub-dir here is what I came up: private void fetchFilesFromFTP() { try { client.connect("ftp.ncbi.nih.gov"); client.login("anonymous", "anonymous"); client.changeWorkingDirectory("genomes/Fungi"); FTPFile dirs[] = client.listDirectories(); dirsToDl.addAndGet(dirs.length); for (final FTPFile ftpFile : dirs) { exec.execute(new Runnable() { //process each FTP directory in a new thread @Override public void run() { processFTPdir(ftpFile.getName()); } }); } } catch (SocketException ex) { Logger.getLogger(FungiProcessor.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(FungiProcessor.class.getName()).log(Level.SEVERE, null, ex); } } private void processFTPdir(String dir) { File f = new File(destination + File.separator + dir); if (!f.mkdirs()) { System.out.println("Error creating dir for " + dir); return; } FTPFile files[]; try { //we are already in the correct directory files = client.listFiles(dir, new FTPFileFilter() { @Override public boolean accept(FTPFile ftpf) { return ftpf.getName().endsWith(".gbk"); } }); for (FTPFile fTPFile : files) { FileOutputStream fout = new FileOutputStream(destination + File.separator + dir + File.separator + fTPFile.getName()); if (client.retrieveFile(dir + "/" + fTPFile.getName(), fout)) { System.out.println("successfully downloaded"); fout.flush(); fout.close(); } System.out.println(client.getReplyString()); } } catch (IOException ex) { Logger.getLogger(FungiProcessor.class.getName()).log(Level.SEVERE, null, ex); } finally { if(dirsToDl.decrementAndGet() == 0) latch.countDown(); } } The sequential version of the code works - I can see files ending with .gbk actually being downloaded whereas with the multithreaded version only the respective subdirectories are created but no files are downloaded. I don't even get any errors. Is is possible that FTP doesn't support multiple file downloads at once? A: A better way is to have one tread with its own client connect to the server and create a list of paths of the files you want to download. Then you start up a number of threads, each with its own client, that grabs the first from the list and starts downloading the file. The number of concurrent connections that you can have to one ftp-server is limited by the settings of that server. A: I highly doubt this would work with multiple threads. All the threads would share the same client (and thus, the same command channel), and FTP doesn't provide a way to do the kind of multiplexing you'd need in order to make it work. (Responses to two threads' commands look pretty much the same; there's no way for FTP to say "this is a response to command 1".) You'd have to have each thread grab a lock before sending a command and unlock only after getting a response...forcing one command at a time to run, and serializing things so much that you'd lose all the benefits of multithreading anyway. The only way around that would be to use a client per thread, but then you'll end up running into per-user connection limits (which tend to be pretty strict). All in all, this sounds like a job for a single thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Get by reflection properties of class ,but not from inherited class class Parent { public string A { get; set; } } class Child : Parent { public string B { get; set; } } I need to get only property B, without property A but Child.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance) return both properties :/ A: From Type.cs : In this case use the DeclaredOnlyLookup private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; internal const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; A: Add BindingFlags.DeclaredOnly A: You should add BindingFlags.DeclaredOnly to your flags, i.e: typeof(Child).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly) A: Try using the DeclaredOnly binding flag. It should limit the properties returned to only those declared on the class you are interested in. And here is a code sample: PropertyInfo[] properties = typeof(Child).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly);
{ "language": "en", "url": "https://stackoverflow.com/questions/7596162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "91" }
Q: Javascript game: moving bar I'm programing a penalty kick off game (javascrit + CSS3) and I need your help to figure out how to build the "pick up your shooting power" screen. Like in those golf games I want it to have a bar that moves from left to right ascending and then descending non stop. The player has to click on the bar and the bar stops selecting the power with which the penalty will be shooted. How can I do that? A: Here is pseudocode for you: on mousedown at bar start charging power on mouseup at bar kick if charge is > 100% kick
{ "language": "en", "url": "https://stackoverflow.com/questions/7596165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Saving images in Document Directory I am downloading images from web in uitableview and want to save in document directory. I am downloading syncronously. I downloaded and saved in document directory successfully, but when i scroll uitable every time images are being saved , i want to save images at the time of downloading only once. What should i do? Can anybody provide me some code? Any help will be appreciated. A: You should never use synchronous download. It will block your UI, make your UITableView scrolling lag, make the user think your app has frozen... Very bad idea. You should instead always use asynchronous download using NSURLConnection's loadRequest: method and implementing the delegate methods yourself (even probably dedicate a class to manage the download, as everybody do) See the LazyTableImages sample code from Apple Documentation, it explains how to load images asychronously to display them in a TableView, loading them on demand, and avoiding to freeze the UI. Never do blocking operations in the delegate methods of UITableView like tableView:cellForRowAtIndexPath: (and I hope you use the reuse-mechanism of UITableViewCells correctly too, to reduce cell allocations. See the TableView Programming Guide about this point) Once you have implemented the asynchronous download using NSURLConnection and its delegate methods, its a piece of cake to move the code that saves the images in the documents folder in the connectionDidFinishLoading: delegate method (thus saving them only once and only when they are downloaded) A: Do the saving of images in didConnectionFinishLoading method. You can also use an NSNotification for this, to know when the download is getting completed. Hope this information is useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Encrypt an decrypt files in iphone I want to encrypt and decrypt file in Iphone using AESEncryption. It works good for NSData. But if i take Data in chunks my file gets currpt. How do i do this. I am able to encrypt and decrypt data using commoncrypto library. But problem occours when i try to read data in chunks. Thank you in advance. Please Help. I need to implement this asap. A: AES encryption is block-based; it works on blocks of 16 bytes of data at a time. If you jump into encrypted data at an arbitrary point that in not on a block boundary then you will get corrupt data when you decrypt. What you need to do is calculate the start and end block boundaries that encompass the region you want to decrypt, do the decryption, then trim the start and end of the extraneous bytes. Alternatively, just make sure that you are always working in multiples of 16 bytes and limit your data access to block boundaries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to combine MSI files created with WiX in differnet languages to one file where yo can select the language? I have a Windows Installer XML (WiX 3.5) project and five localization files for my installer. Therefore WiX creates five .msi files, for every language one. How can i put all in one .msi and let the user select the language when executing the installer? I heard something about a bootstrapper, but then i would have a Setup.exe and i need a msi file. Is it not possible to adabt the localization strings after compiling with WiX? A: This can be done using transforms. Please take a look at this article: http://www.installsite.org/pages/en/msi/articles/embeddedlang/ A: There are 2 parts to making this happen, * *localisation of the Installer UI, and/or *choice of installed files. The method I chose will automatically select the local (or near local) language, and can also be forced to a specific transform using command line options. This doesn't prompt the user to choose which language to install in - so maybe it doesn't actually meet your needs. The second 'installed files' doesn't seem to be documented as well and I was recently asking about it in Why would MST not include files with different content. As a response provided there is now an ANT build script using Windows7 SDK & antdotnet
{ "language": "en", "url": "https://stackoverflow.com/questions/7596172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to kill Thread + .net + System.AddIn I have developed one scheduler which is creating new thread at each new event. In that thread based on some id one dll is loaded using System.AddIn. Now i want to kill that event in a midway? How can i implement this functionality in this situation A: I assume you are loading the addins in a separate appdomain. If not, start doing it. Otherwise you can't kill them in a controlled manner. To kill an addin, unload the appdomain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: when to malloc and when not to -- c programming I have few issues regarding when to use malloc or in this case strdup. Below is the small function which I have stolen from internet. I am trying to understand the code but stuck with few issues. 1. the code has assigned value to psrc and pdest. example char* psrc = dups; char* pdest = s; Doubt: don't we need to use malloc to allocate space for psrc and pdest.? If not then why. * *pdest [0] = '\0'; The above line allocates termination character at the starting of pdest string. then previously why we have assigned pdest to s . example char* pdest = s;? Any help or criticism will be helpful to me. Thanks and regards, Sam char* deldupchars (char* s) { char* dups = strdup (s); if (dups) { char* psrc = dups; char* pdest = s; char ch; pdest [0] = '\0'; while ((ch = *psrc++) != '\0') { if (! strchr (pdest, ch)) { *pdest++ = ch; } } pdest [0] = '\0'; free (dups); } return s; } A: char* psrc = dups; No need to allocate here since dups was allocated by strdup. char* pdest = s; No need to allocate here since s was allocated by the caller. pdest[0] = '\0'; This writes into the contents of the string. The assignment pdest = s assigns pointers but not contents. A: We don't have to allocate memory for for dups because the char* psrc = dups statement does not copy what dups points to, just where it points. This means the allocation done in strdup is enough for both pointers A: strdup() malloc()s the memory for the string, which is why you can store through the pointer that strdup() returns. But you have to free() that memory, which you correctly do. From the strdup() man page: The strdup() function returns a pointer to a new string which is a duplicate of the string s. Memory for the new string is obtained with malloc(3), and can be freed with free(3). A: strdup will do the malloc inside it and return the allocated memory (that's why you need to call free(dups) in the end of the function). pdest/psrc are just a pointers (i.e.: just references the memory that was previously allocated from 's', and later is used to walk in that allocated memory). I think the main confusion is that pointers are just that: they point to an address in memory -- so, you can have many pointers to the same memory address and you can use that pointer to walk -- in the previously malloc'ed memory). See: http://www.mkssoftware.com/docs/man3/strdup.3.asp A: 1) What you get in psrc and pdest is no more than another pointer to the character string. This doesn't mean you have 2 character strings, but two pointers to the same string. String is not duplicated. You don't need to allocate psrc and pdest because the compiler is already allocating memory for those variables when you declare them (just like you don't need to allocate memory for int a, for example). They're just 32 bits unsigned integers (for 32-bit systems, that is). 2) pdest is used to not modify original s value, since pdest is modified inside the while loop. Again, the string is NOT duplicated, so actually pdest is modifying the string pointed by s. A: * *You don't have value assignment there, but pointers assignment. This means that psrc points at the same memory location as dups. If you want to copy content of that memory location then you need to allocate memory and then copy. (malloc + memcpy) *pdest [0] = '\0'; - no allocation here. This just places null-terminator at the beginning of array it points to. char* pdest = s; made pdest pointing at the same memory as s. A: #include <stdio.h> size_t undup (char *str); size_t undup (char *str) { size_t src, dst; for (src=dst=0; str[dst] = str[src++] ; ) { if (str[dst] != str[src] ) dst++; } return dst; } int main (int argc, char **argv) { printf ("Before:%s\n", argv[1] ); (void) undup ( argv[1] ); printf ("After:%s\n", argv[1] ); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7596177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SVG viewer alternative for flash rendering in IE Hi i have a problem with svg viewer in Internet Explorer, because i use flash, maybe you can suggest me another solution for this browser. A: The Chrome Plugin for Internet Explorer is very seamless. We use it in several projects and have been able to display a simple error message to the user indicating that they need to install the plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to include and use new fonts in win32 project.? I have downloaded new ttf font. And I want to use that font in my win32 project. How to include and use new fonts in my project.? A: Add the font as resource, load the resource, then use AddFontMemResourceEx API: This function allows an application to get a font that is embedded in a document or a webpage. A font that is added by AddFontMemResourceEx is always private to the process that made the call and is not enumerable. You can find example code in this codeguru article.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: On Win7, how do I debug in older versions of IE I get reports that a button does not work in my webapp on IE8 (and older). Everything works in IE9, FF and Chrome. The error is triggered in this click-bind: $("#save_refresh").click(function(e) { alert('hello world!'); }); This is the html: <input class='button' type='button' value='Save / Refresh' id='save_refresh' /> When clicking the button in IETester running IE8, the "hello world!" is not shown and I get this error: Line: 17 Character: 28691 Error: Code: 0 URL: jquery-1.6.1.min.js So my question is: is there anything wrong with my above code OR does anyone know how to debug javascript in older version of IE. A: I agree with Quentin. You should download one of Microsoft's Internet Explorer Application Compatibility VPC Images to properly test your code. Paul Irish has a good article on the incompatibilities of Internet Explorer compatibility modes. The IE9 compatibility modes are unreliable in terms of giving you an accurate picture of how the browser will actually render your page and how your page will behave under that browser. It's like putting a Chevrolet Metro engine in your Chevrolet Aveo so you can test drive the Metro. That said, when using IE8, you can just hit F12 like in IE9, but with IE7, you need to have a copy of Visual Studio and use the debugger keyword. A: Microsoft provide virtual machines with older versions of Internet Explorer for testing. A: Using IE9, you can switch to the IE7 or IE8 rendering engine. Press F12 and the developer panel should appear. The header bar has options to switch to the IE7 and IE8 Browser Modes (and their respective notorious Quirks Modes). For IE6, you'll have to rely on Virtual Machines (as mentioned by Quentin above). Microsoft released XP Mode partly for this. A: Internet explorer has compatibility mode for IE7 and IE8 (and even for Quirks mode), it which you can debug most of the issues. Rarely you need true installation of older version of IE
{ "language": "en", "url": "https://stackoverflow.com/questions/7596181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How many messages are send with System.Net.Mail.SmtpClient.Send() if multiple recipients are specified? I have some code which uses System.Net.Mail.SmtpClient.Send to send data from a piece of software I maintain. We're charged on the amount of data we send so it's crucial that we identify the most cost effective way to distribute the information. If I specify multiple recipients, am I right in thinking the software would be transmitting one email per recipient? i.e. if each email was 1MB and I had three recipients, I'd be sending 3MB? A: Usually when you send a mail with multiple recipients, your client sends one email to your provider and this is responsible to send one message to every recipient... If you want to be sure, use WireShark to monitor SMTP port you use and check the traffic amount. EDITED: My previous answer was true if you have an external provider; situation can be different if you have an internal mail server in your company: in this case your server is responsible to send this email and, according to its configuration (using a smarthost, etc...), it could send a single email to an external provider or send multiple emails one for each recipient. In this case you must check what happens on SMTP port of your server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is RVO (Return Value Optimization) applicable for all objects? Is RVO (Return Value Optimization) guaranteed or applicable for all objects and situations in C++ compilers (specially GCC)? If answer is "no", what are the conditions of this optimization for a class/object? How can I force or encourage the compiler to do a RVO on a specific returned value? A: Return Value Optimization can always be applied, what cannot be universally applied is Named Return Value Optimization. Basically, for the optimization to take place, the compiler must know what object is going to be returned at the place where the object is constructed. In the case of RVO (where a temporary is returned) that condition is trivially met: the object is constructed in the return statement, and well, it is returned. In the case of NRVO, you would have to analyze the code to understand whether the compiler can know or not that information. If the analysis of the function is simple, chances are that the compiler will optimize it (single return statement that does not contain a conditional, for example; multiple return statements of the same object; multiple return statements like T f() { if (condition) { T r; return r; } else { T r2; return r2; } } where the compiler knows that r or r2 will be returned...) Note that you can only assume the optimization in simple cases, specifically, the example in wikipedia could actually be optimized by a smart enough compiler: std::string f( bool x ) { std::string a("a"), b("b"); if ( x ) return a; else return b; } Can be rewritten by the compiler into: std::string f( bool x ) { if ( x ) { std::string a("a"), b("b"); return a; } else { std::string a("a"), b("b"); return b; } } And the compiler can know at this time that in the first branch a is to be constructed in place of the returned object, and in the second branch the same applies to b. But I would not count on that. If the code is complex, assume that the compiler will not be able to produce the optimization. EDIT: There is one case that I have not mentioned explicitly, the compiler is not allowed (in most cases even if it was allowed, it could not possibly do it) to optimize away the copy from an argument to the function to the return statement: T f( T value ) { return value; } // Cannot be optimized away --but can be converted into // a move operation if available. A: Is RVO (Return Value Optimization) guaranteed for all objects in gcc compilers? No optimisation is ever guaranteed (though RVO is fairly dependable, there do exist some cases that throw it off). If answer is "no", what is the conditions of this optimization for a class/object? An implementation detail that's quite deliberately abstracted from you. Neither know nor care about this, please. A: To Jesper: if the object to be constructed is big, avoiding the copy might be necessary (or at the very least highly desirable). If RVO happens, the copy is avoided and you need not write any more lines of code. If it doesn't, you'll have to do it manually, writing extra scaffolding yourself. And this will probably involve designating a buffer in advance, forcing you to write a constructor for this empty (probably invalid, you can see how this is not clean) object and a method to ‘construct’ this invalid object. So ‘It can reduce my lines of code if it's guaranteed. Isn't it?’ does not mean that Masoud is a moron. Unfortunately for him however, RVO is not guaranteed. You have to test if it happens and if it doesn't, write the scaffolding and pollute your design. It can't be herped. A: Move semantics (new feature of C++11) is a solution to your problem, which allows you to use Type(Type &&r); (the move constructor) explicitly, instead of Type(const Type &r) (the copy constructor). For example: class String { public: char *buffer; String(const char *s) { int n = strlen(s) + 1; buffer = new char[n]; memcpy(buffer, s, n); } ~String() { delete [] buffer; } String(const String &r) { // traditional copy ... } String(String &&r) { buffer = r.buffer; // O(1), No copying, saves time. r.buffer = 0; } }; String hello(bool world) { if (world) { return String("Hello, world."); } else { return String("Hello."); } } int main() { String foo = hello(); std::cout <<foo.buffer <<std::endl; } And this will not trigger the copy constructor. A: I don't have a yes or no answer, but you say that you can write fewer lines of code if the optimization you're looking for is guaranteed. If you write the code you need to write, the program will always work, and if the optimization is there, it will work faster. If there is indeed a case where the optimization "fills in the blank" in the logic rather than the mechanics of the code and makes it work, or outright changes the logic, that seems like a bug that I'd want fixed rather than an implementation detail I'd want to rely on or exploit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "54" }
Q: Javascript JSONP callback function is method of object? function handler1(data) { } function objectA { this.handler2 = function(data) { } } I can call JSONP page and receive data with handler1 function. But I need to use OOP. How can I call JSONP page and receive data with objectA.handler2 function? A: in the same way, - objectA_instance.handler2( data ). Nothing fancy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linking two activity in android I'm coding a simple android app where you write in a box your name then click ok and a new page will show your name... The problem is that when you click ok nothing happens. Here the main activity public class Click extends Activity implements OnClickListener{ @Override public void onClick(View v) { // TODO Auto-generated method stub String TypedText = (String)MyText.getText().toString(); Intent MyInt = new Intent(this, HelloWorld.class); MyInt.putExtra("user", TypedText); this.startActivity(MyInt); Bundle Retrive = this.getIntent().getExtras(); Retrive.getString("user"); setContentView(R.id.Text); TextView TextV = (TextView)findViewById(R.id.Text); TextV.setText("user"); } android.widget.EditText MyText; public void OnCreate (Bundle savedInstanceState){ super.onCreate(savedInstanceState); this.setContentView(R.layout.name_getter); MyText = (EditText)this.findViewById(R.id.editText1); this.findViewById(R.id.button1); android.widget.Button RefBut = (Button)this.findViewById(R.id.button1); RefBut.setOnClickListener(this); } And here the manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="edu.calpoly.android.lab1Sada" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="4" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Click" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="HelloWorld" ></activity> </application> </manifest> Starting the android emulator will launch the first activity click but then the app doesn't show the new view... A: I dont know what you are doing but you can send/retrieve data from/to activity to another activity like this way: For that you need to understand the concept of Intent. From First activity: Intent i = new Intent(this, ActivityTwo.class); i.putExtra("name", "paresh"); i.putExtra("technology", "android"); startActivity(i); From Second activity: Bundle extras = getIntent().getExtras(); if (extras == null) { return; } String strName = extras.getString("name"); String strTechnology = extras.getString("technology"); Still for your reference, here is the article to know more about the same: Android Intents A: You must pass the text from activity 1 and receive it as bundle in activity 2. Go through the helloworld program as your first tutorial for android. Just extending Activity will work. You do not need to mention the entire package of the superclass.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reason for duplicate keys on http post? Reading about Http Post on Wikipedia it states that This is a format for encoding key-value pairs with possibly duplicate keys. Is this correct and if so what is the reasoning? Why would a client ever post duplicate keys and if a duplicate key is posted how is the correct corresponding value returned on server side? A: To submit multiple values for the same thing. In PHP, for example, you can name multiple input fields somedata[]. All values of the input boxes are then put in an array named somedata.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How should I style HTML "select" and "option" tags I want to make my HTML <select> and <option> tags beautiful, but I also don't want to get far from native implementation. For example, I don't want to use dome <div> elements and create a drop-down list using jQuery (for the purposes of accessibility). However, as we know, HTML <select> is really ugly. How can I achieve these both requirements? What is a good practice to apply styling on HTML <select> tag and its related <option> tags? A: there is a good reason most plugins dealing with forms wanting to style them use divs: as soon as you touch any form element with any css other then font size and margin, things will starts falling apart, because different OS & browser combinations style form elements differently. things will start getting misaligned, you lose vertical alignment, etc... so i suggest using divs (and all the accessibility stuff) if you want to mess around with form elements. edit: yes, there are a couple of other "safe" css properties, but these are not enough to achieve what you describe A: the real trick is simply overcoming user-agent default styles for forms and form controls/labels. you can come pretty close if you target different browsers with specific styles. this can get ridiculously out of hand fast, so its best to know what you're doing. formalize is an awesome lib that resets the styles and works with a plethora of JavaScript libraries. http://formalize.me/ A: This is what I used to make my select dropdown look nicer. I think it looks pretty nice. * { font-size: 18px; } #cars { height: 35px; background-color: lightgray; color: black; border: none; padding: 5px; appearance: none; cursor: pointer; border-radius: 5px; outline: none; margin: 5px; text-align-last: center; } #cars option { background-color: white; color: black; } <!DOCTYPE html> <html> <body> <form> <label for="language"><b>Select a coding language:</b></label><br> <select name="language" id="cars" required> <optgroup label = "Front End"> <option value="HTML">HTML</option> <option value="CSS">CSS</option> <option value="JavaScript">JavaScript</option> </optgroup> <optgroup label = "Preprocessors"> <option value="Sass">Sass</option> <option disabled>Coming soon</option> </optgroup> </select> <br><br> <input type="submit" value="Submit"> </form> <p>Click the "Submit" button and the form-data will be sent to a page on the server called "action_page.php".</p> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7596203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to debug a tokend Is it possible (and if: how) to run a custom tokend that is started by securityd in a debugger? Preferably within the Xcode IDE. A: One can start XCode as root and then configure the debugger to wait for a new instance of the tokend executable. Once the pcscd signals the presence of a smartcard and the securityd therefore launches a new instance of the tokend the debuger will attach to this new instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hbase Stargate REST Interface: How to encode a scanner with filter in XML? I'm using Hbase over Stargate and want to use a scanner with certain filters. In java or thrift, this would be no problem, but I don't find any advice how to encode the filters in XML. The Schema given in the wiki is invalid, so I'd need one or two Examples how to encode those filters (with AND/OR) in XML.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: tips to speed up LINQ query? I have a LINQ query which is searching a SQL table of around 250,000 records and only searching on 2 fields. Both fields have been indexed but I find its still running rather slow. Below is the code, can anyone suggest anything to help speed it up? thanks var qryN = ( from bn in dbs.Uploads orderby bn.ID descending select new { ID = bn.ID, Serial = bn.serial_no, Manufacturer = bn.Mfgr, Model = bn.model, Code = bn.code, Qty = bn.qty, Description = bn.description, Comments = bn.comments, Location = bn.location, Price = bn.price, Email = "Register / Login for full details" }); if (dlType.Text != " " && dlType.Text != "") { qryN = qryN.Where(bn => bn.Manufacturer == dlType.SelectedValue); } if (txtWord.Text != "") { qryN = qryN.Where(bn => bn.Description.Contains(txtWord.Text)); } gvLoggedOff.DataSource = from p in qryN select new { p.ID, p.Serial, p.Manufacturer, p.Model, p.Code, p.Qty, p.Description, p.Comments, p.Location, p.Price, p.Email }; gvLoggedOff.DataBind(); var qryN = ( from bn in dbs.Uploads orderby bn.ID descending select new { ID = bn.ID, Serial = bn.serial_no, Manufacturer = bn.Mfgr, Model = bn.model, Code = bn.code, Qty = bn.qty, Description = bn.description, Comments = bn.comments, Location = bn.location, Price = bn.price, Email = "Register / Login for full details" }); if (dlType.Text != " " && dlType.Text != "") { qryN = qryN.Where(bn => bn.Manufacturer == dlType.SelectedValue); } if (txtWord.Text != "") { qryN = qryN.Where(bn => bn.Description.Contains(txtWord.Text)); } gvLoggedOff.DataSource = from p in qryN select new { p.ID, p.Serial, p.Manufacturer, p.Model, p.Code, p.Qty, p.Description, p.Comments, p.Location, p.Price, p.Email }; gvLoggedOff.DataBind(); A: The filter on Description could be a problem: qryN = qryN.Where(bn => bn.Description.Contains(txtWord.Text)); The Contains calls translates to a SQL description LIKE '%' + @p0 + '%'. Which means that even if you have an index on the description column, SQL server has to loop over the complete index (or perhaps even the complete table). If possible, change the line to the following: qryN = qryN.Where(bn => bn.Description.StartsWith(txtWord.Text)); This will translate to description LIKE @p0 + '%' which allows your database server to effectively use the index. A: Two things: * *Since you're adding filters, move the projection (selecting into a new anonymous type) to the last line instead of the first, the DataSource line. *You're ordering very early. Unless the queryable or the query analyzer are smart enough to analyze and optimize this, the database will have to order 250,000 rows before it starts filtering. Move the ordering to as late as you can, probably just before the projection takes place. Here's a short attempt at modifying your sample: var qryN = dbs.Uploads.AsQueryable(); if (dlType.Text != " " && dlType.Text != "") qryN = qryN.Where(bn => bn.Mfgr == dlType.SelectedValue); if (txtWord.Text != "") qryN = qryN.Where(bn => bn.description.Contains(txtWord.Text)); gvLoggedOff.DataSource = qryN.OrderByDescending(bn => bn.ID) .Select(bn => new { bn.ID, Serial = bn.serial_no, Manufacturer = bn.Mfgr, Model = bn.model, Code = bn.code, Qty = bn.qty, Description = bn.description, Comments = bn.comments, Location = bn.location, Price = bn.price, Email = "Register / Login for full details" }); gvLoggedOff.DataBind(); Since this was accepted as an answer: Steven's answer about text searching is probably also applicable in some situations. Full text searching can drain performance like you wouldn't believe. A: Description.Contains sounds heavy, you may try to use full text search instead. Here is a post describing how you can use FTS from LINQ.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ubuntu 11.04 change in simple desktop I am unable to find the way that my system turn in Ubuntu 10 like desktop. currently, my system is showing me the MAC style start menu and side bar. Can anyone know how to switch my ubuntu in simple desktop. Yours, A: Logout, click on your name, then at the bottom you will have the option to switch off unity by selecting Ubuntu classic mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to scan an image straight onto a cloud database through web browser interface I have a MySQL cloud database with a browser-based front-end. Backend code is written using Perl/Dancer The employee logs on to www.example.com and enters the data into fields, hits ' save ' to create a new record. Now I need to scan in an image and attach it as one of the fields. How can I accomplish this? I realise that I could just scan the image, save it as a file on the desktop, and then upload this file. but there is a high volume of data to process, this method is very clunky. ( It isn't essential that it is a scanner, it could equally well be a web cam or digital camera ) A: To control scanner's from browser u may either use activeX controls or u may use flash, which gives options to take options from web/digital
{ "language": "en", "url": "https://stackoverflow.com/questions/7596227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Strip closing php tag using perl regex I have php file, and I want to remove closing tag (?>), but only if it is last closing tag and there is nothing after. <?php //some code ?> <?php //some other code ?> // <- this and only this should be removed I have tried pattern 's/(\s*\?>\s*)$//s' and several of its mutations, but with no success: they remove all occurrences of ?>, breaking the code, and I don't know how to match EOF. (Yes, I know a workaround: using e.g. tail -1 to check only last line of file, but it would complicate my whole code-formatting script, so if the problem can be resolved with properly constructed regex, it would be great.) A: I now had a chance to test it. Reading all file does work. This perl code worked for me: local $/; open FH, "<", "tmp.php"; $var = <FH>; print "$var\n\n"; close FH; $var =~ s/(\s*\?>\s*)$//s; print "$var\n"; on the following php code: <?php //some code ?> <?php //some other code ?> A: OK, let's break this down. You want to match '?>', so we'll start with ('?>'), but since '?' has special meaning in regex, we need to escape it: ('\?>'). We don't care about what's before the closing tag, but we want to make sure nothing (except whitespace) is after it. You were pretty much on the money with this: we need \s and $. I'd do it like this: ('\?>')\s*$ Hope that works for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Significance of AsEnumerable? var query = from dt1 in dtStudent.AsEnumerable() join dt2 in dtMarks.AsEnumerable() on dt1.Field<int>("StudentID") equals dt2.Field<int>("StudentID") select new StudentMark { StudentName = dt1.Field<string>("StudentName"), Mark = dt2.Field<int>("Mark") }; In the above coding, what is the significance of AsEnumerable? if the AsEnumerable doesn't exist in .NET Framework, then what would be the approach of developers to perform the above the task? A: Assuming I'm interpreting it correctly, it's calling DataTableExtensions.AsEnumerable(). Without that (or something similar), you can't use LINQ to Objects as DataTable doesn't implement IEnumerable<T>, only IEnumerable. Note that an alternative would be to use Cast<DataRow>, but that would be subtly different as that would use the DataTable's GetEnumerator directly within Cast, whereas I believe EnumerableRowCollection<TRow> does slightly more funky things with the data table. It's unlikely to show up any real changes, except possibly a slight performance difference. A: The .AsEnumerable() extension is just short-hand for casting something that implements IEnumerable<T> to be IEnumerable<T> So, if xs is int[], you can call xs.AsEnumerable() instead of (xs as IEnumerable<int>). It uses type inference to avoid needing to explicitly keying the type of xs. Here's the code extracted by Reflector.NET: public static IEnumerable<TSource> AsEnumerable<TSource>( this IEnumerable<TSource> source) { return source; } But in this case I think I have to agree with Jon. It's probably from the System.Data.DataSetExtensions assembly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use "coffee" instead of "node" command in production I have an app.js that is running express.js. I wanna convert the code to coffeescript and thought about to create a app.coffee that I compile to app.js so I can run it with "node app.js". But then it hit me that I could just write that file in app.coffee and run it with "coffee app.coffee". Is this a better way? Can I run the server with "coffee" in production? A: I upvoted Epeli's answer, which is clear and excellent—using a .js "wrapper" rather than the coffee command saves you from potential path headaches—but since this is a subjective question, let me throw in a contrary opinion. Many CoffeeScripters, myself included, recommend compiling non-trivial Node apps to JS before deployment. It's not hard—look at Sam Stephenson's node-coffee-project template, which includes a Cakefile that makes compiling and testing a breeze. One major reason for doing this is that Node stack traces give line numbers that refer to the compiled JavaScript, not the original CoffeeScript. So when errors are recorded in your server logs, it's nice to be able to look at the corresponding code right on the server. Another advantage to compiling to JS is that it lets you work with more tools on the server—many Node debuggers, testing frameworks, and amazing goodies like cluster like to operate directly on .js files. Getting a good compilation setup for your project takes some work, but I think you'll find it worthwhile. A: Yes you can use coffee command in production. I use it. I can see two reasons why you would want to use app.js wrapper. * *You want to use local installation of CoffeeScript. (different versions between apps) *You want to use the default npm start to launch your server :) See npm help scripts Oh, and you don't need compile it. You can use a wrapper like this which compiles the coffee file transparently: server.js: require('coffee-script').register(); require("./yourcoffeeapp.coffee"); This wrapper technique is especially useful if you want to use CoffeeScript in some hosted environments that does not directly support the CoffeeScript command. Such as Cloud 9 IDE. No need to fiddle with compiled js-files. A: I prefer to create main.js like this: require("coffee-script"); require('./yourcoffeeapp'); And yourcoffeeapp.coffee like this: http = require 'http' on_request = (req, res) => res.writeHead 200, {'Content-Type': 'text/plain'} res.end "Hello World\n" server = http.createServer on_request server.listen 1337, "127.0.0.1"
{ "language": "en", "url": "https://stackoverflow.com/questions/7596230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Mono.TextEditor not working. What am I doing Wrong? I am trying to use the Mono.TextEditor assembly with .NET Framework 3.5 in GTK#. But I keep getting System.BadImageFormatException Could not load file or assembly 'Mono.TextEditor, Version = 1.0.0.0,Culture = neutral, PublicKey Token = null' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded. The MonoDevelop version I am using (Mono.TextEditor is an addon of MonoDevelop) is definitely built by .NET version 3.5. Any Help? A: Most possibly your project still targets the 2.0 runtime. You'll need to set Project/Settings/Build General/Runtime: Mono / .Net 3.5 in monodevelop. Don't forget to add the reference to System.Core, if it isn't already added.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stuck with twitcurl this question has gone back and forth a bit as I have learnt some things about g++ about unix systems (sorry if I messed anyone about). For a project I am currently trying to finish I would like to get twitcurl running with Xcode and OpenFrameworks. If anyone has managed to do this please share with me this arcane feat. Below is some of the things I am stuck on: Regurgitating some of the instructions from their wiki it says to * *download the libraries source *build twitcurl library using visual C++ or make (their is also cmake in their). *Include twitcurl.h and curl headers in your twitter application and link to twitcurl.lib and libcurl.lib/libcurl.dll. This seems simple enough but when I make the library, there is no twitcurl.lib. A different file libtwit.a is produced, which I assume must be what OSX needs (as installing puts it in usr/local/ along with the headers). However then if I try to include the twitcurl.h in a header and make a twitCurl object I then get more undefined symbols Undefined symbols for architecture i386: "twitCurl::~twitCurl()", referenced from: testApp::setup() in testApp.o "twitCurl::twitCurl()", referenced from: testApp::setup() in testApp.o ld: symbol(s) not found for architecture i386 I now am assuming twitcurl makes for a 64bit (I have tried adding CFLAGS=-m32, but it fails), and to my knowledge Openframeworks is only 32 bit currently. This means twitcurl may not be an option for me, but again, if anyone knows how please let me know! Thanks in advance. A: You'd probably do well to recompile twitcurl, last I looked (3 months ago), it was compiled with VC6, which has its own way of mangling C++ symbols, so the lib won't link correctly for g++. you could then just import it directly as well and then not need to worry about linking to the libs, however it would be a good idea to test in a small demo app, before integrating into an already build system, that way you know if the error is on your side or somewhere else. Also, when it comes to this type of problem, the exact compiler errors are more helpful than just describing the problem. A: The error message you've posted is the linker's longwinded way of telling you that its looking for a definition of the curl_easy_setopt function, which is part of libcurl. Adding -lcurl to your g++ line should fix this (by telling the linker to link in libcurl). However, twitcurl comes with a Makefile, which already does this. In addition, if you are trying to build a shared library there, you're doing it wrong... A: Maybe you can try ofxTwitter, an openFrameworks addon for twitter, to get your twitter functionality. get it here: http://forum.openframeworks.cc/index.php/topic,2750.0.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7596233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Escape whitespace in filepath I am writing a small Java Application and I am having problems with a filepath. I want to execute a batch file with Runtime.getRuntime().exec("cmd /c start c:\program files\folder\file.bat"); But now Java cries because of the whitespace in the filepath. How can I escape it? EDIT: Ok, thank you for the answers guys. But I just ran into a new problem: If I start the .bat this way it just opens a cmd window and nothing happens. But if I move the .bat into c:/folder/ without spaces it works...the .bat itself is fine too. A: You can avoid any problems like this by using the Runtime#exec that takes a String[]: Runtime.getRuntime().exec(new String[] {"cmd", "/c", "start", "c:\\program files\\folder\\file.bat"}); That way you don't have to worry about quoting the file names. However, you still have to worry about quoting \ in the file names. A: Runtime.getRuntime().exec("cmd /c start \"c:/program files/folder/file.bat\""); should work A: Instead of using Runtime.getRuntime it is better to use ProcessBuilder That way you can have something like: List<String> command = new ArrayList<String>(); command.add("first-arg"); command.add("second arg with spaces") //this one will be accepted as a single argument, eventhough it has spaces A: A solution for windows 7 at least: Runtime.getRuntime().exec("my_program_name.exe \"" + namefile+"\"); The idea is to put namefile between the character ". A: I think it cries because of the unescaped back slashes in your string. Quote the file name. A: Put quotes around and quote backslashes: Runtime.getRuntime().exec("cmd /c start \"c:\\program files\\folder\\file.bat\""); A: surround the filepath with " Runtime.getRuntime().exec("cmd /c start \"c:\\program files\\folder\\file.bat\""); and properly escape the \ in the path as well A: you have to escape the slashes so \\ and in windows white space are escaped with %20. I don't know about other system, could work. But first thing do the \\.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Converting query expression to Linq method syntax I use EF 4 and C#. I have a query like: var contentsAuthor = from c in context.CmsContents join a in context.CmsAuthors on c.AuthorId equals a.AuthorId where a.UserId == userGuid select new { c.Title, c.ContentId }; I would like rewrite it in Linq with Lambda Expression. My questions: * *How to rewrite it? *What is the appropriate name for my query syntax and the new with Linq and Lambda (query expression and Linq to Entities???). Please give me a hit on this point I'm confused. Notes: probably the title for this question is not appropriate, let me know I will improve it Thanks guys for your help on this! A: The lambda expression should look like: var contentsAuthor = context.CmsContents .Join(context.CmsAuthors, content => content.AuthorId, author => author.AuthorId, (content, author) => new { content, author }) .Where(x => x.author.UserId == userGuid) .Select(x => new { x.content.Title, x.content.ContentId }); Both yours and this version are LINQ queries. This one uses lambdas directly whereas your version uses syntactic sugar available in C#. They are the same. LINQ-to-Entities have nothing to do with this. Anyway if you are using LINQ-to-Entities your CmsContent should have Author property and your query would reduce to: var contentsAuthor = context.CmsContents .Where(c => c.Author.UserId == userGuid) .Select(c => new { c.Title, c.ContentId }); The LINQ-to-Entities provider will make join for you when translating expression tree to SQL query. A: Lambda: var contentsAuthor = context.CmsContents .Join(context.CmsAuthors, c => c.AuthorId, a => a.AuthorId, (c, a) => new { Contents = c, Author = a }) .Where(w => w.Author.UserId == userGuid) .Select(s => new { s.Contents.Title, s.Contents.ContentId }); The way you did it is fine though. I call it query syntax, but I'm not sure if it has an official name. For this sort of stuff, check out LINQPad. In "Expression" mode, you can type a query like you have, and click on the Lambda symbol and it'll show you the lambda version of your query. A: var result = context.CmsContents .Join(context.CmsAuthors.Where(x => x.auth.UserId == userGuid), content => content.AuthorId, author => author.AuthorId, (cont, auth) => new { cont, auth }) .Select(x => new { x.cont.Title, x.cont.ContentId });
{ "language": "en", "url": "https://stackoverflow.com/questions/7596239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: real world experience of ext4yii I have been developing in php/mysql/extjs3 for nearly three years, using a home-made MVC approach, even in fairly big projects, but now I would like to switch to a php framework + extjs solution. My home-made solution works fine but I need something more solid and standardized, since I am close to switch from a one-man-band solution to a teamwork solution. I am testing Codeigniter and Yii as frameworks and I found this ext4yii extension that look pretty promising. Anybody out there who is using this extension in the real world and wants to share her/his opinion? Thanks a lot for you time and patience. A: I strongly recommend using Yii and ext4yii. There are several advantage. Since the MVC structure is built in for yii, you can not only save months of coding but also ramp up any new comers on the project and make sure they confirm to the MVC coding style. It is also properly documented. ext4yii was a pleasant surprise to me, it provided the necessary bridge between ext3 and yii. It also has netbeans support, which is as important. My team was migrating from .NET and the ramp up on ext4yii/yii/ext3 was as good as it can get. The only recommendation I have, try postgres instead of mysql. postgres is opensource. Subash
{ "language": "en", "url": "https://stackoverflow.com/questions/7596242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: need jquery slide show for div contents I need a slideshow like this website. as you can see , in the top of the page is a slide show . I just need a slideshow that change the content of each slide . I've made my content for each slide and just need a script that change these content .IVe searched alot but all I have found is for image slide shows . I need a slideshow that change the "div" content . I need your help very much Thanks Thanks buddy for your rely but I don't know how to use it for div's content . All of them have been used images . I want to user div instead of img es . any idea ? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7596246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET MVC File method Hi I would like to send user a file but without showing the url. Using File method the problem is that I have my file in another server and so I have only url not a virtual path, I tried to use WebClient to get file bytes to use in File method but it's quite slow, my files are greater than 20 Mb! Any idea on how can I do this without get all file bytes before sending them to my user? This is my code inside my Controller: using (WebClient Client = new WebClient()) { byte[] fileContent = Client.DownloadData(fileUrl); return File(fileContent, "application/octet-stream", fileName); } Thanks A: You can read from your server in blocks and write them directly to your output stream. Play with the block size to tweak performance. using (var client = new WebClient()) { using (Stream data = client.OpenRead(fileUrl)) { using (var reader = new BinaryReader(data)) { var buffer = new byte[8192]; int nread; while ((nread = reader.Read(buffer, 0, buffer.Length)) > 0) Response.OutputStream.Write(buffer, 0, nread); } } } return null; A: You can use Response.BinaryWrite to write binary data to the output stream. You can do this in multiple chunks if you need to, then flush and end the response when it's finished.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Yahoo Pipes and regex: Why does it work only for my first item? Here is my pipe: http://pipes.yahoo.com/pipes/pipe.info?_id=a732be6cf2b7cb92cec5f9ee6ebca756 I am currently trying to get the part before the first space to my item.url and the second part will be the title. For instance, first item is: http://carto1.wallonie.be/documents/terrils/fiche_terril.idc?TERRIL_id=1 Crachet 7/12 The expected result would be to get the "Crachet 7/12" as title and the other part as link. My regex query "([^\s]+)" seem to work only for my first item, I don't understand why, as all the items are formatted the same way. Thank a lot for any help! EDIT: Pictures to understand better: BEFORE REGEX AFTER REGEX Trying to check the g symbol A: You can use \S+ instead of [^\s]+. Also, you need to specify the "global" flag or the regex engine stops after the first successful match. In order to match only the first non-whitespace part of the line, use the ^ anchor with the "multiline" flag: /^\S+/gm or new RegExp("^\\S+", "gm") In your case, you need to check the appropriate checkboxes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mental Poker Toolkit Can anyone suggest a toolkit or framework (or maybe an idea) that can be useful to implement secure and cheat-resistant online poker (texas hold'em) client without trusted third party server? A: LibTMCG is such a Frameworks http://libtmcg.nongnu.org A: What you're asking about is called mental poker, described in this fascinating paper(PDF) by cryptographic greats Adi Shamir, Ron Rivest, and Leonard Adleman. Per their summary of results: We present two solutions to the problem of playing Mental Poker: * *A rigorous proof that it is theoretically impossible to deal the cards in a way which simultaneously ensures that the two hands are disjoint and neither player has any knowledge of the other player's hand (other than that the opponent's hand is disjoint from his). *An elegant protocol for dealing the cards that permits one to play a fair game of Mental Poker as desired. The blatant contradiction between our two results is not due to any tricks or faults in either result. In fact, we will leave to the reader the enjoyable task of puzzling out the differences in the underlying assumptions that account for our seemingly contradictory results. Note that their result only applies to two player games of poker. The paper Mental poker with three or more players extends this result to multiple players. In short, can it be done? Probably, yes. Is it practical? Almost certainly not. You should establish or find a trusted third party instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Git: Move a few of the last commits to a new branch and then create a patch for them I've made a few commits and now I want them (say from some commit in the branch) to move them into a new branch, i.e.: master - O1-O2-O3-X-C1-C2-C3 to become master - O1-O2-O3-X \ new_branch - C1-C2-C3 After that I need to make patches for the mentioned commits (C1, C2, C3) so that a friend of mine would be able to apply them on their tree. As to the first part I suppose I should do something like: * *Create patches for x -> C3 *Reset to X *Create branch *Apply patches Although here they suggest that I could use git branch new_branch; git reset --hard X; git checkout new_branch. Wouldn't reset --hard delete my commits? I'm not too good with git to do it all without guidance. Thanks! A: No reset --hard wouldn't delete your commits, as they would still be referenced by the 'new_branch' branch. (meaning that, by a checkout of 'new_branch', you would recover and see those commits again) But it would delete any untracked changed in your working tree though, so make sure you don't have any work in progress before typing that command. You can see a more detailed illustration of that sequence of commands in "What will git checkout master + git reset --hard do?". To complete Stuart Golodetz's comment, should a git reset had removed or erased any commit, you would still have been able to get hold of those commit with a git reflog. See: * *"Undoing a git rebase" *"Undoing a git reset --hard HEAD~1"
{ "language": "en", "url": "https://stackoverflow.com/questions/7596255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to scale polygons mapped to a resizeing picture Im craeating a dart scoring program (to use myself in my dart room) and want the user to be able to click in different areas of a picture of a dart board to register the thrown darts. This program will be resizable, so the picture of the dart board can change it's size when the user change the program window size. Im using a list of polygons(pointF-arrays) to map up each area and run some calculation to see if the mouse click is inside the polygons area, but how do I scale those polygons correctly when the picturebox is resized? My polygons are hard coded to map the dartboards area of the picture at a specific size. Edit: After the the really brilliant answer from Olivier Jacot-Descombes, I fixed the scaling with a GetScaledPoint-function that transform the mousepointer x and y value to values matching the original picture size, making it easy to check for hits in the original polygons. I have edited in the solution in the code below if anyone is interrested. In this example, Picture1 is a picture of a dart board (like this one http://quizmasters.biz/Pub%20Genius/Darts/Gfx/Dartboard_05.jpg) that is set to sizemode=stretch and docking=fill. Public Class DartBoard Dim Double20 = New PointF() {New PointF(263, 78), New PointF(275, 76), New PointF(284, 76), New PointF(293, 75), New PointF(306, 75), New PointF(319, 75), New PointF(332, 76), New PointF(330, 89), New PointF(320, 88), New PointF(309, 87), New PointF(300, 87), New PointF(289, 88), New PointF(277, 89), New PointF(267, 91), New PointF(264, 78)} Dim Triple20 = New PointF() {New PointF(279, 154), New PointF(285, 154), New PointF(293, 154), New PointF(301, 152), New PointF(306, 152), New PointF(312, 152), New PointF(314, 151), New PointF(322, 152), New PointF(320, 167), New PointF(312, 165), New PointF(304, 164), New PointF(297, 165), New PointF(289, 166), New PointF(281, 166), New PointF(277, 154), New PointF(283, 153), New PointF(291, 153), New PointF(299, 152), New PointF(308, 152), New PointF(314, 153), New PointF(322, 153)} Private startwidth As Integer = 0 Private startheight As Integer = 0 Public Structure DartBoardAreaStruct Public Points As Integer Public Area() As PointF End Structure Dim DartBoardAreas As New List(Of DartBoardAreaStruct) Private Sub DartBoard_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load DartBoardAreas.Add(New DartBoardAreaStruct With {.Area = Double20, .Points = 40}) DartBoardAreas.Add(New DartBoardAreaStruct With {.Area = Triple20, .Points = 60}) startwidth = PictureBox1.Width startheight = PictureBox1.Height End Sub Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown Dim scaledpos As PointF = GetScaledPoint(e.Location) For Each DartBoardArea In DartBoardAreas If Me.PolyGonHitTest(DartBoardArea.Area, scaledpos) Then MsgBox(DartBoardArea.Points) End If Next End Sub Public Function PolyGonHitTest(ByVal polygonPoints() As PointF, ByVal mousePos As PointF) As Boolean Dim path As New System.Drawing.Drawing2D.GraphicsPath path.AddLines(polygonPoints) Dim region As New Region(path) If region.IsVisible(mousePos) Then Return True Return False End Function Function GetScaledPoint(ByVal s As Point) As PointF Dim xfactor As Double = 0 Dim yfactor As Double = 0 Dim OriginalSize As Size = New Size(startwidth, startheight) Dim NewSize As Size = New Size(PictureBox1.Width, PictureBox1.Height) If NewSize.Width < OriginalSize.Width Then xfactor = OriginalSize.Width / NewSize.Width Else xfactor = NewSize.Width / OriginalSize.Width End If If NewSize.Height < OriginalSize.Height Then yfactor = OriginalSize.Height / NewSize.Height Else yfactor = NewSize.Height / OriginalSize.Height End If Return New PointF(s.X / xfactor, s.Y / yfactor) End Function End Class A: A easy and fast solution would be to keep the polygons unchanged, but to scale the mouse coordinates. For instance you could have polygon coordiantes between 0.0f and 1.0f and scale your mouse coordinates like: xScaled As Single = e.X/DartBoardArea.Width yScaled As Single = e.Y/DartBoardArea.Height scaledPos As PointF = new PointF(xScaled, yScaled)
{ "language": "en", "url": "https://stackoverflow.com/questions/7596272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change in Javascript/CSS not reflecting from CDN I have setup CDN to fetch my images/js/css files. Initially to override browser cache behavior and to reflect the changes in my js/css files, I used to change the version in URL parameters to make it look like a different URL to the browser. Like http://mysite.com/scripts/common.css?v=45. But after porting these resources to CDN, none of my changes reflect. CDN always returns the cached copy and it ignores the version parameters. Please help. I am using Amazon cloudfront A: If you're using CloudFront have you read: https://forums.aws.amazon.com/thread.jspa?messageID=261072 It looks like it ignores the query string when caching the object. This is quite old information, but I've not read anything that tells me otherwise, so you'll have to modify the URL some other way (filename/path/etc). They do provide an invalidation API. Using this might solve your problem depending on your release cycle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Increment the cursor values? My database have 12 values i use the table layout with list view but in the second row its again started to show second value from the database class NoteHolder { private Button b1 = null; private Button b2 = null; private Button b3 = null; NoteHolder(View row) { b1 = (Button) row.findViewById(R.id.one); b2 = (Button) row.findViewById(R.id.two); b3 = (Button) row.findViewById(R.id.three); } void populateFrom(Cursor c, NoteHelper helper) { b1.setText(helper.getNote(c)); c.moveToNext(); b2.setText(helper.getNote(c)); c.moveToNext(); b3.setText(helper.getNote(c)); } } A: Remove static keyword from you class. A: Cursor.moveToNext() moves the cursor. http://developer.android.com/reference/android/database/Cursor.html#moveToNext%28%29
{ "language": "en", "url": "https://stackoverflow.com/questions/7596275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Samsung Tab Emulator in Eclipse i downloaded a tab emulator from http://innovator.samsungmobile.com/down/cnts/toolSDK.detail.view.do?cntsId=9500&platformId=1 and have added it to my android-sdk. i am able to create an AVD but unable to set the build target of my project to this tab. when i try to run the application on the tab AVD, i get the following error: Conversion to Dalvik format failed: Unable to execute dex: wrapper was not properly loaded first A: Just try restarting your Eclipse and start your emulator again. It should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Authenticating a user (in the web application typically Servlet) with his credentials from Android application I am trying to develop an Android application which typically allows users to login (authentication has to be done in the web application. I already have a Servlet which takes username and password and returns success or failure as result in XML format) with their credentials and do some operations (like view, update delete) on the data specific to that user. I found that we have to use REST way of doing this. I am not sure if I understood it correctly. Can someone direct me the way I should proceed to develop this kind of Android application? Thanks, Prasanth A: The easiest way I did this was using GET. Just load the credentials to your URL and load that url username = et1.getText().toString(); password = et2.getText().toString(); String url = "http://www.abc.com?action=ru?loginid="+username+"paswd="+password; wv.loadUrl(url); If you just do the above, you can see "successful" on your screen. If you want to catch this and put a validation, do the following: InputStream isText = text.openStream(); byte[] bytes=new byte[isText.available()]; isText.read(bytes); String s = new String(bytes); System.out.println(s); if(s.equals("unavailable")) { String s1="OK"; AlertDialog.Builder ad=new AlertDialog.Builder(Registration.this); ad.setMessage("username already exists"); ad.setPositiveButton(s1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); ad.show(); return; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7596280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create list of color on Java, Android? I need to create Spinner for list of colors. I will take selected item, get selected color and set this color for another elements. I want to set list of colors in .xml, because I have a few spinners, and want to create resource for it. But if I create a simple list of key -pair , in code I have to create many blocks (if else) for checking colors. How can I create and use resource file (pairs "string-int") for spinner? Thank you A: You already know how you are displaying data in Spinner. Take String Array for displaying the data in Spinner. Consider String[] array={"Green","Blue","Red"}; Now take one other array for colors such that it matches the color in the first array.. Here there are 2 options viz. String or int Array String Array => String[] arrayColors={"#00ff00","#0000ff","#ff0000"}; int Array => int [] arrayColors={Color.GREEN,Color.BLUE,Color.Red} Use any one. (Recommended : use int Array because you dont have to parse the color when using it) So you establish One-to-One correspondence between both arrays. Now register for OnItemSelectedListener listener for listening to selection in Spinner yourSpinner.setOnItemSelectecListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // Change color of other views by using pos argument // IF YOU HAVE USED String Array yourView.setBackgroundColor(Color.parseColor(arrayColors[pos])); // IF YOU HAVE USED int Array yourView.setBackgroundColor(arrayColors[pos]); } public void onNothingSelected(AdapterView parent) { // Do nothing. } }); A: Doesn't something like this help? String[] colorList = {"white", "black"}; int[] color = {Color.WHITE, Color.BLACK}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, colorList ); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); modeSpinner.setAdapter(adapter); modeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { yourView.setColor(color.get(colorList.getSelectedItemPosition()) } public void onNothingSelected(AdapterView<?> arg0) { //... } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7596281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP array sorting cant get the correct output can any one help me how to get the sorting of the numbers; num1 = 1 num2 = 1 num3 = 3 num4 = 5 $values = array($_POST["num1"] => 1, $_POST["num2"] => 2,$_POST["num3"] => 3,$_POST["num4"] =>4); asort($values); foreach($values as $key => $val){ echo "<br>$key = $val<br>"; } The num1 is not printed.. and i got an out put of 1 = 2 3 = 3 4 = 4 how can i got the output complete like this? 1 = 1 | 1 = 2 | 3 = 3 | 4 = 4 A: You have the key => value pair the wrong way round in your array, hence why your key for 1 gets overwritten. Try replacing your $values = ... line with this: $values = array(1 => $_POST["num1"], 2 => $_POST["num2"], 3 => $_POST["num3"], 4 => $_POST["num4"]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7596283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hide counter on FaceBook Like button I have simple html page with FaceBook Like button: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraphprotocol.org/schema/"> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <div id="fb-root"></div> <script type="text/javascript"> window.fbAsyncInit = function() { FB.init({ status: true, // check login status cookie: true, // enable cookies to allow the server to access the session xfbml: true, // parse XFBML channelURL: 'http://myurl.com', // channel.html file oauth: true // enable OAuth 2.0 }); }; (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#xfbml=1"; d.getElementsByTagName('head')[0].appendChild(js); } (document)); </script> <fb:like href="http://myurl.com" layout="button_count" show_faces="false" width="450" height="35" action="like" colorscheme="light" font="trebuchet ms" allowTransparency="true"></fb:like> </body> </html> How can I hide counter next to button? Thanks a lot! A: Use the iframe code provided by Facebook at http://developers.facebook.com/docs/reference/plugins/like then wrap it in a div with height and width and overflow hidden. A: I've tested several versions now. a) You get many problems on different browsers, you have to check every browser version b) There is a noscript addon named "ClearClick" - it will warn/prevent users from clicking on such a hidden FB Button. There is no solution against that. Well there is 1 solution, the hidden space must be OUTSIDe the screen so ClearClick can not reender it and does not warn the user. But you do not want your like button on the top of your page I believe. A: Choose standart facebook like button from John's link it will be ok! ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7596286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to use inputView property? I have created my own keyboard and I want to open that in place of standard keyboard provided by the iPhone in the uitextview to enter text.In the Apple documentation I have found one property inputView in the UIResponder Class Reference. It is given on this link :-here But I m not getting how to use this property.please tell me how to use this property prorpely. I have tried to use this proerty like this UIView *mainView; @property (readwrite,retain) IBOutlet UIView *mainView; - (UIView *)inputView { return mainView; } A: That's a property. You don't have to override its implementation. Just use it as any other regular property and affect to it your custom input view. yourTextField.inputView = yourCustomInputView;
{ "language": "en", "url": "https://stackoverflow.com/questions/7596291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read file from position FileStream infile = new FileStream(@"C:\Users\John\Desktop\ProjectNew\nov.txt", FileMode.Open, FileAccess.Read); int position = x.Length; infile.Seek(position, SeekOrigin.Begin); But Seek method returns number. How to read the file 'infile' from position to end in a string? A: Is this what you're after? Assuming you wanted to start reading from position 100... using (FileStream fs = new FileStream(@"file.txt", FileMode.Open, FileAccess.Read)) { fs.Seek(100, SeekOrigin.Begin); byte[] b = new byte[fs.Length - 100]; fs.Read(b, 0, (int)(fs.Length - 100)); string s = System.Text.Encoding.UTF8.GetString(b); } A: The Seek method is supposed to return a number, the new position in the stream. Now just call whatever Read function you want. A: Seek() only places the file pointer somewhere else. If you do a read before the seek, it will read from the beginning of the file. If you read after the seek, it will start reading from position. So to read the file from position to the end, do Seek(), followed by Read() or ReadToEnd().
{ "language": "en", "url": "https://stackoverflow.com/questions/7596302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I use my HTTP handlers for selected paths and MVC handler for the rest? I have an MVC2 application. I also have a set of ready HTTP handlers that derive from System.Web.IHttpHandler. How do I use them together? I tried the following in web.config: <system.webServer> <!--other stuff--> <handlers> <add name="MyCustomHandler" verb="GET" path="MySpecificPath*" type="CustomHandling.CustomHttpHandlerBase, CustomHAndlingAssembly"/> <add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"/> </handlers> </system.webServer> yet control never reaches my handler and MVC handler is used for all requests. How do I use my handler for one specific path and MVC handler for all other paths? A: I believe that you need to ignore those specific paths from routes collection in application start. For example, routes.IgnoreRoute("MySpecificPath/{*pathInfo}"); Otherwise UrlRoutingModule will match with the route and then http handler will be located via IRouteHandler for that route. See this article for more info about mixing ASP.NET WebForms with ASP.NET MVC .
{ "language": "en", "url": "https://stackoverflow.com/questions/7596303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Scala: Mix traits and case class in pattern match I want to match on some case classes. If I don't know them, I want to match on a specified trait the classes have to extend. This looks like trait Event //root trait trait Status extends Event //special trait trait UIEvent extends Event //special trait case class Results extends Event //concrete case class case class Query extends Event //concrete case class case class Running extends Status //concrete case class case class Finished extends Status //concrete case class case class Update extends UIEvent //concrete case class I run the following test val events = List(Results, Query, Running, Finished, Update) events foreach { case Results => println("Got a Results") case Running => println("Got a Running") case s:Status => println("Got some StatusEvent") case ui:UIEvent => println("Got some UIEvent") case e: Event => println("Generic Event") case x => println("Didn't matched at all " + x) } println("############################") val STATUS = classOf[Status] val EVENT = classOf[Event] val UIEVENT = classOf[UIEvent] val RESULTS = classOf[Results] val eventsClass = events map (_.getClass) eventsClass foreach { case RESULTS => println("Got a Results") case STATUS => println("Got some StatusEvent") case UIEVENT => println("Got some UIEvent") case EVENT => println("Generic Event") case x => println("Didn't matched at all " + x) } which leads to the following output Got a Results Didn't match at all Query Got a Running Didn't match at all Finished Didn't match at all Update ############################ Didn't match at all class de.mukis.scala.test.main.Results$ Didn't match at all class de.mukis.scala.test.main.Query$ Didn't match at all class de.mukis.scala.test.main.Running$ Didn't match at all class de.mukis.scala.test.main.Finished$ Didn't match at all class de.mukis.scala.test.main.Update$ Why can't I pattern match on case class and traits or just only on the class? A: The problem is that you're referring to the companion objects for your case classes, not specific instances of them. The REPL should already have supplied you with deprecation warnings due to this. The solution is to add a few parentheses: sealed abstract trait Event sealed abstract trait Status extends Event sealed abstract trait UIEvent extends Event case class Results() extends Event case class Query() extends Event case class Running() extends Status case class Finished() extends Status case class Update() extends UIEvent and val events = List(Results(), Query(), Running(), Finished(), Update()) events foreach { case Results() => println("Got a Results") case Running() => println("Got a Running") case s:Status => println("Got some StatusEvent") case ui:UIEvent => println("Got some UIEvent") case e: Event => println("Generic Event") case x => println("Didn't match at all " + x) } or, as didierd suggests, use case objects sealed abstract trait Event sealed abstract trait Status extends Event sealed abstract trait UIEvent extends Event case object Results extends Event case object Query extends Event case object Running extends Status case object Finished extends Status case object Update extends UIEvent and val events = List(Results, Query, Running, Finished, Update) events foreach { case Results => println("Got a Results") case Running => println("Got a Running") case s:Status => println("Got some StatusEvent") case ui:UIEvent => println("Got some UIEvent") case e: Event => println("Generic Event") case x => println("Didn't match at all " + x) } A: Your problem is with case class without parantheses (which are now deprecated). A case class implies the creation of a companion object. When you write Results without parantheses, both in your list, and in the pattern matching, it means the companion object. You may try define sortOut(x: Any) = x match { case Results => "companion object" case Results() => "instance" } sortOut(Results) // returns companion object sortout(Results()) // returns instance This explains the behavior in the second part. As Results is the companion object, Results.getClass() is not classOf[Results], which is the class of instance, but the (synthetic) class of the companion object, Results$ If a case class has no parameters, most of the time it means that various instances cannot be distinguished from each other, and you should rather use a case object. Otherwise, put the parantheses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How does it convert _bstr_t to BSTR when passing as an argument? Taking a simple example: _bstr_t smartString(L"MyString"); Process(smartString); // takes BSTR. Initially I thought _bstr_t has a BSTR operator converting from _bstr_t to BSTR, but looking at msdn there is no such operator defined. How does it work when passign _bstr_t to BSTR parameter or _variant_t to VARIANT? A: BSTR is typedefed to be WCHAR* (wtypes.h file) and the latter is typedefed to be wchar_t* (winnt.h file) and _bstr_t has operator wchar_t*() member variable. So the compiler just uses that operator for conversion. A: If I understand your problem correctly, you want to call a method that expects BSTR*. There is no implicit conversion. Instead, use the GetAddress() parameter for the conversion. void foo( BSTR* ) {...} void f() { _bstr_t myBstr; foo( myBstr.GetAddress() ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7596317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: pointing the website from tomcat to the Apache server I have a website website1.com on Apache server developed using PHP and deployed in Apache Server. Now I have implemented a new features/modules in Java and JSP technologies and deployed in Tomcat server. Now what ever I have implemented in Java J2EE techologies should point to the subdomain of actual website website1.com and it should look like subdomain1.website1.com Both Apache Tomcat and Apache Server resides in the Same machine. Is that possible? if yes can you please help me how to do that ? All the environment is set up on LINUX based Server. A: You can try using a virtual host with a proxy pass rule. Core of the configuration would be: NameVirtualHost *:80 # Default host to handle PHP and static content <VirtualHost *:80> DocumentRoot /var/www/www.website1.com ServerName www.website1.com # Other directives here </VirtualHost> # Tomcat redirector <VirtualHost *:80> DocumentRoot /var/www/subdomain1.website1.com ServerName subdomain1.website1.com # Other directives here ProxyPass / ajp://website1.com:8009 </VirtualHost> Assuming you have enabled AJP connecter within your Tomcat configuration and that its running on port 8009.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Function with variable length argument list If I have the following function: function foo($a = 'a', $b = 'b', $c = 'c', $d = 'd') { // Do something } Can I call this function and only pass the value for $d, therefore leaving all the other arguments with their defaults? With code something like this: foo('bar'); Or do I have to call it with something like this: foo(null, null, null, 'bar'); A: You have to use nulls like you said: foo(null, null, null, 'bar'); If you don't mind creating more functions you could do something like this, I'd imagine the overall code would be neater. function update_d($val){ foo(null, null, null, $val); } Or you could use arrays like so: $args = array($a = 'a', $b = 'b', $c = 'c', $d = 'd'); foo($args); A: No, you cannot. Use arrays: function foo($args) { extract($args); echo $bar + $baz; } foo(array("bar" => 123, "baz" => 456)); Write a bug report on php.net and ask them to add named arguments to the language! A: You have to do it like foo(null, null, null, 'bar'); An alternative is to leave the arguments out of the function signature, and use func_get_args() to retrieve the values; function foo() { $args = func_get_args(); But then still, if you would leave out the first three null values, there's no way to know that 'bar' is the $d parameter. Note by the way that this approach is undesirable most of the times, because it obfuscates your function signature and hurts performance. A: Short answer: No. Long answer: Nooooooooooooooooooooooooooooo. Default argument value will be used when the variable is not set at all. A: You can't do it without overloading techniques. In this case, your program assumes that if only one param is passed, it's the fourth. A: func_get_args() - Gets an array of the function's argument list. func_num_args() - Returns the number of arguments passed to the function function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs<br />\n"; } foo(a); foo(1,b,c); will work fine
{ "language": "en", "url": "https://stackoverflow.com/questions/7596327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: wget not working to download jar file from maven repo I'm trying to download a single jar file from the maven repository, from the URL below. http://repo1.maven.org/maven2/com/google/guava/guava-testlib/10.0/guava-testlib-10.0.jar * *Downloading in a browser works fine, and I get the file as expected. *'wget' downloads something, but the file I get doesn't appear to be valid. Running 'jar -tf' on the downloaded file gives 'ZipException: error in opening zip file'. *Downloading the file programmatically from Java ('InputStream' from the URL writing to a 'FileOutputStream') downloads something and creates the file. Opening that with WinZip/7-Zip, it appears to contain one file named 'guava-testlib-10.0', which looks like the jar archive I was expecting to get. *wget another jar does work as expected at least sometimes (with -U user agent string) Is this some dodgy interaction between wget/maven or Java/maven? Is it a malformed jar file that my browser understands and downloads correctly? Both of those seem slightly implausible to me. A: wget generally gets blocked from the central maven repo because some people don't play nice and try to wget too much. Try set the user agent: wget -U "Any User Agent" http://repo1.maven.org/maven2/com/google/guava/guava-testlib/10.0/guava-testlib-10.0.jar
{ "language": "en", "url": "https://stackoverflow.com/questions/7596330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: template not show menu items in joomla 1.7 I am new in joomla 1.7 I have installed tx_freemium template but this template not showing menu items while other templates like beez_20,fruitshop etc work perfectely. A: i hope this works * *log in admin menu *go to extensions > modules *search your usermenu *to the right your parameters add 'tx-menu' to class suffix *set the position where you want the menu, as a reference which position you want look here: http://demo.themexpert.com/joomla16/2011/freemium/index.php/2011-04-17-17-18-46/module-variations *save changes that should work
{ "language": "en", "url": "https://stackoverflow.com/questions/7596335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Three20 get current Navigationcontroller I have an application calling Information from the web while a user is logged in. In case the session expired, the application delegate creates a quick UIAlertView with a password field so the user can login right away. Now the problem is: In case the user is already at the real login-page, i don't want to show him the UIAlertView because that would be only confusing. But how do I find out within the Application delegate, if the currently visible view controller is the login-View? If i had access to the top Navigation-Controller I could just call whether the currently visible view controller is of the login-controller class. But how would i get access to the navigation-controller? I'm using the three20 framework and thus the app delegate doesn't have a reference to a navigation-controller. A: Ok my fault, the TTNavigator reacts to visibleViewController or topViewController, too this allows a call like: [[[TTNavigator navigator] topViewController] isKindOfClass:[LoginView class]]; from anywhere in the Code
{ "language": "en", "url": "https://stackoverflow.com/questions/7596338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are the security risks in using cross-domain XMLHttpRequest? In many places I've seen people have talked about the Cross-Domain XMLHttpRequest, which is not possible, due to some security reasons. However, I haven't found a post indicating what those security reasons actually are? People have mentioned that JSONP is one of the good alternatives. Another alternative would be to use Origin and Access-Control-Allow-Origin headers. However, I just want to know what security problems can be raised due to cross-domain XMLHttpRequest usage? A: Without these "security reasons" the entire Internet as you know it could not exist. In fact i will go out on a limb and say there is no rule that is more important for Internet security than the same-origin policy. No web page could have authentication without these rules, google, web mail accounts, SO, none of this could exist. It would be as if you had XSS on every domain. You could perform an XHR against gmail.com and read anyone's email. CSRF tokens wouldn't work because you could read any page and forge the request. There is no single same-origin policy, but the rules are clearly laid out in the Google Browser Security handbook. These are very logical, and rules for the various platforms are very similar, because this is way the Internet must work. By doing a Access-Control-Allow-Origin: * you are forfeiting your rights granted to you by web browsers for that page. This has major security implications. You will not be able to protect your self from CSRF using tokens. A capthca could mitigate this problem, also checking the referer might also help(it will be blank if the origin is HTTPS). You should read the CSRF prevention cheat sheet. A: I think it would be best to answer your question of an example of WHY it would be horrendously bad. You go to my website (example.org). I load a script that makes a client-side AJAX request to facebook.com/messages/from/yourgirlfriend. You happened to be logged in to facebook, and your browser tells Facebook that my request is actually you. Facebook happily gives my request that message about the strange sexual things you want to try. I now know things about you you probably didn't want me to know. This, of course is a wild exaggeration, and thankfully not possible thanks to the same origin policy. Don't you feel safer now? A: If it was allowed, an attacker who manage to inject Javascript into your page (through exploit/social-engineering) can send data (usually sensitive) which are acquired from your clients without them knowing (since XMLHttpRequests don't require user actions to occur and they are silent). It is a browser security measure. JSONP is just a work around this security measure, where you give the destination a callback and entrust them with whatever they will give you back through this callback. EDIT: Examples of a security risk: you login to your email account through the web (like gmail or yahoo). You carry on browsing (in another tab or even in the current tab) to another malicious site. This malicious site try to do XHR to the same website of your email account. Since the XHR is on your behave, and since it is client/browser-side request, this request will have the same session you used to login, and therefore, this website can do whatever they want with your account (send a spam mail through your account, download your contacts, ...etc). Another example: In a forum, someone manage to inject Javascript with XHR to another website. He now can steal the contacts list (and maybe then delete them) from all the people who visit his post in the forum (by using the same session of your web email). Not to mention that he can share the session of the members of the forum visiting his post to get whatever data they have in the forum (private messages/friends..etc). He can then send these data to his server to save them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to loop a map with minimum resources? I was looking for a best way to loop through a map that involve as minimum resources as possible. Assume I have an object as the value, and the key is a string that referencing to the object. With the following two loop, may I know which one is better and how did you justified it run only minimum resources? for(Map.Entry<String, MyObject> entry : myMap.entrySet()) { ... } for( String key : myMap.keySet() ) { ... } THanks @! A: This depends on which specific Map you use. It's impossible to tell as it stands, since Map is an interface. In most map implementations both entrySet and keySet will return a view of the underlying set of entries / keys, so I'd say that they are likely more or less as efficient in all aspects. Note that if you retrieve all entries you're getting the values at the same time. This may save you some time if you often need the value. A: I believe the following is more efficient: for(Map.Entry<String, MyObject> entry : myMap.entrySet()) { ... } This is because it is probably doing a simple iteration over a collection depending on the Map implementation. On the other hand, if you iterate over the key and then call the Map's get method using the key, you are not only iterating over a collection of keys but also doing a lookup to retrieve each element from the Map. A: For the usual/sensible implementations: * *both loops only create an additional iterator object, so the memory resources are about the same (since for sensible implementations, the iterator objects themselves are quite simple). *the time resources depend on what you do in the loop. If you only need the key, they are about the same, too. If you need to retrieve the value from the key, you need slightly more runtime, but I don't think that makes a big difference. *on the whole, I'd think the differences are so small that it's premature optimization if you choose one implementation just because of it's minimal advantage in resources. A: What resources do you mean? Memory? In both cases you have one object reference beng used in the loop - whether it is entry or key. In neither case are other objects created. Both would be more or less equal in performance and resource usage. A: Why are you worried about resources? Is this honestly a practical, legitimate concern or is it a case of premature optimisation? From a design point of view, I'd use the entryset if you need to deal with the keys and values rather than just the keys. Not from a performance perspective, but from a practical, design perspective it's clearer that you're doing something with the entries in the map if you use that rather than just the keys. (Of course, if you are just doing something with the keys use the keyset.) As others have mentioned from a performance perspective it's impossible to tell without knowing implementation details, but unless you're doing something very specific or dealing with massive maps, that shouldn't be an issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linux: Snoop a signal without trashing the registers for the subsequent core dump? When I get coredump-causing signal, I want to run my own handler to copy the siginfo_t and ucontext_t structures to global variables, so that they may be accessed in the core dump. Currently at the end of my handler I reassign the default handler and call raise(thesig). The problem with doing that is that the core dump "info registers" shows the state of the registers in my handler, and not at the time of the original signal. I realise that since I've saved ucontext_t, I can look in that for the original register values, but that knowledge is likely to get lost/forgotten when core dumps are passed around the team. So my question is: is there a way to reraise a signal, and ensure the core dump file holds the register state of the original signal? I thought maybe I could use some inline asm to manually restore all the regs at the end of the handler, then return to the instruction that caused the signal instead of calling raise(), but I'm not sure if we can guarantee that re-attempting the instruction will cause the same signalling behaviour as the first attempt. A: copy the siginfo_t and ucontext_t structures to global variables, so that they may be accessed in the core dump If you re-raise the signal in your handler, then there is no need to copy anything -- the values will be on stack and accessible in the core dump. "info registers" shows the state of the registers in my handler, and not at the time of the original signal. Just do up 5 (or however many levels you need to step up to get to the crash point) and info reg again. is there a way to reraise a signal, and ensure the core dump file holds the register state of the original signal? Yes: set signal disposition to SIG_DFL using signal(signum, SIG_DFL); and return from your handler. The instruction that caused SIGSEGV will be restarted, and will now cause immediate core dump.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android. How to operate by history stack? Questions 1. How to make the same functionality as physical button "Back" on android phone? 2. Is it possible to make "Next" button using android history stack? I understand that probably it is not possible, but may be yes. So please let me know exactly A: Question 1: Just call finish() Question 2: I'm not sure about this. But I think when you call finish the Activity gets removed from the history stack. If you want something like next you could start the Activities using startActivityForResult() and then use onActivityResult() to determine that the user hit back/you finished the activity and save that somehow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assemblies don't copy to bin directory I have solution with 13 project. One project is WinForm (EArchive), other is class library. When I click on F5(Debug) or F6(Build Solution) the assemblies is building OK, but they don't copy to bin directory of EArchive. When I click right mouse button on EArchive and select Build then works(but not all, for example don't copy resource file). I have tried: 1. Delete all bin and obj folders. 2. Rebuild All. 3. Clean command from context menu. Visual Studio 2010. Thanks. A: (I realize this is an old post, but it's still unanswered.) This sounds like the WinForm project is not set to be built in the solution's build configuration. I've encountered problems like this where a project will unexpectedly be unchecked in the Configuration Manager (under the Build menu). Check there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the difference between cancelBubble and stopPropagation? Can anyone please tell me difference in usage of cancelBubble and stopPropagation methods used in Javascript. A: For compatibility with IE8 and older use .cancelBubble if .stopPropogation() is undefined: if(ev.stopPropagation)ev.stopPropagation(); else ev.cancelBubble=true; // where ev is an event object Read about in MSDN: http://msdn.microsoft.com/en-us/library/ff975961%28v=vs.85%29.aspx A: cancelBubble is an IE-only Boolean property (not method) that serves the same purpose as the stopPropagation() method of other browsers, which is to prevent the event from moving to its next target (known as "bubbling" when the event is travelling from inner to outer elements, which is the only way an event travels in IE < 9). IE 9 now supports stopPropagation() so cancelBubble will eventually become obsolete. In the meantime, the following is a cross-browser function to stop an event propagating: function stopPropagation(evt) { if (typeof evt.stopPropagation == "function") { evt.stopPropagation(); } else { evt.cancelBubble = true; } } In an event handler function, you could use it as follows: document.getElementById("foo").onclick = function(evt) { evt = evt || window.event; // For IE stopPropagation(evt); }; A: Another difference that anyone has described is that e.cancelBubble stops event propagation for the further elements only in bubbling phase (when event reaches the first bubbling element), while .preventDefault() prevent propagation both in capturing and bubbling phase (immediately for the next element in propagation). var a = document.getElementById('a'); var b = document.getElementById('b'); var c = document.getElementById('c'); var d = document.getElementById('d'); a.addEventListener('click',cancel,true); b.addEventListener('click',cancel,true); c.addEventListener('click',cancel,false); d.addEventListener('click',cancel,false); function cancel(event){ var logElem = event.currentTarget.id; console.log(logElem); if(logElem==='a') event.cancelBubble = true; } var e = document.getElementById('e'); var f = document.getElementById('f'); var g = document.getElementById('g'); var h = document.getElementById('h'); e.addEventListener('click',stop,true); f.addEventListener('click',stop,true); g.addEventListener('click',stop,false); h.addEventListener('click',stop,false); function stop(event){ var logElem = event.currentTarget.id; console.log(logElem); if(logElem==='e') event.stopPropagation(); } #a,#b,#c,#d,#e,#f,#g,#h{ box-sizing:border-box; width:100%; height:90%; border:solid 1px #33aaff; padding:10px; padding-top:0px; cursor:pointer; } #a,#e{ width:200px; height:200px; } <h3>cancelBubble</h3> <div id='a'>a capturing <div id='b'>b capturing <div id='c'>c bubbling <div id='d'>d bubbling </div> </div> </div> </div> <h3>stopPropagation</h3> <div id='e'>e capturing <div id='f'>f capturing <div id='g'>g bubbling <div id='h'>h bubbling </div> </div> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7596364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: How can I generate tags files for latex command for use in Vim? I'm using latex-box and omnicomplete when typing latex in Vim. I find that it can just completes some of latex commands. How can we generate a tags file of the full basic latex command using ctags, or maybe generate tags file from the packages needed in my latexFile.tex in further ? Anyone know how to do that ? Or some other solutions ? Thanks! Update: There is a post about ctags+latex: http://caffeinatedcode.wordpress.com/2009/11/16/simple-latex-ctags-and-taglist/ (It could be useful.) A: For the vim completion part you can use the 'dictionary' option that specifies the list of files to look for candidates for completion for the i_CTRL-X_CTRL_K. The next part is to generate those files that you want to refer to in the 'dictionary' option. For this you can google for the list of all 'built-in' latex commands, and for the additional packages you can whip up a shell script to extract all the defined commands. A: Maybe it helps you: http://vim-taglist.sourceforge.net/extend.html See the end of document ("Add the following lines to the $HOME/.ctags or $HOME/ctags.conf file").
{ "language": "en", "url": "https://stackoverflow.com/questions/7596368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Load a view using AJAX in ASP.NET 3 RAZR When using MVC you are calling actions that then load a view and a parent layout/masterpage. When you wish to load a view using AJAX though and then stick that content say inside a div with an id of content you would end up loading all the layout and stuff as well as you are just calling the action. How do I get around this? Is their some way to say if calling this action using AJAX then don't bother with the layout and just shove the view inside the div? Any code examples would be much appreciated. Thanks A: ajax request $.ajax({ url: '/controller/action', type:'POST', success:function(data){ // data will contain the html rendered by partial view $('#someDivID').html(data); } }); your ActionResult will look like public ActionResult ActionName() { //some code return PartialView(); //or // return View(); } A: in your ajax response HTML you can select only the div or elements you want to display lets suppose your ajax calls looks like this:- $.ajax( url: 'some_url', success:function(responseHtml){ $('.div-on-current-page').html( $(responseHtml).find('.div-inside-response') ); }); just give your response HTML to jquery $(responseHtml) and select the content you want $(responseHtml).find('.div-inside-response') and set it in your current page div $('.div-on-current-page').html( $(responseHtml).find('.div-inside-response') );. A: Process: You need to do a ajax call to one action which give you a view you want in a string, bellow you can see the different methods you need to take what you o want. 'RenderPartialViewToString' method convert the view in a string: public static string RenderPartialViewToString<T>( ControllerContext context, string partialViewName, T model, TempDataDictionary tempData) { ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName); if (result.View != null) { StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { using (HtmlTextWriter output = new HtmlTextWriter(sw)) { ViewContext viewContext = new ViewContext(context, result.View, new ViewDataDictionary<T>(model), tempData, output); result.View.Render(viewContext, output); } } return sb.ToString(); } return String.Empty; } In your action, call 'RenderPartialViewToString' method: public ActionResult ActionName(ActionParameters) { return Json(RenderPartialViewToString(this.ControllerContext, "ViewName", model, tempDict), JsonRequestBehavior.AllowGet); } In Javascript make something like this: $.ajax({ url: '/controllerName/actionName', success:function(result){ $('div#someID').html(result); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7596369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the difference between Android's invalidate() and postInvalidate() methods? What is the difference between Android's invalidate() and postInvalidate() methods? When does each one get called? Must the methods be called only in classes which extend View? A: If you want to re-draw your view from the UI thread you can call invalidate() method. If you want to re-draw your view from a non-UI thread you can call postInvalidate() method. Each class which is derived from the View class has the invalidate and the postInvalidate method. If invalidate gets called it tells the system that the current view has changed and it should be redrawn as soon as possible. As this method can only be called from your UI thread another method is needed for when you are not in the UI thread and still want to notify the system that your View has been changed. The postInvalidate method notifies the system from a non-UI thread and the view gets redrawn in the next event loop on the UI thread as soon as possible. It is also shortly explained in the SDK documentation: CLICK HERE UPDATE: There are some problems that arise when using postInvalidate from other threads (like not having the UI updated right-away), this will be more efficient: runOnUiThread(new Runnable() { public void run() { myImageView.setImageBitmap(image); imageView.invalidate(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7596370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Adjusting dropdown in ExtJS combobox I need such combobox, that's it dropdown's width ant that one of input are different and dropdown is adjusted to the right edge of the input. First part is easy - juts set matchFieldWidth to false and assign listConfig.width = something. But what is the easiest way to perform the adjustment? Here is a picture which illustrates the question. A: I'll be the first, but will not gain a reputation - all we should do - is just set pickerAlign to tr-br.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Euro Symbol in RTF I'm trying to get a euro symbol to show in in a RTF document, but am not having much luck. The RTF doc is a template, which is populated with data from .Net (by reading in the text stream and replacing tokens within it). One of these tokens relates to a euro symbol. My code is working as expected, in that the output RTF doc contains the euro symbol in the markup (when viewed in notepad), however, when viewed in word, etc. the euro symbol shows up as '€'. I assume that it's an encoding issue - can anyone help with some suggestions? A: The rtf should contain \'80, not the Euro symbol directly. I don't know how you're inserting the tokens, but this is what should be inserted, not the €. For the full list, see Complete Character List for windows-1258. Thanks Bob. A: Quick google search. Maybe one of these helps: Unicode Character 'EURO SIGN'
{ "language": "en", "url": "https://stackoverflow.com/questions/7596377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to detect if a frame is odd or even on an interlaced image? I have a device that is taking TV screenshots at precise times (it doesn't take incomplete frames). Still this screenshot is an interlace image made from two different original frames. Now, the question is if/how is possible to identify which of the lines are newer/older. I have to mention that I can take several sequential screenshots if needed. A: Take two screenshots one after another, yielding a sequence of two images (1,2). Split each screenshot into two fields (odd and even) and treat each field as a separate image. If you assume that the images are interlaced consistently (pretty safe assumption, otherwise they would look horrible), then there are two possibilities: (1e, 1o, 2e, 2o) or (1o, 1e, 2o, 2e). So at the moment it's 50-50. What you could then do is use optical flow to improve your chances. Say you go with the first option: (1e, 1o, 2e, 2o). Calculate the optical flow f1 between (1e, 2e). Then calculate the flow f2 between (1e, 1o) and f3 between (1o,2e). If f1 is approximately the same as f2 + f3, then things are moving in the right direction and you've picked the right arrangement. Otherwise, try the other arrangement. Optical flow is a pretty general approach and can be difficult to compute for the entire image. If you want to do things in a hurry, replace optical flow with video tracking. EDIT I've been playing around with some code that can do this cheaply. I've noticed that if 3 fields are consecutive and in the correct order, the absolute error due to smooth, constant motion will be minimized. On the contrary, if they are out of order (or not consecutive), this error will be greater. So one way to do this is two take groups of 3 fields and check the error for each of the two orderings described above, and go with the ordering that yielded the lower error. I've only got a handful of interlaced videos here to test with but it seems to work. The only down-side is its not very effective unless there is substantial smooth motion or the number of used frames is low (less than 20-30). Here's an interlaced frame: Here's some sample output from my method (same frame): The top image is the odd-numbered rows. The bottom image is the even-numbered rows. The number in the brackets is the number of times that image was picked as the most recent. The number to the right of that is the error. The odd rows are labeled as the most recent in this case because the error is lower than for the even-numbered rows. You can see that out of 100 frames, it (correctly) judged the odd-numbered rows to be the most recent 80 times. A: You have several fields, F1, F2, F3, F4, etc. Weave F1-F2 for the hypothesis that F1 is an even field. Weave F2-F3 for the hypothesis that F2 is an even field. Now measure the amount of combing in each frame. Assuming that there is motion, there will be some combing with the correct interlacing but more combing with the wrong interlacing. You will have to do this at several times in order to find some fields when there is motion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: PHP Beginner: Where and how are objects stored? In an app written in PHP (e.g., a social network), let's say that 10 users (signed-in) are browsing the website. In PHP code, there is "user" object created to store users data and to pass values to other functions and classes. Question: When these 10 users go to user.php, which has code to create "user" object, how are these objects stored in memory in PHP? Do they not conflict? Is each one of the "user" objects are uniquely stored in the memory or would one be overwritten by another? For example, user a visits first so object "user" contains his/her data but when user second visits, the "user" object in memory is overwritten so when first user calls the object, it's the second users data retrieved. Or, is it unique? I want to understand object in PHP as a newbie, please explain it simply because none of the web pages I found regarding OOP explains this. A: PHP is a CGI application, that means, it's being started and terminated on each request. * *a client sends a request to the web server *the server starts PHP and passes the request to it *PHP allocates a chunk of memory for your script *your script is being executed, all objects it creates are stored in that chunk of memory *you script generates some html, this html is sent to the client *the memory is being freed and PHP is stopped If you have 10 clients requests coming at the same time, 10 copies of php will be started and 10 independent memory chunks will be used. So, no, objects from different requests do not interfere. (Note: this explanation is deliberately simplified, there are actually different php setups and persistence options). A: The best way to learn this is to install php on a local PC or Mac and then create a php info file <?php phpinfo(); ?> ... then open it in your browser...This will show you all the settings on your server for php and other things. Regarding the answer to your question, it's a bit more of an advanced topic for a newbee, but php sessions are what do the work of keeping user info. They usually work off a session id which is unique to the user for a small amount of time, and they dynamically allocate memory or disk space/flat files or a database (again see the settings above) to store the relevant data. Unfortunately for you none of this is "automatic" you have to create the scripts to make it happen and behave in the way you want. Asking questions on this site is a good start... A: You need to look at object design patterns in relation to php which is quite a big subject in its own right. There is an excellent Apress book called 'PHP Objects, Patterns and Practice' which explains some of the more common patterns and how you might use them and would be a good place to start learning. A: The users information is all stored in a database, the user object will have to retrieve this data each time the page loads. The object know what user is looking at the page because of their session_id, which in a nut shell is a random id given to you, stored in a cookie. using the session_id you can retrieve the correct information form the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: custom listview using cursor and it should display image as listitem I am developing one application which uses custom listview and listview is filled by data from simple cursor adapter. Now i want to display an image as listitem and it's varying in each listitem. my code is: dbHelper = new DatabaseHelper(this); try { String strDrSearchName = etSearchVisitDr.getText().toString(); Cursor c = dbHelper.getViewAllDoctorSearch(strDrSearchName); Log.d("Search", "Search"); startManagingCursor(c); from = new String[] { DatabaseHelper.colvarDrCode, DatabaseHelper.colvarDrName, DatabaseHelper.colvarCategory, DatabaseHelper.colvarCityName, DatabaseHelper.colvarSpeciality }; to = new int[] { R.id.txtDrCode, R.id.txtDrName, R.id.txtDrCat, R.id.txtDrCity, R.id.txtDrSpec }; SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.gridvisitdoctor, c, from, to); list.setAdapter(sca); It works fine and display results in list but how can I display image as list item which is different for all listitems. I solved this and this is my code package pkg.ecpTablet; import java.text.SimpleDateFormat; import java.util.Date; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteCursor; import android.graphics.Color; import android.graphics.Path.FillType; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.webkit.WebChromeClient.CustomViewCallback; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.AdapterView.OnItemClickListener; import android.widget.TextView; import android.widget.Toast; public class CurrentVisitDoctor extends Activity { Button btnToggleAP; Button btnDrVisitback; EditText etSearchDrVisit; ListView listDrCurrentVisit; TextView txtDate; TextView txtPlanned; TextView txtVisited; TextView txtTotal; DatabaseHelper dbHelper; String strDate; String strCTDay; ListView list; String[] from; int[] to; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.currentvisitdoctor); btnToggleAP = (Button) findViewById(R.id.btnToggleAP); btnDrVisitback = (Button) findViewById(R.id.btnDrVisitback); etSearchDrVisit = (EditText) findViewById(R.id.etSearchDrVisit); listDrCurrentVisit = (ListView) findViewById(R.id.listDrCurrentVisit); txtDate = (TextView) findViewById(R.id.txtDate); txtPlanned = (TextView) findViewById(R.id.txtPlanned); txtVisited = (TextView) findViewById(R.id.txtVisited); txtTotal = (TextView) findViewById(R.id.txtTotal); btnDrVisitback.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent iBack = new Intent(CurrentVisitDoctor.this, VisitHome.class); startActivity(iBack); } }); // LoadGridTourPlanDr(); fillDataTourPlannedDr(); Bundle b = new Bundle(); b = getIntent().getExtras(); final int flag = b.getInt("flag"); if (flag == 0) { strDate = b.getString("ydate"); txtDate.setText(strDate); } if (flag == 1) { strDate = b.getString("date"); txtDate.setText(strDate); } if (flag == 2) { strDate = b.getString("Date"); txtDate.setText(strDate); } try { String strVisitDate = txtDate.getText().toString().trim(); SimpleDateFormat dateFormatMessage = new SimpleDateFormat( "dd/MM/yyyy"); Date dtVisitDate = dateFormatMessage.parse(strVisitDate); SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd"); String dtMsgDate = postFormater.format(dtVisitDate); // Toast.makeText(this,dtMsgDate, 30).show(); int CountTourPlan = dbHelper.CountTourPlanDr(dtMsgDate); int CountTotalVisited = dbHelper.CountTotalVisited(dtMsgDate); int CountVisit = dbHelper.getTodayDoneVisitDr(dtMsgDate); txtPlanned.setText("Planned(" + CountTourPlan + ")"); txtTotal.setText("Total(" + CountTotalVisited + ")"); txtVisited.setText("Visit(" + CountVisit + ")"); /* * txtPlanned.setText(CountTourPlan); txtTotal.setText(CountVisit); * txtVisited.setText(CountTotalVisited); */ } catch (Exception e) { Alerts.ShowMessageAlert(CurrentVisitDoctor.this, "", String.valueOf(e)); } // Toast.makeText(CurrentVisitDoctor.this, String.valueOf(flag), // 30).show(); btnToggleAP.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { etSearchDrVisit.setText(""); if (btnToggleAP.getText().toString().equals("P")) { btnToggleAP.setText("A"); // LoadGridAllDr(); fillDataAllDr(); } else { btnToggleAP.setText("P"); // LoadGridTourPlanDr(); fillDataTourPlannedDr(); } } }); etSearchDrVisit.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { if (btnToggleAP.getText().toString().equals("P")) { LoadGridTourPlanDrSearch(); } else { // LoadGridAllDrSearch(); fillDataAllDrSearch(); } } public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { if (btnToggleAP.getText().toString().equals("P")) { // LoadGridTourPlanDrSearch(); fillDataTourPlannedDrSearch(); } else { // LoadGridAllDrSearch(); fillDataAllDrSearch(); } } public void afterTextChanged(Editable arg0) { if (btnToggleAP.getText().toString().equals("P")) { // LoadGridTourPlanDrSearch(); fillDataTourPlannedDrSearch(); } else { // LoadGridAllDrSearch(); fillDataAllDrSearch(); } } }); listDrCurrentVisit.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // TODO Auto-generated method stub SQLiteCursor cr = (SQLiteCursor) parent .getItemAtPosition(position); String DrName = cr.getString(cr .getColumnIndex(DatabaseHelper.colvarDrName)); String DrCode = cr.getString(cr .getColumnIndex(DatabaseHelper.colvarDrCode)); int intDrcode = Integer.parseInt(DrCode); int drGlCode = dbHelper.GetDrID(DrName); String DrCategory = cr.getString(cr .getColumnIndex(DatabaseHelper.colvarCategory)); String DrCityname = cr.getString(cr .getColumnIndexOrThrow(DatabaseHelper.colvarCityName)); String DrSpeciality = cr.getString(cr .getColumnIndex(DatabaseHelper.colvarSpeciality)); Bundle b = new Bundle(); Intent deviatedvisits = new Intent(CurrentVisitDoctor.this, DoctorVisit.class); b.putInt("drGlCode", drGlCode); b.putString("drname", DrName); b.putString("drcode", DrCode); b.putString("drspeciality", DrSpeciality); b.putString("drcity", DrCityname); b.putString("drcategory", DrCategory); b.putInt("flag", flag); b.putString("Date", txtDate.getText().toString()); deviatedvisits.putExtras(b); startActivity(deviatedvisits); } }); } public void LoadGridAllDr() { dbHelper = new DatabaseHelper(this); try { // Cursor c=dbHelper.getTourPlan(); Cursor c = dbHelper.getViewAllDoctor(); // Cursor // c=dbHelper.getViewAllDoctor(strDrSearchCode,strDrSearchName,strDrSearchCat,strDrSearchCity,strDrSearchSpec); startManagingCursor(c); // int no = Integer.valueOf((String.valueOf(cr.toString()))); // txtVisitToday.setText(String.valueOf(cr.getColumnIndex("TodayPlan"))); // txtVisitToday.setText(String.valueOf(c.getColumnCount())); String[] from = new String[] { DatabaseHelper.colvarDrCode, DatabaseHelper.colvarDrName, DatabaseHelper.colvarCategory, DatabaseHelper.colvarCityName, DatabaseHelper.colvarSpeciality }; int[] to = new int[] { R.id.txtDrCode, R.id.txtDrName, R.id.txtDrCat, R.id.txtDrCity, R.id.txtDrSpec }; SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.gridcurrentvisitdoctor, c, from, to); listDrCurrentVisit.setAdapter(sca); // Toast.makeText(VisitDoctor.this, // String.valueOf(dbHelper.getTodayPlanDrVisit()), // Toast.LENGTH_LONG).show(); } catch (Exception ex) { // AlertDialog.Builder b=new AlertDialog.Builder(this); // b.setMessage(ex.toString()); // b.show(); } } public void LoadGridTourPlanDr() { dbHelper = new DatabaseHelper(this); try { String strVisitDate = txtDate.getText().toString().trim(); // Toast.makeText(CurrentVisitDoctor.this, strVisitDate, 30).show(); SimpleDateFormat dateFormatMessage = new SimpleDateFormat( "dd/MM/yyyy"); Date dtVisitDate = dateFormatMessage.parse(strVisitDate); SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd"); String dtMsgDate = postFormater.format(dtVisitDate); // Cursor c=dbHelper.getTourPlan(); Cursor c = dbHelper.getViewPlanDoctor(dtMsgDate); // Cursor // c=dbHelper.getViewAllDoctor(strDrSearchCode,strDrSearchName,strDrSearchCat,strDrSearchCity,strDrSearchSpec); startManagingCursor(c); // int intTourPlanToday = dbHelper.getTodayPlanDrVisit(); // int no = Integer.valueOf((String.valueOf(cr.toString()))); // txtVisitToday.setText(String.valueOf(cr.getColumnIndex("TodayPlan"))); // txtVisitToday.setText(String.valueOf(c.getColumnCount())); String[] from = new String[] { DatabaseHelper.colvarDrCode, DatabaseHelper.colvarDrName, DatabaseHelper.colvarCategory, DatabaseHelper.colvarCityName, DatabaseHelper.colvarSpeciality }; int[] to = new int[] { R.id.txtDrCode, R.id.txtDrName, R.id.txtDrCat, R.id.txtDrCity, R.id.txtDrSpec }; SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.gridcurrentvisitdoctor, c, from, to); listDrCurrentVisit.setAdapter(sca); // Toast.makeText(VisitDoctor.this, // String.valueOf(dbHelper.getTodayPlanDrVisit()), // Toast.LENGTH_LONG).show(); } catch (Exception ex) { // AlertDialog.Builder b=new AlertDialog.Builder(this); // b.setMessage(ex.toString()); // b.show(); } } public void LoadGridAllDrSearch() { dbHelper = new DatabaseHelper(this); try { String strDrSearchName = etSearchDrVisit.getText().toString(); String strDrName = etSearchDrVisit.getText().toString(); String finaleDrNameSearch = strDrName; Cursor c = dbHelper.getViewAllDoctorSearch(finaleDrNameSearch); // Cursor c=dbHelper.getViewAllDoctorSearch(strDrSearchCode, // strDrSearchName, strDrSearchCat, strDrSearchCity, // strDrSearchSpec); startManagingCursor(c); // int no = Integer.valueOf((String.valueOf(cr.toString()))); // txtVisitToday.setText(String.valueOf(cr.getColumnIndex("TodayPlan"))); // txtVisitToday.setText(String.valueOf(c.getColumnCount())); String[] from = new String[] { DatabaseHelper.colvarDrCode, DatabaseHelper.colvarDrName, DatabaseHelper.colvarCategory, DatabaseHelper.colvarCityName, DatabaseHelper.colvarSpeciality }; int[] to = new int[] { R.id.txtDrCode, R.id.txtDrName, R.id.txtDrCat, R.id.txtDrCity, R.id.txtDrSpec }; SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.gridcurrentvisitdoctor, c, from, to); listDrCurrentVisit.setAdapter(sca); // Toast.makeText(VisitDoctor.this, // String.valueOf(dbHelper.getTodayPlanDrVisit()), // Toast.LENGTH_LONG).show(); } catch (Exception ex) { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setMessage(ex.toString()); b.show(); } } public void LoadGridTourPlanDrSearch() { dbHelper = new DatabaseHelper(this); try { String strVisitDate = txtDate.getText().toString().trim(); SimpleDateFormat dateFormatMessage = new SimpleDateFormat( "dd/MM/yyyy"); Date dtVisitDate = dateFormatMessage.parse(strVisitDate); SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd"); String dtMsgDate = postFormater.format(dtVisitDate); String strDrName = etSearchDrVisit.getText().toString(); String finaleDrNameSearch = strDrName; Cursor c = dbHelper.getViewPlanDoctorSearch(finaleDrNameSearch, dtMsgDate); // Cursor c=dbHelper.getViewPlanDoctorSearch(strDrSearchCode, // strDrSearchName, strDrSearchCat, strDrSearchCity, // strDrSearchSpec); startManagingCursor(c); // int no = Integer.valueOf((String.valueOf(cr.toString()))); // txtVisitToday.setText(String.valueOf(cr.getColumnIndex("TodayPlan"))); // txtVisitToday.setText(String.valueOf(c.getColumnCount())); String[] from = new String[] { DatabaseHelper.colvarDrCode, DatabaseHelper.colvarDrName, DatabaseHelper.colvarCategory, DatabaseHelper.colvarCityName, DatabaseHelper.colvarSpeciality }; int[] to = new int[] { R.id.txtDrCode, R.id.txtDrName, R.id.txtDrCat, R.id.txtDrCity, R.id.txtDrSpec }; SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.gridcurrentvisitdoctor, c, from, to); listDrCurrentVisit.setAdapter(sca); // Toast.makeText(VisitDoctor.this, // String.valueOf(dbHelper.getTodayPlanDrVisit()), // Toast.LENGTH_LONG).show(); } catch (Exception ex) { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setMessage(ex.toString()); b.show(); } } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); btnToggleAP = (Button) findViewById(R.id.btnToggleAP); btnDrVisitback = (Button) findViewById(R.id.btnDrVisitback); etSearchDrVisit = (EditText) findViewById(R.id.etSearchDrVisit); listDrCurrentVisit = (ListView) findViewById(R.id.listDrCurrentVisit); txtDate = (TextView) findViewById(R.id.txtDate); // LoadGridTourPlanDr(); fillDataTourPlannedDr(); Bundle b = new Bundle(); b = getIntent().getExtras(); final int flag = b.getInt("flag"); if (flag == 0) { strDate = b.getString("ydate"); txtDate.setText(strDate); } if (flag == 1) { strDate = b.getString("date"); txtDate.setText(strDate); } if (flag == 2) { strDate = b.getString("Date"); txtDate.setText(strDate); } } protected void fillDataAllDr() { dbHelper = new DatabaseHelper(this); Cursor c = dbHelper.getViewAllDoctor(); startManagingCursor(c); from = new String[] { DatabaseHelper.colvarDrCode, DatabaseHelper.colvarDrName, DatabaseHelper.colvarCategory, DatabaseHelper.colvarCityName, DatabaseHelper.colvarSpeciality }; to = new int[] { R.id.txtDrCode, R.id.txtDrName, R.id.txtDrCat, R.id.txtDrCity, R.id.txtDrSpec }; // SimpleCursorAdapter sca = new SimpleCursorAdapter(this, // R.layout.gridvisitdoctor, c, from, to); customCursorAdapter cca = new customCursorAdapter(this, R.layout.gridvisitdoctor, c, from, to); listDrCurrentVisit.setAdapter(cca); } protected void fillDataTourPlannedDr() { dbHelper = new DatabaseHelper(this); try { // Cursor c = dbHelper.getViewAllDoctor(); // startManagingCursor(c); String strVisitDate = txtDate.getText().toString().trim(); // Toast.makeText(CurrentVisitDoctor.this, strVisitDate, 30).show(); SimpleDateFormat dateFormatMessage = new SimpleDateFormat( "dd/MM/yyyy"); Date dtVisitDate = dateFormatMessage.parse(strVisitDate); SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd"); String dtMsgDate = postFormater.format(dtVisitDate); // Cursor c=dbHelper.getTourPlan(); Cursor c = dbHelper.getViewPlanDoctor(dtMsgDate); // Cursor // c=dbHelper.getViewAllDoctor(strDrSearchCode,strDrSearchName,strDrSearchCat,strDrSearchCity,strDrSearchSpec); startManagingCursor(c); // int intTourPlanToday = dbHelper.getTodayPlanDrVisit(); from = new String[] { DatabaseHelper.colvarDrCode, DatabaseHelper.colvarDrName, DatabaseHelper.colvarCategory, DatabaseHelper.colvarCityName, DatabaseHelper.colvarSpeciality }; to = new int[] { R.id.txtDrCode, R.id.txtDrName, R.id.txtDrCat, R.id.txtDrCity, R.id.txtDrSpec }; // SimpleCursorAdapter sca = new SimpleCursorAdapter(this, // R.layout.gridvisitdoctor, c, from, to); customCursorAdapter cca = new customCursorAdapter(this, R.layout.gridvisitdoctor, c, from, to); listDrCurrentVisit.setAdapter(cca); } catch (Exception ex) { // AlertDialog.Builder b=new AlertDialog.Builder(this); // b.setMessage(ex.toString()); // b.show(); } } protected void fillDataAllDrSearch() { dbHelper = new DatabaseHelper(this); try { String strDrSearchName = etSearchDrVisit.getText().toString(); String strDrName = etSearchDrVisit.getText().toString(); String finaleDrNameSearch = strDrName; Cursor c = dbHelper.getViewAllDoctorSearch(finaleDrNameSearch); // Cursor c=dbHelper.getViewAllDoctorSearch(strDrSearchCode, // strDrSearchName, strDrSearchCat, strDrSearchCity, // strDrSearchSpec); startManagingCursor(c); // Cursor c = dbHelper.getViewAllDoctor(); // startManagingCursor(c); from = new String[] { DatabaseHelper.colvarDrCode, DatabaseHelper.colvarDrName, DatabaseHelper.colvarCategory, DatabaseHelper.colvarCityName, DatabaseHelper.colvarSpeciality }; to = new int[] { R.id.txtDrCode, R.id.txtDrName, R.id.txtDrCat, R.id.txtDrCity, R.id.txtDrSpec }; // SimpleCursorAdapter sca = new SimpleCursorAdapter(this, // R.layout.gridvisitdoctor, c, from, to); customCursorAdapter cca = new customCursorAdapter(this, R.layout.gridcurrentvisitdoctor, c, from, to); listDrCurrentVisit.setAdapter(cca); } catch (Exception ex) { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setMessage(ex.toString()); b.show(); } } protected void fillDataTourPlannedDrSearch() { dbHelper = new DatabaseHelper(this); try { String strVisitDate = txtDate.getText().toString().trim(); SimpleDateFormat dateFormatMessage = new SimpleDateFormat( "dd/MM/yyyy"); Date dtVisitDate = dateFormatMessage.parse(strVisitDate); SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd"); String dtMsgDate = postFormater.format(dtVisitDate); String strDrName = etSearchDrVisit.getText().toString(); String finaleDrNameSearch = strDrName; Cursor c = dbHelper.getViewPlanDoctorSearch(finaleDrNameSearch, dtMsgDate); // Cursor c=dbHelper.getViewPlanDoctorSearch(strDrSearchCode, // strDrSearchName, strDrSearchCat, strDrSearchCity, // strDrSearchSpec); startManagingCursor(c); // int intTourPlanToday = dbHelper.getTodayPlanDrVisit(); from = new String[] { DatabaseHelper.colvarDrCode, DatabaseHelper.colvarDrName, DatabaseHelper.colvarCategory, DatabaseHelper.colvarCityName, DatabaseHelper.colvarSpeciality }; to = new int[] { R.id.txtDrCode, R.id.txtDrName, R.id.txtDrCat, R.id.txtDrCity, R.id.txtDrSpec }; // SimpleCursorAdapter sca = new SimpleCursorAdapter(this, // R.layout.gridvisitdoctor, c, from, to); customCursorAdapter cca = new customCursorAdapter(this, R.layout.gridcurrentvisitdoctor, c, from, to); listDrCurrentVisit.setAdapter(cca); } catch (Exception ex) { // AlertDialog.Builder b=new AlertDialog.Builder(this); // b.setMessage(ex.toString()); // b.show(); } } } // class complete // ListView Adapter Class class customCursorAdapter extends SimpleCursorAdapter { private int layout; Context context; public customCursorAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to) { super(context, layout, cursor, from, to); this.layout = layout; this.context = context; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder; int flag = 1; if (view != null) { holder = new ViewHolder(); holder.txtViewDrname = (TextView) view.findViewById(R.id.txtDrName); holder.txtViewDrCode = (TextView) view.findViewById(R.id.txtDrCode); holder.txtViewDrSpec = (TextView) view.findViewById(R.id.txtDrSpec); holder.txtViewDrCity = (TextView) view.findViewById(R.id.txtDrCity); holder.txtViewDrCat = (TextView) view.findViewById(R.id.txtDrCat); holder.imgbullet = (ImageView) view.findViewById(R.id.imgVisited); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } String DrName = cursor.getString(cursor .getColumnIndex(DatabaseHelper.colvarDrName)); // String name = cursor.; if (holder.txtViewDrname != null) { holder.txtViewDrname.setText(DrName); holder.txtViewDrname.setTextColor(Color.RED); } String DrCode = cursor.getString(cursor .getColumnIndex(DatabaseHelper.colvarDrCode)); holder.txtViewDrCode.setText(DrCode); String DrSpeciality = cursor.getString(cursor .getColumnIndex(DatabaseHelper.colvarSpeciality)); holder.txtViewDrSpec.setText(DrSpeciality); String DrCityName = cursor.getString(cursor .getColumnIndex(DatabaseHelper.colvarCityName)); holder.txtViewDrCity.setText(DrCityName); String DrCategory = cursor.getString(cursor .getColumnIndex(DatabaseHelper.colvarCategory)); holder.txtViewDrCat.setText(DrCategory); if (DrName.equals("A. B. Mehta")) { holder.imgbullet.setBackgroundResource(R.drawable.yellow_bulet); } } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); final View view = inflater.inflate(layout, parent, false); return view; } @Override public long getItemId(int id) { return id; } @Override public Object getItem(int position) { return position; } } class ViewHolder { TextView txtViewDrname; TextView txtViewDrCode; TextView txtViewDrCity; TextView txtViewDrSpec; TextView txtViewDrCat; ImageView imgbullet; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7596380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hbase regionservers We have installed hadoop cluster. We want to use HBase over it. My hbase-site.xml is below <property> <name>hbase.rootdir</name> <value>hdfs://ali:54310/hbase</value> <description>The directory shared by RegionServers. </description> </property> <property> <name>hbase.cluster.distributed</name> <value>true</value> <description> </description> </property> <property> <name>hbase.zookeeper.quorum</name> <value>ali,reg_server1</value> <description>The directory shared by region servers. </description> </property> <property> <name>dfs.replication</name> <value>1</value> <description> </description> </property> And I have 2 region servers ali and reg_server1. When I open page at http://ali:60010 I see that server reg_server1 has 0 regions. but server ali has n > 0 regions. I put some data to Hbase but, server reg_server1 still has 0 regions. Does it means that this node is not participiating in cluster? How can I resolve it? Thanks A: No, you are ok as long as you see both regionservers in the master's web UI. When you write to an HBase table, it will write to one region (one region is always on one regionserver, in your case, ali). Once you write enough data to make the region exceed the configured max file size, the region will be split and distributed across the two regionservers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: protobuf-net ignores [KnownType] and requires ProtoInclude to be added using protobuf-net.dll 2.0.0.431 I'm attempting to serialize a class hierarchy using [DataContract] and [DataMember]. [DataContract] [KnownType(typeof(LoginRequest))] public class Message { [DataMember(Order = 2)] public int Id { get; set; } } [DataContract] public class LoginRequest : Message { [DataMember(Order = 1)] public string Username { get; set; } [DataMember(Order = 2)] public string Password { get; set; } } and to serialize/deserialize: using (var file = File.Create(filename)) { Serializer.Serialize(file, loginRequest); } LoginRequest deserialized; using (var file = File.OpenRead(filename)) { deserialized = Serializer.Deserialize<LoginRequest>(file); } ReflectionUtils.Compare(loginRequest, deserialized); The Id field of abstract class Message is not serialized. To make it work I have to decorate Message with: [ProtoInclude(1, typeof(LoginRequest))] Why is this? I've read this similar question but Marc concludes that 'this is no longer required in v2 - you can specify this at runtime, or use DynamicType' I would prefer not to specify anything extra other than KnownType A: [KnownType(...)] is not enough, as the library also need a unique (for that type) integer to use as the key (the 1 in the example). Inferring it qutomatically is too risky, as it could cause unexpected breaks when tweaking the type (and version safety is a very deliberate design goal). If you don't want to add an attribute for this, you can tell it what it needs at runtime, i.e. (in your startup code): RuntimeTypeModel.Default[typeof(Message)] .AddSubType(1, typeof(LogonRequest));
{ "language": "en", "url": "https://stackoverflow.com/questions/7596396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Text not flowing correctly around floated elements in Chrome Please see this fiddle: http://jsfiddle.net/VaBCd/ ...view in Chrome (I've got v14) and then any other browser. Notice how in Chrome the text is failing to break at the right place with respect to the 2nd div, which has {float:right;clear:both}. What's the best (preferably non-hack) way to deal with this so as to provide a consistent layout across browsers with the greatest flexibility?
{ "language": "en", "url": "https://stackoverflow.com/questions/7596399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to Detect Unread Text Messages on WP7.1 I'm looking to build a method which needs to see if there are any text messages on the device which have not currently been read Is there a way to expose the phones messages to detect whether there are any unread ones and return a bool/int value? I know in WinMo, you could use SystemState.MessagingSmsUnread to return an int, but I can't seem to find a wp7 equiv. Thanks in advance A: No. In Windows Phone there is no way to access the details of any received messages. This was a deliberate design decision to prevent applications accessing a users personal data without their knowledge.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can iOS Apps have Login Screen? I need to add log in screen and registration forum to my application, such that the user register or log in to the application, is it legal issue or my application will be rejected A: You can have a log in screen. Many apps have them. But Apple has been rejecting apps with a login registration screen, or even a registration web site URL within the app, depending on the exact conditions for that registration. You may have to get users to register for your app outside your app and/or before running your app. Make sure to preregister Apple with a demo account for use during app review. It also helps greatly if your app has some general usefulness even without registering (e.g. banking apps may have a map to the nearest branch even for users who don't have customer account logins, or some public info about interest rates, etc.). A: There are plenty of apps that also live on the web and so require some sort of login, e.g. Foursquare, Facebook A: There are no issues at all with creating a login screen for your application. When you submit your app to the App Store, you will be asked to provide login credentials for the testing team to login and test your app. I wouldn't force them to go through the account creation process as it may delay your app getting approved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: stdio.h not standard in C++? I know most compilers allow both: #include <stdio.h> and #include <cstdio> But someone argued that <stdio.h> is not actually C++ standard. Is that true? A: It's not true, because C++ main goal is backward compatibility with C. The only difference is that for #include <cstdio> all functions are in std namespace A: The C standard headers are included in the C++ standard library for compatibility. The difference is that identifiers in corresponding C++ headers must (also) be in std namespace, whereas identifiers in C headers must (also) be available in global namespace. In addition, the <c...> headers add overloads for functions like abs, pow etc. Also, C++ headers replace some C classification/comparison macros with overloaded functions. A: stdio.h is standard, but deprecated. Always prefer cstdio in C++. [n3290: C.3.1/1]: For compatibility with the Standard C library, the C++ standard library provides the 18 C headers (D.5), but their use is deprecated in C++. [n3290: D.5/3]: [ Example: The header <cstdlib> assuredly provides its declarations and definitions within the namespace std. It may also provide these names within the global namespace. The header <stdlib.h> assuredly provides the same declarations and definitions within the global namespace, much as in the C Standard. It may also provide these names within the namespace std. —end example ] A: The C++ standard library explicitly contains the C standard library, so is an entirely legitimate part of C++. And if you are talking about using #include <stdio.h> in C++ code, then you shouldn't do that, cause that's C syntax, in C++ code, you should use always cstdio
{ "language": "en", "url": "https://stackoverflow.com/questions/7596406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: can not move to retry queue with a clustered MSMQ When I try to move a message to the retry queue inmediatelly it says: "The tranasction's operation sequence is incorrect". I am using windows server 2008 r2 and framework 4.0. BTS is writting to the queue and a WF is reading from it. But I can not see any error at client side when I put the message in retry. Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change Facebook language in iPhone sdk? I am integrating Facebook API for iPhone OS. I want to change the language of the Facebook from English (US) to Spanish. A: These links of some help to you.... https://developers.facebook.com/docs/beta/opengraph/internationalization/ http://johnklingelhoets.com/facebook-locales-graph-api-array/ First one in particular... A: To change the Facebook Language Try this Just go to settings --> General--> International --> Language --> Espanol or Spanish(Select the language you need).
{ "language": "en", "url": "https://stackoverflow.com/questions/7596410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: making an installer and installing the libraries if not already installed How can i make up am installer for my java application (jar file) . The same as that of windows installer which proceeds by clicking next and installs the application. What i want with my java app is, the open source library xuggler to get installed if it is not already present in the system.Then i want JRE to get installed if it is not already present in the system. If the user does not have xuggler or JRE installed , installer should automatically install the xuggler and JRE. Or it should tell the user to get that version of libraries from the given URL and then continue. A: If your app. has a GUI, use deployJava.js for the JRE and then Java Web Start to install/launch the app. An installer-desc can be specified in the JNLP file to install Xuggle. JWS can partition the download between OS. JWS is supplied by the makers of J2SE JREs for desktop PCs (e.g. running Mac OSX, *nix or Windows). A: Your question is similar to this one: how to package a java application Advanced Installer has a separate edition especially for creating installers for Java apps, so this might be what you are looking for. I would recommend other tools but since they're scriptable, they're a hassle to work with, lots of things can go wrong. Hope this helps A: NullSoft have a very good scriptable, opensource installer called NSIS. http://nsis.sourceforge.net/Main_Page A: I'm not aware of a cross platform way to do this. In the Windows world, you can use Wix to generate an MSI file, and in that file you can specify dependencies such as the JRE. In the Linux world you can generate a file with the dependencies read by the package manager, a deb file for Debian based releases for example. It's a bit of a faff to set things like this up separately, but once it's done you can just integrate it into your ant script and build everything automatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Add request headers with WebClient C# I have the following code with which I download a web-page into a byte array and then print it with Response.Write: WebClient client = new WebClient(); byte[] data = client.DownloadData(requestUri); /*********** Init response headers ********/ WebHeaderCollection responseHeaders = client.ResponseHeaders; for (int i = 0; i < responseHeaders.Count; i++) { Response.Headers.Add(responseHeaders.GetKey(i), responseHeaders[i]); } /***************************************************/ Besides of the response headers, I need to add request headers as well. I try to do it with the following code: /*********** Init request headers ********/ NameValueCollection requestHeaders = Request.Headers; foreach (string key in requestHeaders) { client.Headers.Add(key, requestHeaders[key]); } /***************************************************/ However it does not work and I get the following exception: This header must be modified using the appropriate property.Parameter name: name Could anybody help me with this? What's the correct way of adding request headers with WebClient? Thank you. A: The headers collection "protects" some of the possible headers as described on the msdn page here: http://msdn.microsoft.com/en-us/library/system.net.webclient.headers.aspx That page seems to give all the answer you need but to quote the important part: Some common headers are considered restricted and are protected by the system and cannot be set or changed in a WebHeaderCollection object. Any attempt to set one of these restricted headers in the WebHeaderCollection object associated with a WebClient object will throw an exception later when attempting to send the WebClient request. Restricted headers protected by the system include, but are not limited to the following: Date Host In addition, some other headers are also restricted when using a WebClient object. These restricted headers include, but are not limited to the following: Accept Connection Content-Length Expect (when the value is set to "100-continue" If-Modified-Since Range Transfer-Encoding The HttpWebRequest class has properties for setting some of the above headers. If it is important for an application to set these headers, then the HttpWebRequest class should be used instead of the WebRequest class. I suspect the reason for this is that many of the headers such as Date and host must be set differently on a different request. You should not be copying them. Indeed I would personally probably suggest that you should not be copying any of them. Put in your own user agent - If the page you are getting relies on a certain value then I'd think you want to make sure you always send a valid value rather than relying on the original user to give you that information. Essentially work out what you need to do rather than finding something that works and doing that without fully understanding what you are doing. A: Looks like you're trying to set some header which is must be set using one of the WebClient properties (CachePolicy, ContentLength or ContentType) Moreover, it's not very good to blindly copy all the headers, you need to get just those you really need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to upload files using Yahoo uploader widget in asp.net Many might have had experience using File Upload widget from Yahoo User Interface library. The docs and community all know how to receive the files on the server using another server technology other than ASP.NET. If anyone has indeed used the widget in their asp.net pages could you share the code on * *How to receive the uploaded files Stream/Bytes to a file. *How to check Integrity of the File *How to check if file was received correctly. Also i would love to do it in single page because doing so i would learn how to differentiate between a normal webpage request and the one caused my file upload widget Yahoo Upload Widget can be Found here: https://developer.yahoo.com/yui/uploader/. A: Have you tried looking at postedfiles collection though? The API looks like it does a standard post. If it does, the just use that collection. If it doesn't, then you need to use the inputstream property on the request object to read the incoming bytes. Using something like Fiddler or firebug will tell you how it's making the request. Look for the request type being multipart/mime edit Checking the file integrity & whether it was uploaded correctly are pretty much impossible. The only way I can think to do it is to have the user generate a hash of the file then upload the file & the hash & you check the hash is valid. ie not really practical. All you're getting is a stream of bytes. you have to assume when the stream ends, it ended cleanly & you got all the file. A: I answered my own question with code over here. http://labs.deeptechtons.com/asp-net-tuts/how-to-upload-files-asynchronously-using-yahoo-uploader/
{ "language": "en", "url": "https://stackoverflow.com/questions/7596418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I show list of Images in vertical scroll view? I have a list of images like this public Integer[] mImageIdsen = { R.drawable.small, R.drawable.small, R.drawable.small, R.drawable.small, R.drawable.small, R.drawable.small}; and I want to show it in a linear vertical layout which is in a scrollview. How can I assign this images to the vertical scroll list? I can't put the xml code. A: Apply scroll for parent layout in which u want to add your images vertically. A: Custom list view is the best solution for the same. Override getview and add the images within it. A: You could use Gallery to display these. It's horizontal scrollable
{ "language": "en", "url": "https://stackoverflow.com/questions/7596419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server XML Replace values in attribute I want to replace the value in an attribute in a XML. This attribute comes multiple times in the xml. How can i replace these all at once my xml lools some what like below : <Example> <A> <B Type = "x">qqq</B> <B Type = "x">www</B> </A> <C> <D Type = "x">aaa</D> <D Type = "x">uuu</D> </C> </Example> I want to replace all x with y A: You can not replace all at once using replace value of (XML DML). You have to do it in a loop. declare @xml xml = ' <Example> <A> <B Type = "x">qqq</B> <B Type = "x">www</B> </A> <C> <D Type = "x">aaa</D> <D Type = "x">uuu</D> </C> </Example> ' while (select @xml.exist('//*[@Type = "x"]')) = 1 begin set @xml.modify('replace value of (//*[@Type = "x"]/@Type)[1] with "y"') end select @xml Result: <Example> <A> <B Type="y">qqq</B> <B Type="y">www</B> </A> <C> <D Type="y">aaa</D> <D Type="y">uuu</D> </C> </Example> Update Replace values x and z with y: while (select @xml.exist('//*[@Type = ("x","z")]')) = 1 begin set @xml.modify('replace value of (//*[@Type = ("x","z")]/@Type)[1] with "y"') end Replace all values with y: while (select @xml.exist('//*[@Type != "y"]')) = 1 begin set @xml.modify('replace value of (//*[@Type != "y"]/@Type)[1] with "y"') end A: You can try the following. Here ns2zarejestrujStanZgodyAsync is main node and I have updated the value of idSystemy from 13 to 38. UPDATE @t SET yourXML.modify('replace value of (/ns2zarejestrujStanZgodyAsync/rejestrujStanZgody/idSystemy/text())[1] with ("38")') You can check for demo here- XML Node Update
{ "language": "en", "url": "https://stackoverflow.com/questions/7596422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: DB2: How to concatenate null strings in DB2? I have to concatenate 2 columns (ex. FIRSTANME and LASTNAME). I do it this way: FIRSTNAME || ' ' || LASTNAME`. If one of them is null, but the other one is not null, I get null as concatenation result. And I want following behavior FIRSTNAME = null and LASTNAME = "Smith" ==> FIRSTANME || ' ' || LASTNAME == ' Smith'. How to solve this in DB2? A: Use coalesce ... CONCAT( COALESCE(firstname,'') , COALESCE(lastname,'') ) Or using the || concat operator ... COALESCE(firstname,'') || COALESCE(lastname,'') Note that IBM recomments using the keyword concat and not the || operator. Concat: http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=%2Fcom.ibm.db2.doc.sqlref%2Ffconc.htm Coalesce: http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=%2Fcom.ibm.db2.doc.sqlref%2Ffcoal.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7596425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to test HTTP status code set by an ASP.NET MVC action with MSpec I have the following controller: public sealed class SomeController : Controller { public ActionResult PageNotFound() { Response.StatusCode = 404; return View("404"); } } I have created an MSpec specification: [Subject(typeof (SomeController))] public class when_invalid_page_is_requested : SomeControllerSpec { Because of = () => result = Controller.PageNotFound(); It should_set_status_code_to_404 = () => Controller.Response.StatusCode.ShouldEqual(404); } public abstract class SomeControllerSpec { protected static HomeController Controller; Establish context = () => { Controller = new SomeController(); }; } But because of how I instantiate the controller, HttpContext is null. What would be the best way to test status code set by the PageNotFound action? EDIT: Posted an answer below A: Found a way to do it using Moq. [Subject(typeof (SomeController))] public class when_invalid_page_is_requested : SomeControllerSpec { Because of = () => result = Controller.PageNotFound(); It should_set_status_code_to_404 = () => HttpResponse.VerifySet(hr => hr.StatusCode = 404); } public abstract class SomeControllerSpec { protected static SomeController Controller; protected static Mock<ControllerContext> ControllerContext; protected static Mock<HttpResponseBase> HttpResponse; Establish context = () => { ControllerContext = new Mock<ControllerContext>(); HttpResponse = new Mock<HttpResponseBase>(); ControllerContext.SetupGet(cc => cc.HttpContext.Response) .Returns(HttpResponse.Object); Controller = new SomeController { ControllerContext = ControllerContext.Object }; }; } Not very elegant. If you can think of a better way - let me know. A: You can use: _controller.Response.StatusCode A: Another option using MvcContrib's TestControllerBuilder... var myController = new MyController(); var testControllerBuilder = new TestControllerBuilder(); testControllerBuilder.InitializeController(myController); and then using NUnit (I'd guess the Moq version would work just like you have it)... myController.Response.AssertWasCalled( response => response.StatusCode = 400 ); All the ugly setup and mocking work is still being done, but by MvcContrib instead of inside the test. Here's a post on using the TestControllerBuilder.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Velocity String Template Loading at startup I have a list of strings in the memory. I want to load all of them as velocity templates during the application startup. How do I do it ? I know how to create template from a string from here: How to use String as Velocity Template? But I want to know how to load all template strings in one shot A: Loop over the collection of strings and initialize them all--not sure what else you're looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: connect to android device via usb Is there an API or another way to access an android device's data (contacts, gallery, messages) while being connected via USB ? Can it be done using java or .net framework ? Thanks! A: Can either use: 1. ADB commands to view and pull the device data. 2. Connect the device in USB Connected mode and access it from your PC. Procedure : Drag a screen from the top in your home screen- Select usb connected mode- Turn on usb storage- then access.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java - Object reference or identifier? I am currently creating a big project, and as such I would like to have everything worked out very well and as efficient as possible. In my project, I have a class called Teams, which contains a HashMap(Integer, Team) of Team objects. Each instance of Team has a unique ID (integer). There is also an object called Player. Each instance of Player can be assigned to a Team (but not always). Now, I wonder what the best approach would be to know what Team a Player is assigned to: -> Store the ID of the team in Player (private int team), this ID is then used to get the Team from the HashMap in Teams. -> Store a reference to the Team in Player (private Team team) Does anyone know which is better, and what the most important pro's, con's and dangers are of each? Thanks! A: Use private Team team! Other classes should not need to know the ID of an object unless there is a good reason. Don't implement a Database structure in Java. Java is designed to be Object-based, use it that way. There are a couple additional reasons you should hold the Team instance: * *We can assume that your Player will need to access the Team object. It is better to have the instance rather than having to do a lookup. *If you hold onto IDs instead of instances, there might not be any reference to an object being held and it could be garbage collected. I know that probably won't happen in your case since you hold all Teams in a Map, but it is still a risk and therefore should be avoided. A: Obviously it's impossible to say for certain here without knowing the context in which it'll be used - but from a code design perspective, the "natural" expectancy is that a team contains players, so it's the team that would reference the player objects, not the other way around. If you start messing around with IDs and need to store large numbers of different objects, it sounds like you're after more of a database, in which case look at something like HSQLDB if you don't want to step out of Java. A: The potential danger with using the object reference as the key in a HashMap (or any Map) is that it can, if done improperly, become a memory leak. An object will not be garbage collected if there are still references to it. If used as a key in a Map, that is considered a reference to that object. You can get around this using WeakReference. In the situation you describe you should probably be using the objects as keys, but be wary of the above conditions. A: private Team team is the way to go between the two approaches you mention. If you store the Id , what will happen if the HashMap is updated along ? This is creating unnecessary dependemcies. A: You using database? If so, store the ID of the team in player, or else I suggest that you store the reference of the team.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Java daemon under Linux: Choices? I have a console application (written in Java), which should run on a Linux machine until it is stopped. Logging is done by the application itself. The application needs to be stopped whenever a new version is available (i. e. I login, stop the application, copy the new JAR file, and then launch it again). What are the options for implementing this, apart from those specified below? Known ways to do it: 1) Tanuki service wrapper 2) nohup java -jar myapp-1.32.jar & A: I use Java Service Wrapper, but you already mentioned it. I think it should suit your needs. Apache Commons Daemon is also popular: http://commons.apache.org/daemon/, but I never used it. A: I'm using this startup script: http://shrubbery.homeip.net/c/display/W/Java+Daemon+Startup+Script [Changed domain name - by wiki owner] A: Some modern Linux distributions have switched to upstart. That's a daeomon starting and stopping all the other services. I'd definitely look into that. Since it solves some tricky problems with production ready start scripts. The downside is that it has no java specific functionality. A: There also the apache commons deamons http://commons.apache.org/proper/commons-daemon/jsvc.html Jsvc is a set of libraries and applications for making Java applications run on UNIX more easily. Jsvc allows the application (e.g. Tomcat) to perform some privileged operations as root (e.g. bind to a port < 1024), and then switch identity to a non-privileged user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to avoid redirect after form submission if you have a URL in your form's action? I have a form that looks like this: <form name="formi" method="post" action="http://domain.name/folder/UserSignUp?f=111222&postMethod=HTML&m=0&j=MAS2" style="display:none"> ... <button type="submit" class="moreinfo-send moreinfo-button" tabindex="1006">Subscribe</button> In the script file I have this code segment where I submit the datas, while in a modal box I say thank you for the subscribers after they passed the validation. function () { $.ajax({ url: 'data/moreinfo.php', data: $('#moreinfo-container form').serialize() + '&action=send', type: 'post', cache: false, dataType: 'html', success: function (data) { $('#moreinfo-container .moreinfo-loading').fadeOut(200, function () { $('form[name=formi]').submit(); $('#moreinfo-container .moreinfo-title').html('Thank you!'); msg.html(data).fadeIn(200); }); }, Unfortunately, after I submit the datas, I'm navigated to the domain given in the form's action. I tried to insert return false; in the code (first into the form tag, then into the js code) but then the datas were not inserted into the database. What do I need to do if I just want to post the data and stay on my site and give my own feedback. I edited Eric Martin's SimpleModal Contact Form, so if more code would be necessary to solve my problem, you can check the original here: http://www.ericmmartin.com/projects/simplemodal-demos/ (Contact Form) A: Usually returning false is enough to prevent form submission, so double check your code. It should be something like this $('form[name="formi"]').submit(function() { $.ajax(...); // do your ajax call here return false; // this prevent form submission }); Update Here is the full answer to your comment I tried this, but it didn't work. I need to submit the data in the succes part, no? Maybe, it depends from your logic and your exact needs. Normally to do what you asking for I use the jQuery Form Plugin which handle this kind of behavior pretty well. From your comment I see that you're not submitting the form itself with the $.ajax call, but you retrieve some kind of data from that call, isn't it? Then you have two choices here: With plain jQuery (no form plugin) $('form[name="formi"]').submit(function() { $.ajax(...); // your existing ajax call // this will post the form using ajax $.post($(this).attr('action'), { /* pass here form data */ }, function(data) { // here you have server response from form submission in data }) // this prevent form submission return false; }); With form plugin it's the same, but you don't have to handle form data retrieval (the commented part above) and return false, because the plugin handle this for you. The code would be $(document).ready(function() { // bind 'myForm' and provide a simple callback function $(form[name="formi"]).ajaxForm(function() { // this call back is executed when the form is submitted with success $.ajax(...); // your existing ajax call }); }); That's it. Keep in mind that with the above code your existing ajax call will be executed after the form submission. So if this is a problem for your needs, you should change the code above and use the alternative ajaxForm call which accepts an options object. So the above code could be rewritten as $(document).ready(function() { // bind 'myForm' and provide a simple callback function $(form[name="formi"]).ajaxForm({ beforeSubmit: function() { $.ajax(...); /* your existing ajax call */}, success: function(data) { /* handle form success here if you need that */ } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7596438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jeasy-ui runs the div twice In master.php <?php //echo "session check: ".$_SESSION['session_array']; //exit; session_start(); // Session Starts if( !isset($_SESSION['session_array']) ) { header("Location: index.php"); exit; } include("conn.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>LMS</title> <link rel="stylesheet" type="text/css" href="jui/themes/gray/easyui.css"> <link rel="stylesheet" type="text/css" href="jui/general.css"> <link rel="stylesheet" type="text/css" href="jui/themes/icon.css"> <script type="text/javascript" src="jui/jquery-1.6.min.js"></script> <script type="text/javascript" src="jui/jquery.easyui.min.js"></script> <script type="text/javascript" src="js/jquery.validate.js"></script> <script type="text/javascript" src="js/date.js"></script> <script type="text/javascript" src="js/core.js"></script> </head> <body class="easyui-layout"> <div region="north" class="north_master" border="false" split="false" > <div style="float:left;"> <img src="images/usr_logo.jpg" alt="Lead Management System" width="168" height="66" title="Lead Management System" > </div> <div style="float:right;"> <br/><br/> <a id="logout" name="logout" href="logout.php?logout=1" class="easyui-linkbutton" iconCls="icon-cancel" onClick="javascript: return confirm('Are you sure you want to log out?');">Logout</a> </div> </div> <div region="south" class="south" border="false"> <?php include('footer.php'); ?> </div> <div region="center" class="center" style="background-image:url(img/product-display.jpg);background-repeat:no-repeat;background-attachment:fixed;background-position:right bottom; "> <?php include('dashboard.php'); ?> </div> </body> </html> In dashboard.php <script language="javascript"> jQuery(document).ready(function($){ alert("check"); }); </script> <div class="content"> <h1>Slot Dashboard</h1> <div> <a href="master.php?page=5" class="easyui-linkbutton">Add Slot</a> </div> <table border='1' bordercolor='#B4B4B4' cellpadding='1' cellspacing='0' width='80%' align="center"> <tr align="left"> <th>Week</th> <th>Dates</th> <th>Status</th> <th>Date</th> <th>Action</th> </tr> <tr> <td>1</td> <td>09/04/2011 - 09/10/2011</td> <td>Revised</td> <td>09/04/2011</td> <td><a href="#">View</a></td> </tr> <tr> <td>2</td> <td>09/11/2011 - 09/17/2011</td> <td>Revised</td> <td>09/11/2011</td> <td><a href="#">View</a></td> </tr> <tr> <td>3</td> <td>09/18/2011 - 09/24/2011</td> <td>Not Submitted</td> <td>09/18/2011</td> <td><a href="#">View</a></td> </tr> </table> </div> Question: While master.php runs "check" alerts twice. I need to know why "check" alerts twice. How to solve this <div region=center> The scripts within the div runs twice. there is some bug with jeasy-ui. Help me how to solve that. A: Technically included page alert shouldn't fire twice. it is only possible in case of you add sample.php file in php.ini as auto_append_file A: i found same problem in easyui every version, when script is included in to panel/layout, the script will be run twice, the reason I think: the page be loaded in browser ,the browser run the script of page once, when dom is loaded ,the easyui render style for the node in dom, the script in the node will be called second by easyui. this problem isn't only in layout , but in panel, Maybe even for the every thing inherit from panel. this problem may be in the easyui's root render method, so I can't find solved for this without src. now i have to change easyui to another ui framework. example for theis problem, the alert be called twice in browser: </div> <div region="south" class="south" border="false"> </div> <div region="center" class="center" > <script> alert("here"); </script> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7596445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to extract id3tag using id3lib under windows ce? I am trying to extract id3 from mp3 under windows ce. After a week test, I have successfully compiled id3lib under windows ce. (The other two failed: taglib and libid3tag. "taglib" requires cmake to build, but I don't know how to build it to serve windows ce. "libid3tag" lack doc to know how to extract id3.) Now, I am using id3lib. According to its doc, I should do this: ID3_Tag myTag; myTag.Link("\\Storage Card\\Revive_id3v1.mp3"); //***** Problem ! ID3_Frame *myFrame = myTag.Find(ID3FID_ALBUM); //TCHAR tmp[100]; if (NULL != myFrame) { //wcscpy(tmp, (TCHAR *)myFrame); printf("ALBUM: %s\n", myFrame); } else { printf("File not find!\n"); } The problem is myTag.Link cannot get "Revive_id3v1.mp3". How to solve this ? Anyone knows ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7596446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NUnit: SetUp and TearDown for each test in a test fixture across multiple Fixtures I would like to have a generic SetUp and TearDown that is run with every test across multiple fixtures but all within a common namespace. This would be something similar to the [SetUpFixture] attribute but would be run with every test. I've tried using a base class with [SetUp] but resharper resolves this as inconclusive which isn't really ideal. A: I don't see any problem in using a base class with the generic code. public class BaseTest { [SetUp] public void SetUp() { //Do generic Stuff } [TearDown] public void TearDown() { // Do generic stuff } [TestFixture] public class TestClass : BaseTest { [SetUp] public void SetUp() { //Do Stuff } [TearDown] public void TearDown() { // Do stuff }
{ "language": "en", "url": "https://stackoverflow.com/questions/7596447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to include and use new fonts in wxWidgets projet? How to include and use new fonts in wxWidgets projet? I am using VS2005. I just want to print text using new ttf font. Thanks in advance!! A: Unless you're willing to link against something like FreeType: http://en.wikipedia.org/wiki/FreeType ...most any program is going to require the font to be installed to the operating system, by the user or by some OS-specific script. You can't just load it by filename off the cuff in your app. Because of the platform dependence of naming and accessing custom fonts, the path of least resistance is not to try and hardcode a font...but to let the user pick one out of a dialog. You would use a wxFontDialog for this: http://docs.wxwidgets.org/stable/wx_wxfontdialog.html It will let you retrieve the wxFontData, from which you can get the chosen wxFont: http://docs.wxwidgets.org/stable/wx_wxfontdata.html#wxfontdatagetchosenfont Once you have that, you can save and reload an identity of the font via the native string interface: http://docs.wxwidgets.org/stable/wx_wxfont.html#wxfontgetnativefontinfodesc Trying to formulate these strings on your own or work with the "face name" is a little dodgier: http://docs.wxwidgets.org/stable/wx_wxfont.html#wxfontsetfacename Generally speaking a lot of the same problems arise here as dealing with fonts in HTML. If you have a very specific idea about the cross-platform appearance of some text, your best bet is often to make an image out of that text and use that instead of going through the hoops to get the font you want in the app. If you're more flexible and have a lot of text the user is interested in, then they may be interested in changing the font too. So just use a default but offer the user a choice to pick anything they want which is installed on their system. (Note: I personally consider the handling of fonts in pretty much every OS or document system to be a disgrace. Imagine a world where in order to get a graphic to display in your program you had to register it with the operating system through a complex process and it would not copy from machine to machine when you copied a document in which it was embedded. We're dealing now with graphics that are orders of magnitude larger than font files, and yet they are handled seamlessly while people seem to accept the lack of seamless font transfer as "normal". Archaic DRM mindsets of font vendors is one side of the problem, but lame technology is another big component.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7596448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Background PHP Processes I am developing a website that requires a lot background processes for the site to run. For example, a queue, a video encoder and a few other types of background processes. Currently I have these running as a PHP cli script that contains: while (true) { // some code sleep($someAmountOfSeconds); } Ok these work fine and everything but I was thinking of setting these up as a deamon which will give them an actual process id that I can monitor, also I can run them int he background and not have a terminal open all the time. I would like to know if there is a better way of handling these? I was also thinking about cron jobs but some of these processes need to loop every few seconds. Any suggestions? A: Creating a daemon which you can make calls to and ask questions would seem the sensible option. Depends on wether your hoster permits such things, especially if you're requiring it to do work every few seconds, then definately an OS based service/daemon would seem far more sensible than anything else. A: You could create a daemon in PHP, but in my experience this is a lot of hard work and the result is unreliable due to PHP's memory management and error handling. I had the same problem, I wanted to write my logic in PHP but have it daemonised by a stable program that could restart the PHP script if it failed and so I wrote The Fat Controller. It's written in C, runs as a daemon and can run PHP scripts, or indeed anything. If the PHP script ends for whatever reason, The Fat Controller will restart it. This means you don't have to take care of daemonising or error recovery - it's all handled for you. The Fat Controller can also do lots of other things such as parallel processing which is ideal for queue processing, you can read about some potential use cases here: http://fat-controller.sourceforge.net/use-cases.html A: I've done this for 5 years using PHP to run background tasks and its no different to doing in any other language. Just use CRON and lock files. The lock file will prevent multiple instances of your script running. Also its important to monitor your code and one check I always do to prevent stale lock files from preventing scripts to run is to have second CRON job to check if if the lock file is older than a few minutes and if an instance of the PHP script is running, if not it then removes the lock file. Using this technique allows you to set your CRON to run the script every minute without issues. A: Use the System::Daemon module from PEAR. A: One solution (that I really need to try myself, as I may need it) is to use cron, but get the process to loop for five mins or so. Then, get cron to kick it off every five minutes. As one dies, the next one should be finishing (or close to finishing). Bear in mind that the two may overlap a bit, and so you need to ensure that this doesn't cause a clash (e.g. writing to the same video file). Some simple inter-process communication may be useful, even if it is just writing to a PID file in the temp directory. This approach is a bit low-tech but helps avoid PHP hanging onto memory over the longer term - sort of in-built task restarts!
{ "language": "en", "url": "https://stackoverflow.com/questions/7596450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Increase quantity when adding same Option I have managed to implement OOP of Cart Basket An Item contain 1 or more options. If I add same OptionID again then the number of quantity should increase rather than creating another Option Object. How can that be done? If I add same ItemID again, it should refuse to create another Item object. Also is my OOP is good? class Cart { public $item = array(); public function addItem($id) { $item = new Item(); $item->setItem($id); $this->item[] = $item; return $item; } } class Item { private $id = array(); private $option = array(); public function setItem($id) { $this->id = $id; return $this; } public function addOption($id) { $option = new Option(); $option->setOption($id); $this->option[] = $option; } } class Option { private $quantity; private $id; public function setOption($id) { $this->quantity = 1; $this->id = $id; return $this; } } $cart = new Cart(); //ItemID 10 $item = $cart->addItem(10); //OptionID $item->addOption(11); $item->addOption(22); $item->addOption(22); //should increase quantity //It should not create another object because we already have Item Object of ItemID10 $item = $cart->addItem(10); $Shop = $cart; echo "<pre>"; print_r($Shop); echo "</pre>"; A: If you can have only one item with the unique id in the cart - then rewrite the addItem() method like this: public function addItem($id) { $result = false; if (empty($this->item[$id])) { $item = new Item(); $item->setItem($id); $this->item[$id] = $item; $result = $item; } return $result; } The same is with addOption() method: public function addOption($id) { if (empty($this->option[$id])) { $option = new Option(); $option->setOption($id); $this->option[$id] = $option; } else { $this->option[$id]->setQuantity($this->option[$id]->getQuantity() + 1); } } And of course you should implement setQuantity() and getQuantity() methods in Option class. Hope this helps. A: Partialy rewrote the code and tested: <?php class Cart { public $items = array(); public function addItem($id) { if(array_key_exists($id, $this->items)){ $item = $this->items[$id]; }else{ $item = new Item($id); $this->items[$id] = &$item; } return $item; } } class Item { private $id; private $options = array(); public function __construct($id) { $this->id = $id; return $this; } public function addOption($id) { if(array_key_exists($id, $this->options)){ $this->options[$id]->addQuantity(); }else{ $option = new Option($id); $this->options[$id] = $option; } } } class Option { private $quantity; private $id; public function __construct($id) { $this->quantity = 1; $this->id = $id; return $this; } public function addQuantity() { $this->quantity++; } } $cart = new Cart(); //ItemID 10 $item = $cart->addItem(10); //OptionID $item->addOption(11); $item->addOption(22); $item->addOption(22); //should increase quantity //It should not create another object because we already have Item Object of ItemID10 $item = $cart->addItem(10); $Shop = $cart; echo "<pre>"; print_r($Shop); echo "</pre>"; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7596451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }