text
stringlengths
8
267k
meta
dict
Q: what is logic behind this java code I came across below java line and puzzled about its output. Can you please explain me logic behind this code System.out.println((int)(char)(byte) -1); Output: 65535 A: it's the same as System.out.println((int) '?'); * *(byte) -1 gives: -1 *(char) -1 gives: ? *(int) '?' gives 65535 A: Well, it's equivalent to: byte b = -1; char c = (char) b; // c = '\uFFFF' - overflow from -1 int i = c; // i = 65535 Really the explicit conversion to int in the original is only to make it call System.out.println(int) instead of System.out.println(char). I believe the byte to char conversion is actually going through an implicit widening conversion first - so it's like this really: byte b = -1; int tmp = b; // tmp = -1 char c = (char) tmp; // c = '\uFFFF' Does that help at all? A: In java byte is a signed (twos-complement) 8-bit primitive type. The binary representation of a byte with a value of -1 is 11111111. This then gets cast to a char which is a 16-bit primitive with a value between \u0000 and \uFFFF (0 and 65535) - it would appear that the bits of the byte are left-shifted by 8, with sign-extension. So at this point the binary representation is: 1111111111111111 ...or 65535. However, it is then not quite as simple as saying "Oh yes then it is turned into an int so we don't see the character representation and is printed out". In java, all numeric primitives are signed! If we cast the char as a short which is another 16-bit primitive, the program would output -1. However, when we cast it to a 32-bit int. The final binary representation becomes: 00000000000000001111111111111111 ...which is 65535 both signed and unsigned!
{ "language": "en", "url": "https://stackoverflow.com/questions/7500523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: internet explorer ajax request not authenticated My application workflow is like this: users are authenticated, they start a game and after some time I make an ajax request to get some data, but this request is also authenticated. The problem is that when first ajax request is made, internet explorer sees the user as unauthenticated and it forces redirect, and everything works fine. This problem occurs only on internet explorer. Any ideas? A: If your application runs in an IFRAME then you should set P3P headers in order to enable cookies. You should send a special HTTP header in your first response: P3P: CP="ALL DSP COR CURa ADMa DEVa OUR IND COM NAV" This should solve the problem for IE, but you'll probably hit the same problem in Chrome and Safari. It only appears when user visits your app for the first time. You can emulate it by clearing all the personal information from your browser using browser cleanup feature. I resolved this problem by storing initial signed_request attribute to a Javascript variable and sending it in all AJAX request as an additional HTTP header (it's possible if you use jQuery). Also, I added the same attribute to all links and forms. Sample code: var signed_request = '...'; // My signed request goes here ... function signedUrl(url){ var url_parts = url.split('#', 2); var new_url = url_parts[0] + (url_parts[0].indexOf('?') == -1 ? '?' : '&') + 'stored_signed_request=' + signed_request; if(url_parts.length == 2) { new_url = new_url + '#' + url_parts[1]; } return new_url; } ... if(document.cookie.indexOf('fbsr_') == -1){ $('a').live('click', function(){ var href = $(this).attr('href') || ''; if(href !== ''){ $(this).attr('href', signedUrl(href)); } }); $('form').live('submit', function(){ $(this).append('<input type="hidden" name="stored_signed_request" value="' + signed_request + '">'); }); $.ajaxSetup({ beforeSend : function(request){ request.setRequestHeader('signed-request', signed_request); } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7500524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP error_log method doesn't write errors to my error log file The PHP error_log method does not write errors to the custom error log file. It will only write to /var/log/apache2/php_error.log Here are the logging settings in my php.ini: error_reporting = E_ALL & ~E_DEPRECATED & ~E_NOTICE display_errors = Off log_errors = On log_errors_max_len = 0 ; also tried with 9999999 error_log = /var/log/apache2/php_errors.log PHP writes its errors to the regular Apache error log (/var/log/apache2/error.log) rather than the one I specified above. Things I already tried: * *I stopped and restarted apache after changing the php.ini file *The file /var/log/apache2/php_errors.log is 777 permissions and the file exists. *There are no other overriding php.ini files. (There is /etc/php5/cli/php.ini but I'm not using cli). *There are no other error_log = xxx settings further down the php.ini file which could overrule the first one *phpinfo() says error_log = /var/log/apache2/php_errors.log (i.e. the correct file), both under Local Value and Master Value *The test script I'm using to generate errors doesn't contain any ini_set calls (FYI: I'm using Apache/2.2.17 and PHP/5.3.5-1ubuntu7.2 on Ubuntu 11.04) What am I doing wrong? A: You could try specifying the filename like this: I'm using Apache 2.2.22 on Ubuntu. Use this PHP command: error_log("eric", 3, "/home/el/error.log"); The first parameter is the message to be sent to the error log. The 2nd parameter 3 means "expect a filename destination. The third parameter is the destination. Create the file /home/el/error.log and set its ownership to this: el@apollo:~$ ll error.log -rwxrwxr-x 1 www-data www-data 7 Dec 13 14:30 error.log When the PHP interprets the error_log method, it appends the message to your file. Source: http://www.php.net/manual/en/function.error-log.php A: I'd like to answer this as it's a high result on Google even though it's an old question. I solved this by adding write permissions for all users on the log directory. In my case, the user 'http' needed to be able to write to /var/log/httpd/ so I ran # chmod a+w /var/log/httpd If the file already exists, it may help to delete it first and allow Apache to create it. My php.ini file included the entire path, also. error_log = /var/log/httpd/php_errors.log A: You can set the error log file for a site in the VirtualHost site configuration file, e.g: /etc/apache2/sites-enabled/example.com.conf: <VirtualHost *:80> .... ErrorLog ${APACHE_LOG_DIR}/www.example.com-error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/www.example.com-access.log combined </VirtualHost> In unix system ${APACHE_LOG_DIR} is usually /var/log/apache2 The errors and access will saved in ${APACHE_LOG_DIR}/www.example.com-error.log and ${APACHE_LOG_DIR}/www.example.com-access.log. A: Make sure that the Apache user has at least EXECUTION permission on any parent folders in the path to the logfile. Without it, Apache cannot list anything in the folder and thus not see the logfile. ls drwxr-x--- root adm folder chmod o+x folder ls drwxr-x--x root adm folder That one is a real gotcha! ;-) After that, also check that the Apache user does have read and write permission to the actual logfile. A: I've got that problem and then I gave the right permission to the apache log folder and then restarted my apache with this commands: sudo chmod a+w /var/log/apache2/ sudo service apache2 restart A: I spent several hours today trying to figure out why this wasn't working and trying to debug code working around the fact that I could log anything to the php error log. Needless to say, I was going at a snails pace until I got the logging working. I would guess that more than 90% of the time it is a permission issue. In my case daemon was the owner and group for the log file and I had to sudo su to root and then change the permissions of the log file. I changed to: chmod 777 myphperror.log Thank God for stackoverflow.com A: remove php_errors.log and restart apache2, the server itself will create a new php_errors.log file with proper permission and owner. rm -f /var/log/apache2/php_errors.log service apache2 restart ll /var/log/apache2/php_errors.log
{ "language": "en", "url": "https://stackoverflow.com/questions/7500532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Cascading ddl with jquery, asmx, but not MS ajax or plugin How can populate a ddl list dynamically (cascading ddl) using jquery w/o ms ajax framework or jquery plugins? (where I work am very limited on the libraries I can use). I am using ASP.Net with jquery accessing an asmx webmethod. The $.ajax call to the web method looks like the following: function getText() { $.ajax({ type: "POST", url: "SearchFilters.asmx/HelloWorld", dataType: "html", // also tried "text" success: function(response) { alert(response); $("#ddlCase").html(response); } }); } This return xml that looks like the following: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/">&lt;option value='1'&gt;Hello World&lt;/option&gt;</string> In the success function, the js only clears out the values of the ddl: $("#ddlCase").html(response) Can this be done? How can I decode the returned xml? What am I missing? Previously I attempted a datatype of json without success. Please refer to the following: using JQuery .ajax, a Success method is not called when using jquery 'json' vs 'text' Thanks! D A: This is the sample Code which I worked few months ago. ASP.NET HTML Code where you have two dropdowns a.) Category b.)Items I have hardcoded the first DropDown with Categories: Fruits, Vegetables and Desserts. The Items DropDown is empty initially, since we will fill these through jQuery AJAX, when the onChange event of the Category DropDown will be fired. <form id="form1" runat="server"> <asp:DropDownList ID="ddlCategories" runat="server"> <asp:ListItem>Select</asp:ListItem> <asp:ListItem>Fruits</asp:ListItem> <asp:ListItem>Vegetables</asp:ListItem> <asp:ListItem>Desserts</asp:ListItem> </asp:DropDownList> <br /> <asp:DropDownList ID="ddlItems" runat="server"></asp:DropDownList> </form> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#<%=ddlCategories.ClientID %>").change( function() { var category = this.options[this.selectedIndex].value; var ddlItems = document.getElementById("<%=ddlItems.ClientID%>"); ddlItems.options.length = 0; $.ajax ({ type: "POST", contentType: "application/json; charset=utf-8", url: "Webservice.asmx/getItems", data: "{'category':'"+category+"'}", dataType: "json", success: function(msg) { var arrItems = msg.d.split("|"); for(var i=0; i< arrItems.length; i++) { var opt = document.createElement("option"); ddlItems.options.add(opt) opt.text = arrItems[i]; opt.value = arrItems[i]; } } }); } ); }); </script> Webservice Code: [System.Web.Services.WebMethod] public static string getItems(string category) { string strItems = ""; if (category == "Fruits") { strItems = "Apple|Orange|Pinapple|Grapes"; } else if (category == "Vegetables") { strItems = "Tomato|Cauliflower|Brinjal|Potato"; } else if (category == "Desserts") { strItems = "Cakes|Cookies|IceCreams|Pastries"; } return strItems; } Regards, Sayed (Please mark as answer if you find this article suitable) A: In the end the source of my issue was the lack of the [ScriptService] attribute on the class decoration. I changed to class declartion to: [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] public class SearchFilters : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return ""; } } Using Fiddler I discovered the following error message was returned: Only Web services with a [ScriptService] attribute on the class definition can be called from script
{ "language": "en", "url": "https://stackoverflow.com/questions/7500533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Amazon s3 - browse exact directory's files within a bucket in Java How do I browse an exact directory say "210911" within a bucket, say "bucketName" in java? I need to do so in order to download the files within that directory. A: Start by using the AWS java sdk Then you can use the ObjectListing method with ListObjectsRequest to return all the objects in a bucket. If you specify a prefix value (210911/ in your case) you can limit the results to a specific virtual folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Synchronizing NSMutableData troubles We have an NSMutableData object that frequently has data appended to it. We also frequently pull out data via the bytes method for reading. We've synchronized access to this NSMutableData object via a pthread mutex: pthread_mutex_t _mutex; pthread_mutexattr_t attributes; pthread_mutexattr_settype( &attributes, PTHREAD_MUTEX_DEFAULT ); pthread_mutex_init( &_mutex, &attributes ); and then every time we access this object we: pthread_mutex_lock(&_mutex); const UInt8* rawData = [_coverage bytes]; //code that works with the raw bytes pthread_mutex_unlock(&_mutex); Also, every addData method we have locks the mutex before adding data to the NSMutableData object. The problem is we still get the occasional EXC_BAD_ACCESS while working with rawData. I understand that NSMutableBytes will grow its byte array as data gets added to it. I also understand that I shouldn't expect rawData to magically grow also. I'm just wondering how we can ever get into this situation where rawData has been free'd from underneath us when we have explicitly locked access for both read and write? Are we doing something wrong with the mutex or the way we are accessing the bytes? EDIT I discovered the real reason why I was getting an EXC_BAD_ACCESS. I was not initializing the mutex attributes, so locking the mutex did nothing. Here is the corrected code: pthread_mutex_t _mutex; pthread_mutexattr_t attributes; pthread_mutexattr_init(&attributes); pthread_mutex_init(&_mutex, &attributes); pthread_mutexattr_destroy(&attributes); A: Yes it is possible that is being freed from underneath you. According to the documentation: bytes Returns a pointer to the receiver’s contents. You should make copies of the data to ensure that it will not be changed or freed from underneath you. When your done with your copy make sure to free() it. pthread_mutex_lock(&_mutex); const UInt8 *origData = [_coverage bytes]; UInt8 *rawData; memmove(rawData, origData, [_coverage length]); //code that works with the raw bytes free(rawData); pthread_mutex_unlock(&_mutex);
{ "language": "en", "url": "https://stackoverflow.com/questions/7500542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding MySQL status statistics in Java App In my Java app, I want to query the MySQL status statistics. I'm adding some simple monitoring (mostly writing alerts when certain settings reach certain thresholds). In any case, I can't get it working using standard JDBC code. I want something like this: ResultSet s = DBUtil.executeQuery("SHOW STATUS LIKE '%conn%'"); But this isn't working from what I see in the debugger. Any solutions? A: Thanks for the link to the documentation. It helped clear up some confusion. For the record, here's how I navigated the ResultSet properly to find the values I wanted... String sql = "SHOW GLOBAL STATUS LIKE '%conn%'"; ResultSet rs = null; try { rs = DBUtil.executeQuery(stmt, sql); while (rs != null && rs.next()) { if (StringUtils.equals(rs.getString(1), "Max_used_connections")) return rs.getString(2); } } catch (Exception e) { throw e; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7500545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to page refresh after page redirect in Jquerymobile MVC Hi all i have create a small jquerymoblie mvc3 aplication in that i have a list-view controle when click on the link in the list-view it render to the next page, in that page i have upload some data into database using text-boxes.After updated completed i have redirect to the previous page,Now i again redirect to same page for upload some other data but the text boxes fields are not clear it shows old data how can i clear that data when i page redirect. I am using jquerymobile mvc3(Razor) application please help me how can i solve this probles.. A: If you go back to the "list page" with: $.mobile.changePage("/control/list/", { reloadPage: true }); It should reload the page from scratch with AJAX. There are also several more options for the changePage method which you can find in the docs: http://jquerymobile.com/test/docs/api/methods.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7500546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why Enum in DependencyProperty returns first value from Enum? I had tried to use an Enum in a DependencyProperty but it always takes the first value of the Enum. e.g. My Enum : public enum LayoutType { Horizontal, Vertical } Property Declaration : public static readonly DependencyProperty LayoutTypeProperty = DependencyProperty.RegisterAttached("LayoutType", typeof(LayoutType), typeof(ctrlAllLayouts), new PropertyMetadata(null)); I can access the property in my xaml but problem is that it always give value "Horizontal" if set it is to either "Horizontal" or "Vertical". A: With Attached Properties (these are not plain Dependency properties as you used RegisterAttached) you must also declare the matching static setter and getter methods for it to be parsed. The Xaml parser actually uses those methods. e.g. public static void SetLayoutType(DependencyObject element, LayoutType value) { element.SetValue(LayoutTypeProperty, value); } public static LayoutType GetLayoutType(DependencyObject element) { return (LayoutType)element.GetValue(LayoutTypeProperty); } If these methods are missing, and because you do not specify a default value in the PropertyMetadata, it will always be set to 0, which is the value of your first enum.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Terminating app due to uncaught exception 'NSInvalidArgumentException' I've finished my own project. So I tested it on the simulator and everything is ok. But unfortunately, the project does not run on my real iphone. This error occurs: "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSFileManager copyItemAtPath:toPath:error:]: source path is nil'" What is the reason? Here is some code that I used: RootViewController *rootViewController; ... - (void) startApp; { [rootViewController init]; // error occured } RootViewController is one of Project Simple File. void Game::readData() { NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1 NSString *documentsDirectory = [paths objectAtIndex:0]; //2 NSString *path = [documentsDirectory stringByAppendingPathComponent:@"GameInfo.plist"]; //3 NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath: path]) //4 { NSString *bundle = [[NSBundle mainBundle] pathForResource:@"GameInfo" ofType:@"plist"]; [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6 } NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path]; //load from savedStock example int value gameMaxLevel = [[savedStock objectForKey:@"GameMaxLevel"] intValue]; [savedStock release]; } void Game::readData() { NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1 NSString *documentsDirectory = [paths objectAtIndex:0]; //2 NSString *path = [documentsDirectory stringByAppendingPathComponent:@"GameInfo.plist"]; //3 NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath: path]) //4 { NSString *bundle = [[NSBundle mainBundle] pathForResource:@"GameInfo" ofType:@"plist"]; [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6 } NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path]; //load from savedStock example int value gameMaxLevel = [[savedStock objectForKey:@"GameMaxLevel"] intValue]; [savedStock release]; } A: check if your GameInfo.plist exist in your application's resource, and it reside inside your application folder(if you are executing your code on two or more devices). If problem doesn't get solved, share your, complete exception log.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get a database backup without using runtime commands from Java I want to know how to get a mysql database backup without using runtime commands from Java code. A: Getting a MySQL backup need not have anything to do with Java. Use the MySQL backup scripts. Run them using a cron job if you wish.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How do I redirect to the cshtml page created inside shared folder in ASP.NET MVC3 Please help me out how do I redirect to a .cshtml page which is created inside a shared folder. I want something like this href="@Url.Content("Shared/UnderConstruction")" Here it's not getting redirecting to the UnderConstruction page, which I created. A: You cannot redirect to anything that's stored inside the ~/Views folder including the ~/Views/Shared. This folder is simply not served by ASP.NET MVC and cannot be accessed directly. Also notice that in ASP.NET MVC you are not serving .cshtml pages directly. You are always passing through controller action that return views and those views might represent .cshtml pages. Now if you have some Shared folder directly under the site root ~/Shared, then you can do this: <a href="@Url.Content("~/Shared/UnderConstruction")">construction</a> A: In ASP.NET MVC3 you can't render views directly by calling the files directly. They can only be served via controllers. In order to call the view in your shared folder you woul have to do something similar to the following: public class HomeController : Controller { public ActionResult About() { return View("Construction"); } } A: If you want to display a page at url "shared/underconstruction" as per the other posts: * *Create controller SharedController. *Define action "UnderConstruction" *Create "UnderConstruction.cshtml" in Views/Shared/ folder. *Map URL "Shared/{action}" , new { Controller = "Shared" } if you want to be explicit. Give that a shot... to be honest even I don't know if this will work, and you will pollute your "Shared" folder. You could rename existing Shared folder to something else, maybe, and modify ViewStart.cshtml to point to new folder, maybe. A: In ASP.NET MVC you can only redirect to controllers, and the controllers return a view. You can access views in Shared the same way as your normal controller views, by their name. ASP.NET MVC first looks in your controller view folder then in your shared view folder when resolving view names.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MSMQ Activation for WCF Workflow Service -- turning off? I'm setting up a Workflow Service that is activated by an MSMQ, as outlined here: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=21245 (the synopsis: WCF Workflow Service Application has a receive request that polls from a MSMQ). I'm using .NET 4.0. It works like a charm. However, is there an easy way to tell it turn it off or not run during a specific time? Ideally, I'd like to do this either programatically (only run during non-working hours), or through a configuration (we need to disable it manually to handle an issue). I could point it to an empty queue, but that seems like a copout. A: If your workflow service is hosted as a windows service then you can use Task Scheduler to stop and start it at certain times. Inbound messages will build up on the queue during downtime and will be processed when the service is started back up. To my knowledge, msmq does not have the concept of a service window. But, I'm hosting the workflow service through IIS If you're hosting the workflow in IIS you can unwind the app pool at a certain time and then wind it up again for your service window. Here's a powershell script you can call from a scheduled task: Start/Stop App Pool IIS6.0 with Powershell or command line However, the above approach is pretty horrible, and I wouldn't be surprised if you encountered issues if you did this in production.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get row count of database table I am just new in abap language and I am trying to practice an inner join statement but I don't know how whether I will be able to get the number of rows of my select statement before output. Here's what I want to achieved. <--------------------------------------- > < total number of rows > Record(s) found | Column Header 1|Column Header 2 .. < data .... retrieved > <--------------------------------------- > Below is my select statement : SELECT spfli~carrid scarr~carrname sflight~planetype sflight~fldate sflight~price spfli~cityfrom spfli~cityto INTO (g_carrid ,g_carrname ,g_planetype,g_fldate ,g_price ,g_cityfrom ,g_cityto) FROM spfli INNER JOIN sflight ON spfli~carrid = sflight~carrid AND spfli~connid = sflight~connid INNER JOIN scarr ON scarr~carrid = spfli~carrid WHERE spfli~carrid = s_carrid-low. WRITE: / g_carrname ,g_planetype,g_fldate ,g_price ,g_cityfrom ,g_cityto. ENDSELECT. And if you have any advice and idea on how to do this using internal table, please, show me a sample. I just really want to learn. Thank you and God Bless. A: The system variable SY-DBCNT should give you the number of rows selected, but only after the select ends. The alternative to SELECT-ENDSELECT is to select all the rows at once with SELECT INTO TABLE into an internal table (provided you are not selecting too much at once!). For example: data: lt_t000 type table of t000. select * from t000 into table lt_t000. This will select everything from that table in one go into the internal table. So what you could do is to declare an internal table with all the fields currently in your INTO clause and then specify INTO TABLE for your internal table. After the SELECT executes, SY-DBCNT will contain the number of selected rows. Here is a complete example, built around the SELECT statement in your question, which I have not checked for sanity, so I hope it works! tables: spfli. select-options: s_carrid for spfli-carrid. * Definition of the line/structure data: begin of ls_dat, carrid type s_carr_id, carrname type s_carrname, planetype type s_planetye, fldate type s_date, price type s_price, cityfrom type s_from_cit, cityto type s_to_city, end of ls_dat. * Definition of the table: data: lt_dat like table of ls_dat. * Select data select spfli~carrid scarr~carrname sflight~planetype sflight~fldate sflight~price spfli~cityfrom spfli~cityto into table lt_dat from spfli inner join sflight on spfli~carrid = sflight~carrid and spfli~connid = sflight~connid inner join scarr on scarr~carrid = spfli~carrid where spfli~carrid = s_carrid-low. * Output data write: 'Total records selected', sy-dbcnt. loop at lt_dat into ls_dat. write: / ls_dat-carrid, ls_dat-carrname, ls_dat-planetype, ls_dat-fldate, ls_dat-price, ls_dat-cityfrom, ls_dat-cityto. endloop. Note: Report (type 1) programs still support the notion of declaring internal tables with header lines for backward compatibility, but this is not encouraged! Hope it works! A: If you only need row count without retrieving data itself the following syntax works as well SELECT COUNT(*) FROM spfli INNER JOIN sflight ... After execution of this query you will be able to get row count value from SY-DBCNT and DB load will be much less than during usual SELECT ... INTO itab. This is, however, true only if you don't need actual data. If you need both row count and data itself it is not sensible to split this into separate select statement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UITableview section issue I have a tableview with two sections. I have loaded values from same array to the tableview. It is working fine, and I have customized the alpha value of the cell text in section 1, 1.0 and in section 2, 0.5. When I scroll down the table it is working fine. But when I scroll up (bottom to top), the alpha value of the section got changed to 0.5 (that is the value of section 1). Then the alpha value in both the sections are 0.5. Why it is happening so? Does anybody know the solution, please let me know. A: It is probably because you are reusing the cells, but not resetting the alpha values in the cell you are reusing. If you have a line with dequeueReusableCellWithIdentifier in your cellForRowAtIndexPath method, then this is retrieving a cell for reuse - if you use this reused cell then you need to make sure you reset the alpha values of the background accordingly because it could be reused for a different row to the one the cell was originally created for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there something similar to 'zoomToRegion' in Android? I want to zoom in or out of the map depending on where markers on my map are placed. The markers are dynamic so I can not chose a static zoom level. I understand that there is 'zoomToRegion' method in iOS to acheive this. Is there something similar in Android? A: Yes. You have to use the method zoomToSpan of MapController. // zoom into map to box of results int centerLat = (int)(((maxLat-minLat)/2+ minLat)*1E6); int centerLon = (int)(((maxLon-minLon)/2 + minLon)*1E6); mapView.getController().animateTo(new GeoPoint( centerLat, centerLon)); mapView.getController().zoomToSpan((int)((maxLat-minLat)*1E6), (int)((maxLon-minLon)*1E6));
{ "language": "en", "url": "https://stackoverflow.com/questions/7500593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to copy text from one ViewController to another? I'm writing a little quiz application. So I have a first view, where I ask a person to enter his/her name and a button which is the IBAction to go the next view with the first question. In the end, after a person has answered all questions, comes the congratulations view, where I want to copy the name, that was entered on the first view. Say there will be a phrase "Well done, John!" How can I do it? On the first view(FirstViewController) I made a textfield IBOutlet UITextField *text1; And on the last view in .h: IBOutlet UITextField *text2; and -(IBAction)copy:(id)sender; And in .m: - (IBAction)copy:(id)sender { [text2 setText:[text1 text]]; } and #import "FirstViewController.h" But it says identifier text1 is undefined I don't know what else to do... A: You can override the - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil method of last view controller with something like: - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil andUserName:(NSString*)userName (don't forget to declare this method in your .h file.) Now while initializing your last view controller, you can pass the name of the user to last view controller. In the implementation of the this overriden method in last view controller, copy this name in some local variable. and use it. Hope this will solve your problem. A: In your firstView add NSString with its property Something like this in .h file NSString *username; and @property (nonatomic , retain) NSString *username; in .m file username = text1.text; In LastView im .m file #import "FirstView.h" And where ever you want username try this FirstView *firstview = [[FirstView alloc] init]; text2 = firstview.username; Hope it works..!! A: Override the init method of SecondViewController as follows -(id)initWithUsername:(NSString *)username { //create instance and then do text2.text = username ; } And in the FirstViewController , where you create the instance of SecondViewController init it using the above SecondViewController *second = [[SecondViewController alloc] initWithUsername:text1.text]; A: For passing value from one VC to other you have to do following code : * *First declare local variable in next view where you want to move like. @property(nonatomic, strong) NSString *personName; *Now prepare object of second VC in the first VC.m file on button click action. But before that must set storyboard identifier of that second VC in storyboard. SecondViewController *obj = (SecondViewController *) [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"]; obj.personName = self.txtUserName.text; *Now go on there on second VC and do whatever you want. Note : Here you don't need to used userdefaults, OR prepared init methods with parameters, OR using delegates etc. A: I would make use of NSUserDefaults to set the user's name when they enter it. Then, in your last view controller, just query NSUserDefaults again for the name you want. Granted, this is still global state, but NSUserDefaults is meant for this sort of purpose: // In the first view controller NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:@"John Doe" forKey:@"XXUserNameKey"]; // This should actually be an extern for your app to use globally // In the last view controller NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSString *userName = [userDefaults stringForKey:@"XXUserNameKey"]; Adding state to your app delegate is an abuse of the design pattern. Also, I should clarify that NSUserDefaults should not be used as a general-purpose storage container. Its intent is for common, shared data like user names, preferences, etc. Something like the name a user enters at the beginning of a game seems to fall within the usage pattern. A: The best way to do this would be taking the variables you need on various views and handling them on the delegate since the delegate has access to everything. Making a Global variable is never advisable that is what the delegate is for. You can refer to this question that treats the same issue: Passing data between view controllers A: You can add a NSString member (along with a property) in the application delegate class. /// AppDelegate.h, or whatever it's called in your application @interface AppDelegate : NSObject <UIApplicationDelegate> { NSString *username; // <rest of the members> } ... @property (nonatomic, retain) NSString *username; @end /// AppDelegate.m @implementation AppDelegate @synthesize username; @end /// FirstViewController.m -(void)viewDidDissappear:(BOOL)animated{ [super viewDidDissappear:animated]; AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.username = text1.text; } /// LastViewController.m (or whatever it's called) -(void)viewDidLoad{ [super viewDidLoad]; AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; [text2 setText:[NSString stringWithFormat:@"Well done %@", appDelegate.username]]; } Ok, so for everyone to be happy, you can (and are suggested to) create your own singleton class in which you can hold non-persistent global variables, and use in the code above instead of the application delegate. /// SharedData.h @interface SharedData: NSObject { NSString *username; /// or instead you can have a NSMutableDictionary to hold all shared variables at different keys } +(SharedData *)sharedInstance; @property(nonatomic, retain) NSString *username; @end /// SharedData.m #include "SharedData.h" static SharedData *_sharedInstance=nil; @implementation SharedData @synthesize username; +(SharedData)sharedInstance{ if(!_sharedInstance){ _sharedInstance = [[SharedData alloc] init]; } return _sharedInstance; } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7500594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Stored Procedure in Oracle and IDataReader.Read() in VB.NET I have a Stored Procedure that seems to be very slow. Executing it in Oracle SQL Developer; SET TIMING ON; DECLARE CUR_OUT UTILS.T_CURSOR; P_ARTTYID NUMBER; P_ORDERST VARCHAR2(200); P_DRUMNO VARCHAR2(200); P_SHIPPINGNO VARCHAR2(200); P_DELIVERYDATEFROM DATE; BEGIN P_ARTTYID := 2; P_ORDERST := '3'; P_DRUMNO := '611-480'; P_SHIPPINGNO := NULL; P_DELIVERYDATEFROM := '2005-01-01'; C_T_ORDER_GETOVERVIEW( CUR_OUT => CUR_OUT, P_ARTTYID => P_ARTTYID, P_ORDERST => P_ORDERST, P_DRUMNO => P_DRUMNO, P_SHIPPINGNO => P_SHIPPINGNO, P_DELIVERYDATEFROM => P_DELIVERYDATEFROM ); --DBMS_OUTPUT.PUT_LINE('CUR_OUT = ' || CUR_OUT); -- Doesn´t work ;| END; Gives the "Statement output" anonymous block completed 139ms elapsed Now the problem is when I call it from my VB.NET application using Microsoft.Practices.EnterpriseLibrary.Data.Database.ExecuteReader() that returns a System.Data.IDataReader and the following function to convert the IDataReader to a DataSet. Public Shared Function ConvertIDataReaderToDataSet(ByVal reader As IDataReader) As DataSet Dim schemaTable As DataTable = reader.GetSchemaTable() Dim dataTable As DataTable = New DataTable For intCounter As Integer = 0 To schemaTable.Rows.Count - 1 Dim dataRow As DataRow = schemaTable.Rows(intCounter) Dim columnName As String = CType(dataRow("ColumnName"), String) Dim column As DataColumn = New DataColumn(columnName, CType(dataRow("DataType"), Type)) dataTable.Columns.Add(column) Next Dim dataSet As DataSet = New DataSet dataSet.Tables.Add(dataTable) 'dataSet.Load(reader, LoadOption.OverwriteChanges, dataTable) ' DEBUG While reader.Read() Dim dataRow As DataRow = dataTable.NewRow() For intCounter As Integer = 0 To reader.FieldCount - 1 dataRow(intCounter) = reader.GetValue(intCounter) Next dataTable.Rows.Add(dataRow) End While Return dataSet End Function Debugging and stepping through the function ends at the line for "While reader.Read()". Also tried another version using DataSet.Load() but with the same result. Found this thread on MSDN where others with the same problem seems to have solved it by tuning their queries by adding indexes. How can I continue investigating the issue when it seems like the procedure works (responds within ~100 - 200ms) and the IDataReader.Read() just ends (or continues in the background?) * *Can I time the procedure in another (better) way? *Can there be any table or transaction locks involved? All advices are highly appreciated :) A: Your test in SQL Developer is simply measuring the time required to open the cursor. Opening the cursor does not cause Oracle to actually execute the query-- that does not happen until you fetch data from the cursor and each time you fetch, Oracle will continue processing the query to get the next set of rows. Oracle does not, in general, need to execute the entire query at any point in time. To be a comparable test, your PL/SQL block would need to fetch all the data from the cursor. Something like DECLARE CUR_OUT UTILS.T_CURSOR; P_ARTTYID NUMBER; P_ORDERST VARCHAR2(200); P_DRUMNO VARCHAR2(200); P_SHIPPINGNO VARCHAR2(200); P_DELIVERYDATEFROM DATE; BEGIN P_ARTTYID := 2; P_ORDERST := '3'; P_DRUMNO := '611-480'; P_SHIPPINGNO := NULL; P_DELIVERYDATEFROM := '2005-01-01'; C_T_ORDER_GETOVERVIEW( CUR_OUT => CUR_OUT, P_ARTTYID => P_ARTTYID, P_ORDERST => P_ORDERST, P_DRUMNO => P_DRUMNO, P_SHIPPINGNO => P_SHIPPINGNO, P_DELIVERYDATEFROM => P_DELIVERYDATEFROM ); LOOP FETCH cur_out INTO <<list of variables to fetch data into>>; EXIT WHEN cur_out%notfound; END LOOP; --DBMS_OUTPUT.PUT_LINE('CUR_OUT = ' || CUR_OUT); -- Doesn´t work ;| END; Are you saying that in your .Net code, the reader.Read() line never returns? Or are you saying your code aborts at that point?
{ "language": "en", "url": "https://stackoverflow.com/questions/7500600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Understanding How Many Times Nested Loops Will Run I am trying to understand how many times the statement "x = x + 1" is executed in the code below, as a function of "n": for (i=1; i<=n; i++) for (j=1; j<=i; j++) for (k=1; k<=j; k++) x = x + 1 ; If I am not wrong the first loop is executed n times, and the second one n(n+1)/2 times, but on the third loop I get lost. That is, I can count to see how many times it will be executed, but I can't seem to find the formula or explain it in mathematical terms. Can you? By the way this is not homework or anything. I just found on a book and thought it was an interesting concept to explore. A: Consider the loop for (i=1; i <= n; i++). It's trivial to see that this loops n times. We can draw this as: * * * * * Now, when you have two nested loops like that, your inner loop will loop n(n+1)/2 times. Notice how this forms a triangle, and in fact, numbers of this form are known as triangular numbers. * * * * * * * * * * * * * * * So if we extend this by another dimension, it would form a tetrahedron. Since I can't do 3D here, imagine each of these layered on top of each other. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * These are known as the tetrahedral numbers, which are produced by this formula: n(n+1)(n+2) ----------- 6 You should be able to confirm that this is indeed the case with a small test program. If we notice that 6 = 3!, it's not too hard to see how this pattern generalizes to higher dimensions: n(n+1)(n+2)...(n+r-1) --------------------- r! Here, r is the number of nested loops. A: The 3rd inner loop is the same as the 2nd inner loop, but your n is a formula instead. So, if your outer loop is n times... and your 2nd loop is n(n+1)/2 times... your 3rd loop is.... (n(n+1)/2)((n(n+1)/2)+1)/2 It's rather brute force and could definitely be simplified, but it's just algorithmic recursion. A: The mathematical formula is here. It is O(n^3) complexity. A: This number is equal to the number of triples {a,b,c} where a<=b<=c<=n. Therefore it can be expressed as a Combination with repetitions.. In this case the total number of combinations with repetitions is: n(n+1)(n+2)/6 A: 1 + (1+2) + (1+ 2+ 3 ) +......+ (1+2+3+...n) A: You know how many times the second loop is executed so can replace the first two loops by a single one right? like for(ij = 1; ij < (n*(n+1))/2; ij++) for (k = 1; k <= ij; k++) x = x + 1; Applying the same formula you used for the first one where 'n' is this time n(n+1)/2 you'll have ((n(n+1)/2)*(n(n+1)/2+1))/2 - times the x = x+1 is executed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Storing cartesian product results in SQL? Thanks for reading, I hope this makes sense! I am trying to modify a bespoke CMS which gives different product options and lets you set various attributes based on combinations of those options. These are getting pulled from a mySQL database. For example, a t-shirt might have: Colour Size ------ ---- Red Small Red Medium Blue Small Blue Medium Each colour and size would have a unique ID so red = 1, blue = 2 and small = 3, medium = 4. Colour and Size would each have a parent id, so colour = 1, size = 2. At the moment I am storing a string in a database table in the database that identifies each combination (e.g. Red + small would be &1=1&2=3). This string then associates this combination of options with various attributes: price, stock code etc. However the problem comes when we want to add a new option group to the mix, say sleeve length. At the moment this would mean having to go through the strings and changing them to also include the new option. This seems like a very inefficient and long-winded way to be doing this! So (eventually!) my question is - is there a better way I can be doing this ? I need to ensure that there is no real limit on the number of option groups that can be added, as well as letting new option groups be added at any time. Thanks in advance for your help. Stuart A: I would counter instead with asking you, why would you want to store that in the first place? Cartesian products are a controller issue, not a domain model one. Your domain model (your database) should only care to keep the data in a normalized fashion (or as close as it's feasible), let the database system do the joins as needed (inner join in sql), that's what they're optimized to do in the first place.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Autogenerate dummy documentation in the source code for Python in eclipse At the time I am documenting a lot of my code (Python) and I was wondering if there is a plugin to Eclipse that can automatically generate a doc string for my functions, like visual studio does it for C# when writing /// over a method. I have been searching around for a solution, but I had no luck - do any of you know a solution? Example: From my parameter list on a method the "dummy" documentation will be created under my method definition as shown below: def myFunction(self, a, b): """ :param a: :type a: :param b: :type b: :return: :rtype: """ return 'Hello, world' A: Well, according to this doc, if you press Ctrl + 1 on a method name, you will get what you need. For your example (EDIT : if you set the option PyDev>Editor>Code Style>Docstrings>Doctag generation to always to get the type of the param), you will get : def myFunction(self, a, b): ''' @param a: @type a: @param b: @type b: ''' return 'Hello, world'
{ "language": "en", "url": "https://stackoverflow.com/questions/7500615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to use Java to encode/decode/transcode byte array using a charset directly I have a malformed string which may be caused by a bug of MySQL JDBC driver, The bytes of a sample malformed string (malformed_string.getBytes("UTF-8")) is this: C3 A4 C2 B8 C2 AD C3 A6 E2 80 93 E2 80 A1 (UTF-8 twice) which should encoded the following bytes (it's already UTF-8 encoded, but treat them as ISO-8859-1 enoded) ----- ----- ----- ----- -------- -------- E4 B8 AD E6 96 87 (UTF-8) which should encoded the following Unicode BigEndian bytes --------------- --------------------- 4E 2D 65 87 (Unicode BigEndian) I want to decode the 1st one to the 2nd one, I tried new String(malformed_string.getBytes("UTF-8"), "ISO-8859-1"), but it does not transcode as expected. I'm wondering if there's something like byte[] encode/decode (byte[] src, String charsetName), or how to achieve the transcode above in java? Background: I have a MySQL table which have Chinese column names, when I update such columns with long data, MySQL JDBC driver thrown an exception like this: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column '中文' at row 1 The column name in the exception is malformed, it should be "中文", and it must be correctly displayed to user as the following. com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column '中文' at row 1 EDIT Here's MySQL statement to demonstrate how the malformed string occured, and how to restore it to correct string show variables like 'char%'; +--------------------------+--------------------------+ | Variable_name | Value | +--------------------------+--------------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | | character_set_database | utf8 | | character_set_filesystem | binary | | character_set_results | utf8 | | character_set_server | utf8 | | character_set_system | utf8 | | character_sets_dir | C:\mysql\share\charsets\ | +--------------------------+--------------------------+ -- encode select hex(convert(convert(unhex('E4B8ADE69687') using UTF8) using ucs2)) as `hex(src in UNICODE)`, unhex('E4B8ADE69687') `src in UTF8`, 'E4B8ADE69687' `hex(src in UTF8)`, hex(convert(convert(unhex('E4B8ADE69687') using latin1) using UTF8)) as `hex(src in UTF8->Latin1->UTF8)`; +---------------------+-------------+------------------+--------------------------------+ | hex(src in UNICODE) | src in UTF8 | hex(src in UTF8) | hex(src in UTF8->Latin1->UTF8) | +---------------------+-------------+------------------+--------------------------------+ | 4E2D6587 | 中文 | E4B8ADE69687 | C3A4C2B8C2ADC3A6E28093E280A1 | +---------------------+-------------+------------------+--------------------------------+ 1 row in set (0.00 sec) -- decode select unhex('C3A4C2B8C2ADC3A6E28093E280A1') as `malformed`, 'C3A4C2B8C2ADC3A6E28093E280A1' as `hex(malformed)`, hex(convert(convert(unhex('C3A4C2B8C2ADC3A6E28093E280A1') using utf8) using latin1)) as `hex(malformed->UTF8->Latin1)`, convert(convert(convert(convert(unhex('C3A4C2B8C2ADC3A6E28093E280A1') using utf8) using latin1) using binary)using utf8) `malformed->UTF8->Latin1->binary->UTF8`; +----------------+------------------------------+------------------------------+---------------------------------------+ | malformed | hex(malformed) | hex(malformed->UTF8->Latin1) | malformed->UTF8->Latin1->binary->UTF8 | +----------------+------------------------------+------------------------------+---------------------------------------+ | 中文 | C3A4C2B8C2ADC3A6E28093E280A1 | E4B8ADE69687 | 中文 | +----------------+------------------------------+------------------------------+---------------------------------------+ 1 row in set (0.00 sec) A: Check out this tutorial: http://download.oracle.com/javase/tutorial/i18n/text/string.html The punch line is the way to transcode using only the jdk classes is : try { byte[] utf8Bytes = original.getBytes("UTF8"); byte[] defaultBytes = original.getBytes(); String roundTrip = new String(utf8Bytes, "ISO-885-9"); System.out.println("roundTrip = " + roundTrip); System.out.println(); printBytes(utf8Bytes, "utf8Bytes"); System.out.println(); printBytes(defaultBytes, "defaultBytes"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } For a more robust transcoding mechanism I suggest you check out ICU>
{ "language": "en", "url": "https://stackoverflow.com/questions/7500616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AOP with Spring 3 using Annotations I am trying to get Aspect working with Spring 3 and annotations. @Aspect public class AttributeAspect { @Pointcut("@annotation(com.mak.selective.annotation.Attribute)") public void process(){ System.out.println("Inside Process ...."); } @Around("process()") public void processAttribute(){ System.out.println("Inside Actual Aspect .."); } } XML: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <aop:aspectj-autoproxy proxy-target-class="false" /> <context:component-scan base-package="com.mak.selective.annotation.*" /> <bean name="attribute" class="com.mak.selective.annotation.AttributeAspect"/> </beans> MY Test to test the Aspect: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/springcontext/*.xml") public class AttributeTest { @Attribute(tableName = "firstTable", columnName = "New Column") private void getAttribute() { System.out.println("Inside Attribute call..."); } @Test public void testAttributeAspect() { getAttribute(); } } With this code i can only see "Inside Attribute call..." but nothing from Aspect. Please guide. Got this working by making a new Object (Component) and injected to the Junit test class. A: Good to see that you got it working from XML, but you could have also done it from annotations. The issue is that the @Aspect annotation is not a Spring stereotype, so the scanner is not registering the aspect as a Spring Bean. Just add either @Service or @Component above or below @Aspect and it will be registered. Also, either directly name the bean (e.g., @Service("myNamedService")) or have it implement an interface (e.g., public class AttributeAspect implements IAspect {), as per standard Spring design. A: You need to use real AspectJ if you want to intercept invocations of methods within the same bean form where it is invoked. (What you have done, should work if the method testAttributeAspect() is located in an other bean.) How to do real AspectJ? Using the AspectJ compiler and weaver enables use of the full AspectJ language, and is discussed in Section 7.8, “Using AspectJ with Spring applications”. @See Spring Reference A: A few things: Firstly, when you do around advice you need to write the advice method like this: @Around(...) public void aroundAdviceMethod(ProceedingJoinPoint pjp) throws Throwable { try { System.out.println("before..."); pjp.proceed(); } finally { System.out.println("After..."); } } But also (and this at least applies when you're using proxies, not entirely sure in your case), the method you're putting advice on needs to be public (yours isn't), spring managed (via @Component or otherwise) and called external from the class so the proxy can take effect (also not the case in your example). So you need something like this: @Component public class SomeClass { @Attribute public void someMethodCall() { System.out.println("In method call"); } } public class SomeUnitTest { @Autowired SomeClass someClass; @Test public void testAspect() { someClass.someMethodCall(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7500617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Axis2 : Handling Userdefined Exceptions I am seeing Exception handling in Apache Axis2 Webservices . My Skelton class throws a Userdefined Exception named as "NoUserFound" , which in have configured inside WSDL file Inside my skelton class public samples.quickstart.xsd.GetPriceResponse getPrice( samples.quickstart.xsd.GetPrice getPrice0) throws GetSolutionByIdFault { samples.quickstart.xsd.GetPriceResponse response = new samples.quickstart.xsd.GetPriceResponse(); response.set_return("Hi"); String value = (String) getPrice0.getSymbol(); if (value.equals("Pavan")) throw new GetSolutionByIdFault("name not present"); return response; } Inside my client class , i am handling this in this way : try { // Some Logic here } catch (AxisFault er) { er.getMessage(); } catch (Exception e) { e.printStackTrace(); } So when ever a user defined exception is thrown for example (GetSolutionByIdFault) , i am handling it in the AxisFault block . is this the correct approach ?? A: Yes, that looks fine - if you want, you catch more specific exceptions as well... A: It depends on what you have to do in order to handle the exception. If you need to do special things according to the backend exception then you need to catch each and every exception and handle them separately. Normally I used to handle exceptions separately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OR operators and Ruby where clause Probably really easy but im having trouble finding documentation online about this I have two activerecord queries in Ruby that i want to join together via an OR operator @pro = Project.where(:manager_user_id => current_user.id ) @proa = Project.where(:account_manager => current_user.id) im new to ruby but tried this myself using || @pro = Project.where(:manager_user_id => current_user.id || :account_manager => current_user.id) this didnt work, So 1. id like to know how to actually do this in Ruby and 2. if that person can also give me a heads up on the boolean syntax in a ruby statement like this altogether. e.g. AND,OR,XOR... A: You should take a look at the API documentation and follow conventions, too. In this case for the code that you might send to the where method. This should work: @projects = Project.where("manager_user_id = '#{current_user.id}' or account_manager_id = '#{current_user.id}'") This should be safe since I'm assuming current_user's id value comes from your own app and not from an external source such as form submissions. If you are using form submitted data that you intent to use in your queries you should use placeholders so that Rails creates properly escaped SQL. # with placeholders @projects = Project.where(["manager_user_id = ? or account_manager_id = ?", some_value_from_form1, some_value_from_form_2]) When you pass multiple parameters to the where method (the example with placeholders), the first parameter will be treated by Rails as a template for the SQL. The remaining elements in the array will be replaced at runtime by the number of placeholders (?) you use in the first element, which is the template. A: You can't use the Hash syntax in this case. Project.where("manager_user_id = ? OR account_manager = ?", current_user.id, current_user.id) A: Metawhere can do OR operations, plus a lot of other nifty things.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How shared memory would be accessed in manycore systems In multicore systems, such as 2, 4, 8 cores, we typically use mutexes and semaphores to access shared memory. However, I can foresee that these methods would induce a high overhead for future systems with many cores. Are there any alternative methods that would be better for future many core systems for accessing shared memories. A: Transactional memory is one such method. A: I'm not sure how far in the future you want to go. But in the long-long run, shared memory as we know it right now (single address space accessible by any core) is not scalable. So the programming model will have to change at some point and make the lives of programmers harder as it did when we went to multi-core. But for now (perhaps for another 10 years) you can get away with transactional memory and other hardware/software tricks. The reason I say shared-memory is not scalable in the long run is simply due to physics. (similar to how single-core/high-frequency hit a barrier) In short, transistors can't shrink to less than the size of an atom (barring new technology), and signals can't propagate faster than the speed of light. Therefore, memory will get slower and slower (with respect to the processor) and at some point, it becomes infeasible to share memory. We can already see this effect right now with NUMA on the multi-socket systems. Large-scale supercomputers are neither shared-memory nor cache-coherent. A: 1) Lock only the memory part your are accessing, and not the entire table ! This is done with the help of a big hash table. The bigger the table, the finer the lock mechanism is. 2) If you can, only lock on writing, not on reading (this requires that there is no problem in reading the "previous value" while it is being updated, which is very often a valid case). A: Access to shared memory at the lowest level in any multi-processor/core/threaded application synchronization depends on the bus lock. Such a lock may incur hundreds of (CPU) wait states as it also encompasses locking those I/O buses that have bus-mastering devices including DMA. Theoretically it is possible to envision a medium-level lock that can be invoked in situations when the programmer is certain that the memory area being locked won't be affected by any I/O bus. Such a lock would be much faster because it only needs to synchronize the CPU caches with main memory which is fast, at least in comparison to latency of the slowest I/O buses. Whether programmers in general would be competent to determine when to use which bus lock adds worrying implications to its mainstream feasibility. Such a lock could also require its own dedicated external pins for synchronization with other processors. In multi-processor Opteron systems each processor has its own memory which becomes part of the entire memory that all installed processors can "see". A processor trying to access memory which turns out to be attached to another processor will transparently complete the access - albeit more slowly - through a high-speed interconnect bus (called HyperTransport) to the processor in charge of that memory (the NUMA concept). As long as a processor and its cores are working with the memory physically connected to it processing will be fast. In addition, many processors are equipped with several external memory buses to multiply their overall memory bandwidth. A theoretical medium-level lock could, on Opteron systems, be implemented using the HyperTransport interconnections. As for any forseeable future the classic approach of locking as seldom as possible and for as short a time as possible by implementing efficient algorithms (and associated data structures) that are used when the locks are in place still holds true.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does tomcat detect changes in decompressed war? I have a problem with Tomcat. It hangs. I suppose that this is because I have change one XML file inside decompressed folder inside webapps. Is it possible? Thanks. A: Not because the change of the xml file itself. However, if you change web.xml, web application will be redeployed, and each redeploy causes memory leak, which eventually will lead to hangout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: SQL Server 2008 DATETIME2 Format Question I am dealing with a date/time from Australia (I am located in the USA). I am unable to get the following string to insert into a DATETIME2 column: 2010/19/10 04:38:12.892 As you can see, it's formatted in yyyy/dd/mm HH:MM:ss.MMM format. I understand that the normal format is yyyy-mm-dd HH:MM:ss.MMM. What I am wondering is if there is a locality setting on SQL Server that I can change to get it to accept this format, or if I need to parse it and rearrange it myself. EDIT: Just for your information, I have been importing a mm/dd/YYYY HH:MM:ss.MMM format string into the field just fine. A: It depends on the "locale" date format, I guess. Some samples on how to convert here : http://www.java2s.com/Code/SQLServer/Date-Timezone/Formatdatemmddyyyy.htm Hope this was helpful. A: Try issuing SET DATEFORMAT ydm; before INSERT. Then CONVERT(DATETIME,('2010/19/10 04:38:12.892')); works fine. More info A: You can try this: SET DATEFORMAT YDM; select cast('2010/19/10 04:38:12.892' as datetime) And it will parse it correctly UPDATE: I found help here. But I tried casting to datetime2 directly and it didn't work. I don't understand why you can cast to datetime and not datetime2. Perhaps a good question for SO. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7500627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XML validation error using nested XSD schema - Type not declared I am using a nested XSD schema to validate an XML document. The imported XSDs use their own target namespaces and I can validate the sample XML given below using Liquid XML Studio. But when I run the validation using my C# code below, it fails with the type declaration error (see below). I have spend alot of time trying to figure out, but no luck: Main XSD Schema (DataItem.xsd): <?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns:DataNumeric="Doc.DataNumeric" xmlns:DataYesNo="Doc.DataYesNo" attributeFormDefault="qualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:import schemaLocation="DataNumeric.xsd" namespace="Doc.DataNumeric" /> <xs:import schemaLocation="DataYesNo.xsd" namespace="Doc.DataYesNo" /> <xs:complexType name="tDataItem"> <xs:choice> <xs:element name="DataNumeric" type="DataNumeric:tDataNumeric" /> <xs:element name="DataYesNo" type="DataYesNo:tDataYesNo" /> </xs:choice> </xs:complexType> <xs:element name="DataItem" type="tDataItem" /> </xs:schema> Included XSD Schema (DataNumeric.xsd): **<?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns:DataNumeric="Doc.DataNumeric" elementFormDefault="qualified" targetNamespace="Doc.DataNumeric" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="tDataNumeric"> <xs:sequence> <xs:element name="Answer" type="xs:double" /> </xs:sequence> </xs:complexType> <xs:element name="DataNumeric" type="DataNumeric:tDataNumeric" /> </xs:schema>** The XML: <DataItem> <DataNumeric xmlns:DataNumeric="Doc.DataNumeric"> <DataNumeric:Answer>37.8</DataNumeric:Answer> </DataNumeric> </DataItem> Validation Error: XmlSchemaValidationException: Type 'Doc.DataNumeric:tDataNumeric' is not declared. C# Validation Code: XDocument xDoc = XDocument.Parse(xxxxxxx); string xsdPath = ConfigUtils.GetXsdPath(XsdSchemaIdentifier.HHDataItem); FileStream fs = new FileStream(xsdPath, FileMode.Open); XmlReader reader = XmlReader.Create(fs); XmlSchemaSet xss = new XmlSchemaSet(); xss.Add("", reader); fs.Close(); fs.Dispose(); xDoc.Validate(xss, null); A: I have found the problem after a frustrating day and a half of iterations. Changing: FileStream fs = new FileStream(xsdPath, FileMode.Open); XmlReader reader = XmlReader.Create(fs); XmlSchemaSet xss = new XmlSchemaSet(); xss.Add("", reader); to XmlSchemaSet xss = new XmlSchemaSet(); xss.Add("", xsdPath); solved the problem. However I am still looking for the answer to WHY? Both are valid ways of adding a schema to the schema set (i.e. 2 overloads). A: arootbeer is right about how your xsd imports another xsd. However another solution is to add the the imported xsd into the XmlSchemaSet first, then add the xsd that is doing the actual importing. //Xsd file that is being imported FileStream importedXsdStream = new FileStream(importedXsdPath, FileMode.Open); XmlReader xmlReader = XmlReader.Create(importedXsdStream); XmlSchemaSet xmlSchemaSet = new XmlSchemaSet(); xmlSchemaSet.Add("NameSpace.SomeNameSpace", xmlReader); //Your code FileStream fs = new FileStream(xsdPath, FileMode.Open); XmlReader reader = XmlReader.Create(fs); XmlSchemaSet xss = new XmlSchemaSet(); xss.Add("", reader); Notice I put the Namespace as the first parameter when adding the imported xsd to the XmlSchemaSet. This may be necessary depending on if there are errors with the target namespace not matching the namespace provided in the imported xsd.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: SQLite3 database opens but doesn't show table data in Android emulator I am trying to view a single table data from android emulator sqlite shell. It shows the database is there, but when I run a query on it, I get the error "Error: no such table: note". Here is the output seq name file --- --------------- ---------------------------------------------------------- 0 main /data/data/myapp.barcode/databases/barcodedb.db 1 temp sqlite> select * from note; select * from note; Error: no such table: note I have pulled the database file from DDMS perspective, and shows the concerned table with all rows. I have tried to open the shell while app is running, then quitting the app and running shell command, but no change in error message. Any clues, as how I might be able to open, update the table from shell? A: Type .tables and verify that table note exists while in the sqlite shell. See this for a sqlite reference. A: Thanks for all the replies, I have figured out what I was doing wrong. I was referring to the wrong database i.e. barcodedb.db previously created, while android was populating the new database barcodedb with no extension. A: If .tables shows nothing, it means your database is empty. As you mention an error culd be selecting wrong database file. In order to select correct database you can list all files inside databases folder. $ls -la then look for database name and checking the size. For example(attached image) there are 2 files ATC_MOVIL_DB and ATC_MOVIL_DB.db, the correct one would be ATC_MOVIL_DB because of it size.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Elegant indexing up to end of vector/matrix Is it possible in R to say - I want all indices from position i to the end of vector/matrix? Say I want a submatrix from 3rd column onwards. I currently only know this way: A = matrix(rep(1:8, each = 5), nrow = 5) # just generate some example matrix... A[,3:ncol(A)] # get submatrix from 3rd column onwards But do I really need to write ncol(A)? Isn't there any elegant way how to say "from the 3rd column onwards"? Something like A[,3:]? (or A[,3:...])? A: You can use the following instruction: A[, 3:length(A[, 1])] A: For rows (not columns as per your example) then head() and tail() could be utilised. A <- matrix(rep(1:8, each = 5), nrow = 5) tail(A, 3) is almost the same as A[3:dim(A)[1],] (the rownames/indices printed are different is all). Those work for vectors and data frames too: > tail(1:10, 4) [1] 7 8 9 10 > tail(data.frame(A = 1:5, B = 1:5), 3) A B 3 3 3 4 4 4 5 5 5 For the column versions, you could adapt tail(), but it is a bit trickier. I wonder if NROW() and NCOL() might be useful here, rather than dim()?: > A[, 3:NCOL(A)] [,1] [,2] [,3] [,4] [,5] [,6] [1,] 3 4 5 6 7 8 [2,] 3 4 5 6 7 8 [3,] 3 4 5 6 7 8 [4,] 3 4 5 6 7 8 [5,] 3 4 5 6 7 8 Or flip this on its head and instead of asking R for things, ask it to drop things instead. Here is a function that encapsulates this: give <- function(x, i, dimen = 1L) { ind <- seq_len(i-1) if(isTRUE(all.equal(dimen, 1L))) { ## rows out <- x[-ind, ] } else if(isTRUE(all.equal(dimen, 2L))) { ## cols out <- x[, -ind] } else { stop("Only for 2d objects") } out } > give(A, 3) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 1 2 3 4 5 6 7 8 [2,] 1 2 3 4 5 6 7 8 [3,] 1 2 3 4 5 6 7 8 > give(A, 3, dimen = 2) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 3 4 5 6 7 8 [2,] 3 4 5 6 7 8 [3,] 3 4 5 6 7 8 [4,] 3 4 5 6 7 8 [5,] 3 4 5 6 7 8 A: Sometimes it's easier to tell R what you don't want. In other words, exclude columns from the matrix using negative indexing: Here are two alternative ways that both produce the same results: A[, -(1:2)] A[, -seq_len(2)] Results: [,1] [,2] [,3] [,4] [,5] [,6] [1,] 3 4 5 6 7 8 [2,] 3 4 5 6 7 8 [3,] 3 4 5 6 7 8 [4,] 3 4 5 6 7 8 [5,] 3 4 5 6 7 8 But to answer your question as asked: Use ncol to find the number of columns. (Similarly there is nrow to find the number of rows.) A[, 3:ncol(A)] [,1] [,2] [,3] [,4] [,5] [,6] [1,] 3 4 5 6 7 8 [2,] 3 4 5 6 7 8 [3,] 3 4 5 6 7 8 [4,] 3 4 5 6 7 8 [5,] 3 4 5 6 7 8 A: A dplyr readable renewed approach for the same thing: A %>% as_tibble() %>% select(-c(V1,V2)) A %>% as_tibble() %>% select(V3:ncol(A))
{ "language": "en", "url": "https://stackoverflow.com/questions/7500644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "89" }
Q: How to set vim to unindent when meets a empty line in Python? It could be useful if vim could do a unindentation automatically when I type an empty line, but it seems it is not the default behavior. This would especially useful for Python, could Vim be configured to do so? A: I made some mods to my own indent/python.vim to enable full dedent when the third empty line is entered. You may be able to adapt this to your needs. diff --git a/python.vim b/python.vim index 0c04e81..c60c30e 100644 --- a/python.vim +++ b/python.vim @@ -142,8 +142,14 @@ function GetPythonIndent(lnum) " If not, recommend one dedent return indent(plnum) - &sw endif - " Otherwise, trust the user - return -1 + + " Is user trying to break out of this function? + if plnum < a:lnum - 2 + return 0 + else + " Otherwise, trust the user + return -1 + endif endif " If the current line begins with a keyword that lines up with "try" @@ -186,6 +192,11 @@ function GetPythonIndent(lnum) return plindent endif + " Double linebreaks means we're starting a new function (probably) + if plnum < a:lnum - 2 + return 0 + endif + return -1 endfunction
{ "language": "en", "url": "https://stackoverflow.com/questions/7500645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: understanding jquery ui autocomplete json I am very new to programming and I am stumped with this problem. I want to create am autocomplete textbox. From what I see I would need to use json. However for the source of the json I need a url to a file script, and I do not quite get this part. This is an example from http://jqueryui.com/demos/autocomplete/#option-source $( "#birds" ).autocomplete({ source: "search.php", minLength: 2, select: function( event, ui ) { log( ui.item ? "Selected: " + ui.item.value + " aka " + ui.item.id : "Nothing selected, input was " + this.value ); } }); Does it mean that whenever I type something in the autocomplete textbox it accesses the file in the url and the file script would change dynamically according to my input? Also, I can only see some examples of the url file in php. Can it be done in Django? such as specifying a url as the source and link that url with a view outputting the data? A: Whenever you type something in the autocomplete textbox it accesses the url to retrieve the array of data. (Use firebug or chrome developer tools while testing the demo to see the HttpRequests sent as you type) From the documentation you linked: "When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data." So yes, you can use Django as long as the URL returns JSON data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: return to the application using phonegap I am not able to return to my application after loading a webpage.Is there any way to return to the application after loading web page in iphone when we use phonegap? A: Your question is the use case for the PhoneGap ChildBrowser plugin in. See here
{ "language": "en", "url": "https://stackoverflow.com/questions/7500649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: better performance in vector to string array possible duplicate As question was asked How to convert Vector to String array in java which one is the best performance for store the vector value to String array. And how it will perform in background? Vector<String> v = new Vector<String>(); // this one String s[] = v.toArray(new String[v.size()]); // or this one String s[] = v.toArray(new String[0]); A: As a general rule of thumb, it's faster to properly size an array or collection the first time, because it prevents the need to resize it one or more times later. Less work == faster. BTW, you almost certainly shouldn't be using a Vector; an ArrayList is a better choice in the vast majority of cases. UPDATE: For your particular case, the results are going to be heavily dependent on the data in your Vector. As with any question about performance, you should profile it for yourself. Since you've said you don't know how to benchmark, I suggest you read up on profiling and performance measurement for Java applications. If you aren't measuring things, you shouldn't waste your time worrying about the performance of standard library operations. You're likely worrying about things that have nothing to do with the actual bottlenecks in your applications. A: I had expected new String[list.size()] to be fastest, however this appears to result in an extra lock for Vector, making it slower. import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Vector; public class Main { private static final String[] NO_STRINGS = {}; private static final int runs = 50000000; public static void main(String... args) { List<String> strings = Arrays.asList("one,two,three,four,five,six".split(",")); List<String> arrayList = new ArrayList<String>(strings); Vector<String> vector = new Vector<String>(strings); testNoStrings(arrayList); testStrings0(arrayList); testSize(arrayList); testNoStrings(vector); testStrings0(vector); testSize(vector); } private static String[] testSize(List<String> list) { String[] ret = null; long start = System.nanoTime(); for (int i = 0; i < runs; i++) ret = list.toArray(new String[list.size()]); long time = System.nanoTime() - start; System.out.printf(list.getClass().getSimpleName() + " Using new String[list.size()] took an average of %,d ns%n", time / runs); return ret; } private static String[] testNoStrings(List<String> list) { String[] ret = null; long start = System.nanoTime(); for (int i = 0; i < runs; i++) ret = list.toArray(NO_STRINGS); long time = System.nanoTime() - start; System.out.printf(list.getClass().getSimpleName() + " Using NO_STRINGS took an average of %,d ns%n", time / runs); return ret; } private static String[] testStrings0(List<String> list) { String[] ret = null; long start = System.nanoTime(); for (int i = 0; i < runs; i++) ret = list.toArray(new String[0]); long time = System.nanoTime() - start; System.out.printf(list.getClass().getSimpleName() + " Using new String[0] took an average of %,d ns%n", time / runs); return ret; } } Any difference you see is highly likely to be machine dependant, however one obvious factor is that ArrayList is faster than Vector. ArrayList Using NO_STRINGS took an average of 17 ns ArrayList Using new String[0] took an average of 22 ns ArrayList Using new String[list.size()] took an average of 27 ns Vector Using NO_STRINGS took an average of 28 ns Vector Using new String[0] took an average of 29 ns Vector Using new String[list.size()] took an average of 46 ns
{ "language": "en", "url": "https://stackoverflow.com/questions/7500651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Autosys Box run configuration I have an Autosys box and there is a couple of jobs inside it. For example, MY_BOX is the name of the box and it has the jobs JOB_1 and JOB_2. I would like to configure the box in such a way that it runs continuously. (i.e.) as soon as the JOB_2 completes (success or failure), MY_BOX should start running again. Could you please tell me how to configure this? I tried setting the "run condition" for MY_BOX as SUCCESS(JOB_2), however, the Box does not start after the completeion of JOB_2. A: I'm not exactly sure how to make MY_BOX run immediately after the success of JOB_2, but you could set the interval on which MY_BOX runs to just about (or a little bit more) than the average run of MY_BOX. I.E. - if MY_BOX runs for about 10 minutes, have MY_BOX run every ten/eleven minutes. Or try setting it's condition to the SUCCESS(MY_BOX). A: You can also give the condition as done(MY_BOX) to the MY_BOX as you want the MY_BOX to run immediately irrespective of the success or failure of JOB_2. If the JOB_2 fails then the MY_BOX also fails then the condition success(MY_BOX) will not make the MY_BOX to run. So if you give the condition as done(MY_BOX),irrespective of the success or failure of MY_BOX, the MY_BOX will start running immediately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Maven Jar signing and target rearrangement I'm converting an Ant based project to be buildable by Maven. Standard build is working for now. I'm trying to migrate the additional build targets which are specified in the original Ant build descriptor. Our project can be deployed as a desktop application or as a Web Start launchable client. You can invoke the original Ant file naturally with dist, which simply builds the project but doesn't do post processing for web start, and also there's a dedicated target for JWS which calls dist, then do jar signing and rearranging the distribution files to be be easily deployable to the web server. I've found out that Maven has a Jarsigner plugin for doing code signing. My project currently builds the core jar, copies all artifact dependencies to target, creates the correct manifest file for the core jar, and also unpacks the configuration artifact to target/ (this contains various things, like XMLs and property files). However i don't know how to fit into the Maven descriptor the following additional steps: * *Sign all jar files (also external dependencies), removing existing signatures as well. *Rearrange the resulting jar files to a different directory layout. I also need to edit XML files for this configuration and pack them to a configuration jar which needs to get signed also. After modification the project have to be buildable the standard way. So Web Start build have to be optional. I should note that we are using NetBeans to build/debug/profile the application. I'm a little bit lost how to achive these with Maven. Could someone please give some suggestion how should i move forward? A: I've solved my problem this way: * *I've created a new jar module for the web start client configuration. During build Maven unpacks only those parts of the original config artifact to the build directory which are required for Web Start (you can specify filter rules for the dependency-unpack plugin). Then i'm using the Maven XML plugin to modify XML files using XSLT templates. Finally Maven takes care of packaging all these to a web start client configuration artifact. *I've also created a pom only module for the actual web start client building. This project has no classical artifact output so only the POM gets installed to the artifact repository. This module has dependencies for the source code (excluding original configuration) and for the web start client artifact. I'm using the dependency copying capability of Maven to arrange jar files in the correct structure in target directory. Finally i'm using the Maven jarsigner to sign all jars.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My tableview crash when i scroll I don't undestand... i succeed in populate my table view but when i scroll it crash without message.. i create my tabQuestion with a NSMutablearray and then add this in my delegate : cellForRowAtIndexPath NSDictionary *question = [self.tabQuestion objectAtIndex:indexPath.row]; [cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator]; cell.textLabel.text = [NSString stringWithFormat:@"%@", [question objectForKey:@"question"]]; cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [question objectForKey:@"reponse"]]; if ([[question objectForKey:@"bOk"] isEqualToString:@"1"]) { cell.imageView.image = [UIImage imageNamed:@"ok.png"]; } else { cell.imageView.image = [UIImage imageNamed:@"ok.png"]; } [question release]; return cell; A: You shouldn't release objects that were returned by method objectAtIndex: of NSArray. It happens very rare. Try to remove first of all line: [question release]; Then check if your self.tabQuestion contains needful amount of objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Close topic once Paypal purchase is made I have an option on my phpBB forum to add a Paypal Buy Now button to enable users to sell and purchase items. I would like to have the ability to automatically close a topic once a user makes a purchase through paypal to avoid multiple users from purchasing the same item. Is it possible to get the user's session data from paypal once they make a transaction? Then incorperate session data into a variable like: $paypal = (isset($_POST['purchased'])) ? true : false; Not sure if I need to download the Paypal SDK for this or not. Any suggestions would be great, thanks. A: Is it possible to get the user's session data from paypal once they make a transaction? You really want to trust the user's session data? I am sure you can read the session data, you don't want to do that, would be trivial task to alter it. Even if you can you really shouldn't read the session data for another website. Not sure if I need to download the Paypal SDK for this or not. This would be the correct way to do it. A: When I last used it, Paypal Standard allowed you to specify a return URL (where to send the user) for failures and for successes. Dynamically generate some secret hashes to facilitate when the user is finally redirected. Or you can use IPN. A: Don't rely on the return URL. Buyers can (and will) close their browser / tab after completing a payment. Instead, use PayPal Instant Payment Notifications to receive a server-to-server notification from PayPal which you can subsequently verify and use to update your database with the appropriate flag for a phpBB closed thread. IPN works as follows: * *You create the PayPal and incude a "notify_url". The value for this parameter will be the full URL to a script on your server, called the 'IPN script' or 'IPN handler'. You can specify an IPN handler as follows for Website Payments Standard <input type="hidden" name="notify_url" value="http://blah.com/ipn.php For Express Checkout or Website Payments Pro, simply include the following in your SetExpressCheckout/DoExpressCheckoutPayment or DoDirectPayment API call respectively. NOTIFYURL=http://blah.com/ipn.php * *A buyer completes a transaction via PayPal *Once the buyer completes the transaction, he/she may close the browser, or return to your website *Once the transaction is accepted and processed by PayPal, PayPal will send out a notification to http://blah.com/ipn.php *You need to take all POST data that was sent to this script, and POST it back to https://www.paypal.com/cgi-bin/webscr?cmd=_notify-validate *If the data you send back matches the data PayPal sent you, a 'VERIFIED' response is returned. *If the response is VERIFIED, it's at this point that you would look up the matching transaction/buyer on your end, and update the phpBB thread status appropriately. Some sample code and documentation for PayPal IPN is available at https://www.paypal.com/ipn/ In addition, some tips on making a secure IPN script are available at https://www.x.com/developers/community/blogs/ppmtsrobertg/securing-your-instant-payment-notification-ipn-script Note: If you want to include any custom data along with the transaction which you can read out later, use 'custom'. <input type="hidden" name="custom" value="xxxxx"> This will also be returned in the IPN POST data sent from PayPal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem in Setting Style of a button I am setting the following style to a button: <Style x:Key="CustomButtonStyle1" TargetType="Button"> <Setter Property="Background" Value="Transparent"/> <Setter Property="BorderBrush" Value="{StaticResource PhoneForegroundBrush}"/> <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/> <Setter Property="BorderThickness" Value="{StaticResource PhoneBorderThickness}"/> <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiBold}"/> <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMediumLarge}"/> <Setter Property="Padding" Value="10,3,10,5"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid Background="Transparent"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"/> <VisualState x:Name="MouseOver"/> <VisualState x:Name="Pressed" /> <VisualState x:Name="Disabled"/> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer"> <DiscreteObjectKeyFrame KeyTime="0" Value="White"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <ImageBrush ImageSource="Images/aaa2.png"/> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}"> <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/> </Border> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> However i'm getting the following error which i don't know how to resolve: Error 1 Cannot add instance of type 'System.Windows.Media.Animation.Storyboard' to a collection of type 'MS.Internal.!VisualStateCollection'. [Line: 23 Position: 17] The button is defined as follows: <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,30,0,0"> <Button Name="aaa" Width="200" Content="aaa" Margin="0,0,-10,0" Click="aaa_Click" BorderThickness="0" BorderBrush="{x:Null}" Height="91" Foreground="Black" Style="{StaticResource CustomButtonStyle1}"> <Button.Background> <ImageBrush ImageSource="../Images/aaa.png"/> </Button.Background> </Button> A: The Storyboard should be inside a VisualState. <VisualState x:Name="Pressed"> <Storyboard>...</Storyboard> </VisualState>
{ "language": "en", "url": "https://stackoverflow.com/questions/7500663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JMagick - How to convert a picture from CMYK to RGB? I know there exists another post dealing with that problem How to convert colorspace using JMagick? but but there is something I do not understand: String baseName = "Pictures/"; String fileName = "dragon.gif"; MagickImage imageCMYK; try { ImageInfo info = new ImageInfo( baseName + fileName); info.setColorspace(ColorspaceType.CMYKColorspace); System.out.println("ColorSpace BEFORE => " + info.getColorspace()); imageCMYK = new MagickImage( info ); System.out.println("ColorSpace AFTER => " + imageCMYK.getColorspace()); When I create the new MagickImage, the CMYKColorSpace is not kept as I obtain : ColorSpace BEFORE => 12 (CMYK) How to correctly convert a picture from CMYK to RGB ? Thanks. ColorSpace AFTER => 1 (RGB) A: Update: You are using GIF images. They don't support "CMYK" so the transform won't work for you (see this forum post at imagemagick's web site)! Use MagicImage.rgbTransformImage(ColorspaceType.CMYKColorspace). From the API: public boolean rgbTransformImage(int colorspace) throws MagickException Converts the reference image from RGB to an alternate colorspace. The transformation matrices are not the standard ones: the weights are rescaled to normalized the range of the transformed values to be [0..MaxRGB]. Example: try { MagickImage image = new MagickImage(new ImageInfo(baseName + fileName)); if (!image.rgbTransformImage(ColorspaceType.CMYKColorspace)) throw new Exception("Couldn't convert image color space"); ... } catch (MagickException e) { ... } A: This still won't work for other image formats such as PNG.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Allow dirty reads of rows changed by certain transaction I have a transaction which changes data in Sql Server 2008 database. Is there are any way to allow reading of dirty data for concurrent transactions? I know I can avoid blocking of tables on database level by using of the following code: ALTER DATABASE AdventureWorks SET READ_COMMITTED_SNAPSHOT ON; But I want to allow dirty reads of rows changed only by one certain transaction. Is that possible?
{ "language": "en", "url": "https://stackoverflow.com/questions/7500672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replace éàçè... with equivalent "eace" In GWT I tried s=Normalizer.normalize(s, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", ""); But it seems that GWT API doesn't provide such fonction. I tried also : s=s.replace("é",e); But it doesn't work either The scenario is I'am trying to générate token from the clicked Widget's text for the history management A: You can take ASCII folding filter from Lucene and add to your project. You can just take foldToASCII() method from ASCIIFoldingFilter (the method does not have any dependencies). There is also a patch in Jira that has a full class for that without any dependencies - see here. It should be compiled by GWT without any problems. License should be also OK, since it is Apache License, but don't quote me on it - you should ask a real lawyer. A: @okrasz, the foldToASCII() worked but I found a shorter one Transform a String to URL standard String in Java
{ "language": "en", "url": "https://stackoverflow.com/questions/7500673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: For what reasons does my text contain black diamonds in this brief code? I created a file on my localhost with the following code: <?php header('Content-Type: text/plain; charset=UTF-8'); echo "yoá"; The output in my Firefox is: Why the Unicode replacement character? A: Because your PHP script file is not saved as UTF-8 from inside your editor. All decent editors allow you to convert between and save as several different encodings (even Notepad does this now). Save in UTF-8 and you will see the character appear normally. Technical explanation: The character in question is code point U+00E1 ("latin small letter a with acute"). Supposing that you have saved your script in a single-byte encoding (which is most likely), this character would be represented by the byte with hex value 0xE1, which in binary is 11100001 From the UTF-8 encoding rules, we see that this byte falls in the category 1110zzzz which is the first of exactly three bytes that encode a single character in the code point range U+0800 to U+FFFF. However, in your case there are either no more bytes following this one or if there are they do not satisfy the UTF-8 encoding restrictions. Hence, the browser determines that there is a malformed byte sequence and displays the question mark instead. A: you're sending an utf-8-header but your source-file isn't set to (and saved as) utf-8. check the settings of your code-editor/ide to correct that. A: Try this : header('Content-Type: text/plain; charset=UTF-8'); $txt= "yoá"; echo iconv("ISO-8859-1","UTF-8",$txt); if you are not sure of if string is valid UTF8 then use lib to test it http://hsivonen.iki.fi/php-utf8/ if(is_valid_utf8($txt)==true) ....
{ "language": "en", "url": "https://stackoverflow.com/questions/7500675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: File compression and codes I'm implementing a version of lzw. Let's say I start off with 10 bit codes and increase whenever I max out on codes. For example after 1024 codes, I'll need 11 bits to represent 1025. Issue is in expressing the shift. How do I tell decode that I've changed the code size? I thought about using 00, but the program can't distinguish between 00 as an increment and 00 as just two instances of code zero. Any suggestions? A: You don't. You shift to a new size when the dictionary is full. The decoder's dictionary is built synchronized with the encoder's dictionary, so they'll both be full at the same time, and the decoder will shift to the new size exactly when the encoder does. The time you have to send a code to signal a change is when you've filled the dictionary completely -- you've used all of the largest codes available. In this case, you generally want to continue using the dictionary until/unless the compression rate starts to drop, then clear the dictionary and start over. You do need to put some marker in to tell when that happens. Typically, you reserve the single largest code for this purpose, but any code you don't use for any other purpose will work. Edit: as an aside, note that you normally want to start with codes exactly one bit larger than the codes for the input, so if you're compressing 8-bit bytes, you want to start with 9 bit codes. A: This is part of the LZW algorithm. When decompressing you automatically build up the code dictionary again. When a new code exactly fills the current number of bits, the code size has to be increased. For the details see Wikipedia. A: You increase the number of bits when you create the code for 2n-1. So when you create the code 1023, increase the bit size immediately. You can get a better description from the GIF compression scheme. Note that this was a patented scheme (which partly caused the creation of PNG). The patent has probably expired by now. A: Since the decoder builds the same table as the compressor, its table is full on reaching the last element (so 1023 in your example), and as a consequence, the decoder knows that the next element will be 11 bits.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to fix madExcept creating temporal files in User\LocalSettings\Temp I sterated using "Standard User Analyzer" from Application Compatibility toolkit and it reported that my app is not UAC compatible because: "DeleteFileA: File (\Device\HarddiskVolume1\Documents and Settings\Administrator\Local Settings\Temp\mtgstudio.madExcept) is denied 'DELETE' access with error 0x5." "DeleteFileA: File (\Device\HarddiskVolume1\Documents and Settings\Administrator\Local Settings\Temp) is denied 'DELETE' access with error 0x5." Checking the madExcept.pas file I found: function GetTempPath : AnsiString; var arrCh : array [0..MAX_PATH] of AnsiChar; begin if windows.GetTempPathA(MAX_PATH, arrCh) > 0 then begin result := arrCh; if result <> '' then begin CreateDirectoryA(PAnsiChar(result), nil); if result[Length(result)] <> '\' then result := result + '\'; result := result + KillExt(ExtractFileName(ModuleName(0))) + '.madExcept'; CreateDirectoryA(PAnsiChar(result), nil); result := result + '\'; end; end else result := ''; end; Is there a good way to overwrite the madExcept behaviour and store the temp files in a UAC allowed location? A: It doesn't look like there's anything to fix. The GetTempPath API function is exactly the function to use to get a location where a program is allowed to create temporary files. That the compatibility tester was unable to delete the directories doesn't mean that the directories should have been someplace else. It only means they couldn't be deleted at the time the program tried. It could be that another program (such as the one being tested) had a file open in one of those directories; Windows doesn't allow folders to be deleted when there are open files in them. One possible source of problems is the way MadExcept creates the directories. It creates them such that they inherit the permissions of their parent directories. If deletion is forbidden for the parent directory, then it will also be forbidden for the newly created temp directories. That partly points to a configuration problem on your system: GetTempPath might be returning a path for a directory that doesn't exist. It just returns the first value it finds in any of the TMP, TEMP, and USERPROFILE environment variables. It's the user's responsibility (not your program's) to make sure those are accurate. Knowing that MadExcept uses GetTempPath to discover the temp directory gives you an opportunity. You can call SetEnvironmentVariable to change the TMP value for your process, and MadExcept will create its directory there instead. (But if the system-designated location for temporary files already doesn't work, good luck finding some alternative to use.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7500679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data from my class is null? I have a class holding a boolean, and two doubles, and then an array of that class, I need the boolean and doubles to have defaults values of false, 0.0, and 0.0, and then I have function that refers to an element of the array and the moment I try to access an one of the variables from the class it throws an exception saying its null. Here is my class and my function calling it. public class PanelData { boolean flag = false; double tempStart = 0.0; double tempEnd = 0.0; } private PanelData[] panelInfo = new PanelData[115]; private void panelInfoHandler (int i, double timeStart, double timeEnd) throws SQLException { if (!panelInfo[i].flag) { delete(); insert(); panelInfo[i].flag = true; panelInfo[i].tempStart = timeStart; panelInfo[i].tempEnd = timeEnd; } else if (panelInfo[i].tempStart <= timeStart && panelInfo[i].tempEnd >= timeEnd) { } else { insert(); panelInfo[i].tempStart = timeStart; panelInfo[i].tempEnd = timeEnd; } } here is how I call the class. panelInfoHandler(9, parsedStart, parsedEnd); A: new PanelData[115] creates an array of 115 null references. Have you populated panelInfo with references to actual objects? At a minimum, you then need to loop through that array and create new instances of PanelData for each element in the array, e.g. for (int i = 0; i < panelInfo.length; i++) panelInfo[i] = new PanelData(); A: Your array is full of null elements until you initialize it. To clarify, if you create an array of primitive objects, you get an array of default (i.e. 0) values. However, an array of Objects gets created with null elements. int[] myIntArray = new int[10]; // 10 default values of 0 Integer[] myIntegerArray = new Integer[10]; // 10 null elements A: add this line and then assign the values: if(panelInfo[i] == null) panelInfo[i] = new PanelInfo(); A: You need to do something like for(int i=0;i<115; i++) { PanelInfo[i] = new PanelData(); } (Or whatever is the correct Java Syntax) A: public class PanelData { boolean flag = false; double tempStart; double tempEnd; public PanelData() { flag = false; tempStart = 0.0; tempEnd = 0.0; } private PanelData[] panelInfo = new PanelData[115]; for(int i = 0; i < 115; i++) panelInfo[i] = new PanelData(); Creating the default constructor lets you instantiate the variables with the default values (false, 0.0, 0.0) in this case so you can test if you are getting a vanilla object back or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TableView's indexPathsForVisibleRows returns data for old screen orientation I am dynamically changing annotations on the map based on the tableview's items that are visible (works ok when user scrolls in tableview). When the screen rotation changes, i call indexPathsForVisibleRows in willAnimateRotationToInterfaceOrientation to show the pins for the visible tableviews, but indexPathsForVisibleRows doesn't return data for new orientation. When and where should i call indexPathsForVisibleRows to get the correct data for new orientation? A: You should call it in - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation Sent to the view controller after the user interface rotates. Method - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration Sent to the view controller before performing a one-step user interface rotation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Format string like a chemical formula What is the best way to convert a string such as CO2 and make it output CO<sub>2</sub> via PHP? A: Use preg_replace() to surround groups of digits with <sub></sub> $input = "CO2"; echo preg_replace('/(\d+)/', '<sub>$1</sub>', $input); // Using $input = "H2SO4"; // Prints: H<sub>2</sub>SO<sub>4</sub> A: This will correctly NOT sub some of the digits. $s = "O2+2H2=H2O"; $len = strlen($s); $html = ''; if($len > 0) { $prev = $s[0]; $html = $prev; for($i=1;$i<$len;$i++){ $ch = $s[$i]; if(is_numeric($ch) && 'a' <= strtolower($prev) && strtolower($prev) <= 'z') { $html .= "<sub>$ch</sub>"; } else { $html .= $ch; } $prev = $ch; } } echo $html; prints O2+2H2=H2O Note the non-sub-ed 2 A: Do you know LaTeX? It renders fomulars very nicely. You could use it on your page by including <script language="JavaScript" src="http://thewe.net/tex/textheworld6.user.js"></script> and writing your fomular like this [;CO_2;] see here. A: //With ions in the equation: // charge written like: sign number $s= "1H2SO4=> 2H+1 + 1SO4-2 " ; //$s = "1O2 + 2H2=> 2H2O"; $len = strlen($s); $html = ''; if($len > 0) { $prev = $s[0]; $html = $prev; for($i=1;$i<$len;$i++) { $ch = $s[$i]; if(is_numeric($ch) && 'a' <= strtolower($prev) && strtolower($prev) <= 'z') { $html .= "<sub>$ch</sub>"; } else { if(($ch=="+" or $ch=="-") && '1' <= strtolower($s[$i+1]) && strtolower($s[$i+1]) <= '9') { $html .= "<sup>$ch</sup>"; $html .= "<sup>".$s[$i+1]."</sup>"; $i=$i+1; } else { $html .= $ch; } $prev = $ch; } } } echo $html; A: The better way would be: preg_replace('/([A-Z)])([0-9]+)/', '\1<sub>\2</sub>', $input) That way you wouldn't have individual <sub> and </sub> around numbers higher than 9 next to each other (e.g., <sub>12</sub> and not <sub>1</sub><sub>2</sub>). It also accounts for parentheses and when you have numbers before the letters. A: function formular($string){ $string .= ' '; $len = strlen($string); $str_return = ''; if($len > 0) { $prev = $string[0]; $str_return = $prev; for($i = 1; $i < $len; $i++){ $ch = $string[$i]; if(is_numeric($ch)){ if('a' <= strtolower($prev) && strtolower($prev) <= 'z' || $prev == ')'){ if(( $string[$i+1] == '-' || $string[$i+1] == '+') && !in_array(@$string[$i+2], ['C', 'O', 'H'])){ $str_return .= '<sup>' . $ch . '</sup>'; $str_return .= '<sup>' . $string[$i+1] . '</sup>'; $i++; }else{ $str_return .= "<sub>$ch</sub>"; } }else{ $str_return .= $ch; $prev = $ch; } }else{ $str_return .= $ch; $prev = $ch; } } } return $str_return; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7500686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RVM: "sha256sum nor shasum found" I've just installed RVM on a new machine and when switching into a directory containing a .rvmrc file (which I've accepted) I'm getting: ERROR: Neither sha256sum nor shasum found in the PATH I'm on OS X 10.5.8. — Probably missing something somewhere. Any ideas what's going on and how to fix this? A: ciastek's answer worked for me until I tried to run rvm within a $() in a bash script - rvm couldn't see the sha256sum function. So I created a file called sha256sum with the following contents: openssl sha256 "$@" | awk '{print $2}' put it in ~/bin, made it executable, and added that folder to my path (and removed the function from my .bashrc). (Many thanks to my coworker Rob for helping me find that fix.) A: Means you're missing the binary in /usr/bin or your path is somehow missing /usr/bin. Open a new shell and run echo $PATH | grep '/usr/bin' and see if its returned. Also, ls -alh /usr/bin/shasum and make sure the binary is there and executable. There is no sha256sum on OS X, just shasum. A: On MacOS Sierra run $ shasum -a 256 filename Based on @vikas027 comment just add alias sha256sum='shasum -a 256' to your ~/.zshrc A: In my opinion Leopard just doesn't have /usr/bin/shasum. Take a look at shasum manpage - this manpage is only for Snow Leopard. Other manpages, like ls manpage (can't link to it, not enough reputation), are for previous versions of MacOS X. Workaround: Use OpenSSL to calculate sha256 checksums. Leopards' OpenSSL (0.9.7) doesn't handle sha256. Upgrade OpenSSL. I've used MacPorts (can't link to it, not enough reputation). OpenSSL's dependecy zlib 1.2.5 required to upgrade XCode to 3.1. Can I get Xcode for Leopard still? is helpful. Alias sha256sum to OpenSSL and correct the way it formats an output. I've put in my .bash_profile: function sha256sum() { openssl sha256 "$@" | awk '{print $2}'; } A: I'm on a relatively fresh install of Lion (OS X 10.7.4). In my /usr/bin/ folder I had these files: -rw-rw-rw- 35 root wheel 807B /usr/bin/shasum -rwxr-xr-x 1 root wheel 7.5K /usr/bin/shasum5.10 -rwxr-xr-x 1 root wheel 7.5K /usr/bin/shasum5.12 I had a shasum, it just wasn't marked as executable. A quick sudo chmod a+x /usr/bin/shasum solved the issue for me. A: My OpenSSL happened to not have a sha256 enc function for some reason: $ openssl sha256 openssl:Error: 'sha256' is an invalid command. After some googling, I found that there is an equivalent called gsha256sum that comes with the homebrew recipe "coreutils". After installing that (brew install coreutils), I had a gsha256sum binary in /usr/local/bin, so it was just a matter of symlinking it: $ sudo ln -s /usr/local/bin/gsha256sum /usr/local/bin/sha256sum That fixed it for me. A: For mac os X 10.9.5 and you profile get /usr/bin path date +%s | shasum | base64 | head -c 32 ; echo A: And if you found yourself here in 2022 wondering what works on the latest Mac (Mac OS Big Sur). Do following. sudo brew install coreutils sudo ln -s /usr/bin/shasum<Version_for_your_installation> /usr/local/bin/sha256sum
{ "language": "en", "url": "https://stackoverflow.com/questions/7500691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: jQuery UI Multiple Dialog & PHP I am having some issues with having multiple dialogs on one page and linking them to IDs that are being generated by PHP. I would like multiple image to be links to a dialog containing the content... here is my code: PHP: <div id="children"> <?php $children = array_values(get_pages(array('child_of' => $post->ID))); foreach( $children as $ch => $child ){ echo '<div id="dialog-'.$child->ID.'" title="Basic dialog">'; echo $child->post_content; echo '</div>'; } foreach( $children as $ch => $child ){ $attachments = get_posts(array('numberposts'=> 1, 'post_parent' => $child->ID, 'post_type' => 'attachment', 'order' => 'DESC', 'orderby' => 'post_date')); //print_r($attachments); foreach( $attachments as $a => $attachment ){ echo '<a href="#opener-'.$child->ID.'" id="opener-'.$child->ID.'" >'; echo '<img class="attachment-thumb" src="'.$attachment->guid.'" width="150" height="150" />'; echo '</a> '; } } //print_r($children) ?> Now I realize that my jQuery is producing each id with 1,2,3 rather than the actual PHP IDs, but I dont know how to set it so jQuery will link to the proper dialogs and openers. Do I need to use Ajax? jQuery: <script> $(function() { var options = { autoOpen: false, width: 'auto', modal: true }; var num = 1; $("#children").each(function() { var dlg = $('#dialog-' + num).dialog(options); $('#opener-' + num).click(function() { dlg.dialog("open"); return false; }); num = num + 1; }); }); </script> </div> A: $("#children").each only runs once, for the one "children" div. Thus num never becomes greater than 1 in this function. You likely want $("#children div").each, which will execute for all the div children of 'children'. (Well technically num becomes 2 (after 1 executes)... but never gets executed while 2.) A: Tutorial on targeting dynamic elements with jquery.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error : Detected background switch for MyApp(24) who has NO tunnels open - defocus NOT called when i run or debug my BB application i got this Detected background switch for MyApp(180) who has NO tunnels open - defocus NOT called Error i have no idea regarding this that how this error occur . my application install in Simulator and device but no effect after click on application icon. i have done clean all simulator and get suggetion from this url link and change my rimpublic from eclipse >plugin > MDS > config folder please let me some suggetion regarding same :( Thanks in Advance !!!! A: Kindly clean the simulator. work in blackberry perspective and you will see new buttons related to blackberry development! Press the 'Clean Simulator' or Press ALT+SHIFT+E and this will open box and asked choose the project. Then select you project and try again to run your app!
{ "language": "en", "url": "https://stackoverflow.com/questions/7500695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Telerik RadScheduler - select multiple resources I'm using Telerik scheduler to display a Timeline view of meetings. The resources derive from the Person class, and they are Advocate, and Legislator. On the Y axis, I am listing Advocates, and on the X axis, I am listing blocks of time in one hour increments. When I double click an appointment, the Edit Appointment modal dialog pops up and lists Advocates and Legislators. Since meetings will have multiple advocates and possibly multiple legislators in attendance, I would like to have a checkbox list inside the resource dropdowns on the edit screen. Is there any way to accomplish this? I believe this will allow me to solve one problem in that, if Peter Pan and Homer Simpson both are to attend the same meeting, clicking the meeting in the row for either of those two advocates will display 'Peter Pan' in both instances (or sometimes '-', not yet sure where that comes from) rather than 'Homer Simpson' where I open up the meeting from his row. If it is not possible to introduce checkboxes to the resources list, can you suggest an alternate way around the ultimate issue in the above paragraph? Thanks in advance. A: Telerik supports the adding of a listbox to support what you are trying to do. On the Scheduler itself add the code below that mimics your field names that your advocates are pulling from in your DB: <ResourceTypes> <telerik:ResourceType DataSourceID="SqlDataSource2" ForeignKeyField="Adv_AdvocateID" KeyField="Adv_AdvocateID" Name="Advocate" TextField="Adv_FullName" AllowMultipleValues="true" /> </ResourceTypes> The next step is to populate the resources using a custom provider. See this program here for a great project in which you can see resource population in action. Using the SchedulerDBProvider class you can then adjust their example to more represent your fields and populate the appointments accordingly with your desired ResourceTypes. A: In terms of getting that particular drop down to have multiple selections via checkboxes you would most likely have to define your own custom advanced template. This route allows you to take a UserControl and use that as the edit view for your appointments. There's a demo that displays all of this (including source code) right here. However, having that RadComboBox there might not even be the ideal approach to take. What about just a simple list of checkboxes? This demo shows off how a very simple declaration for the RadScheduler can achieve this functionality. Additionally, there is some code-behind (both in C# and VB.NET) that shows off how you can customize the text on each appointment, which might be helpful in the case that you're referring to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: Programmatically Setting width of Child View using Percentage I've read this article: Setting width of Child View using Percentage So far it works great if we set the weight and width in XML but I want to do it programmatically. I've a table in my layout (XML) and I am adding rows to it programmatically. In each row, I am adding 2 Text Views. I tried doing like this: TableLayout tl = (TableLayout)findViewById(R.id.myTable); for(int i = 0; i < nl.getLength(); i++){ NamedNodeMap np = nl.item(i).getAttributes(); TableRow trDetails = new TableRow(this); trDetails.setBackgroundColor(Color.BLACK); TextView tvInfo = new TextView(this); tvInfo.setTextColor(Color.WHITE); tvInfo.setGravity(Gravity.LEFT); tvInfo.setPadding(3, 3, 3, 3); tvInfo.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10); tvInfo.setText("info"); TextView tvDetails = new TextView(this); tvDetails.setTextColor(Color.WHITE); tvDetails.setGravity(Gravity.LEFT); tvDetails.setPadding(3, 3, 3, 3); tvDetails.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10); tvDetails.setText(np.getNamedItem("d").getNodeValue()); trDetails.addView(tvInfo, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 0.50f)); trDetails.addView(tvDetails, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 0.50f)); tl.addView(trDetails,new TableLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); } but with no luck, it shows blank screen but if I do it in XML then it shows perfectly. Please help me sorting out this issue where I am doing wrong? Thanks A: You should use TableRow.LayoutParams and not Linearlayout.LayoutParams trDetails.addView(tvInfo, new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 0.50)); trDetails.addView(tvDetails, new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 0.50));
{ "language": "en", "url": "https://stackoverflow.com/questions/7500703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: regex for accepting spaces only between words I am trying to create a regular expression where the user should enter just a word or words with space between them and its length must have a limit [1 to 32]. For instance, it should accept below line; wordX[space]wordX[space][space][space]wordX but it should not accept that: [space]wordX or wordX[space] or only [space] wordX must be compatible with this regex: ^(([0-9A-Za-z!"#$%'()*+,./:;=?@^_`{|}~\\\[\]-]))$ A: Try this: ^(?:\w+\s){0,31}\w+$ \w means: digits, letters, underscore For strictly accepted chars: ^(?:[\w!"#$%'()*+,./:;=?@^_`{|}~\\\[\]]+\s){0,31}[\w!"#$%'()*+,./:;=?@^_`{|}~\\\[\]]+$ Or: ^(?:\S+\s){0,31}\S+$ \S - any character other than whitespace Update: If word length is between 1 and 32 than use this regex: ^(?:\w{1,31}\s)*\w{1,31}$ In the same manner you can modify other regexes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: UIImageView rotates my UIImage I'm trying to show an image taken through the camera in Portrait mode but I always get it shown on my UIImageView in Landascape mode. The image is scaled before being added to the UIImageView but it seems this is not the problem as I tried many different solutions found on the web (even some quite smart ones like the one coming from Trevor's Bike Shed). Here is my code: UIImage *image = [UIImage imageWithContentsOfFile:imgPath]; CGRect newFrame = [scrollView frame]; UIImage *resizedImage = [ImageViewController imageFromImage:image scaledToSize:newFrame.size]; imageView = [[UIImageView alloc] initWithFrame:newFrame]; [imageView setImage:resizedImage]; [scrollView setContentSize:imageView.frame.size]; [scrollView addSubview:imageView]; [imageView release]; imgPath is the path of the image coming as a parameter and scrollView is an IBOutlet linked to a UIScrollView. Is there something I'm missing about the UIImageView? As I wrote above, it seems that the problem is not related to the scaling... A: There is an imageOrientation property for a UIImage. Check out the docs. It can be set through the initializer: UIImage *rotatedImage = [UIImage imageWithCGImage:[resizedImage CGImage] scale:1 orientation:UIImageOrientationUp] Creates and returns an image object with the specified scale and orientation factors. + (UIImage *)imageWithCGImage:(CGImageRef)imageRef scale:(CGFloat)scale orientation:(UIImageOrientation)orientation Parameters: * *imageRef The Quartz image object. *scale The scale factor to use when interpreting the image data. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size (page 12) property. *orientation The orientation of the image data. You can use this parameter to specify any rotation factors applied to the image. *Return Value A new image object for the specified Quartz image, or nil if the method could not initialize the image from the specified image reference. A: Are you certain that imageOrientation is set as you expect on resizedImage? Incorrect scaling can absolutely mess up imageOrientation. A: UIImage* image=[UIImage imageNamed:@"abc.jpg"]; UIImageOrientation orientation=image.imageOrientation; Use image in imageView or where ever you want to use, UIImageView* imageView=[[UIImageView alloc] initWithImage:image]; After that reset the image to orientation it was before usage UIImage* image1=[UIImage imageWithCGImage:[image CGImage] scale:1.0 orientation:orientation]; image1 is your image in the orientation it was before
{ "language": "en", "url": "https://stackoverflow.com/questions/7500715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .Net MemberwiseClone vs Java Clone I'm converting C# code to Java. There are many different places that relies on .Net MemberwiseClone in the code I'm converting. It seems that they both make shallow copy. So is it possible to simply replace these calls with Java's clone()? I want to make sure there are not any minor differences that would cause difficult to fix bugs. A: Assuming the clone() call in Java is just calling the Object.clone() implementation, then I believe they have the same behaviour: * *Another object of the same class is created *The fields are copied (up and down the inheritance hierarchy) *All copies are performed in a shallow way *No user-specified code is executed (constructors etc)
{ "language": "en", "url": "https://stackoverflow.com/questions/7500716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Mango Secondary Live Tile issue I have a panorama application and I have successfully created secondary live tile with URI pointing to the desired xaml.cs. Now the xaml part which is separate from mainpage.xaml is of no use to me so what happens is when user goes to the secondary live tile, code from desired.xaml.cs is seen by the user. But when he presses the back button, he goes to an empty page and then goes to homepage and I am aware it is not possible to jump directly to home screen. So how do I solve this issue? If you are wondering how this works - try network dashboard for Windows phone. Quite similar. A: Can't reproduce. When you are navigated from a Live Tile, and presses back, you'll exit the application, since there are no other pages in the navigation stack. The Network Dashboard works the same way. If you somehow managed to have other pages in your navigation-stack , consider removing them using NavigationService.RemoveBackEntry
{ "language": "en", "url": "https://stackoverflow.com/questions/7500725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A simple tutorial on how to call a WCF I have created a simple WCF by following several tutorials. I have modified my web.config file to add the endpoint (whatever that is). I added a ServiceReference to my solution... Now I just want to call the darn thing to see if it works... I found this code when I viewed the service in the browser: ServiceClient client = new ServiceClient(); // Use the 'client' variable to call operations on the service. // Always close the client. client.Close(); But when I plug it into my default.aspx on my website I get errors: The type or namespacen anme 'ServiceClient' could not be found. All I want to do is call it to see how I reference the method (with parameters) and how it returns the data. I just need a jumping point to start working with WCF. Please help. Answered! SnOrfus - His answer did the trick. As soon as I added the ServiceReference to the project then when I hovered over the client variable it prompted me to add ServiceReference name (which was ServiceReference1). I was then able to call my method and display the results. Thanks! A: What is your service interface called and what namespace did you give it when you added it? For instance, if you defined it thusly: [OperationContract] public interface IMyService { [OperationMethod] void MyServiceMethod(); } public class MyService : IMyService { } if you imported it using the Add Service Reference dialog and gave it a namespace of JeffService... it would look like: var client = new JeffService.MyServiceClient(); client.MyServiceMethod(); client.Close(); A: When you added the Service Reference, what namespace did you type in ? Normally, to access it via code you'd just have to use code that looks like this: NameSpace.ClientName client = new NameSpace.ClientName();
{ "language": "en", "url": "https://stackoverflow.com/questions/7500728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: display tag always using the last action I am using displaytable tag to display a table. Below is the code snippet of the same. <display:table export="false" id="admin" class="displaytag" name="requestScope.adminConsoleForm.businessList" style="width:100%" requestURI="/adminConsole.do" pagesize="2" > In the form, i enter some fields and click on save button. The data will be saved and refreshed in the page. But when i click on some other page numbers, it is again performing the save and goes to that clicked page. A: Please use the specific action name for the RequestURI that will be map to the specific action. I faced the similar problem. Please check the below link for details. display tag with struts2 display tag sorting duplicate the last action performed on the page Hope this help. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can git submodule update be made to fetch tags in submodules? I have a git repository which uses a submodule which I'd like to point at an annotated tag, but when I do git submodule update new tags don't get fetched. I can get new tags in the submodule by cd-ing into the submodule and doing a git fetch --tags there, but I'd really like to do all of this from the outside as it's scripted. I can't find anything in the git documentation suggesting a way to get git submodule update to include tags (my git version is 1.7.3.5). Obviously there is another possibility - to point the submodule at the commit which the tag points to rather than the tag itself, but this doesn't seem as neat. Is there a way of getting git submodule update to include tags? A: git submodule update doesn't fetch anything if your submodules are up-to-date. So this might be a misapprehension. git submodule update will bring the working directory contents of the submodules in your repository to the defined state (i.e. check out the submodule commit that has been defined in your repository). A better way would be to cd into your submodule (which is a Git repository itself) and simply run git fetch --tags and then git checkout some-tag. After that the submodule has been updated in your working directory to some-tag and you can stage it for committing. A: Late answer here, but I'm surprised that no one mentioned git submodule foreach. This is basically the way I solved the exact problem you encountered: git submodule foreach --recursive 'git fetch --tags' git submodule update --recursive --recursive flag is there to recurse into child submodules. A: git submodule is implemented as a shell script, so it's easy to see what it's doing — it might be at /usr/lib/git-core/git-submodule if you're using a packaged version. Essentially it just runs git-fetch in the submodule if it the object name (SHA1sum) stored in the main project's tree doesn't match the version checked out in the submodule, as Koraktor points out. The documentation for git fetch (or man git-fetch while kernel.org is down) says that it should fetch every tag that points to a downloaded object, and the downloaded objects will include every commit that's an ancestor of every branch that's fetched. That means it's surprising to me that you don't get all the relevant tags on a git submodule update. If it's the case that what you really want is for your script is to try to set a new submodule version and commit that result, I don't think that git submodule update is the tool that you want - that's just for making sure that your submodules are at the right version based on what's currently in the main project's commit. Instead you should just do something like: ( cd my-submodule && \ git fetch && \ git fetch --tags && \ git checkout my-tag ) git add my-submodule git commit -m 'Update the submodule to the "my-tag" version' my-submodule (I added an extra git fetch --tags just in case your tag isn't one that points to a downloaded commit.) Obviously there is another possibility - to point the submodule at the commit which the tag points to rather than the tag itself, but this doesn't seem as neat. Well, the only thing that's stored in the main project's tree for the submodule is just the hash of the commit object, so even if there were a command that said "set my submodule to the tag my-tag in that submodule", it would end up just storing the hash corresponding to that tag anyway... A: you can script it so that you do a (cd path-to-submod && git fetch) wrapping the commands in brackets puts the environment in a subshell, meaning, you don't have to CD back out to where you were. Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7500741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Never Generate Random Number Again I am looking for a random number generating PHP Solution which did not generate same number again.. is there any solution then please let me know.. I need this solution for one of my Project which generate uniqu key for URL and i don't want to check Generated number is existed or not from the data.. Thanks.. --------- EDIT ---------- I am using this random number generating method is its help full? function randomString($length = 10, $chars = '1234567890') { // Alpha lowercase if ($chars == 'alphalower') { $chars = 'abcdefghijklmnopqrstuvwxyz'; } // Numeric if ($chars == 'numeric') { $chars = '1234567890'; } // Alpha Numeric if ($chars == 'alphanumeric') { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; } // Hex if ($chars == 'hex') { $chars = 'ABCDEF1234567890'; } $charLength = strlen($chars)-1; for($i = 0 ; $i < $length ; $i++) { $randomString .= $chars[mt_rand(0,$charLength)]; } return $randomString; } A: Look at the php function uniqid(): http://php.net/manual/en/function.uniqid.php A: It's impossible to generate a random number which is unique - if the generator is dependent on state, then the output is by definition not random. It is possible to generate a set of random numbers and remove duplicates (although at the numbers again cease to be be truly random). Do you really need a random number or do you need a sequence number or a unique identifier - these are 3 separate things. which generate unique key for URL MySQL and SQLite both support auto-increment column types which will be unique (effectively the same as a sequence number). MySQL even has a mechanism for ensuring uniqueness across equivalent nodes - even where they are not tightly coupled. Oracle provides sequence generators. Both MySQL and PHP have built-in functionality for generating uuids, although since most DBMS support surrogate key generation, there is little obvious benefit to this approach. A: You can use a database... Everytime a random number has shown up, put it in a database and next time, compare the random number of the new script with those already in the database. A: There are no real "perfect and low price" random number generators!! The best that can be done from mathematical functions are pseudorandom which in the end seem random enough for most intents and purposes. mt_rand function uses the Mersenne twister, which is a pretty good PRNG! so it's probably going to be good enough for most casual use. give a look here for more info: http://php.net/manual/en/function.mt-rand.php a possible code implementation is <?php $random = mt_rand($yourMin, $yourMax); ?> EDITD: find a very good explanation here: Generate cryptographically secure random numbers in php A: Use a random number generator, keep stored the already generated values, discard and generate again when you get a duplicate number. Ignore uniqids and stuff like that because they are just plain wrong. A: The typical answer is to use a GUID or UUID, although I avoid those forms that use only random numbers. (Eg, avoid version 4 GUID or UUIDs)
{ "language": "en", "url": "https://stackoverflow.com/questions/7500744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Login button: doesn't work when user is logged in Facebook edit: explanation: When Facebook login button should appear and when not? On facebook tutorial page it is not accurately explained. There is written: "If the user is already logged in, no login button is shown". But for me, it is true only when user is logged in both in facebook profile and my facebook application connected to my website! It is not true, that button is removed when you are logged in just on facebook profile, as it is mentioned on the facebook tutorial. Am I right? – could anybodey help? thanks tomas //old message I have Facebook login button on my website. Sometime visitors are logged in facebook byt are not logged into my website (my application on fb). In this case, Login buton is displayed but does nothing. As I know, Login button should not only log in facebook but also login to my application. It works OK when user is logged out both from facebook and application (website) before clicked. But what if user is logged in just to facebook? Then my button does nothing. A: You can render a button for connect session and another for those with out session. Sample Usage: Using getLoginStatus() to determane if user is connected to app, and XFBML.parse to render the button. https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/ I opted out of using channelURL but you can create your own and read about here. https://developers.facebook.com/docs/reference/javascript/ * *if user is connected and logged in, logout button appears. *if user is not connect but logged into facebook login button appears. *if no session or login login button appears. Async JavaScript SDK <div id="fb-root"></div> <!-- build1 is where we render our button based on connected status. --> <div id="build1"></div> <script> window.fbAsyncInit = function() { FB.init({ appId : 'YourAppId', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true, // parse XFBML //channelUrl : 'http://WWW.MYDOMAIN.COM/channel.html', // channel.html file oauth : true // enable OAuth 2.0 }); if (window!=window.top) { FB.Canvas.setAutoResize(); } FB.getLoginStatus(function(response) { if (response.authResponse) { // logged in and connected user, someone you know // render button Cbuild1 = document.getElementById('build1'); Cbuild1.innerHTML = ""; Cbuild1.innerHTML = "<fb:login-button autologoutlink=\"true\"></fb:login-button>"; FB.XFBML.parse(Cbuild1); } else { // no user session available, someone you dont know // render button Cbuild1 = document.getElementById('build1'); Cbuild1.innerHTML = ""; Cbuild1.innerHTML = "<fb:login-button></fb:login-button>"; FB.XFBML.parse(Cbuild1); } }); }; (function() { var e = document.createElement('script'); e.async = true; e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; document.getElementById('fb-root').appendChild(e); }()); </script> functionality of loginStatus tested here https://shawnsspace.com/fb.test.connect.loginbutton.php A: I have the same problem. I tried Shawn E Carter 's solution and still no improvements. But i observed the new parameter for oauth in the FB.init call. If i set it on true it works as expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Entity Framework one to many relation code first I am having my first steps in EF 4.1. Because I was using NHibenate, the code first approach seems to me as the best one. I have problem with good mapping of one-to-many (or many-to-one) realtionship. Let's say I have 2 entities: class ClientModel { int ClientID; string Name; virtual IList<OrderModel> Orders; } class OrderModel { int OrderID; string Details; virtual ClienModel Client; } When I leave it like that, there is an error while generating database - keys in tables are missing. I figured out I can fix it by changing names of the keys to ID (but it's not OK with my naming convention) or by adding [Key] annotation. Even if I add this annotation, still the names of tables are wrong - just like classes names but with 's'. So I tried to use fluent API - I made mappings. But if I set mappings just like here: class ClientMapping { ClientMapping() { this.HasKey(e => e.ClientID).Property(e => e.ID).HasColumnName("ClientID"); this.Property(e => e.Name).HasColumnName("Name"); this.HasMany(e => e.Orders).WithOptional().Map(p => p.MapKey("OrderID")).WillCascadeOnDelete(); this.ToTable("Clients"); } } class OrderMapping { OrderMapping() { this.HasKey(e => e.OrderID).Property(e => e.OrderID).HasColumnName("OrderID"); this.Property(e => e.Details).HasColumnName("Details"); this.HasRequired(e => e.Client).WithMany().Map(p=>p.MapKey("Client")).WillCascadeOnDelete(false); this.ToTable("Orders"); } } the relation betweene tables in database is doubled. What is the proper way to do one-to-many relationship using code-first approach? Am I thinking in a good direction or is it a wrong approach? EDIT OK, I have done it in the way @Eranga showed, but there is still a problem. When I'm getting Client from database, its Orders property is null (but in database it has some Orders with Order.ClientID == Client.ClientID). A: You need to map both properties participating in the relationship. You need to add ClientID column to Orders table. class ClientMapping { ClientMapping() { this.HasKey(e => e.ClientID).Property(e => e.ID).HasColumnName("ClientID"); this.Property(e => e.Name).HasColumnName("Name"); this.HasMany(e => e.Orders).WithRequired(o => o.Client) .Map(p => p.MapKey("ClientID")).WillCascadeOnDelete(); this.ToTable("Clients"); } } class OrderMapping { OrderMapping() { this.HasKey(e => e.OrderID).Property(e => e.OrderID).HasColumnName("OrderID"); this.Property(e => e.Details).HasColumnName("Details"); this.ToTable("Orders"); } } Configuring the relationship from one entity is sufficient. A: This may help (it helped me, when i couldn't figure out how this works): If you would have the classes like this: class ClientModel { int ClientId; string Name; } class OrderModel { int OrderId; string Details; int ClientId; } Then this would represent 2 tables in your database which "wouldn't" be connected with each other via a foreign key (they would be connected via the ClientId in the OrderModel) and you could get data like "GetAllOrdersWithSomeClientId" and "GetTheClientNameForSomeClientId" from the database. BUT problems would arise when you would delete a Client from the database. Because then there would still be some Orders which would contain a ClientId which doesn't exist in the Client table anymore and that would lead to anomalies in your database. The virtual List<OrderModel> Orders; (in the ClientModel) and virtual ClienModel Client; (in the OrderModel) are needed to create the relation aka. the foreign key between the tables ClientModel and OrderModel. There is one thing about which i'm still not sure about. Which is the int ClientId; in the OrderModel. I guess that it has to have the same name as the ClientId in the ClientModel so that the entity framework knows which 2 attributes the foreign key has to connect. Would be nice if someone could explain this in detail. Also, put this into your DbContext constructor if something souldn't work: this.Configuration.ProxyCreationEnabled = false; this.Configuration.LazyLoadingEnabled = false;
{ "language": "en", "url": "https://stackoverflow.com/questions/7500747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: html email alignment issue I am trying to send out an html email. <table width="180" border="0"> <tr> <td> <img src="image.jpg" width="180"> <table border="0" width="180" border="2" height="100"> <tr> <td width="10"></td> <td width="160"></td> <td width="10"></td> </tr> </table> </td> </tr> </table> However the image in this case is not aligned with the table. Is this because of the 2px border? How do I align them? I need the 2px border. Any thoughts? A: This should give the image 2px margin right and left, and make it allign with the table: <img src="image.jpg" width="180" style="margin-left: 2px; margin-right: 2px;"> A: <img src="image.jpg" width="180" style="margin:0 0 0 2px;padding:0;display:block" alt="" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7500748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linux: Whether calling wait() from one thread will cause all other threads also to go to sleep? "The wait() system call suspends execution of the current process until one of its children terminates" . Waitpid also is similar. My Question is whether calling wait() from one thread will cause all other threads (in the same process) also to go to sleep ? Do the behavior is same for detached threads also? A: This is just a bug in the manual. wait suspends the calling thread, not the process. There is absolutely no way to suspend the whole process short of sending it SIGSTOP or manually suspending each thread one at a time. A: As far as I know, calling wait from any thread will cause all threads which are associated with that process to halt. But don't hold me to that. Best thing to do would be to test it. A: Should only stop the current thread. If you want to make people ill when they look at your code and cause yourself a lot of problems you can use this for jury rigged thread synchronization. I wouldn't reccommend it though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing CSV values into a map with PHP If my text file is Jack Jones;batter;100; Bobby Brown;bowler;90; I know how to get them into an array but how would I get them into an array with Keys? For example, after I read the text file my array would be - $player1 = ('name' => 'Jack Jones', 'skill' => 'batter', 'points' => '100'); $player2 = ('name' => 'Bobby Brown', 'skill' => 'bowler', 'points' => '90'); // therefore - echo $player1['name']; #This would output the name 'Jack Jones' A: you can't directly as there's no information about column names in the text file. but if you know how to get this: $player = (0 => 'Jack Jones', 1 => 'batter', 2 => '100'); and the column names are fixed, you could set up a second array containing the keys: $column_names = array('name','skill','points'); and then use array_combine to get your desired result: $player = array_combine($column_names, $player); echo $player['name']; // 'Jack Jones' A: How do you parse your CSV file? Do you use the Class CsvReader ? In this case you can do something like: Class CsvManager { function __construct() { $this->reader = new CsvReader(); $this->reader->SetCsvEncoding('yourEncoding'); $this->reader->SetDelimiter(';'); } function Run($inString) { $this->reader->ParseCsv($inString,array(&$this, 'CsvCallback'), NULL); } function CsvCallback($inCsvArray) { $newArray = array(); $newArray['name'] = $inCsvArray[0]; $newArray['skill'] = $inCsvArray[1]; $newArray['points'] = $inCsvArray[2]; } $file = pathToYourCsvFile.csv $manager = new CsvManager(); $manager->Run($file); hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: A semicolon to suppress output does not work in IPython In the documentation at IPython Tips & Tricks, it says to put a semicolon (;) at the end of a command to suppress its output. This does not seem to work in my case as even a print('Hello'); outputs Hello Do I have the wrong idea of output suppression or is this a bug? This is especially annoying when working in PuDB, as it flashes horribly in my case as I press 'next' or 'step into'. P.S.: The output is neither on my Ubuntu IPython 0.10 nor OS X v10.7 (Lion) IPython 0.11 suppressed. Although the flashing issue is worse in OS X, probably because of item2. A: Add %%capture as the first line of the cell. For example, %%capture print('Hello') This simply discards the output, but the %%capture magic can be used to save the output to a variable—consult the documentation. A: Try something like 1 + 1;. Without the semicolon, it should give you feedback about the result by printing it (formatted by repr, though it doesn't matter in the case of integers) - I assume that it's this output that's supposed to be suppressed. The shell doesn't (and shouldn't) suppress writing to the file that happens to be referenced by sys.stdout (which is essentially what print does). This is an entirely different matter, and not the job of the shell. A: Here's another example from the Dataquest — 28 Jupyter Notebook tips, tricks, and shortcuts post: # Use a semicolon to suppress the output of a final function. %matplotlib inline from matplotlib import pyplot as plt import numpy x = numpy.linspace(0, 1, 1000)**1.5 plt.hist(x); # Output not suppressed w/ semicolon? And an example of a "working" semicolon suppression: x = 1 + 1 x; # Output suppressed with semicolon! So it appears to suppress for statements that would normally show up in the terminal, but not "inline" types, like plots.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: http post with blackberry I am trying to set up an http post in my Blackberry app. I have successfully implemented this in my corresponding Android app, so I know the server it working find. I have tried several different things, and I'm not really getting errors, its just the info on the server is not getting updated. I have looked at this post: Http POST in BlackBerry, and several others. I found them helpful, but they didn't ultimately solve my problem. Again, I don't get errors, but the server doesn't get updated. Here is the code I am currently using: String url = "http://xxxx.com/ratings/add?;deviceside=true"; String postStr1 = "business_id=790"; String postStr2 = "&rating=4"; HttpConnection httpConnection = (HttpConnection) Connector.open(url); httpConnection.setRequestMethod(HttpConnection.POST); httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false); encPostData.append("business_id", String.valueOf(790)); encPostData.append("rating", String.valueOf(4)); byte[] postData = encPostData.toString().getBytes("UTF-8"); httpConnection.setRequestProperty("Content-Length", String.valueOf(postData.length)); OutputStream os = httpConnection.openOutputStream(); os.write(postData); os.flush(); Anyone have any ideas on what could be wrong? A: A few things were going on. First, my simulator was not connecting to the internet properly. Once that got straightened out, I removed the deviceside=true from my url, and it now works great. Thanks all!
{ "language": "en", "url": "https://stackoverflow.com/questions/7500760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Most usable way to convert a non-associative array to an associative array I often need the functionality to convert an array to an associative array (often in order to be able to check for existance of an entry using isset). Let me give an example: $test = array("foo", "bar", "faz"); I'd like to convert this to something like: $test = array("foo" => true, "bar" => true, "faz" => true); I know of these techniques which (almost) achieve what I want to do, but I'm searching for something slick and more elegant than this: $new = array(); foreach ($test as $v) $new[$v] = true; // want to do it without a loop $new = array_flip($test); // works for isset but array_values($new) are all different $new = array_map(function() { return true; }, array_flip($test)); // would work but verbose Any ideas? A: $new = array_combine( $test, array_fill(0, count($test), true) ); A: As usual, you just have to ask a question and then you find the answer yourself :-) With PHP 5.2 you can do this: $new = array_fill_keys($test, true); below that version you can use this workaround: $new = array_combine($test, array_fill(0, count($test), true)); A: Use array_combine together with array_fill A: want to do it without a loop Here goes a secret knowledge: every time you're messing with array, a loop involved. Even if you don't see it. works for isset but array_values($new) are all different so what? what's the problem with these different values? would work but verbose here goes another piece of secret knowledge: one can create a function. and hide as much code within it, as they wish. Honestly, you've got your question out of nowhere. Don't you have no real problems to solve? BTW, from where did you get your initial array?
{ "language": "en", "url": "https://stackoverflow.com/questions/7500762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Command-line streaming webcam with audio from Ubuntu server in WebM format I am trying to stream video and audio from my webcam connected to my headless Ubuntu server (running Maverick 10.10). I want to be able to stream in WebM format (VP8 video + OGG). Bandwidth is limited, and so the stream must be below 1Mbps. I have tried using FFmpeg. I am able to record WebM video from the webcam with the following: ffmpeg -s 640x360 \ -f video4linux2 -i /dev/video0 -isync -vcodec libvpx -vb 768000 -r 10 -vsync 1 \ -f alsa -ac 1 -i hw:1,0 -acodec libvorbis -ab 32000 -ar 11025 \ -f webm /var/www/telemed/test.webm However despite experimenting with all manner of vsync and async options, I can either get out of sync audio, or Benny Hill style fast-forward video with matching fast audio. I have also been unable to get this actually working with ffserver (by replacing the test.webm path and filename with the relevant feed filename). The objective is to get a live, audio + video feed which is viewable in a modern browser, in a tight bandwidth, using only open-source components. (None of that MP3 format legal chaff) My questions are therefore: How would you go about streaming webm from a webcam via Linux with in-sync audio? What software you use? Have you succeeded in encoding webm from a webcam with in-sync audio via FFmpeg? If so, what command did you issue? Is it worth persevering with FFmpeg + FFserver, or are there other more suitable command-line tools around (e.g. VLC which doesn't seem too well built for encoding)? Is something like Gstreamer + flumotion configurable from the command line? If so, where do I find command line documentation because flumotion doc is rather light on command line details? Thanks in advance! A: You should consider giving flumotion a try. You can easily set up a webm pipeline capturing from a webcam with flumotion-admin and let it run in the background. A: I set this up recently, but it's kind of a pain. Here's what I had to do: First, build ffmpeg from source to include the libvpx drivers (even if your using a version that has it, you need the newest ones (as of this month) to stream webm because they just did add the functionality to include global headers). I did this on an Ubuntu server and desktop, and this guide showed me how - instructions for other OSes can be found here. Once you've gotten the appropriate version of ffmpeg/ffserver you can set them up for streaming, in my case this was done as follows. On the video capture device: ffmpeg -f video4linux2 -standard ntsc -i /dev/video0 http://<server_ip>:8090/0.ffm * *The "-f video4linux2 -standard ntsc -i /dev/video0" portion of that may change depending on your input source (mine is for a video capture card). Relevant ffserver.conf excerpt: Port 8090 #BindAddress <server_ip> MaxHTTPConnections 2000 MAXClients 100 MaxBandwidth 1000000 CustomLog /var/log/ffserver NoDaemon <Feed 0.ffm> File /tmp/0.ffm FileMaxSize 5M ACL allow <feeder_ip> </Feed> <Feed 0_webm.ffm> File /tmp/0_webm.ffm FileMaxSize 5M ACL allow localhost </Feed> <Stream 0.mpg> Feed 0.ffm Format mpeg1video NoAudio VideoFrameRate 25 VideoBitRate 256 VideoSize cif VideoBufferSize 40 VideoGopSize 12 </Stream> <Stream 0.webm> Feed 0_webm.ffm Format webm NoAudio VideoCodec libvpx VideoSize 320x240 VideoFrameRate 24 AVOptionVideo flags +global_header AVOptionVideo cpu-used 0 AVOptionVideo qmin 1 AVOptionVideo qmax 31 AVOptionVideo quality good PreRoll 0 StartSendOnKey VideoBitRate 500K </Stream> <Stream index.html> Format status ACL allow <client_low_ip> <client_high_ip> </Stream> * *Note this is configured for a server at feeder_ip to execute the aforementioned ffmpeg command, and for the server at server_ip so server to client_low_ip through client_high_ip while handling the mpeg to webm conversation on server_ip (continued below). This ffmpeg command is executed on the machine previously referred to as server_ip (it handles the actual mpeg --> webm conversion and feeds it back into the ffserver on a different feed): ffmpeg -i http://<server_ip>:8090/0.mpg -vcodec libvpx http://localhost:8090/0_webm.ffm Once these have all been started up (first the ffserver, then the feeder_ip ffmpeg process then then the server_ip ffmpeg process) you should be able to access the live stream at http://:8090/0.webm and check the status at http://:8090/ Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Two-Way Routing Service I have the following requirement: Client can call the router/relay service, which in turn calls a service on the target server. The target server sends back a result to the relay service which will forward it back to the client. I've looked at this SO question but I do not think it would suffice my needs because I assume this is only a one-way message from the client, to the relay service and finally to the target server. I'm fairly new to WCF so I would like to get some insight about this issue so I would focus my research in the right direction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to do validation of file exist with error handling here is my function function loadscript(request, callback){ fs.readFile('scripts/'+request.filename, function(err, data){ callback(data); }); } how can i pass that if file not exist then it should reply error to call back . i tried fs.stat but one time it return the error.code to callback but second time when i call the function from the url of the server it gives the error. The error it given with TypeError: first argument must be a string, Array, or Buffer at ServerResponse.write (http2.js:598:11) at /home/reach121/basf/index.js:37:17 at /home/reach121/basf/index.js:81:3 at [object Object].<anonymous> (fs.js:81:5) at [object Object].emit (events.js:67:17) at Object.oncomplete (fs.js:948:12) what should i used to solve this . A: If you want to know whether there was an error loading the file, check if err is not null. var fs = require("fs"); fs.readFile("foo.js", function(err, data) { if (err) { console.log("error loading file"); return; } console.log("file loaded"); }); If you only want to do something if the file can't be found, you can check for err.code being equal to ENOENT: var fs = require("fs"); fs.readFile("foo.js", function(err, data) { if (err && err.code == "ENOENT") { console.log("file not found"); return; } console.log("file found, but there might be other errors"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7500768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simple codeigniter base directory-like function/definition for relative directory structure I'm developing a website with codeigniter, and I have a simple issue. For html and styles I'm using base_url() for paths to work, but in html source a full path including http:// My folder structure is like this: application/ system/ my_template/ *styles.css *images/ *etc.etc. index.php when I'm on index.php/controller/method/param1/param2, I want to set e.g css path like this: <link href="../../../my_template/styles.css" rel="stylesheet" type="text/css" media="screen" /> But with using base_url() they become like this: <link href="http://www.site.com/my_template/styles.css" rel="stylesheet" type="text/css" media="screen" /> How can I do this for css and <script> tags ? I'm sure I'm missing a simple step, but could not find it. I'm using CI 2.03. Thanks, A: You can use / to reference a file relative to the root directory of your web site. Both paths will reference the same file assuming you are on http://www.site.com/. <link href="/my_template/styles.css" ... /> <link href="http://www.site.com/my_template/styles.css" ... />
{ "language": "en", "url": "https://stackoverflow.com/questions/7500770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Shared Pointer on a thread counts 1 after join? Having a boost::condition_variable which waits for a thread to complete: boost::condition_variable mContd; boost::shared_ptr<boost::thread> mThread; Imagine, the Thread was started some time before, and now wait: if(!mContd.timed_wait(tLock, boost::posix_time::seconds(1))) { // cancel thread if deadline is reached mThread.interrupt(); mThread.join(); std::cout << "Thread count = " << mThread.use_count() // still prints '1' << std::endl; } else { // continue } So, when is this count set to a zero? I assumed, after a join a thread is finished. But when it is? A: use_count() simply tells you how many shared_ptr object points to the same boost::thread object. It has nothing to do with whether the thread has terminated. The counter will automatically get decremented when mThread goes out of scope. If you no longer need the thread object, you could call mThread.reset(). That'll also cause mThread.use_count() to go down to zero. A: Objects can't properly delete themselves like that. When the thread terminates, the boost::thread object representing it goes into a "finished" state, but it must still "exist" because shared_ptr is controlling it. You still have the one, now-"finished" boost::thread object that you have before, so the count is still 1. In fact, in general, boost::shared_ptr::use_count() will only return 0 when it's representing a "null pointer" rather than an actual object that exists. A direct analogy follows: boost::thread mThread(&f); // Create thread object mThread.interrupt(); mThread.join(); // Thread is now "finished" cout << (mThread.get_id() == boost::thread::id()); // ^ Outputs `true`, because the object mThread is now in the // not-a-thread state, but of course it still must exist.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Complex TSQL Merge I have 'inherited' a brilliant piece of TSQL code that does this: * *Loops row-by-row over a cursor. *The cursor contains data that need to be merged (Upserted) in Table A *For each row loop in the cursor a stored proc is called. The proc: * *If a corresponding row exists in Table A then it is updated *If such a row does not exist then: * *Inserts a single row in in a different Table B. *Fetches the newly generated ID (say its called IDB) *Inserts a single row in Table A. Table A insertions need an IDB (the field is not null, it is supposed to have values ONLY from table B, but no FK constraint is in place) Obviously this sucks (performance & elegance reasons)!! Question At first this looks like a standard case of MERGE usage. I tried doing: MERGE [dbo].[TableA] AS Target USING <cursor data set as a select statement> as Src on target.IDA = Src.IDA WHEN MATCHED //update WHEN NOT MATCHED //insert <------ Fails because obviously a new IDB is required Also tried various approaches like a nested select that sends IDB on the OUTPUT but it fails because IDB is a PK. Other kinds of merges also failed eg: MERGE Table A with <cursor data set as a select statement> ... MERGE Table A with Table B WHEN NOT MATCHED //insert on Table A WHEN NOT MATCHED // Update Table B Does anyone have an idea on this? Essentially I think if we generalise the question would be: Can I insert and return the PK in one statement that can be nested in other statements Thanks in advance for any replies George A: If you have an autogenerated PK on TableB, you can use code similar to this. Otherwise, just change the INSERT into TableA to grab the PK from TableB first. DECLARE @OldData CHAR(10) SET @OldData = 'Old' DECLARE @NewData CHAR(10) SET @NewData = 'New' CREATE TABLE #TableA ( IDA INT IDENTITY(1,1) PRIMARY KEY, IDB INT NOT NULL, DataA CHAR(10) ) CREATE TABLE #TableB ( IDB INT IDENTITY(1,1) PRIMARY KEY, DataB CHAR(10) ) DECLARE @IDsToUpsert TABLE ( ID INT ) -- Add test values for existing rows INSERT INTO #TableB OUTPUT INSERTED.IDB, @OldData INTO #TableA SELECT @OldData UNION ALL SELECT @OldData UNION ALL SELECT @OldData UNION ALL SELECT @OldData -- Add test values for the rows to upsert INSERT INTO @IDsToUpsert SELECT 1 UNION -- exists SELECT 3 UNION -- exists SELECT 5 UNION -- does not exist SELECT 7 UNION -- does not exist SELECT 9 -- does not exist -- Data Before SELECT * From #TableA SELECT * From #TableB DECLARE rows_to_update CURSOR FOR SELECT ID FROM @IDsToUpsert DECLARE @rowToUpdate INT DECLARE @existingIDB INT OPEN rows_to_update; FETCH NEXT FROM rows_to_update INTO @rowToUpdate; WHILE @@FETCH_STATUS = 0 BEGIN BEGIN TRANSACTION IF NOT EXISTS ( SELECT 1 FROM #TableA WITH (UPDLOCK, ROWLOCK, HOLDLOCK) WHERE IDA = @rowToUpdate ) BEGIN -- Insert into B, then insert new val into A INSERT INTO #TableB OUTPUT INSERTED.IDB, INSERTED.DataB INTO #TableA SELECT @NewData -- Change code here if PK on TableB is not autogenerated END ELSE BEGIN -- Update UPDATE #TableA SET DataA = @NewData WHERE IDA = @rowToUpdate END COMMIT TRANSACTION FETCH NEXT FROM rows_to_update INTO @rowToUpdate; END CLOSE rows_to_update; DEALLOCATE rows_to_update; SELECT * FROM #TableA SELECT * FROM #TableB DROP TABLE #TableA DROP TABLE #TableB A: To answer your general question - 'Can I insert and return the PK in one statement that can be nested in other statements' - yes, absolutely. But it depends on the logic behind the creation of your PK. In this case, it seems like to generate a PK, you need to insert into a different table and then grab the newly generated ID from there. This is not very efficient (IMHO) unless there is a very specific reason for doing so. Autoincrements, GUIDs, etc tend to work better as PKs. If you can simplify/change the logic behind this, and you can find a simpler way to accomplish that, so the PK 'CAN' be generated in one statment/function and thus can be used in other statements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Silverlight sdk:DataGridCell Template with TextBox - the Binding? i search fot the correct way to bind a TextBlock in the sdk:DataGridCell Template; the way like in WPF - Text={Binding} doesn't work. <Style TargetType="sdk:DataGridCell"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ContentControl"> <Grid> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="MouseOver"> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border Background="{x:Null}"> <TextBlock Text="{Binding}" Foreground="Black"/> </Border> </Grid> </ControlTemplate> </Setter.Value> </Setter> Also Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text}" doesn't work. Any other ideas? Thanks a lot. A: Please see my answer here to a similar problem when you need to get out of the datagrid to get a parent datacontext. : Silverlight - Access the Layout Grid's DataContext in a DataGrid CellTemplate's DataTemplate? Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I ensure certain hadoop jobs dont end up running in the same datanode when using Fair Scheduler? When using the nutch crawler, the fetch jobs are created such that URLs from same host end up in a single data node to maintain crawl politeness(1 QPS). However, certain hosts allow more than 1 QPS and so the URLs are partitioned accordingly. For such hosts, the URLs will be in two fetch jobs meant to be run on two different data nodes. But sometimes Fair scheduler schedules those jobs(reduce tasks) to the same data node. So is there any way to work around this issue? Any help is greatly appreciated. Thanks A: I'm not sure if you want to do something like this because it will impact the rest of your Hadoop cluster... You can set the number of reduce slots per node to 1. The configuration parameter you want to change for this is mapred.tasktracker.reduce.tasks.maximum.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to move from view to activity and back in android I have two classes A and B A is main activity class and B is View class. Now I am calling View by setcontentview. when the view is active and i am drawing on it . I want the activity class is active so how do i do that ? public class A extends Activity { B b; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.button); b = new B(this); Button but = (Button) findViewById(R.id.showView); but.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setContentView(drawView); drawView.requestFocus(); } }); } } public class b extends View implements OnTouchListener { public DrawView(Context context) { super(context); setFocusable(true); mContext = context; setFocusableInTouchMode(true); this.setBackgroundColor(Color.WHITE); this.setOnTouchListener(this); paint.setColor(Color.GRAY); paint.setAntiAlias(true); } public void onDraw(Canvas canvas) { mCanvas = canvas; draw something } } A: setContentView() replaces the entire view of the Activity. If you want to go back to the old view, call setContentView() again with the old view again. By convention though, this is bad. Generally you only do one view per activity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: phone gap map issue for android i am just trying to get practiced with phone gap for android devices. I found an map based app here Following is the javascript i tried to run <html> <head> <meta name="viewport" content="width=device-width; height=device-height; user-scalable=no" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Beer Me</title> <link rel="stylesheet" href="/master.css" type="text/css" media="screen" /> <script type="text/javascript" src="scripts/phonegap.js"></script> <script type="text/javascript"> function loader() { var state = document.readyState; if (state == 'loaded' || state == 'complete') { run(); } else { if (navigator.userAgent.indexOf('Browzr') > -1) { setTimeout(run, 250); } else { document.addEventListener('deviceready',run,false); } } } function run() { var win = function(position) { // Grab coordinates object from the Position object passed into success callback. var coords = position.coords; var url = "http://maps.google.com/maps/api/staticmap?center=" + coords.latitude + "," + coords.longitude + "&zoom=13&size=320x480&maptype=roadmap&key=xxxxxxxxxxxxxxxxxxx&sensor=true"; document.getElementById('map').setAttribute('src',url); }; var fail = function(e) { alert('Can\'t retrieve position.\nError: ' + e); }; navigator.geolocation.getCurrentPosition(win, fail); } </script> </head> <body onload="loader();"> <img id="map" /> </body> </html> when i run in the android device it shows an alert box that Can\'t retrieve position. The function for Position is not been called. How to get the position of a place in phone gap javascript, please help me.... A: Well, if you are talking about that exact code, it looks like it wants a key for google maps. That tutorial is a year old which is ancient in google map time. If you are willing to move to Google Maps JavaScript v3 (non-static - no key, much more powerful and interesting to use than static maps), here's a gettting-started google map route finder tutorial. It's also from the phonegap wiki pages, see android tutorials, scroll down to the one titled jQuery Google Maps Plugin for Google Maps v3: Route Finder App.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP If and Else operating incorrectly The following PHP should determine if there ?purpose=email and then if it is determine the sting contains ?emailaddress or not. If there is an emailaddress then it triggers one set of scripts and if not another. But regardless it is acting as if emailaddress !== ''; Any idea why. <?php if($_GET['purpose'] == 'email') {?> <?php if($_GET['emailaddress'] !== '') {?> <script type="text/javascript"> alert('<?php echo $_GET['emailaddress'];?>'); window.setTimeout(function(){ $('.dirops .loadpanel div span', window.parent.document).html('Complete'); $('.dirops .loadpanel', window.parent.document).removeClass('slideup'); },1000); </script> <?php } else { ?> <script type="text/javascript"> window.setTimeout(function(){ $('.dirops .loadpanel div span', window.parent.document).html('Loading'); $('.dirops .confirmemail', window.parent.document).addClass('slideup'); },1000); $('#confirmemail', window.parent.document).attr('href', 'http://www.golfbrowser.com/A4/directions.php?purpose=email&start=<?php echo $_GET['start'];?>&end=<?php echo $_GET['end'];?>') </script> <?php } ?> <?php } ?> Any ideas? Marvellous A: Try if($_GET['emailaddress'] != ''), i.e. != instead of !== A: Use: array_key_exists('emailaddress', $_GET) instead of $_GET['emailaddress'] !== '' A: if (isset($_GET['emailaddress'])) { .... A: Somehow I don't think that if/else is not working... try var_dump($_GET) maybe isset($_GET['emailaddress']) can help you. A: Try this changing the first two lines: <?php if(array_key_exists('purpose', $_GET) && $_GET['purpose'] == 'email') {?> <?php if(array_key_exsist('emailaddress', $_GET) && $_GET['emailaddress'] != '') {?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7500792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: MODX dynamic generate image-paths i am searching for a solid solution, to get img-paths for all images inside a ressource folder. To easy fill in path information to a fullscreen background slider. Anyone out there keen on Modx or Modx-Plugins? thx sven A: I would create an image TV and use this jquery plugin, is rock-solid http://www.ajaxblender.com/bgstretcher-2-jquery-stretch-background-plugin-updated.html check this example: http://s401229343.mialojamiento.es/es/home
{ "language": "en", "url": "https://stackoverflow.com/questions/7500797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create custom Flex 4 components I've created a extended Scroller component based on Spark Scroller... (only AS3 Code/no MXML) the neu component is list on the component library on the left window of flash builder in the custom section... * *how can i change the section to a own section *how can i replace the icon of the component *when I drag the component into the stage, it has a size of (100,0) Pixel... if I drag the original Scroller to the stage... there pops up a dialog for customize the scroller-size.... how can I predefine the size? or create a dialog by dropping my component? A: http://blog.another-d-mention.ro/programming/create-professional-flex-components/
{ "language": "en", "url": "https://stackoverflow.com/questions/7500799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to duplicate a set of rows changing only the value of one column without listing the other columns? Given a table T(x, y, z, t, u, v, ...) is it possible in Oracle to write this query without listing all columns (be it in the SELECT or in the INSERT part)? INSERT INTO T (x, y, z, t, u, v, ...) SELECT 'new', y, z, t, u, v, ... FROM T WHERE x = 'old' The effect is that all rows for which x has the value of old are duplicated, except that now x has the value of new. A: "is it possible in Oracle to write this query without listing all columns (be it in the SELECT or in the INSERT part)" No. The only way to avoid typing an explicit projection is to use all the table's columns. You aren't doing that, because you want to use a literal instead of column X. That means you have to list all the other columns in the SELECT projection. Of course, you don't have to specify the columns in the INSERT clause. Over the years developers have occasionally wished for an "except" syntax, something like: select * except X from t but it's never made it into the ANSI standard. In fact, I doubt if it's even been discussed. "PLSQL answers are welcome then!" Okay, here is a proof of concept which uses the data dictionary to produce a dynamic insert statement. It makes the following assumptions: * *You only want to substitute the value of one column. *The column you want to substitute is a string datatype. *You want to clone all the records in the source table. You will need to adjust the code if any of those assumptions are wrong. The procedure loops round the USER_TAB_COLUMNS table, sorting the columns into the table's projected order. It concatenates the column names into the SELECT clause of an INSERT statement, except where the name is that of the substituted column when it concatenates the provided literal instead. Finally it uses Native Dynamic SQL to run the assembled INSERT statement. create or replace procedure clone_minus_one ( p_sub_col in user_tab_columns.column_name%type , p_sub_val in varchar2 ) is stmt varchar2(32767) := 'insert into source_table select '; begin for lrec in ( select column_name , column_position from user_tab_columns. where table_name = 'SOURCE_TABLE' order by column_position ) loop if lrec.column_position != 1 then stmt := stmt ||','; end if; if lrec.column_name != p_sub_col then stmt := stmt ||lrec.column_name; else stmt := stmt ||''''||p_sub_val||''''; end if; end loop; stmt := stmt || ' from source_table'; execute immediate stmt; end; / A: You can do exactly as you describe, provided your selected columns are ordered correctly. The following is Valid INSERT INTO T SELECT 'new', y, z, t, u, v, ... FROM T WHERE x = 'old' or you could try this (Rough script not tested) CREATE TABLE TEMPTABLE AS SELECT * FROM T WHERE X = 'Old'; UPDATE TEMPTABLE SET X='New'; INSERT INTO T (SELECT * FROM TEMPTABLE); DROP TABLE TEMPTABLE; A: The following is going too far to avoid some typing imo, but I like a challenge, so here it goes... insert into T select * from T where x='old'; commit; -- update every other row to 'new' update T set x='new' where rowid in ( select rowid from (select rownum rnum, rowid row_id from T where x='old' ) where mod(rnum,2)=0 ); commit; In 2 steps, but personally I'd just query all_tab_columns for the table (order by column_id) and copy/paste into my script/procedure. But may be some other reason to avoid this, not sure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Url re-writing regular expression Using ASP.NET, and trying to implement friendly url re-writing but I'm having a heck of a time working with the regular expression. Basically, I'm checking the url directly following the domain to see whether it is using the french-canadian culture, or whether it is a number - and not a number followed by characters. I need to catch anything that begins with 'fr-ca' OR a number, and both scenarios can have a trailing '/' (forward slash), but that's all... fr-ca - GOOD fr-ca/ - GOOD fr-ca/625 - GOOD fr-ca/gd - BAD fr-ca43/ - BAD 1234 - GOOD 1234/ - GOOD 1234/g - GOOD 1234g - BAD 1g34 - BAD This is what I've come up with : ^(fr-ca)?/?([0-9]+)? But it doesn't seem to be working the way I want.. so I started fresh and came up with (^fr-ca)|(^[0-9]), which still isn't working the way I want. Please...HELP! A: no idea about Asp.net, but the regexp was tested with grep. you could try in your .net box: kent$ cat a fr-ca fr-ca/ fr-ca/625 fr-ca/gd fr-ca43/ 1234 1234/ 1234/g 1234g 1g34 updated kent$ grep -P "(^fr-ca$|^\d+$|^(fr-ca|\d+)/(\w|\d*)$)" a fr-ca fr-ca/ fr-ca/625 1234 1234/ 1234/g -- well this may not be the best regex, but would be the most straightforward one. it matchs string ^fr-ca$ or ^\d+$ or ^(fr-ca|\d+)/(\w|\d*)$ the above line can be broken down as well ^(fr-ca|\d+)/(\w|\d*)$ : starting with fr-ca or \d+ then comes "/" after "/" we expect \w or \d* then $(end) A: What about ^(fr-ca(?:\/\d*)?|[0-9]+(\/[a-zA-Z]*)?)$ See it here on Regexr, it matches all your good cases and not the bad ones. A: Probably can try... ^(fr-ca|\d).*$ But of course this a regex to match the entire string (as it has the end-of-sting $ anchor). Are you wanting to pull out multiple matches? In light of re-reading the post :) ^(fr-ca|\d+)(\/\d+|\/)?$ A: ^(\d+(\/\w*)?)$|^(fr-ca\/\d+)$|^(fr-ca\/?)$ This worked for me for all of your examples. I'm not sure your intention for using this regex so I don't know if it is capturing exactly what you want to capture.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I disable console.log when I am not debugging? I have many console.log (or any other console calls) in my code and I would like to use them only when my app is in some kind of "debug mode". I can't seem to use some kind of logger function and internally use console.log because then I wouldn't know what line fired it. Maybe only with a try/catch, but my logs are very general and I don't want try/catch in my code. What would you recommend? A: One more way to disable console.log in production and keep it in development. // overriding console.log in production if(window.location.host.indexOf('localhost:9000') < 0) { console.log = function(){}; } You can change your development settings like localhost and port. A: I would probably abuse the short-circuiting nature of JavaScript's logical AND operator and replace instances of: console.log("Foo."); With: DEBUG && console.log("Foo."); Assuming DEBUG is a global variable that evaluates to true if debugging is enabled. This strategy avoids neutering console.log(), so you can still call it in release mode if you really have to (e.g. to trace an issue that doesn't occur in debug mode). A: Just replace the console.log with an empty function for production. if (!DEBUG_MODE_ON) { console = console || {}; console.log = function(){}; } A: Clobbering global functions is generally a bad idea. Instead, you could replace all instances of console.log in your code with LOG, and at the beginning of your code: var LOG = debug ? console.log.bind(console) : function () {}; This will still show correct line numbers and also preserve the expected console.log function for third party stuff if needed. A: This Tiny wrapper override will wrap the original console.log method with a function that has a check inside it, which you can control from the outside, deepening if you want to see console logs and not. I chose window.allowConsole just as an example flag but in real-life use it would probably be something else. depending on your framework. (function(cl){ console.log = function(){ if( window.allowConsole ) cl(...arguments); } })(console.log) Usage: // in development (allow logging) window.allowConsole = true; console.log(1,[1,2,3],{a:1}); // in production (disallow logging) window.allowConsole = false; console.log(1,[1,2,3],{a:1}); This override should be implement as "high" as possible in the code hierarchy so it would "catch" all logs before then happen. This could be expanded to all the other console methods such as warn, time, dir and so on. A: Since 2014, I simply use GULP (and recommend everyone to, it's an amazing tool), and I have a package installed which is called stripDebug which does that for you. (I also use uglify and closureCompiler in production) Update (June 20, 2019) There's a Babel Macro that automatically removes all console statements: https://www.npmjs.com/package/dev-console.macro A: Simple. Add a little bash script that finds all references to console.log and deletes them. Make sure that this batch script runs as part of your deployment to production. Don't shim out console.log as an empty function, that's a waste of computation and space. A: This code works for me: if(console=='undefined' || !console || console==null) { var console = { log : function (string) { // nothing to do here!! } } } A: The newest versions of chrome show which line of code in which file fired console.log. If you are looking for a log management system, you can try out logeek it allows you to control which groups of logs you want to see. A: // In Development: var debugMode = true // In Prod: var debugMode = false // This function logs console messages when debugMode is true . function debugLog(logMessage) { if (debugMode) { console.log(logMessage); } } // Use the function instead of console.log debugLog("This is a debug message"); A: console can out put not just log but errors warnings etc. Here is a function to override all console outputs (function () { var method; var noop = function noop() { }; var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn' ]; var length = methods.length; var console = (window.console = window.console || {}); while (length--) { method = methods[length]; console[method] = noop; } }()); Refer to detailed post here https://stapp.space/disable-javascript-console-on-production/
{ "language": "en", "url": "https://stackoverflow.com/questions/7500811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: TFS2010 web - Send notification to user who logged the work item How can i send notification to user about accepting the work item? i have send notification to me, but how do i send the email to user who logged the work item? any ideas ? A: You requirements are a bit to complex to be handled out of the box. Please take a look at the Event Notification Plugin for TFS2010 hosted at codeplex under project name Team Alert: http://teamalert.codeplex.com/. It is a server side extension for TFS 2010, which allows you sending E-Mail notifications to any person field in the event, regardless the field contain a SID, account name or display name. The creator talks about your very needs on his own website: http://fszlin.dymetis.com/post/2011/03/22/Event-Notification-Plugin-for-TFS-2010.aspx. The configuration for you could be something like this: <alert name="Bug Changes" event="WorkItemChangedEvent" filterExpression="$&quot;CoreFields/StringFields/Field [ReferenceName='System.WorkItemType']/NewValue&quot; = Bug AND $&quot;CoreFields/StringFields/Field[ReferenceName='System.AuthorizedAs']/NewValue&quot; &lt;&gt; $&quot;CoreFields/StringFields/Field[ReferenceName='System.CreatedBy']/NewValue&quot;"> <recipients> <recipient name="Owner" address="CoreFields/StringFields/Field[ReferenceName='System.CreatedBy']/NewValue" type="DisplayNameField" allowHtml="true"/> </recipients> </alert> Does that solve your needs?
{ "language": "en", "url": "https://stackoverflow.com/questions/7500813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Encoding request parameters after JSF2.0 Post-Redirect-Get I've upgraded a JSF application from 1.1 to 2.0 and I'm trying to encode request parameters after performing an action. The situation: * *The user presses a save-button on viewA.xhtml which invokes save() on a backing bean A. After the save() is performed successfully I navigate to viewB.xhtml?faces-redirect=true. *View B, which is navigated to, defines a couple of view parameters (f:viewParam). *The two views currently have to use different backing beans. *The button must be a commandButton such that a action method is invoked prior to the navigation so I cannot use a regular button with f:param elements. I found another issue already solved Passing parameters with h:commandButton -- or the equivalent but I'm dependent on the redirect. A: Just pass those parameters along in the redirect URL. String outcome = String.format( "viewB?faces-redirect=true&amp;foo=%s&amp;bar=%s", URLEncoder.encode(foo, "UTF-8"), URLEncoder.encode(bar, "UTF-8")); return outcome;
{ "language": "en", "url": "https://stackoverflow.com/questions/7500816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot assign to Func from Func If I have public class MyClass { public Func<IModel> InputFunc { get; set; } } and try to do public void SetInput<TInput>(Func<TInput> funcInput) where TInput:IModel { ... var c = new MyClass(); c.InputFunc = funcInput; ... } I get a compile-error Cannot implicitly convert type 'System.Func<TInput>' to 'System.Func<IModel>' Why is this caused? How can I overcome this issue? (I tried the where clause but is not helping) A: Two possibilities: * *You're probably using C# 3 / .NET 3.5 (or earlier). Generic covariance for interfaces and delegates was only introduced in C# 4. *It's just because you haven't required that TInput is a reference type. Try this: void SetInput<TInput>(Func<TInput> func) where TInput : class, IModel This is required because otherwise TInput could be a value type implementing IModel (I'm assuming IModel is an interface) and covariance isn't supported for value types (due to representation differences). I've just tried it with the extra constraint, and it's fine in C# 4.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Setting core data relationship reusing same object removes previous relation I am importing data from a web service, in such data I have a tree of categories. For example:    Restaurants      - Italian      - Mexican      - Steakhouse In my model I have set a relation called ParentCategory with an inverse relation called Subcategories. Everything is good so far. Now, when I am importing my categories I am doing something like this: (Note: My code does not look like this. I have changed it to exemplify my problem) NSEntityDescription *categoryEntity = [NSEntityDescription entityForName:@"Categories" inManagedObjectContext:context]; NSDescription *parentCategory = [NSEntityDescription insertNewObjectForEntityForName:[categoryEntity name] inManagedObjectContext:context] //Then I actually set some values for parentCategory. //Then create the subcategories. NSDescription *italianDescription = [NSEntityDescription insertNewObjectForEntityForName:[categoryEntity name] inManagedObjectContext:context]; [italianDescription objectForKey:@"Italian" forKey:@"name"]; //Set the relationship [italianDescription objectForKey:parentCategory forKey:@"ParentCategory"]; //All this works great but then when NSEntityDescription *mexicanDescription = [NSEntityDescription insertNewObjectForEntityForName:[categoryEntity name] inManagedObjectContext:context]; [mexicanDescription objectForKey:@"Mexican" forKey:@"name"]; [mexicanDescription objectForKey:parentCategory forKey:@"ParentCategory"]; It seems like when that last line of code runs it removes the relation from "italianDescription", therefore after I save my context it shows like it doesn't have a parent category. I removed some data from my web service and only the last subcategory that I set the relation to parent category object X keeps it. All previous will loose it. I checked the apple developer documentation and it doesn't really help. That being said, how can I overcome this? Or what would be a efficient way to import that with relations. A: I don't think you are setting anything, the way to set values for NSManagedObjects is setValue: forKey: Instead of NSDescription*'s you should be using NSManagedObject* You may want to look into subclassing your entities as it allows for much easier access and setting of properties. In which case it would be MyCustomEntity* myobj=[NSEntityDescription insertNewObjectForEntityForName:@"MyentityName" inManagedObjectContext:context]; Then you can set the values just by using it's properties with dot notation or messaging. You can do this by selecting the entity in the core-data editor and then under Editor on the Menu bar there is an option to create a NSManagedObject subclass, after you create that you need to tell the entity that it has a custom class now. This is done in the right hand Utiliies bar under Entity there is a Class field, just enter the name of your new class and it should be set up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SCSF Services question Quick question (and my last today about SCSF) about what Services are intended to be used for. Services exist within the WorkItem, so I assume they are supposed to provide UI services specifically. Only the code I'm hating on at the moment is using them for business services which is making the whole MVP separation, specifically the M from VP not so separate. A: I know you probably won't even care about the answer at this point, but its my first shot at answering something at SO, so here it goes. I've been using SCSF for about 6 months so far, so I am not an expert by any means but a couple of the things I've been mainly using Module Services for: * *When making a "business service" call (which I assume from your question means making a call to a data store of some sort or calling a web service etc.) you can use a service to attach any additional data that might not be directly related to the business logic but necessary to be persisted with the call to the database. One example I can provide is attaching the currently logged in user credentials to a call to web service or to the database for audit trail logging. You call the Service from your presenter which appends any additional info and proceeds the call to the next layer. *Another use for Services is to abstract any implementation of UIExtensions away from your modules. If you are using a Ribbon for example, you can have a Service which gets injected into your business modules with methods such as "AddRibbonButton()" or "AddRibbonGroup()" which your modules can call to add the necessary user interface elements when loading up without worrying about how its done. Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7500819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Writing application with a calendar feed I am writing an application that provides a calendar feed for people to subscribe to. Changes may be made to the calendar feed up to moments before the event occurs, and it would be really nice if those changes could be propagated out to all subscribers when this happens. The only solution I have today is to provide an iCal format so that people can add it to their Google calendars (the most popular for my target audience), but Google calendar seems to be especially slow to notice changes. Is there a way to force Google calendar to re crawl my url if a change occurs? Is there another way to provide a calendar feed to people that may work better for my needs? A: I'm not sure what technology you are using, but have a look at the Google Calendar Data API. The Calendar Data API lets you incorporate Calendar functionality into your own application or website. You can edit calendars, create and delete events, send invitations, and more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a free date/time entry spin-wheel control for Silverlight? Not sure what this control is actually "called", but I'm looking for a free version of one of these for Silverlight: Does anyone know of something like this? A: The Silverlight toolkit has a DatePicker and a TimePicker control. http://silverlight.codeplex.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7500826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Htaccess rules for dynamic sub domain conflicting for index file Here is my htaccess file Options +FollowSymLinks RewriteEngine on # For Accessing Page http://www.domain.com/news/news-details.php RewriteCond %{HTTP_HOST} ^www.domain\.com$ [NC] RewriteRule ^news/news-details.php$ news.php [QSA,NC,L] # For www.domain.com it should go to the index page RewriteCond %{HTTP_HOST} ^(www\.)?domain.com$ [NC] RewriteRule ^(.*)$ index.php [NC,L] when i type http://www.domain.com/news/news-details.php in the browser it takes me to the index.php page rather than news.php. WHY? EDIT: Check these rule # For www.domain.com it should go to my-index.php page # RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC] RewriteRule ^(.*)$ my-index.php [NC,L] # For Page URL http://www.domain.com/news/news-details.php # RewriteCond %{REQUEST_URI} ^/news/news\-details\.php [NC] RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC] RewriteRule ^(.*)$ my-news.php [NC,QSA,L] A: Options +FollowSymLinks RewriteEngine On # For Page URL http://www.domain.com/news/news-details.php RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC] RewriteRule ^news/news-details\.php$ /my-news.php [NC,QSA,L] # For Accessing Division Page http://user1.domain.com/news/news-details.php RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com [NC] RewriteCond %{HTTP_HOST) !^www\. RewriteRule ^news/news-details\.php$ /my-news.php?user=%1 [QSA,NC,L] # For Accessing Users Page RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC] RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$ RewriteRule ^$ /users.php?user=%1 [L] # For www.domain.com it should go to my-index.php page # (but only if requested resource is not real file) RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /my-index.php [L] A: You can't the name of the file in the path. RewriteRule ^news/news-details.php$ news.php [QSA,NC,L] here you have the file "news.php" and in the path you have "news". try another word than news in the path or another name for the file. for example: RewriteRule ^news/news-details.php$ news_main.php [QSA,NC,L]
{ "language": "en", "url": "https://stackoverflow.com/questions/7500829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Combining file permissions I want to set executable permissions for a file I have created in python. If I do os.chmod(file, stat.S_IXUSR), the existing permissions are overwritten. How do I combine the existing permissions for the file with executable permissions? A: stat it first. mode = os.stat(filename).st_mode os.chmod(filename, mode | stat.S_IXUSR) A: Probably just with os.system('chmod %d "%s"' % ("+x", file)) should do the trick
{ "language": "en", "url": "https://stackoverflow.com/questions/7500840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to resize and rotage image while orientation change in android I am taking picture using camera in landscape mode .I am displaying picture in potrait mode also how to display picture properly in all modes can anybody give example Thanks A: Check onConfigurationChanged(). Hope this provide the data you need
{ "language": "en", "url": "https://stackoverflow.com/questions/7500841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Batch Script - Create user in Windows XP programmatically Is there a way to create a user in Windows XP via Batch Script and even assign it administrator/limited user value? A: Suppose the username is rased and password is pAsS net user rased pAsS /add net localgroup administrators rased /add here user is added under administrators group. A: Yes, you can create a user by running net user USERNAME PASSWORD /add (omit the PASSWORD if you do not wish to have a password for this account, use * for PASSWORD to require the user to enter a password at run time). This creates a "limited user"; if you wish to make the new user an administrator, run net localgroup Administrators USERNAME /add after creating the user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Save as png dynamically in Matlab? I am very new to Matlab so sorry if this is trivial. I have a matlab code done by another student and I am trying to do something. There is a pattern generated which should be saved to a .png image. For now, it asks for user input on where to save the file like following: [filename,pathname,dummy] = uiputfile('*.png'); imwrite(image_blobs,[pathname filename '.png'],'png'); I need it to be saved as soon as the pattern is generated, I did try to do the following: pathname='H:\matlab_modified'; filename='pic'; imwrite(image_blobs,[pathname filename '.png'],'png'); but this will not work. I also did try the save but the save will not save it as image, right ? Any idea how to do it ? thanks A: pathname='H:\matlab_modified'; filename='pic'; % build full filename from path, filename and extension full_filename = fullfile(pathname, filename, '.png'); imwrite(image_blobs, full_filename, 'png');
{ "language": "en", "url": "https://stackoverflow.com/questions/7500854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How is it possible that I see Facebook URLs in my server logs? I have been seeing URLs in my apache server logs that are clearly meant for another site. The most common one that I see is Facebook, but I've also seen Tumblr and YouTube. I am trying to figure out how that could happen. Here is an example of a request that was logged on my server (I removed the remote IP address): [IP Redacted] - - [21/Sep/2011:13:31:35 +0000] "POST /ajax/chat/buddy_list.php?__a=1 HTTP/1.1" 404 797 "http://www.facebook.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_1) AppleWebKit/534.48.3 (KHTML, like Gecko)" This looks like someone was on facebook.com, using Facebook chat, and for whatever reason the post got sent to my server. Does anyone have an idea for how this could happen, or how I could go about investigating it further? A: As far as I know, when posting a link on Facebook to your site, Facebook will commonly try to get some information (page title, article title, some text, maybe a photo) from the link. I suspect that that's what's happening here. A: There are all kinds of script kiddies that try to use your apache server as a proxy. I don't know of any vulnerabilities on this, but results related to that i found also on my logs. You should not worry about them. A: My guess would be "automated 'hacking' scripts blindly trying everything and anything in their arsenal" - similar to this question. If your server handles the requests correctly (i.e. returns an appropriate error page, and doesn't forward them), you should be in the clear. A: Check your hosts file if any traffic is being directed or this could be the referer of the website they last used to reach your server. Also they could be using your server as a proxy to gain access to blocked websites seeing as the traffic is going through you. I'm looking at again and it seems you are blocking Facebook because the 404? EDIT: You could try blocking common websites from your server using the hosts file to make them piss off.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access to sql compact 4 db not allowed in ASP.NET MVC 3 Scaffolding This is a bit of a weird one. I'm doing an MVC 3 code first development using the SQL compact 4 stuff. Its all running fine but I'm getting issues when I try to scaffold a new controller. I fire up the new controller dialog and select my entity and the datacontext (both of which are in a separate assembly in the same solution) and get the following error: Unable to retrieve metadata for 'MyNamespace.MyClassName'. Access to the database file is not allowed. [ 1884,File name=C:\Program Files\Microsoft Visual Studio 10.0\Common7\EntityContext.sdf,SeCreateFile ] That file does not exist on disk at the moment - the EntityContext.sdf file is sat in my App_Data folder. I'm not sure if its trying to create that file (and if so why?) but if it is I'm not logged in as admin so it won't have permissions. In that case do I need to define a difference working folder or something? I've tried it running as admin now and it works, so it's definitely trying to create a file in my Program Files directory, there must be a setting for temp files somewhere? Any help would be great :) A: Did you find an answer to the issue? I was having the same problem but handled it through the deployment transforms... In Web.Config I used full path to the SDF: <configuration> <connectionStrings> <add name="DBContext" connectionString="Data Source=C:\full-path\DBContext.sdf" providerName="System.Data.SqlServerCe.4.0" /> ... In Web.Release.config I replace the connectionString attribute... <?xml version="1.0"?> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <connectionStrings> <add name="DBContext" connectionString="Data Source=\DBContext.sdf" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> </connectionStrings> <system.web> <compilation xdt:Transform="RemoveAttributes(debug)" /> </system.web> </configuration> After a release deploy the correct "|DataDirectory|" setting is made rather than "C:\full-path\". I would like a fix to the original issue though!! PK :-) A: I have also faced the same problem when tried to export SQL CE db script with number of utils. Got error "Access to the database file is not allowed". Then I have just connected to that db-file from VS2010, copied connection string and... it worked! :) A: I ran into this issue when using the T4Scaffolding. I got around the problem by installing the MVCScaffolding nuget package and used the "MVCScaffolding: Controller with read/write action and views, using EF data access code" template. It produces similar controller actions and views. I was unable to uninstall and reinstall the T4Scaffolding nuget package to see if this was a bug or corrupt install.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }