text
stringlengths
8
267k
meta
dict
Q: SQl exception in VS I'm getting an SQLexception while debugging in VS. The error is: The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 8 ("@Pris"): The supplied value is not a valid instance of data type float. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision. string query = "INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris) Values (@ListID, @ListeNr, @Stregkode, @Navn, @Antal, @Pris)" ; SqlCommand com = new SqlCommand(query, myCon); com.Parameters.Add("@ListID",System.Data.SqlDbType.Int).Value=id; com.Parameters.Add("@ListeNr",System.Data.SqlDbType.Int).Value=listnr; com.Parameters.Add("@Stregkode",System.Data.SqlDbType.VarChar).Value=strege ; com.Parameters.Add("@Navn",System.Data.SqlDbType.VarChar).Value=navn ; com.Parameters.Add("@Antal",System.Data.SqlDbType.Int).Value=il.Antal; com.Parameters.Add("@Pris",System.Data.SqlDbType.Float).Value=il.Pris; com.ExecuteNonQuery(); com.Dispose(); myCon.Close(); I'm getting it at the ExecuteNonQuery. I know what the exception is about, but i Dont know haów to fix it. In my database i'm using float on my "prices", and in VS im using double. I think that I have read something that says a double en VS are like a float in sql. Thanks! A: This error appears when source exceeds the target parameter range. Ensure precision and scale are in range of target data type. http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/4392aad1-eed0-4d6a-b891-90685b2e8258/
{ "language": "en", "url": "https://stackoverflow.com/questions/7555981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flot re-draw single series I am looking for a way to re-draw a single series in Flot, I know I can use plot.setData(newData) and plot.draw() to re-draw all the data series but I have one series with 100,000+ points so I dont really want to re-draw this one every time At a guess I could use the drawSeries hook but Im not sure how to implement this? Thanks in advance David
{ "language": "en", "url": "https://stackoverflow.com/questions/7555983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting numbers from a string in iPhone programming I have a string. It's always 3 letters long, and it can be counted on to only contain three integers. Say it looks like this: NSString * numberString = @"123"; Now, I want to extract those numbers from it. 1, 2 and 3. In any other language I'd just fetch the character for each position and parse it, or even cast it. However, Objective-C doesn't seem to have that. I found some other answer recommending that i use the characterAtIndex method, use numberWithChar on that, and then subtract the number "48" from it, leaving even myself scratching my head at the apparent stupidity of it all. Is there no other, more elegant way to do this? I tried using substringWithRange, but apparently there's no method for creating an NSRange, and it's incompatible with CFRangeMake for some reason. A: How about [[numberString substringWithRange:NSMakeRange(0,1)] intValue]? A: int n=[@"123" intValue]; From this you can get the individual numbers by n/100, n/10 and n%10. A: How about this? NSString * numberString = @"123"; NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; NSNumber *number = [formatter numberFromString:numberString]; int n = [number intValue]; (Don't forget to release the formatter after you finish your conversions.) A: NSString *numberString = @"123"; int firstDigit = [numberString characterAtIndex:0] - '0'; int secondDigit = [numberString characterAtIndex:1] - '0'; int thirdDigit = [numberString characterAtIndex:2] - '0'; NSLog(@"Your digits are %d, %d, %d", firstDigit, secondDigit, thirdDigit); If you want to cheat: char *numberString = [@"123" cStringUsingEncoding:NSASCIIStringEncoding]; printf(@"Your digits are %d, %d, %d\n", numberString[0] - '0', numberString[1] - '0', numberString[2] - '0');
{ "language": "en", "url": "https://stackoverflow.com/questions/7555995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Versioning assemblies built off source code stored in a DVCS What I'm up to is to have an ability to tell a changeset which was used to build an assembly. With Subversion it's all nice and simple: embed repository revision number straight into assembly version (like 1.0.5873 with 5873 being revision number). DVCSes, however, do not have reliable human-readable revision numbers but they do have changesets which are long hexadecimal strings. Those obviously don't fit into any version number. So the question is: what's the current best practice to version such assemblies? A: Usually, you would use git describe to get that kind of human-readable information. As illustrations, see: * *"Moving from CVS to git: $Id:$ equivalent?" *"Build sequencing when using distributed version control" *"what is the git equivalent for revision number?"
{ "language": "en", "url": "https://stackoverflow.com/questions/7556000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Redirect request to CDN using nginx I have a couple of server addreses, like cdn1.website.com, cdn2.website.com, cdn3.website.com. Each of them holds simillar files. Request comes to my server and I want to redirect or rewrite it to a random cdn server. Is it possible ? A: You could try using the split clients module: http { # Split clients (approximately) equally based on # client ip address split_clients $remote_addr $cdn_host { 33% cdn1; 33% cdn2; - cdn3; } server { server_name example.com; # Use the variable defined by the split_clients block to determine # the rewritten hostname for requests beginning with /images/ location /images/ { rewrite ^ http://$cdn_host.example.com$request_uri? permanent; } } } A: This is of course possible. Nginx comes with load balancing: upstream mysite { server www1.mysite.com; server www2.mysite.com; } This defines 2 servers for load balancing. By default requests will be equally distributed across all defined servers. You can however add weights to the server entries. Inside your server {} configuration you can now add the following to pass incoming requests to the load balancer (e.g. to load balance all requests for the images directory): location /images/ { proxy_pass http://mysite; } Have a look at the documentation for a more detailed description.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Avoid transformation text to link ie contentEditable mode In contenteditable div, in IE text like "http://blablabla", "www.blablabla", "bla@blabla" and so on automatically transforms into hyperlinks http://blablabla, www.blablabla, bla@blabla. How can I avoid this? A: Unfortunately, there is no cross-version solution. In IE9 there is opportunity, allowing to disable automatic hyperlinking: document.execCommand("AutoUrlDetect", false, false); More information: http://msdn.microsoft.com, http://bytes.com
{ "language": "en", "url": "https://stackoverflow.com/questions/7556007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Aggregating Data using R I'm trying to plot the data using R by reading my CSV file which contains some values which were logged on per-second basis. I would like R to aggregate the data to per-minute basis so that I can plot the per-minute data using plot(TIME,VALUE.). My CSV file contains something like this; Store No.,Date,Time,Watt 33,2011/09/26,09:11:01,0.0599E+03 34,2011/09/26,09:11:02,0.0597E+03 35,2011/09/26,09:11:03,0.0598E+03 36,2011/09/26,09:11:04,0.0596E+03 37,2011/09/26,09:11:05,0.0593E+03 38,2011/09/26,09:11:06,0.0595E+03 39,2011/09/26,09:11:07,0.0595E+03 40,2011/09/26,09:11:08,0.0595E+03 41,2011/09/26,09:11:09,0.0591E+03 I'm having trouble aggregating the Time and Watt column on per-minute basis as I'm a newbie to R. Any help would be highly appreciated. A: Assuming Store No. is irrelevant and changing the last three rows in the example data shown in the question to be 09:12:.. rather than 09:11:.. so we have at least two different minutes: # create test data Lines <- "Store No.,Date,Time,Watt 33,2011/09/26,09:11:01,0.0599E+03 34,2011/09/26,09:11:02,0.0597E+03 35,2011/09/26,09:11:03,0.0598E+03 36,2011/09/26,09:11:04,0.0596E+03 37,2011/09/26,09:11:05,0.0593E+03 38,2011/09/26,09:11:06,0.0595E+03 39,2011/09/26,09:12:07,0.0595E+03 40,2011/09/26,09:12:08,0.0595E+03 41,2011/09/26,09:12:09,0.0591E+03" cat(Lines, "\n", file = "data.txt") # read in aggregating at the same time library(zoo) library(chron) z <- read.zoo("data.txt", header = TRUE, sep = ",", index = 2:3, FUN = paste, FUN2 = function(x) trunc(as.chron(x), "00:01:00"), aggregate = mean)[, -1] Here FUN is applied to the columns specified by index. It pastes them together and then FUN2 is applied to the result of FUN creating a chron date/time. Finally rows with the same values of FUN2 are then aggregated taking the mean of Watt giving: > z (09/26/11 09:11:00) (09/26/11 09:12:00) 59.63333 59.36667 Depending on what is wanted the aggregate argument could be changed to aggregate = function(x) tail(x, 1) in place of the aggregate argument shown. For more info and examples, load the zoo package and look in ?read.zoo, ?aggregate.zoo and vignette("zoo-read") as well as the other vignettes and help files. UPDATE: Slight simplification by using the FUN2 argument. Not sure but that read.zoo argument may not have existed at the time this question was first answered.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Select where column not in an other one 2 times If I have table like this called "table" +--------------+ | id | c1 | c2 | +--------------+ | 1 | a | 0 | | 2 | b | 1 | | 3 | c | 1 | | 4 | d | 2 | | 5 | e | 2 | | 6 | f | 3 | | 7 | g | 4 | | 8 | h | 5 | +--------------+ I want to SELECT 'c1' FROM 'table' WHERE 'id' not in 'c2' 2 times A: SELECT * FROM table WHERE id NOT IN (SELECT c2 FROM table GROUP BY c2 HAVING Count(c2) = 2) A: SKIP IDS WHICH ARE NOT IN C2 AT ALL: SELECT d.id, d.c1, g.gcount FROM ( SELECT c2 as gc2, COUNT(*) as gcount FROM @data GROUP BY c2 ) g INNER JOIN @data d ON d.id = g.gc2 AND gcount != 2 OUTPUT: id | c1 | gcount 3 | c | 1 4 | d | 1 5 | e | 1 INCLUDE IDS WHICH NOT IN C2: SELECT d.id, d.c1, ISNULL(g.gcount, 0) as gcount FROM ( SELECT c2 as gc2, COUNT(*) as gcount FROM @data GROUP BY c2 ) g RIGHT JOIN @data d ON d.id = g.gc2 WHERE gcount IS NULL OR g.gcount != 2 OUTPUT: id c1 gcount 3 c 1 4 d 1 5 e 1 6 f 0 7 g 0 8 h 0 A: select t.* from table t left outer join ( select c2, count(*) as Count from table group by c2 ) tc on t.id = tc.c2 where Count is null or Count < 2 A: select t1.c1 from t t1, t t2 where t1.id = t2.c2 group by t1.c1 having count(t2.c2) != 2;
{ "language": "en", "url": "https://stackoverflow.com/questions/7556019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Perl regex matching problem I think I'm missing something simple here... $key = "deco-1-LB-700F:MAR:40"; if ($key =~ m/deco-(.*?)-(.*?)-(.*?):(.*?):(.*?)/) { print "1=$1 2=$2 3=$3 4=$4 5=$5"; } This results in the output: 1=1 2=LB 3=700F 4=MAR 5= Why isn't $5 returning the value 40 ? Cheers, Stu A: Because .*? is lazy and will match zero characters if it can. Anchor the regex to the end of the string: $key =~ m/deco-(.*?)-(.*?)-(.*?):(.*?):(.*?)$/ But it's nearly always better to use something more explicit than the catch-all .* and .*?. Tell the regex engine exactly what you want to allow to match. Assuming that the delimiters - and : never occur in the actual matches, I suggest $key =~ m/deco-([^-]*)-([^-]*)-([^:]*):([^:]*):([^:]*)$/ * *[^-] means "match any character except -". *[^:] means "match any character except :". A: split qr/[:-]/, 'deco-1-LB-700F:MAR:40' returns ( 'deco', 1, 'LB', '700F', 'MAR', 40, )
{ "language": "en", "url": "https://stackoverflow.com/questions/7556023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using GAE/UserService to login to XMPP I am working on a problem solving game which will be hosted on GAE. I use the UserService API to validate the user before letting them play the game. During the game, I would like to update the users gtalk status to something like "User X is on step y of the game". Is this possible? I toyed around with smack library and I could do it, provider I knew the password. However, in my GAE scenario I rely on the UserService. How can I login to XMPP using GAE UserService? A: you don't have access to change the status message of the user A: The XMPP service provides 'bot accounts' on a dedicated domain, which you can use to send and receive XMPP messages on any connected network. It doesn't give you access to a user's gtalk account, or let you authenticate as arbitrary XMPP accounts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split a string into multiple sections by index perl I have the output from a diskpart command: Volume ### Ltr Label Fs Type Size Status Info ---------- --- ----------- ----- ---------- ------- --------- -------- Volume 0 D DVD-ROM 0 B No Media Volume 1 C OSDisk NTFS Partition 232 GB Healthy Boot Volume 2 BDEDrive NTFS Partition 300 MB Healthy System I want to capture each of these into their own specific variable, so my first inclination was to do something like ($volume, $ltr, ..., $info) = $line =~ ((\w+\s\d+)\s+([A-Z])?... The problem I ran into with that is that there's nothing unique between Label, FS, and Type so if I'm using (\w+)\s+ on each of those columns, there's a chance Label doesn't exist but a FS does, and thus the filesystem reads into $label improperly. I'm not too sure if I can make this work with regex, but I'm open to suggestions! Instead I was going to go in a new direction and just split the string up based on the indices of beginning - and ending -. If I pulled in all these indices, what's the best method to split this string up into their respective substrings Perl? I looked at substr, and attempted to pass it multiple indices like ($a,$b,$c) = substr('abcd', 1,2,3); but this merely resulted in $a being split between 2,3 Is there any elegant solution to this besides just splitting everything up one line at a time? A: Instead of using a (not very maintainable) regex, it is much easier to use unpack: my @l = unpack('A12 A5 A13 A7 A12 A9 A11 A9', $_); You still have to throw away the second line, but you don't have to care about how your data looks like. A: How about: #!/usr/bin/perl use strict; use warnings; use Data::Dump qw(dump); while(<DATA>) { chomp; my @l = /^(\w*\s\d*)\s+(\w|\s)\s+(\w+|\s+)\s+(\w+|\s+)\s+([\w-]+|\s+)\s+(\d+\s\w{1,2})\s+?([\w\s]+)\s+?([\w\s]+)$/; dump(@l) if @l; } __DATA__ Volume ### Ltr Label Fs Type Size Status Info ---------- --- ----------- ----- ---------- ------- --------- -------- Volume 0 D DVD-ROM 0 B No Media Volume 1 C OSDisk NTFS Partition 232 GB Healthy Boot Volume 2 BDEDrive NTFS Partition 300 MB Healthy System output: ( "Volume 0", "D", " ", " ", "DVD-ROM", "0 B", " No Media ", " ", ) ( "Volume 1", "C", "OSDisk", "NTFS", "Partition", "232 GB", " Healthy ", "Boot", ) ( "Volume 2", " ", "BDEDrive", "NTFS", "Partition", "300 MB", " Healthy ", "System", )
{ "language": "en", "url": "https://stackoverflow.com/questions/7556028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting classname of a object in Perl I have an object reference and it could be a reference to an object of type 'FooInvalidResults' There is a file called FooInvalidResults.pm and there is a line 'package FooInvalidResults' in it. will the following work? my $class = blessed $result; if ($class eq 'FooInvalidResults') { # do something } else { # do something else } A: String-comparing class names is generally a bad idea, because it breaks polymorphism based on subtypes, and because it's generally not good OO practice to be that nosy about intimate details of an object like its exact package name. Instead, write $result->isa('FooInvalidResults') — or, if you're paranoid about the possibility that $result isn't an object at all, blessed $result && $result->isa('FooInvalidResults'). Using UNIVERSAL::isa is a bad idea because some objects (for instance, mock objects for testing) have legitimate reasons to override the isa method, and calling UNIVERSAL::isa breaks that. A: Why didn't you use UNIVERSAL::isa? if UNIVERSAL::isa( $result, "FooInvalidResults" ) { ... } This was bad advice, please use $obj->isa( 'FooInvalidResults' ); I wasn't full aware of the difference between subroutine call ( BAD ) and method call ( GOOD ), but it became clear after I did some RTFM myself ( perldoc UNIVERSAL ). Thanks ( and +1 ) to all folks that pointed out my fault. A: It is also possible to do the job with the ref() builtin rather than Scalar::Util::blessed(): $ perl -E '$ref = {}; bless $ref => "Foo"; say ref $ref' Foo Note that if the reference is not blessed, this will return the type of reference: $ perl -E '$ref = {}; say ref $ref' HASH However, as others have mentioned, UNIVERSAL::isa is a better solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Load or functional testing of GWT app using JMeter I am new to JMeter. I wanted to do some functional testing of my GWT application using JMeter. Does it support GWT testing? For example I would like to write a script that might check if the login module of my GWT application is doing good or not. Please let me know if we have some sort of documentation specific to GWT testing with JMeter. Thanks a million. -- Mohyt A: There is a commercial solution called UbikLoadPack which offers a plugin for Apache JMeter to load test GWT and GWT RPC applications. You can easily record, variabilize and replay GWT and GWT RPC based applications with standard knowledge of Apache JMeter. See this blog for a tutorial: * *http://www.dzone.com/links/load_testing_gwtrpc_applications_with_ubik_load_p.html And this for commercial infos: * *http://www.ubikloadpack.com/ A: I think GWTRpcComLayer might be useful for your case: http://code.google.com/p/gwtrpccommlayer/ A: if you wanna test gwt client side then you have to use junit because jmeter does not support javascript and if you want to test at backend side than you have JMeter send it HTTP requests via HttpClient (http://hc.apache.org/httpclient-3.x/) or something similar. A: JMeter is not the right tool for GWT-testing. From jmeter homepage: JMeter is not a browser. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. In clear words: jmeter doesn’t load your gwt-application. I would recommend selenium for browser based testing. Or just use JUnit with GWTTestCase for functional testing inside your IDE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Setup MonkeyRunner on Android I'd like to use MonkeyRunner. I've got a monkeyrunner.jar and import it into my project. How can I use it now? Could you tell me what should I do step-by-step. I've seen some code snippet on python, but I don't understand how can I use python in eclipse. A: Maybe this link can help you how to use monkeyrunner in eclipse: http://fclef.wordpress.com/2011/11/24/using-android-monkeyrunner-from-eclipse-in-windows/
{ "language": "en", "url": "https://stackoverflow.com/questions/7556037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Having trouble with the Socket.IO Tutorial samples. Incomplete documentation or PEBCAK? Over the weekend, I was trying to figure out websockets (since I think it would probably be a really fun thing to know). I did a search around for socket.io tutorials and found this Good beginners tutorial to socket.io? which suggested I start on http://socket.io On a fresh ubuntu I built node.js 4.1.13-pre (many packages won't work with the current 0.5.8) I added, NPM and the express, jade & socket.io packages. I set up and ran a server: var io = require('socket.io').listen(8000); // I moved the port var express = require('express'); // I had to add this io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); }); I cloned https://github.com/LearnBoost/socket.io.git and made an index.html in the directory above the place I cloned socket IO into <script src="socket.io/lib/socket.io.js"></script> <!-- changed path from example --> <script> var socket = io.connect('http://localhost:8000'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); </script> When I load up the index page locally, I get the error: require not defined I'm assuming that I've missed something here, is the client-side JS not the same one from the lib folder? DO I need to add something to allow for the existence of 'require'? What am I missing? How do I serve up the client side JS correctly? A: Try <script src="/socket.io/socket.io.js"></script> instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to map function address to function in *.so files backtrace function give set of backtrace how to map it with function name/file name/line number? for ex:- backtrace() returned 8 addresses ./libtst.so(myfunc5+0x2b) [0xb7767767] ./libtst.so(fun4+0x4a) [0xb7767831] ./libtst.so(fun3+0x48) [0xb776787f] ./libtst.so(fun2+0x35) [0xb77678ba] ./libtst.so(fun1+0x35) [0xb77678f5] ./a.out() [0x80485b9] /lib/libc.so.6(__libc_start_main+0xe5) [0xb75e9be5] ./a.out() [0x80484f1] From the above stack how can I get the file name and line number? I did following things, but no luck. Correct me if I am wrong :) for ex:- ./libtst.so(fun2+0x35) [0xb77dc887] 0xb77dc887(fun2 addr+offset)-0xb77b6000 (lib starting addr) = 0x26887 (result) result is no way related to function in nm output. I used addr2line command:- addr2line -f -e libtst.so 0xb77dc887 ?? ??:0 So, how can I resolve either at runtime or post runtime? Thanks in advance... nm:- 00000574 T _init 00000680 t __do_global_dtors_aux 00000700 t frame_dummy 00000737 t __i686.get_pc_thunk.bx 0000073c T myfunc5 000007e7 T fun4 00000837 T fun3 00000885 T fun2 000008c0 T fun1 00000900 t __do_global_ctors_aux 00000938 T _fini 000009b4 r __FRAME_END__ 00001efc d __CTOR_LIST__ 00001f00 d __CTOR_END__ 00001f04 d __DTOR_LIST__ 00001f08 d __DTOR_END__ 00001f0c d __JCR_END__ 00001f0c d __JCR_LIST__ 00001f10 a _DYNAMIC 00001ff4 a _GLOBAL_OFFSET_TABLE_ 00002030 d __dso_handle 00002034 A __bss_start 00002034 A _edata 00002034 b completed.5773 00002038 b dtor_idx.5775 0000203c B funptr 00002040 A _end U backtrace@@GLIBC_2.1 U backtrace_symbols@@GLIBC_2.1 U free@@GLIBC_2.0 U __isoc99_scanf@@GLIBC_2.7 U perror@@GLIBC_2.0 U printf@@GLIBC_2.0 U puts@@GLIBC_2.0 w __cxa_finalize@@GLIBC_2.1.3 w __gmon_start__ w _Jv_RegisterClasses pmap:- START SIZE RSS PSS DIRTY SWAP PERM MAPPING 08048000 4K 4K 4K 0K 0K r-xp /home/test/libtofun/a.out 08049000 4K 4K 4K 4K 0K r--p /home/test/libtofun/a.out 0804a000 4K 4K 4K 4K 0K rw-p /home/test/libtofun/a.out ... b7767000 4K 4K 4K 0K 0K r-xp /home/test/libtofun/libtst.so b7768000 4K 4K 4K 4K 0K r--p /home/test/libtofun/libtst.so b7769000 4K 4K 4K 4K 0K rw-p /home/test/libtofun/libtst.so .... Total: 1688K 376K 82K 72K 0K 128K writable-private, 1560K readonly-private, 0K shared, and 376K referenced libtst.c:- void myfunc5(void){ int j, nptrs; #define SIZE 100 void *buffer[100]; char **strings; nptrs = backtrace(buffer, SIZE); printf("backtrace() returned %d addresses\n", nptrs); strings = backtrace_symbols(buffer, nptrs); if (strings == NULL) { perror("backtrace_symbols"); } for (j = 0; j < nptrs; j++) printf("%s\n", strings[j]); free(strings); } void fun4(){ char ip; char *fun = "fun4\0"; printf("Fun name %s\n",fun); scanf("%c",&ip); myfunc5(); } void fun3(){ char *fun = "fun3\0"; printf("Fun name %s\n",fun); funptr = fun4; funptr(); } void fun2(){ char *fun = "fun2\0"; printf("Fun name %s\n",fun); fun3(); } void fun1(){ char *fun = "fun1\0"; printf("Fun name %s\n",fun); fun2(); } main.c:- int main(){ char ip; funptr = &fun1; scanf("%c",&ip); funptr(); return 0; } Let me know if need more information... A: objdump -x --disassemble -l <objfile> This should dump, among other things, each compiled instruction of machine code with the line of the C file it came from. A: At runtime with eu-addr2line (automatically finds the libraries and calculates offsets): //------------------------------------- #include <sys/types.h> #include <unistd.h> int i; #define SIZE 100 void *buffer[100]; int nptrs = backtrace(buffer, SIZE); for (i = 1; i < nptrs; ++i) { char syscom[1024]; syscom[0] = '\0'; snprintf(syscom, 1024, "eu-addr2line '%p' --pid=%d > /dev/stderr\n", buffer[i], getpid()); if (system(syscom) != 0) fprintf(stderr, "eu-addr2line failed\n"); } Stick a --debuginfo-path=... option if your debug files are somewhere else (matched by the build-id, etc.). eu-addr2line is in the elfutils package of your distribution. A: Try giving the offset to addr2line, along with the section name. Like this: addr2line -j .text -e libtst.so 0x26887 Edit: By the way, if it wasn't clear, the 0x26887 comes from what you provided: 0xb77dc887(fun2 addr+offset)-0xb77b6000 (lib starting addr) = 0x26887 (result) A: I've had a look at files backtrace.c and backtracesyms.c files in glibc source code (git://sourceware.org/git/glibc.git, commit 2482ae433a4249495859343ae1fba408300f2c2e). Assuming I haven't misread/misunderstood things: backtrace() itself looks like it will only give you symbol addresses as they are at runtime, which I think means you need the library load address as it was from pmap or similar. However, backtrace_symbols() recalculates things so that the addresses are relative to the shared library ELF, and not the process at runtime, which is really convenient. It means you don't need information from pmap. So, if you've compiled with -g (or with -rdynamic), then you're in luck. You should be able to do the following: $ # get the address in the ELF so using objdump or nm $ nm libtst.so | grep myfunc 0000073c T myfunc5 $ # get the (hex) address after adding the offset $ # from the start of the symbol (as provided by backtrace_syms()) $ python -c 'print hex(0x0000073c+0x2b)' 0x767 $ # use addr2line to get the line information, assuming any is available addr2line -e libtst.so 0x767 Or, using gdb: $ gdb libtst.so (gdb) info address myfunc Symbol "myfunc" is at 0x073c in a file compiled without debugging. # (Faked output) (gdb) info line *(0x073c+0x2b) Line 27 of "foo.cpp" starts at address 0x767 <myfunc()+21> and ends at 0x769 <something>. # (Faked output) Also, if you've stripped the library, but stashed off debug symbols for later use, then you'll likely only have ELF offsets printed out by backtrace_syms() and no symbol names (so not quite the case in the original question): In this instance, using gdb is arguably more convenient than using other command line tools. Assuming you've done this, you'll need to invoke gdb like so (for example): $ gdb -s debug/libtst.debug -e libtst.so And then go through a similar sequence as above, using 'info line' and 'info address' depending on whether you only have ELF symbol offsets, or symbol names plus offsets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }
Q: Does Haskell have an equivalent to Sage? Is there something like Sage for Haskell programmers? A: Unfortunately, the answer seems to be "NO". Possibly interesting to some readers is the following: Often, one programming language is not enough for a task. E.g. when I need to solve a problem which is remotely related to statistics, R (r-project.org) is just the best fit. But I don't want to program all code in R because, Haskell has this great type system and so many other important features. I think the best way is a hybrid approach. I write a RESTful web service around the functionality of the R code, and with Haskell I access the web service to get or send data. (Or maybe another way to access R directly.) Perhaps a hybrid approach with Haskell and Python+Sage makes sense. Currently I have following three programming languages on my "stack": * *Haskell *R (r-project.org) *Agda (or maybe Coq) Also possibly interesting: In R there is a little overlap in functionality with Sage. Mainly the linear algebra, plotting functionality, and further some of the libraries (e.g. GD library) are also available in R. Agda has some support for * *Algebra and Polynomials *Rings Agda should work well together with Haskell and even the syntax is very similar. Coq can also be used with Haskell. See: Proving "no corruption" in Haskell I wrote "maybe" and "perhaps" because I don't know if the information is relevant to the question. A: As it was said, there is none. However there is Axiom, whose language Spad is the closest too Haskell among general purpose advanced CAS's. It has strong static typing and abstraction with categories which are similar (I would say the same) as Haskell's classes. Previously Axiom could also use Aldor which is superior to Haskell since it features dependent types. But unfortunately Aldor is dead due to licensing problems. Be sure to check also FriCAS, Axiom's fork. A: honestly,as far as i know none exists. But there is something called REPA which is similar(well in a haskellish way),to numpy. A: There are two option that have been produced after hammers answer: * *Github Ghc live, Hackage *Ghci in a new dress GHC live is the more recent of the two.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: MySQL db design for products I am developing a web application that will allow people to keep track of products that they will move around. Example: I have 10 cups in my warehouse. I move 5 cups to ShopA and 5 cups to ShopB. I then move 3 cups from ShopA back to my warehouse. In terms of my db structure, i thought of having a products table that looked something like this: product_id location_id quantity But it seems a little clumsy. In the example i would have 1 record in products table for this product, then 2, then 3. My question is: Is it better in this case to have 10 rows (1 row per item instead of a quantity field) for this product and change location of each product? But if this table stores the products for lots of users, in a very short period of time, the table will have millions of rows... should i be worried about that? I am very interested in what is considered the best practice in this kind of situation. thank you! A: The question is this: What items in your inventory have a unique identity? Does each cup have a distinct barcode on it? (never mind cups; let's talk about books). If your items have unique identifiers (their own barcodes or RFID tags) you definitely need a row for each item. As you acquire, relocate, or sell each item you'll update its row to reflect its new location. For example, consider books in a library. Each book is unique. Even if the library owns two copies of the book, they are handled separately. On the other hand, if the items are interchangeable, like copies of books in a bookstore, then you can make the simplifying assumption that you can have an item count for each item for each location. The book store has five copies of the latest Harry Potter on the shelf. When a customer buys one, the bookstore now has four copies. When the bookstore receives another boxful, it how has 14 copies. Of course, the two approaches are quite different in the nature of the DBMS transaction that takes place when you relocate inventory. The second approach looks more like double entry bookkeeping, and the first like a census of products. Considering how cheap data storage is these days, and the proliferation of unique identifiers like RFID tags, you are probably better off using the first approach, with a row for each item. A: I think the simple question is do you want easier programability, or a smaller database? With storage as cheap as it is now, and only getting cheaper, the answer is clear: save yourself significant heartburn and build your database in a manner that gives you the simplest code in the future. A: I agree with Ollie Jones' answer, but I would like to add that the "Double Entry Bookkeeping" method would be to have rows like this: CREATE TABLE [Transactions] ( [FromLocationId] /* foreign key to the locations */, [ToLocationId] /* ditto */, [Amount] ) This way, there is only one row per transaction. A: If your save 1 row per item: * *No concurerency locks. Fast insert/delete item. Simplest design. If save item with quantity: * *Concurency update is more complex. For avoid blocks we added new field in table and verify/set it before every update. Millions of rows - not problem for MySQL See also NoSQL-store: maybe above efficient for your. P.S. Sorry for my english. A: In my opnion whatever the situation -> you have just two ways to follow: * *concurerency *no concurerency In short words it mean, you are going to record a lot of lines in your database or just record the Quantity of that item. Partiulary I prefer to record only the quantity of that item (using concurerency), it is sometimes more complex to manage, but a good routine to take care of it, will give you no trouble at all in the future, because your database will not grow up if you are not going to use concurerency. But of course, mysql can hold easily milions of rows without a problem, It is up to you to decide the best aprouch. Forecast your databse growth, measure it, if the database will grow up a lot in a short span of time, then is better you go with concurerency method. Good Luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7556057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to perform a PDF conversion in Event Receiver? I am trying to convert the document a .docx file available in document library(conversion) to PDF format in same library whenever the file is updated. The code I am using is given below: public override void ItemUpdated(SPItemEventProperties properties) { ConversionJob job = new ConversionJob(wordAutomationServiceName); job.UserToken = properties.Web.CurrentUser.UserToken; job.Settings.UpdateFields = true; job.Settings.OutputFormat = SaveFormat.PDF; string input = siteURL + "Conversion/Test.docx"; string output = siteURL + "Conversion/Test.pdf"; job.AddFile(input, output); job.Start(); } When I run it in debug mode, it executes without any error or exception but it is not generating any PDF file. I am not able to find out what the problem is it tried this simple code using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; using Microsoft.Office.Word.Server.Conversions; class Program { static void Main(string[] args) { string siteUrl = "http://siteurl"; string wordAutomationServiceName = "Word Automation Services"; using (SPSite spSite = new SPSite(siteUrl)) { ConversionJob job = new ConversionJob(wordAutomationServiceName); job.UserToken = spSite.UserToken; job.Settings.UpdateFields = true; job.Settings.OutputFormat = SaveFormat.PDF; job.AddFile(siteUrl + "/Shared%20Documents/Test.docx", siteUrl + "/Shared%20Documents/Test.pdf"); job.Start(); } } } This also did nt workd what i feel is there is no error in code must be some problem with sharepoint settings A: Do you have a Document object? I'm not sure if you can use this in your context, but if yes, you could try: docObject.ExportAsFixedFormat("Yourdoc.pdf", WdExportFormat.wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateNoBookmarks, true, false, false, ref oMissing); More info here A: I assume you took your code from here. Where did you wordAutomationServiceName? Because it needs to match the name of the Word Automation Service you configured in the Central Administration. Also check the SharePoint TraceLog (14/LOGS) or the EventViewer for further information/errors. Also see this article about how to configure Word Automation Services for Development. How Word Automation Services Work
{ "language": "en", "url": "https://stackoverflow.com/questions/7556059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Split in Java and substring the result Possible Duplicate: string split in java I have this Key - Value , and I want to separate them from each other and get return like below: String a = "Key" String b = "Value" so whats the easiest way to do it ? A: String[] parts = str.split("\\s*-\\s*"); String a = parts[0]; String b = parts[1]; A: int idx = str.indexOf(" - "); String a = str.substring(0, idx); String b = str.substring(idx+3, str.length()); split() is a bit more computation intensive than indexOf(), but if you don't need to split billions of times per seconds, you don't care. A: String s = "Key - Value"; String[] arr = s.split("-"); String a = arr[0].trim(); String b = arr[1].trim(); A: I like using StringUtils.substringBefore and StringUtils.substringAfter from the belowed Jakarta Commons Lang library. A: String[] tok = "Key - Value".split(" - ", 2); // TODO: check that tok.length==2 (if it isn't, the input string was malformed) String a = tok[0]; String b = tok[1]; The " - " is a regular expression; it can be tweaked if you need to be more flexible about what constitutes a valid separator (e.g. to make the spaces optional, or to allow multiple consecutive spaces). A: something like String[] parts = "Key - Value".split(" - "); String a = parts[0]; String b = parts[1]; A: As a little bit longer alternative: String text = "Key - Value"; Pattern pairRegex = Pattern.compile("(.*) - (.*)"); Matcher matcher = pairRegex.matcher(text); if (matcher.matches()) { String a = matcher.group(1); String b = matcher.group(2); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: An asp.net page structure question In Default.aspx I have below code, <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> Place 1 <form id="form1" runat="server"> Place 2 <br /> <div> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> </div> </form> </body> </html> I put a button on the page to write "I am clicked!". And codebehind: public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button1.Text = "Button"; } protected void Button1_Click(object sender, EventArgs e) { Response.Write("I am clicked!"); } } When I build, the view of page is like below: Place 1 Place 2 Button When I click the button, "I am clicked!" is appeared before Place 1. The result is: I am clicked! Place 1 Place 2 Button Why does it appear before "Place 1"? Have you got any idea? A: Because you are writing directly in the response. If you want to have the text on specific position on the page, put an asp:label control on the page and set the Text property of the label control in the Button1_Click A: that's to be expected - look at the Page-Live-Cycle Please observe that the rendering is after the postback event handling. Normaly you don't use Response.Write put a control or asp-tag to output something in ASP.net A: Because control events are processed before page PreRender event. So all page content would be rendered after manual output within a control event handler. Basically you should not do this using Response.Write(), simply: button.Text ="I am clicked!"; MSDN - ASP.NET Page Life Cycle Control events Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android - ImageView exact coordinates how can I get the exact coordinates of a point in imageview? Just think my image is a bitmap of map of a city and it's width is greater that screen and it is in a scrollview. I want to take the same x and y values for same place on image after scrolling? How can I calculate these? Math calculations is not a problem but I couldn't find which data(property) I have to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is operator ~ for? Possible Duplicate: javascript bitwise operator question Documentation says, that it is bitwise NOT. But I don't understand these examples: var a = ~1; a -2 var a = ~8; a -9 var a = ~-1; a 0
{ "language": "en", "url": "https://stackoverflow.com/questions/7556081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# xattr file attributes I'm creating a cross-platform software and I want to know if there is any (easy) way to read/write Unix (Mac OSX/Linux) extended file attributes in C#. I've just read about xattr namespaces, but I haven't found any information about C# implementation or bindings of this feature. P.S. The only thing I found so far is python-xattr library, but I don't want to use it because: * *I don't want to obligate the users to install Python (there is already Mono/.NET dependency to deal with) *By using Python I will have a performance decrease (C# is compiled, while Python is interpreted) *I don't want to rely/depend on external tools (if it's possible), because it's not safe A: You should use the syscalls in Mono.Unix.Native.Syscall.*attr*. The nuget assembly is called Mono.Posix.NETStandard Note that the name of the name-value pair is prefixed with a namespace. According to man 7 xattr Currently, the security, system, trusted, and user extended attribute classes are defined as described below. Additional classes may be added in the future. public static void Test() { string path = "/root/Desktop/CppSharp.txt"; // Mono.Unix.Native.Syscall.getxattr() // Mono.Unix.Native.Syscall.fgetxattr() // Mono.Unix.Native.Syscall.lgetxattr() // Mono.Unix.Native.Syscall.setxattr() // Mono.Unix.Native.Syscall.fsetxattr() // Mono.Unix.Native.Syscall.lsetxattr // Mono.Unix.Native.Syscall.llistxattr() // Mono.Unix.Native.Syscall.flistxattr() // Mono.Unix.Native.Syscall.llistxattr() // Mono.Unix.Native.Syscall.removexattr() // Mono.Unix.Native.Syscall.fremovexattr() // Mono.Unix.Native.Syscall.lremovexattr() if (System.IO.File.Exists(path)) System.Console.WriteLine("path exists"); else System.Console.WriteLine("path doesn't exists"); System.Text.Encoding enc = new System.Text.UTF8Encoding(false); string[] values = null; int setXattrSucceeded = Mono.Unix.Native.Syscall.setxattr(path, "user.foobar", enc.GetBytes("Hello World äöüÄÖÜ"), Mono.Unix.Native.XattrFlags.XATTR_CREATE); if (setXattrSucceeded == -1) { Mono.Unix.Native.Errno er = Mono.Unix.Native.Stdlib.GetLastError(); string message = Mono.Unix.Native.Stdlib.strerror(er); // https://stackoverflow.com/questions/12662765/how-can-i-get-error-message-for-errno-value-c-language System.Console.WriteLine(message); } // End if (setXattrSucceeded == -1) byte[] data = null; long szLen = Mono.Unix.Native.Syscall.getxattr(path, "user.foobar", out data); string value = enc.GetString(data); System.Console.WriteLine(value); Mono.Unix.Native.Syscall.listxattr(path, System.Text.Encoding.UTF8, out values); System.Console.WriteLine(values); // https://man7.org/linux/man-pages/man2/getxattr.2.html } // End Sub TestExtendedAttributes A: The final solution might be the following, tell me what do you think? FileAttrsManager is an abstract class, used to create 2 derived classes: * *FileAttrsManagerDos: manages advanced attributes using DSOFile.dll* *FileAttrsManagerUnix: manages advanced attributes using IronPython* and python-xattr** [ * ] http:\\www.microsoft.com/download/en/details.aspx?displaylang=en&id=8422 [ ** ] http:\\ironpython.codeplex.com [ ** * ] http:\\pypi.python.org/pypi/xatt Extended attributes operation (such as SetPropery(string key, object value) and GetProperty(string key) etc) will be managed in a static class (FileAttrsProvider) that initializes a FileAttrsManager object to one of two derived types i.e.: public static class FileAttrProvider { private static FileAttrReader _reader = null; public static void Initialize() { switch (Environment.OSVersion.Platform) { case PlatformID.MacOSX: case PlatformID.Unix: _reader = new FileAttrReaderUnix(); break; case PlatformID.Win32NT: _reader = new FileAttrReaderDos(); break; } } } While the derived type depends on the environment, the original type is used in order to ensure an automatic dispatch of all the methods call on _reader object). A: I think Mono.Unix.Native.Syscall.setxattr would be a better solution, which is in Mono.Posix module.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set Facebook App Settings I have written an ASP.NET page for a customer which uses the C# Facebook API to post to Facebook. // Post to Facebook. // Build the Arguments. Dictionary postArgs = new Dictionary(); postArgs["message"] = "Hello World!"; // Post. var response = api.Post("/me/feed", postArgs); // Get New Post ID. var id = response.Dictionary["id"].String; I registered the application http://developers.facebook.com/setup/ using my personal Facebook account to test the integration. Under the section 'Select how your app integrates with Facebook' I chose 'Website' and entered the Site URL. When I view the App under my Account Settings it has the following 'App Settings': Access my basic information; Access my profiel information; Post to Facebook as me; Access my data anytime. Everything works great. I have set up the same application using my customer's Facebook account. I changed the Client ID and the Client Secret to the new details. It no longer works. When I view the App under my customer's Account Settings it doesn't have any of the 'App Settings' listed above. My 'App Settings' allows the App greater access to my Facebook Account compared to my customer's 'App Setttings' - which I guess is why it fails to post to my customer's Facebook Account. Unfortunately, I do not recall explicitly setting these 'App Settings' on my Facebook Account. I also can't seem to find anywhere on Facebook where I can set these 'App Settings' on my customer's account. Can someone please help / direct me please. Thanks in advance. Kind Regards Walter Update: Here is my code: First of all I authenticate: // Authenticate. string clientId = "0123456789"; string redirectUrl = "http://www.abc.com/oauth/oauth-redirect.aspx"; Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}", clientId, redirectUrl)); Next the oauth/oauth-redirect.aspx page is performed. Here is the code-behind of oauth/oauth-redirect.aspx.cs: if (Request.Params["code"] != null) { Facebook.FacebookAPI api = new Facebook.FacebookAPI(GetAccessToken()); // Build the Arguments. Dictionary postArgs = new Dictionary(); postArgs["message"] = "Hello World"; postArgs["link"] = "http://www.abc.com"; postArgs["name"] = "abc.com"; postArgs["type"] = "link"; postArgs["caption"] = "www.abc.com"; // Post. var response = api.Post("/me/feed", postArgs); // Get New Post ID. var id = response.Dictionary["id"].String; } private string GetAccessToken() { if (HttpRuntime.Cache["access_token"] == null) { Dictionary args = GetOauthTokens(Request.Params["code"]); HttpRuntime.Cache.Insert("access_token", args["access_token"]); } return HttpRuntime.Cache["access_token"].ToString(); } private Dictionary GetOauthTokens(string code) { Dictionary tokens = new Dictionary(); string clientId = "0123456789"; string redirectUrl = "http://www.abc.com/oauth/oauth-redirect.aspx"; string clientSecret = "a1a2a3a4a5a6a7a8a9a0"; string scope = "read_friendlists,user_status,publish_stream,user_about_me,offline_access"; string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&scope={4}", clientId, redirectUrl, clientSecret, code, scope); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); string retVal = reader.ReadToEnd(); foreach (string token in retVal.Split('&')) { tokens.Add(token.Substring(0, token.IndexOf("=")), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1)); } } return tokens; } A: When a user accesses your app you need them to authenticate (Sounds like you are). During that authentication process you can request permissions that your app requires and they user can grant those permissions to your app (Sounds like this step is missing). Not sure what you're using to develop your app but a quick search for grant facebook permissions should bring you up some resources to work with. The Facebook SDK's have built in methods for requesting these additional permissions so if you're using one of them you should be in good shape. A: In the end I could never get the authentication to work. A workable workaround - and the way I implemented the solution for my client - was to email the status update to the Facebook account. Apparently every Facebook account has a secret email address that can be used to email Status updates. Works a treat.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a Java library to cache files? Is there are java library that will cache files to memory and disk? Basically, I would like the library to cache the file to memory. However, if the in memory cache gets larger than a certain threshhold, some of the files should be written to disk. Is there any Java library that will do this? Grae Update: Just a couple general comment. I am only going to using these files once. They are just temp files. In a perfect world, I would keep them all in memory. However, I think I would run out of memory. What I guess I am really looking for is some sort of paging system. That can keep me form running out of memory, but also allow me to avoid writting everyhting to disk. A: Sure, try Terracotta or EhCache. Or Google for "java cache" and pick something else. A: The OS caches files automatically. It will also automatically keep in the memory the most recently used portions of files (it can partially cache a file) I suggest you let the OS do the caching for you and find a way to efficient get data between Java and the OS. A: I have had good luck with ehcache. It is very configurable. A: Open Source Cache Solutions in Java
{ "language": "en", "url": "https://stackoverflow.com/questions/7556091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Tomcat 7.0.x Manager login problem I'm trying to access the manager app, but I can't login. I get the logon screen, but when I enter the username and password, the login screen keeps coming back. Any suggestions? This is what I've done: The manager app is deployed in $CATALINA_BASE/webapps/manager Part of the server.xml file: <Resource name="UserDatabase" auth="Container" type="org.apache.catalina.UserDatabase" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" pathname="$CATALINA_BASE/conf/tomcat-users.xml" /> ... <Realm className="org.apache.catalina.realm.LockOutRealm"> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> </Realm> tomcat-users.xml: <?xml version='1.0' encoding='utf-8'?> <tomcat-users> <role rolename="manager-script"/> <role rolename="manager-gui"/> <user username="tomcat-user" password="tomcat" roles="manager-gui,manager-script"/> <user username="tocmat2" password="tomcat" roles="manager-script"/> </tomcat-users> In $CATALINA_BASE/conf/Catalina/localhost/manager.xml: <Context privileged="true" docBase="path/to/webapps/manager"> </Context> A: Change pathname="$CATALINA_BASE/conf/tomcat-users.xml" /> to pathname="conf/tomcat-users.xml" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7556093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Where do I execute "rails generate scaffold" command in AptanaStudio? There used to be a UI for scaffolding a model in my previous version of AptanaStudio. Where did this functionality go? Must I use the command line exclusively? A: It seems you need to use the console provided in Aptana. reference: http://beans.seartipy.com/category/ruby/ hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7556103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Graph API me/home posts disappear and appear I am using graph API 'me/home' to get the posts in news feed. Since last week posts disappear and then reappear in response received. The first call gives the response with post x. In the second request post x is missing. In the third request the response contains post x and this response is identical to response of first call. This behavior repeats after several correct responses in subsequent requests. Also this behavior repeats for the same set of posts. Please help. Thanks in advance. A: From what you describe above, it sounds like one of the servers in Facebook's cluster may have a stale cache it's sending back to you. If you continue seeing it, you can log it as a bug with facebook.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: does not display Is it normal for <fb:add-to-timeline show-faces="true"></fb:add-to-timeline> to display only for the app creator and not other users? I am trying to test my app with my girlfriends account and * *Permission Dialog/page is still the old one *No asking for permissions to "add activity" *add-to-timeline displays "error occurred please try again later" or blank (random) The other account I am testing on also has Timeline enabled. A: As Timeline hasn't been rolled out officially, you need to add the Facebook users to your app as testers. In the Developer App under Roles for your app, add your girlfriend's account. She will receive a notification. Once she accepts, she should be able to test your Open Graph app. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Closure fail - even after reading all about it I have this countdown fiddle here I would LIKE to make the following work in an onload but I obviously have a problem with closures for (var o in myDates) { var myDate = myDates[o]; var iid = o; funcs[o] = function() { var dateFuture = new Date(); dateFuture.setSeconds(dateFuture.getSeconds()+myDate.durationInSecs); GetCount(dateFuture,iid); } myDates[iid].tId = setTimeout("funcs['"+iid+"']()",myDates[o].delay*1000); } The code below works. BUT it has an implicit eval and 2 global vars and I would like to loop like the non-working code above <html> <head> <script type="text/javascript"> var myDates = { d0: { durationInSecs: 5, delay:0, repeat:false, duringMessage : " until something happens", endMessage : " something happened", repeatMessage : "" }, d1: { durationInSecs: 10, delay:3, repeat:true, duringMessage : " until something else happens", endMessage : " something else happened", repeatMessage : "This will repeat in 3" } } var funcs = {}; window.onload=function(){ // the below could be done in a loop, if I was better in closures setTimeout(function() { funcs["d0"] = function() { var myDate = myDates["d0"]; var dateFuture0 = new Date(); dateFuture0.setSeconds(dateFuture0.getSeconds()+myDate.durationInSecs); GetCount(dateFuture0,"d0"); } funcs["d0"](); },myDates["d0"].delay*1000); // --------------- setTimeout(function() { funcs["d1"] = function() { var myDate = myDates["d1"]; var dateFuture1 = new Date(); dateFuture1.setSeconds(dateFuture1.getSeconds()+myDate.durationInSecs); GetCount(dateFuture1,"d1"); } funcs["d1"](); },myDates["d1"].delay*1000); }; //###################################################################################### // Author: ricocheting.com // Version: v2.0 // Date: 2011-03-31 // Description: displays the amount of time until the "dateFuture" entered below. // NOTE: the month entered must be one less than current month. ie; 0=January, 11=December // NOTE: the hour is in 24 hour format. 0=12am, 15=3pm etc // format: dateFuture1 = new Date(year,month-1,day,hour,min,sec) // example: dateFuture1 = new Date(2003,03,26,14,15,00) = April 26, 2003 - 2:15:00 pm // TESTING: comment out the line below to print out the "dateFuture" for testing purposes //document.write(dateFuture +"<br />"); //################################### //nothing beyond this point function GetCount(ddate,iid){ dateNow = new Date(); //grab current date amount = ddate.getTime() - dateNow.getTime(); //calc milliseconds between dates delete dateNow; // is this safe in IE? var myDate = myDates[iid]; // if time is already past if(amount < 0){ document.getElementById(iid).innerHTML=myDate.endMessage; if (myDate.repeat) { setTimeout(funcs[iid],myDate.delay*1000); document.getElementById(iid).innerHTML=myDate.repeatMessage; } } // else date is still good else{ secs=0;out=""; amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs secs=Math.floor(amount);//seconds out += secs +" "+((secs==1)?"sec":"secs")+", "; out = out.substr(0,out.length-2); document.getElementById(iid).innerHTML=out + myDate.duringMessage; document.title=iid; setTimeout(function(){GetCount(ddate,iid)}, 1000); } } </script> </head> <body> <div> <span id="d0" style="background-color:red">!!</span> <span style="float:right¨;background-color:green" id="d1">??</span> </div> </body> A: You fell into the trap of declaring a closure inside a loop. The inner function closes ever the variable myDate and not over its value. This is particularly unexpected since variables are supposed to have block scope and not persist over multiple iterations (not the case in Javascript - everything is function scope). You can work around this by having a closure-maker function. This way you can create a new instance of the variable to close over at will. WRONG var i; for(i=0; i<xs.length; i++){ something = function(){ f(i); }; } //all closures share the i variable and will have it //be i=xs.length in the end. We don't want that. OK function make_handler(i){ return function(){ f(i); }; //each call gets its own copy of i } var i; for(i=0; i<xs.length; i++){ something = make_handler(i); } or have the closure-maker inline var i; for(i=0; i<xs.length; i++){ something = (function(i){ return function(){ f(i); }; }(i)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting new Migrations generated after 3.1 upgrade I have upgraded my app to rails 3.1 following Ryan Bates' instructions in Railscast Episode 282. Everything is working wonderfully except that new migrations generated are still following the old style of class MigrationName < ActiveRecord::Migration def up end def down end end How do I upgrade things so new migrations are generated in the new style of: class MigrationName < ActiveRecord::Migration def change end end A: The 3.1.0 generator only uses change if it detects a migration that adds something. Maybe you didn't call rails g migration AddSomething?
{ "language": "en", "url": "https://stackoverflow.com/questions/7556115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I access server specific options in Capistrano? I'm trying to configure Capistrano to do the same task on two different servers, each of them having different credentials. I'd like to do something simmilar to: namespace :deploy do role :db, "192.168.1.1", :credentials => "db1.yml" role :db, "192.168.1.1", :credentials => "db2.yml" task :mytask, :roles => :db do credentials = YAML.load_file(something) ... Is that possible? What should I substitute something with, in order to access the current server configuration? A: I'm working on this problem at the moment. The 'parallel' function doesn't give you the opportunity to modify the command line being executed, but it does give you the ability to have alternative command lines depending on the server options. I am thinking about doing a monkey-patch on the replace-placeholders function in command.rb. Only having $CAPISTRANO:HOST$ as an option seems very limiting. I wonder how much chaos would be caused by just doing the following: module Capistrano module Command class Tree def replace_placeholders(command, channel) server = channel[:server] command.eval(command) end end end end In theory now you could do this: role :whatever, "myserver.com", :special_feature => "foo" run "do-something #{server.options[:special_feature]}" The above code might needs some work. A: OK, I finally had some time to solve this. Hopefully someone else will find this answer useful. Here's how i eventually solved the problem: role :db, "db1" ,{ :credentials => 'db1-credentials'} role :db, "db2" ,{ :credentials => 'db2-credentials'} role :db, "db3" namespace :stackoverflow do # Don't run this task on host that don't have credentials defined task :default, {:role => :db, :except => {:credentials => nil } } do servers = find_servers_for_task(current_task) servers.each do |server| credentials = server.options[:credentials] puts credentials # actual task end end end I see now that I may had stated the question in a confusing way - that's because I hadn't understood, that task are run concurrently. This will in fact execute the task (here puts credentials) once for each server, which was what I was trying to do. Output: $ cap stackoverflow * executing `stackoverflow' db1-credentials db2-credentials It's a good idea to add a filter to a task so it won't run if the server has no credentials. That being said, making everybody in the team maintain current (and for security reasons non-versioned) credentials to all servers turned out to be too much hassle (thus defeating the idea of using Capistrano). Now instead of keeping the external configuration on the disks of users I'm going to keep the data on the servers affected (mostly in form of runnable scripts with all credentials hidden inside). Like this: task :dump {:role => :db} do run "/root/dump_db.sh | gzip > /tmp/dump.sql.gz" download "/tmp/dump.sql.gz", "somewhere" end A: You can use capistrano in multi environment setup. You can require capistrano multistage gem that in deploy.rb file as - require 'capistrano/ext/multistage' For this you work you need to capistrano-ext gem as well. After this, you can setup two environments as - set :stages, %w(staging production) set :default_stage, "staging" After that, inside your deploy/production.rb and deploy/staging.rb file, you can use configurations which are different for both server. All common configurations will go inside the deploy.rb file. A: If you actually want use the server's options on remote commands you can still use find_servers_for_task without patching it: server 'server-one', :db, :credentials => 'cred1.yml' server 'server-two', :db, :credentials => 'cred2.yml' namespace :stackoverflow do task :default, :roles => :db do find_servers_for_task(current_task).each do |server| run "start_your_db -c #{server.options[:credentials]}", :hosts => server.name end end end But the :hosts on the run command is essential, as Capistrano commands will execute in parallel and without it would execute two commands on each server in this example. A: Check out the gem capistrano-ext, and use the multi-stage feature. It is described fully here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: GlassFish 3.1.1 - getting jdbc connection I'm trying to get OracleConnection from glassfish by this lines: EntityManager em = getEntityManager(); Connection c = em.unwrap(Connection.class); But, in debugger I see that the actual class for c is ConnectionHolder40 class. Where I can find a jar with ConnectionHolder40 definition? A: You can get only interfaces. If you use the Connection interface, you will get a first wrapper in hierarchy that implements Connection, so ConnectionHolder40 is that case. If you want to get OracleConnection - and I see here that it is an interface, you should ask for it. But you need a JDBC4 driver. With JDBC3 drivers you can have problems (as I have with Informix 3.70) because they do not implement unwrap and isWrapperFor methods and also ConnectionHolder40, *StatementWrapper40 and ResultSetWrapper40 are not implemented correctly. If I want to unwrap IfmxConnection from holder, I can. But I cannot ask holder if he is a wrapper for IfmxConnection - it causes exception because it tries to ask the driver implementation: ConnectionHolder40 . StatementWrapper and ResultSetWrapper throw exception from both methods if they don't directly implement interface (exactly, if you don't ask for java.sql.*Statement resp. java.sql.ResultSet). A: Try public OracleConnection getOracleConnection(Connection connection) throws SQLException { OracleConnection oconn = null; try { if (connection.isWrapperFor(oracle.jdbc.OracleConnection.class)) { oconn = (OracleConnection) connection.unwrap(oracle.jdbc.OracleConnection.class)._getPC(); } } catch (SQLException e) { throw e; } return oconn; } A: java.sql.Connection is an interface, ConnectionHolder40 is just the connection wrapper that is used by Glassfish, it is probably a generated class, so will not be in any jar file. You should only use the Connection API, so should not need the class. JDBC also supports an unwrap API if you want to get the real JDBC driver connection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Chrome new content behaviour I know that Google Chrome has this effect for tabs where they light up when new content appears on the page and you are not viewing that tab currently.It usually shows up on sites like grooveshark.If you know what i am talking about i would like to simulate this effect if anyone knows how.Thanks! A: Change the page title (document.title). That's all there is to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the RFC 2822 date format in PHP (without using date('r'))? Is date('D, j M Y H:i:s O') equivalent to date('r') (RFC 2822 date) in PHP? I'm asking because 'r' seems to be non-working with the format parameter of date_parse_from_format. A: You can use date(DateTime::RFC2822); if you want dates in the RFC 2822 format.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: BeansBinding in JTable and JTable's TableColumn One of my JTable is update with a bean property(util.List).It is ok. But I want a column in my JTable named "Action". This column should have JComboBox for each row to do some thing for that row's data. I read this and it has some tutorials how to set a Jcombobox into a JTable row. I use NetBeans IDE for coding. In the netbeans "Table Content" of the JTable display box under the Column tab, there are properties to set our JTable. I added a column for my "action" then set javax.swing.table.TableCellEditor as new DefaultCellEditor(comboBox) in "Editor" Options. Here I added a JComboBox combobox for the cell editor. But when I ran the project, there is no any combo box but only a text "Object" .(I had use Object as the Exression type of the column) Any one tell me how can I insert a JCombobox into a JTable cell when JTable is bound to a beans propery . specially in NetBeans A: you forget to set DefaultCellEditor for that
{ "language": "en", "url": "https://stackoverflow.com/questions/7556121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: intellij- where are the artifacts? I am building jars using build artifacts from the menu. In "Project structure" I have in the artifacts - output directory. When the build stops - it doesn't say anything is wrong and it doesn't put the jar file in the output directory. Are there readable logs for the artifact build? Where is the jar folder set? A: Artifact output directory configuration defines where your artifacts will be placed. Check idea.log for possible problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse breakpoint events In my Eclipse plugin, I would like to be notified when a breakpoint is created, removed or disabled. Is there an event that I can subscribe to for this? Thanks, Alan A: I haven't used it, but from the docs it looks like you might be interested in IBreakpointManager. It looks like you should add an IBreakpointListener or an IBreakpointsListener to this. Have a look at this help section: http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/debug_breakpoints.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7556130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Allow a specific text string and a range of numbers to be used on PHP promo code script I have a simple promo code script to apply a discount to an amount before it is passed to Paypal, it works fine but I want to use a number of different codes so I can monitor their performance (all give the same discount). At the moment I have: if($_POST['promoCode'] == "ABC123") This allows me to use one code - I would like the letters to remain the same but allow a range of numbers, from maybe 001 to 999. Looking forward to a reply from you good people, this site has been such a great resource for me over the last twelve months just from reading answers to other people's questions, however I couldn't find one that related to my specific issue. Thanks in advance! Scott. A: Thanks @M42 if(preg_match('/^ABC(\d{2}[1-9]|\d[1-9]\d|[1-9]\d{2})$/', $_POST['promoCode'])) {}
{ "language": "en", "url": "https://stackoverflow.com/questions/7556133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show a div as pop-up using Fancybox I need to show a div with application form as a pop-up using fancybox. Is it possible to .fancybox() anything but image because all the tutorials i came across on the internet use . Thanks in advance! I have the following code: <input type="button" value="Preview" id="btnPreview" /> testen text! <script type="text/javascript"> $(document).ready(function () { $('#divDetails').hide(); $('#divPreview').hide(); $('.image').click(function () { var imgPath = $(this).attr('src'); var imgName = imgPath.substring(0, imgPath.length - 4); var imgAlt = $(this).attr('alt'); $('#mainDiv').hide(); $('#divDetails').show('slow'); $('#detailedImage').attr('src', imgName + '-large.jpg').attr('alt', imgAlt); }); $('#btnPreview').click(function () { $('#divDetails').show(); $("#divPreview").fancybox(); }); }) </script> The rest of the code is not relevant. when I click the btnPreview button I want the div with ID divPreview to pop-up and I call $("#divPreview").fancybox(); I include these scripts <link href="../css/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" /> <script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script> <script src="../fancybox/jquery.fancybox-1.3.4.pack.js" type="text/javascript"></script> <script src="../fancybox/jquery.mousewheel-3.0.4.pack.js" type="text/javascript"></script> <script src="../fancybox/jquery.easing-1.3.pack.js" type="text/javascript"></script> What am I doing wrong? Thank you!! A: Give some more information please... What context? What is your html? Possible mistakes: 1) jQuery is not loaded before you run this snippet (include it as first) 2) One or both id's are not found. 3) fancybox is not included before you run this snippet. A: I personally use prettyPhoto, its very simlar to fancy box, however Ive found it to be more compatible with older browsers. have a look http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/ I belive the page you are looking for, for loading custom content is here http://www.no-margin-for-errors.com/blog/2010/09/28/tutorial-opening-custom-content-in-prettyphoto/ In that example they use a google maps :) Hope this helps you out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which operators and functions expect their string arguments as octets? Does somewhere exist a list with all Perl operators and functions which expect their string arguments as octets? For example the file test operators need octets ( Question about pathname encoding comment ). Now I found a code with symlink and I am not sure if I should encode the file names. A: It’s simply because the traditional Unix syscalls that Perl either uses or emulates are all defined in terms of bytes, not characters. If you want a UTF-8 encoded or decoded filename, then you have to do that for yourself. You will not get what you want if you do not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieving Information associated with IAP Product Registered on iTunes Connect I've created an eBook player application which has books that need to be sold under In-App-Purchase. These books i've added as Non-Consumable Product's under my application in iTunes Connect. While registering the Product's i've uploaded a SCREENSHOT for every product. I want to download this Screen Shot uploaded against each product into my application while showing the In-App-Book-Store to user. I've gone through the Store Kit Programming guide & didn't find a way to retrieve the screenshot's associated with product's. Is this possible? If so, then how do i go about achieving this? A: No, there's no API for retrieving screenshots in-app. The in-app purchase screenshots are designed to help app reviewers understand how to find the item. The easiest thing to do would be to package the screenshots with the app. You could name them with the product ID to make them easy to match. You could also make them available at a URL: NSString *productId = @"my.app.product.one"; NSString *imageName = [NSString stringWithFormat:@"%@.png", productId]; UIImage *image = [UIImage imageNamed:imageName]; if (image == nil) { NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://someserver.com/productImages/%@", imageName]]; NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; image = [UIImage imageWithData:imageData]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Explicitly casting all string parameters to Unicode Is there a performance hit to prefixing all SP parameters with N' even when the parameter is not a unicode string? I'm generating calls to a database dynamically in my .net code. Without actually checking each time I generate the code, I don't know which parameters are Unicode. If the answer is yes (there is a performance hit), what's the simplest way to check whether a paramter is unicode? A: No, there isn't. If your column is Unicode you should always pass in a Unicode string. However you shouldn't need to prefix strings from your .NET application with N. Are you not using parameterized statements?
{ "language": "en", "url": "https://stackoverflow.com/questions/7556143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I Remove Special Formatting with PowerShell (Tabs, Cariage Enter, BackSpaces, Newlines, and more) I want to remove these carriage returns (or at least I think that's what they are) using PowerShell but I am having trouble doing so. I've used: -replace "`n","" -replace "`t","" -replace "`b","" -replace "`r","" nothing seems to work. any suggestions? A: If you want to be surgical about the deletions, one crude but effective method is to use a .Net ASCII encoding object to get a numeric value of the offending character(s): $text = "Test`n`b`r" $enc = New-Object System.Text.ASCIIEncoding $text.ToCharArray() | Foreach-Object { echo "$($_) $($enc.GetBytes($_))" } For every character in a line of your text, that code will output the character and then its numeric value. It will look something like this (characters in parentheses won't appear in the actual output, they're there for clarification): T 84 e 101 s 115 t 116 10 (`n) 8 (`b) 13 (`r) By running it against one line of your CSV file, you should be able to detect what needs to be stripped. You can then perform a replacement by converting the numeric value back into the ASCII character it represents. For instance, both of these statements will delete a `b character from your text: $text -replace "`b","" $text -replace $enc.GetChars(8),"" A: try using regex: [regex]::Replace("←xxxx←", "←" , "" ) # give xxxx or if values are numbers [regex]::Replace("←356←", "\D" , "" ) # give 356
{ "language": "en", "url": "https://stackoverflow.com/questions/7556148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Informix can't connect via IBM.Data.Informix I'm trying to connect to Informix database using sample code from https://www.ibm.com/developerworks/data/library/techarticle/dm-0510durity/ I'm using IBM.Data.Informix.dll version 9.7.4.4 I get an error: "argument is not correct": This is my code: static void Main(string[] args) { MakeConnection("PLPC06", "9090", "TestServer", "clients", "informix", "Password"); } public static void MakeConnection(string HOST, string SERVICENUM, string SERVER, string DATABASE, string USER, string PASSWORD) { string ConnectionString = "Host=" + HOST + "; " + "Service=" + SERVICENUM + "; " + "Server=" + SERVER + "; " + "Database=" + DATABASE + "; " + "User Id=" + USER + "; " + "Password=" + PASSWORD + "; "; //Can add other DB parameters here like DELIMIDENT, DB_LOCALE etc //Full list in Client SDK's .Net Provider Reference Guide p 3:13 IfxConnection conn = new IfxConnection(); conn.ConnectionString = ConnectionString; try { conn.Open(); Console.WriteLine("Made connection!"); } catch (IfxException ex) { Console.WriteLine("Problem with connection attempt: " + ex.Message); } Console.ReadLine(); } This settings works on RazorSQL to connect: Please help! A: I have had installed 64 bit version of IBM tools. Removing everything and installed 32 bit version helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I initialize ActionDispatch::ParamsParser in Rails 3.1? My application defines a custom Mime type for its Rest interface. So I register it in the mime_types.rb initializer: Mime::Type.register "application/vnd.example.app-v1+xml", :xml_v1 and Rails correctly handles the respond_to blocks in the controllers. However, I still need to tell Rails that incoming requests should be parsed as an XML, using ActionDispatch::ParamsParser. I just don't know how to use it inside an initializer. What's the correct way? A: This works well: Mime::Type.register "application/vnd.example.app-v1+xml", :xml_v1 MyRailsApp::Application.config.middleware.delete "ActionDispatch::ParamsParser" MyRailsApp::Application.config.middleware.use ActionDispatch::ParamsParser, { Mime::XML_V1 => :xml_simple }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Invalid return type for a mapped stored procedure Have a very large ASP.NET application I'm creating Automated UI test cases for, part of the final part of this test case is to remove the user it just created (so we keep the same details every single test run, and will expect the same results, no data will change.) and so I took to a stored procedure to do this. The SP works fine in SQL, have tested it. Have now mapped it into LINQ2SQL. However when it is ran I get this: System.InvalidOperationException: 'System.Void' is not a valid return type for a mapped stored procedure method. The bottom line is that my SP doesn't have a return type, I don't want it to. A: By default, the successful execution of a stored procedure will return the numeric value 0. Can you change the return type for your LINQ2SQL mapping to int? If you don't care about the returned value, you can just ignore it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Localization in a databound ComboBox isn't working correctly I want to translate items of my combo box. So I use a personalized converter KeyToTranslationConverter which convert an Enum value to a translated string. [ValueConversion(typeof(object), typeof(string))] public class KeyToTranslationConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return LocalizationResourcesManager.GetTranslatedText(value); } } My combo box is bound to the observable collection LanguagesEntries and the selectItem is bound to LanguageEntry attribute. <ComboBox ItemsSource="{Binding LanguageEntries}" SelectedItem="{Binding LanguageEntry}"> <ComboBox.ItemTemplate> <DataTemplate> <Label Content="{Binding Converter={StaticResource Converter}}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> My problem is: When the user change the language the method is called : CollectionViewSource.GetDefaultView(this.LanguageEntries).Refresh(); All items collections are translated except the selected item which is duplicated : For example the selected item "Anglais" is not translated but the word English is in the combo box list. Can someone help me. Arnaud. A: I had this exact problem, I solved it by binding the converter to the itemssource instead of the itemtemplate. <ComboBox ItemsSource="{Binding LanguageEntries, Converter={StaticResource LanguageEntriesConverter}}"> And the convert need to handle the collection instead of each item: public object Convert(object value, Type targetType, object parameter, string language) { if (value is System.Collections.ObjectModel.Collection<string>) { foreach (var c in (System.Collections.ObjectModel.Collection<string>)value) { c = LocalizationResourcesManager.GetTranslatedText(c); } } return value; } The converter is called every time you update your itemssource either by assigning it to a new value or calling OnPropertyChanged.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Git: Set up a fetch-only remote? When I run git remote -v in one of my Git repositories that has a remote(s) configured, I see that each remote has both fetch and push specs: $ git remote -v <remote-name> ssh://host/path/to/repo (fetch) <remote-name> ssh://host/path/to/repo (push) For remotes that point to peer developers there's no need to push, and Git will refuse to push to a non-bare repository anyway. Is there any way to configure these remotes as "fetch-only" with no push address or capabilities? A: The general statement "Git will refuse to push to a non-bare repository" is not true. Git will only refuse to push to a non-bare remote repository if you are attempting to push changes that are on the same branch as the remote repository's checked-out working directory. This answer gives a simple explanation: https://stackoverflow.com/a/2933656/1866402 (I am adding this as an answer because I don't have enough reputation to add comments yet) A: If you already have a remote set up and just want to prevent yourself from doing something like accidentally pushing directly to master or release/production, you can prevent this using git config. # prevent pushing to branch: master $ git config branch.master.pushRemote no_push # prevent pushing to branch: release/production $ git config branch.release/production.pushRemote no_push For the record, no_push is not a special name. It's just the name of any nonexistent branch. So you could use $ git config branch.master.pushRemote create_a_pr_and_do_not_push_directly_to_master and it would work just fine. More info: git-config pushRemote A: Apart from changing the push URL to something invalid (e.g., git remote set-url --push origin DISABLED), one can also use the pre-push hook. One quick way to stop git push is to symlink /usr/bin/false to be the hook: $ ln -s /usr/bin/false .git/hooks/pre-push $ git push error: failed to push some refs to '...' Using a hook allows for more fine-grained control of pushes if desirable. See .git/hooks/pre-push.sample for an example of how to prevent pushing work-in-progress commits. To prevent pushing to a specific branch or to limit pushing to a single branch, this in an example hook: $ cat .git/hooks/pre-push #!/usr/bin/sh # An example hook script to limit pushing to a single remote. # # This hook is called with the following parameters: # # $1 -- Name of the remote to which the push is being done # $2 -- URL to which the push is being done # # If this script exits with a non-zero status nothing will be pushed. remote="$1" url="$2" [[ "$remote" == "origin" ]] A test repo with multiple remotes: $ git remote -v origin ../gitorigin (fetch) origin ../gitorigin (push) upstream ../gitupstream (fetch) upstream ../gitupstream (push) Pushing to origin is allowed: $ git push origin Enumerating objects: 3, done. Counting objects: 100% (3/3), done. Writing objects: 100% (3/3), 222 bytes | 222.00 KiB/s, done. Total 3 (delta 0), reused 0 (delta 0) To ../gitorigin * [new branch] master -> master Pushing to any other remote is not allowed: $ git push upstream error: failed to push some refs to '../gitupstream' Note that the pre-push hook script can be modified to, among other things, print a message to stderr saying the push has been disabled. A: I don't think you can remove the push URL, you can only override it to be something other than the pull URL. So I think the closest you'll get is something like this: $ git remote set-url --push origin no-pushing $ git push fatal: 'no-pushing' does not appear to be a git repository fatal: The remote end hung up unexpectedly You are setting the push URL to no-pushing, which, as long as you don't have a folder of the same name in your working directory, git will not be able to locate. You are essentially forcing git to use a location that does not exist. A: If you have control over the repository, you can achieve this by making use of permissions. The user who is fetching repository shouldn't have write permissions on master repository.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "172" }
Q: How to change Database in Enterprise Library 5.0 I created a db object as sqlDB = EnterpriseLibraryContainer.Current .GetInstance<Database>("ProdConn"); But later in code, i want to change the Database name. In previous enterprise version, we use conn.ChangeDatabase("ABCD"); to change the database but how we can do it here? Please advice. thanks, Mujeeb. A: I don't think ChangeDatabase is an Enterprise Library method (I couldn't find it in version 4.1 either). I think it's just an ADO method on IDbConnection. There are 3 ways I can think of to do what you want: * *Create a new Database entry in Enterprise Library configuration and use that value *Use ADO.NET to change the connection and perform data access *Programmatically create a new Enterprise Library Database object using a different database value 1. Create a new Database Entry in Config Personally, I think this is the cleanest option. Add the database as a new entry in configuration and treat it as a separate database. However, if you need to support dynamic databases because the database names are not known at design time or are retrieved from a different system then this won't work. 2. Use ADO.NET You can retrieve a connection and just use ADO.NET (I think this may be what you were already doing?): // Get Original EL DB Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("MYDB"); object result = db.ExecuteScalar(CommandType.Text, "select top 1 name from sysobjects"); Console.WriteLine(result); // Change DB with ADO.NET using (IDbConnection conn = db.CreateConnection()) { conn.Open(); conn.ChangeDatabase("AnotherDB"); using (IDbCommand cmd = conn.CreateCommand()) { cmd.CommandText = "select top 1 RoleName from Roles"; cmd.CommandType = CommandType.Text; result = cmd.ExecuteScalar(); } } Console.WriteLine(result); Mixing the EL code with the ADO.NET code feels a bit wrong, though. 3. Create a new Enterprise Library Database Object Instead of using ADO.NET you can use the Enterprise Library Database class. You can't modify the ConnectionString (it's readonly) but you can create a new Database object with a new connection string. // Get Original EL DB Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("MYDB"); object result = db.ExecuteScalar(System.Data.CommandType.Text, "select top 1 name from sysobjects"); Console.WriteLine(result); // Change Database DbConnectionStringBuilder builder = new DbConnectionStringBuilder() { ConnectionString = db.ConnectionString }; builder["database"] = "AnotherDB"; // Create new EL DB using new connection string db = new GenericDatabase(builder.ConnectionString, db.DbProviderFactory); result = db.ExecuteScalar(CommandType.Text, "select top 1 RoleName from Roles"); Console.WriteLine(result); I think this looks better than option 2. We can make it a bit cleaner by adding the change database logic to a helper method or, as in the following, an extension method: public static class DatabaseExtensions { public static Database ChangeDatabase(this Database db, string databaseName) { // Change Database DbConnectionStringBuilder builder = new DbConnectionStringBuilder() { ConnectionString = db.ConnectionString }; builder["database"] = databaseName; // Create new EL DB using new connection string return new GenericDatabase(builder.ConnectionString, db.DbProviderFactory); } } ... // Get Original EL DB Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("MYDB"); object result = db.ExecuteScalar(System.Data.CommandType.Text, "select top 1 name from sysobjects"); Console.WriteLine(result); db = db.ChangeDatabase("AnotherDB"); result = db.ExecuteScalar(CommandType.Text, "select top 1 RoleName from Roles"); Console.WriteLine(result);
{ "language": "en", "url": "https://stackoverflow.com/questions/7556159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using Mock() in Python Can you give some clear examples of uses of the Mock() in Django unittests? I want to understand it more clearly. Update: I've figured out some things, so I share it below. A: Part 1: Basics from mock import Mock Mock object is an object that is a kind of a Dummy for the code that we want not to be executed, but for which we want to know some information (number of calls, call arguments). Also we might want to specify a return value for that code. Let us define simple function: def foo(value): return value + value Now we're ready to create a Mock object for it: mock_foo = Mock(foo, return_value='mock return value') Now we can check it: >>> foo(1) 2 >>> mock_foo(1) 'mock return value' And get some information on calls: >>> mock_foo.called True >>> mock_foo.call_count 1 >>> mock_foo.call_args ((1,), {}) Available attributes of Mock() instance are: call_args func_code func_name call_args_list func_defaults method_calls call_count func_dict side_effect called func_doc func_closure func_globals They're quite self-explanatory. Part 2: @patch decorator The @patch decorator allows us to easily create mock objects for imported objects (classes or methods). It is very useful while writing unit-tests. Let us assume that we have following module foo.py: class Foo(object): def foo(value): return value + value Let us write a test for @patch decorator. We are going to patch method foo in class Foo from module foo. Do not forget imports. from mock import patch import foo @patch('foo.Foo.foo') def test(mock_foo): # We assign return value to the mock object mock_foo.return_value = 'mock return value' f = foo.Foo() return f.foo(1) Now run it: >>> test() 'mock return value' Voila! Our method successfully overridden. A: The Mock site has some really nice API documentation that cover all of this. Note that patch replaces all instances of foo.Foo.foo where ever they are called. It is not the preferred way to mock something but can be the only way -- see open().
{ "language": "en", "url": "https://stackoverflow.com/questions/7556161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to create a group for a string / filename? OK, I am a newbee to stackoverflow. Developing an ecommerce site, I have as many as 50 unique images on the home page that needs to be loaded. I am using the Amazon CDN for my images and all these files are in a bucket with a unique domain. I would like to have multiple domains mapped to this bucket. However for each image, I should be able to find at runtime, which domain it was servered last time so that the caching is most optimized. My idea is to have a function func(filename) which can return a value between 0-9 every-time for the same filename. This can be used for the domain name. I do not want the func to be very heavy like a hash and in this case, I would want a collision rather than avoid it. A simple method would be to use a intval(filename) and then use the least significant digit. However I am not sure this would be a good solution and if the spread would be balanced. Any suggestions ? A: How about something as simple as this: function customHash($str) { $hash = 0; for ($i = 0; $i < strlen($str); $i++) { $hash += ord($str[$i]); } return $hash % 10; } You can optimize this in many ways, like using iconv_strlen() to treat utf-8 strings right and instead of the whole length, $len = max(6, $strlen); could be used (though the perfomance boost isn't really significant...).
{ "language": "en", "url": "https://stackoverflow.com/questions/7556162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: setuptools entry_points. Installing executable to /usr/sbin I have a setup.py script, that has entry_points defined like this: entry_points = { 'console_scripts': [ 'gun = gun.sync:main' ] }, This installs the executable into /usr/bin. Is there any way I can tell entry_points to install it to /usr/sbin instead? A: No. You have to pass the --script-dir option to easy_install to specify that. (You could add it to your project's setup.cfg file, but it's not recommended because it'll surprise people who have configured their Python installation to install scripts to some other location... and even if you do it, it'll only take effect for users who actually run your setup.py. Most other installation tools will ignore a script path specified in a project's setup.cfg.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7556168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get Number Of Lines without Reading File To End Is there a way to get Number of Lines within a Large Text file ,but without Reading the File content or reading file to end and Counting++. Maybe there are some File Attributes ,but cannot find it out at all . Because i might be in some cases where i should get Total Number of Line's and compare it to Current line to display the Percentage,and just for a Percentage Display it might be stupid to read first all Content than read it Again to Display the raw text at user. bests A: As Guffa and Jason said, there is no way to get the lines other than reading to the end. To solve your problem differently: If you are interested only in the percentage display you COULD try to acummulate that value from the total file size and the line you are currently at. You need to apply some voodoo tricks there to get the actual bytes read (like say, you have read to line 10, and a total of 200 bytes or whatever) and the file size is 400bytes. You could probably guess that you are at 50%, without giving needing to know a total line number. Thats just some random numbers there, btw. A: No. You have to read the file. Consider storing it at the beginning of the file or in a separate file when you write the file if you want to find it quickly without counting. Note that you can stream the file, and it's surprisingly fast: int count = File.ReadLines(path).Count(); Because i might be in some cases where i should get Total Number of Line's and compare it to Current line to display the Percentage,and just for a Percentage Display it might be stupid to read first all Content than read it Again to Display the raw text at user. Oh, just get the file size and the length of each line in bytes and keep a cumulative count of the number of bytes processed so far. A: No, there is no other way. A file is not line based (or even character based), so there is no meta information about the number of lines (or even number of characters). The only meta data about the content is the length in bytes. If you have some additional information about the file, for example that each line is exactly the same length, and it uses an 8-bit encoding so that the number of characters is the same as the number of bytes, you could calculate the number of lines from the file size.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Sencha Touch: List setActiveItem error: Cannot read property 'isComponent' of undefined? I have a normal list with 'onItemDisclosure' on this, now when an item is clicked the panel opens fine, but I would like to have this panel placed on an external page / js file rather than clog up the code workings page etc I have the following all within the same file: var newPanel = new Ext.Panel({ id : 'pagedetails', tpl:'Show details panel' }); ....... onItemDisclosure: function(record, btn, index) { newPanel.update(); App.viewport.setActiveItem('pagedetails', {type: 'slide', direction: 'left'}); } this works fine but then I create it as a separate page as below page name pagedetails.js: App.views.pagedetails = Ext.extend(Ext.Panel, { id: 'pagedetails', tpl:'Show details page' }); Ext.reg('pagedetails', App.views.pagedetails); I have loaded this within the main index page no problems its when I code it to try and get it to work. in my viewport initComponent: function() {... i have the following App.views.pagedetails = new App.views.pagedetails(); Ext.apply(this, { items: [ App.views.pagedetails .......etc then within my 'onItemDisclosure' i nwo have the following: App.views.pagedetails.update(); App.viewport.setActiveItem('pagedetails', {type: 'slide', direction: 'left'}); then in the items section of this page .... items:[list, App.views.pagedetails]; But this gives the the following error: Uncaught Trying to add a null item as a child of Container with itemId/id: ext-comp-1017 What am i doing wrong or is this possbile / do i need to have my detailed panel in the same file? EDITED SECTION Anyway until I resolve this issue, i decided to go back to basics and now I cannot get this to work. My code is below and when I click on the detailed icon I get the error below: var detailsPanel = new Ext.Panel({ id : 'pagedetails', tpl:'Show details panel' }); var list = new Ext.List({ itemTpl : App.views.showlistTpl, grouped : true, indexBar: true, store: 'showsStore', onItemDisclosure: function(record, btn, index) { detailsPanel.update(); App.viewport.setActiveItem('pagedetails', {type: 'slide', direction: 'left'}); } }); App.views.displayList = Ext.extend(Ext.Panel, { scroll: 'vertical', styleHtmlContent: false, layout: 'card', dockedItems: [{ xtype: 'toolbar', title: 'Shows &amp; Events' }], items: [list, detailsPanel] }); Ext.reg('displayList', App.views.displayList ); Now the error I am getting is: Chrome: Uncaught TypeError: Cannot read property 'isComponent' of undefined Safari: TypeError: 'undefined' is not an object (evaluating 'config.isComponent') Any ideas to get the basic working again UPDATE I have the following code set up: var detailPanel = new Ext.Panel({ id: 'detailpanel', tpl: 'Hello', layout: 'card' }); var listPanel = new Ext.List({ id: 'indexlist', store: 'showStore', itemTpl: App.views.showlistTpl, grouped: true, layout:'card', onItemDisclosure: function(record, btn, index) { detailPanel.update(record.data); App.viewport.setActiveItem('detailPanel', {type: 'slide', direction: 'left'}); } }); App.views.showList = Ext.extend(Ext.Panel, { scroll: 'vertical', styleHtmlContent: false, dockedItems: [{ xtype: 'toolbar', title: 'My List'         }], items: [listPanel, detailPanel], layout:'card' }); Ext.reg('showList', App.views.showList); The list shows all ok, but then when I click on the disclosure icon, I get the following error: Uncaught TypeError: Cannot read property 'isComponent' of undefined Been through everything but still cannot see whats wrong? whats strange (when trying a few things) is when I change the layout of 'App.views.showList' to layout:'fit', then click on a disclosure icon, my detailed page displays over my list so I get the list and the detailed page view, so it looks like its not removing my list view....? thanks A: Do not load the Detail Panel into the list of items of the App.views.showList, just use the setActiveItem method that will load the panel and set it as active. DO not use the xtype, but use the instance you created before like this: onItemDisclosure: function(record, btn, index) { detailPanel.update(record.data); App.viewport.setActiveItem(detailPanel, {type: 'slide', direction: 'left'}); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to force the character encoding of HTML e-mails in Rails 3? I'm using Rails 3.1 (3.1.1 RC1) and I have configured ActionMailer to use windows-1252 as default encoding. (External requirement) This works perfectly with plain text mails, but as soon as I send HTML mails the text is converted to UTF-8 again resulting in garbled text. Here's what I've done/found out. * *I configured the default encoding: ActionMailer::Base.default :charset => 'windows-1252' *My .erb template is actually windows-1252 encoded. *I added the required marker <%# encoding: windows-1252 -%> as the first line of the template. *The mail has a correct content type header: Content-Type: text/html; charset="windows-1252" Here's the code snippet I'm using to send the mail: mail(:to => ..., :subject => "...") do |format| format.html end I suspect that somehow during mail processing Rails/ActionMailer decides to convert the characters to UTF-8. How can I change that? A: You don't mention what version of Ruby you are using (1.9.x do things differently then 1.8.x,) but assuming you are using a 1.9 version, you can set the following in your application.rb: config.encoding = "windows-1252" Which will set an application wide encoding. (which is utf-8 by default) A: You should try to use the charset option within the mailer. See here: http://railsdispatch.com/posts/actionmailer
{ "language": "en", "url": "https://stackoverflow.com/questions/7556173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Where to download SunPKCS11Provider I'm trying to access smardCard folowing this article but I have no idea where to find jar with SunPKCS11Provider. In Oracle docs they say it is standard since 1.5. Here is my block where compiler is complaining it can't find SunPKCS11: String configName = "d:\\dev\\ws\\pkiTest\\pkcs11.cfg"; Provider p = new sun.security.pkcs11.SunPKCS11(configName); Security.addProvider(p); A: 64 bit windows support should become available in next few months. it's being backported to a jdk 6 update. http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6931562 A: It wasn't available for download until Java 8 (for 64 bit): "The class SunPKCS11 is not available even in JDK/JRE 7 for WIndows 64 bit." (Duplicate bug description) http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6880559 It was introduced in Java 5 (32 bit), and is included in Oracle's JDK downloads since then. It was not backported to the 64 bit versions after introduced in Java 8 (64 bit). I think the other answer is referring to a different provider (SunMSCAPI).
{ "language": "en", "url": "https://stackoverflow.com/questions/7556174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rubular versus javascript regexp capture groups Noticed a difference between what Rubular.com and Javascript regexes: 'catdogdogcatdog'.match(/cat(dog)/g); // JS returns ['catdog', 'catdog'] I expected to capture 'dog' twice but instead I get 'catdog' twice. Rubular captures 'dog' twice as expected: http://rubular.com/r/o7NkBnNs63 What is going on here exactly? A: No, Rubular also matches catdog twice. It also shows you the contents of the capturing group, which captured dog twice. You want something like this: var myregexp = /cat(dog)/g; var match = myregexp.exec(subject); while (match != null) { dog = match[1] // do something, Gromit! match = myregexp.exec(subject); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are there good tools for debugging, profiling, tracing in MySQL? If I want to debug queries on SQL Server, I'll use the profiler built into SQL Studio Management Studio. Do similar tools exist for MySQL? I'm aware of showing running queries, profiling CPU usage per query, and other techniques, but because I'm going to be spending a lot of time working on query performance over the coming weeks, I'm wondering if tools exist to streamline the debugging process. Both commercial and open source solutions are welcome. A: Take advantage of dbForge Studio for MySQL (Query Profiler and Session Manager tools). Also have a look at Debugger for MySQL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is is possible to make a client to client connection with HTML5 I know that HTML5 has the new feature called WebSockets for making a connection between browser and server. But is it possible that the server helps clients make a connection between them? I want to transfer file from client A to client B A: No, WebSockets don't (yet) help in this instance, because browsers only support the client half of the protocol. It's certainly possible to have a central WebSocket server responsible for relaying messages between any set of clients, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Character insert to String How can I insert '\n' ( a new line) into a string, to be custom displayed on the device's screen ? The code : String s3=""; for(int i=0; i<timp.size(); i++) { s3 = s3 + sbt.get(i); } That's how I form the string . Now I would like to put '\n' on the s3.charAt(55) position . Thanks. PS : I Don't want to replace the character on the s3.charAt(55) , I just want to add the newline there . A: String yourLongString = "...A huge line of string"; String preLongStr = yourLongString.subString(0, 55); String postLongStr = yourLongString.subString(55); String finalString = preLongStr + "\n" + postLongStr; A: You could do it like this: String first = s3.substring( 0, 55 ); String second = s3.substring( 56, s3.length ); s3 = first + "\n" + second; Or change your for-loop by adding this after you append to s3 (if the string just needs to break as soon as it exceeds 55 characters.) if( s3.length > 55 ) s3 += "\n"; A: You can use StringBuilder to edit Strings. StringBuilder total = new StringBuilder(); String first = "Hello"; String second = " World"; total.append(first); total.append("\n"); total.append(second);
{ "language": "en", "url": "https://stackoverflow.com/questions/7556188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Update table with condition I have the following problem: I have table: TEST_TABLE x_Id|y_Id --------- 2| 7 2| 8 3| 7 4| 7 5| 8 I want remove record if x_Id has y_Id(7) and y_Id(8). And update y_Id to 7 if y_Id = 8 and y_Id(7) is not exist in the unique x_Id. x_Id and y_Id is composite key. Example of result: TEST_TABLE x_Id|y_Id --------- 2| 7 3| 7 4| 7 5| 7 A: Delete duplicates (where for x_Id exists both y_Id's 7 and 8) and update all remaining y_Id where y_Id=8 DELETE FROM TEST_TABLE t1 WHERE y_Id=8 AND EXISTS (SELECT * FROM TEST_TABLE WHERE x_Id=t1.x_Id AND y_Id=7) UPDATE TEST_TABLE SET y_Id=7 WHERE y_Id=8 A: These queries do not use corelated subqueries (ones where they must be executed for every row of the outer query), so they should be quite efficient. delete from test_table where y_id = 8 and x_id in (select x_id from test_table where y_Id = 7); update test_table set y_id = 7 where x_id in (select x_id from test_table where y_id = 8) and x_id not in (select x_id from test_table where y_id = 7);
{ "language": "en", "url": "https://stackoverflow.com/questions/7556191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does this JavaScript cause a "Permission Denied" error in IE The following code throws a Permission Denied error in IE, citing jQuery (1.6.2) line 6244 Char:2: function addAgreement() { var url = window.location.toString(); var pieces = url.split('/'); var site_url = url.replace(pieces[pieces.length -1], ''); $('.login').append('<div id="dialog"></div>'); $('#dialog').load(site_url + '?page_id=443'); } $('#dialog').dialog({ width: 800, position: 'top', modal: true, buttons: { "Agree": function() { agreed = true; var val = $('#registerform').attr('action') + '&agreed=1'; $('#registerform').attr('action', val); $(this).dialog("close"); $('#registerform').trigger('submit'); }, "Disagree": function() { agreed = false; $(this).dialog("close"); } } }); It works in Firefox — is this something to do with same origin policy? jQuery is being served by Google CDN. UPDATE The content being loaded is a WordPress page which also contains includes for cufon-yui.js (served locally). I have tried serving jQuery locally too (i.e not from the Google CDN) and this made no difference. UPDATE 2 Removing the following script tags from the loaded page stops the error from appearing. <script type='text/javascript' src='<?php echo bloginfo('template_url') ?>/inc/js/cufon-yui.js'></script> <script type='text/javascript' src='<?php echo bloginfo('template_url') ?>/inc/js/path/to/font.js'></script> <script type='text/javascript'> Cufon.replace('#page')('.title'); </script> A: For AJAX requests, www. is seen as a sub-domain and breaks the same-origin policy for the xmlhttprequestobject. Make sure the domain in your AJAX request matches the domain of the page and your javascript file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Get message from Facebook inbox I have some trouble in getting messages from inbox. I used Graph API with endpoint @"me/inbox" and then used fql query like this one : SELECT thread_id, author_id, body FROM message WHERE thread_id IN (SELECT thread_id FROM thread WHERE folder_id=0) But in both cases result was incorrect. Firstly, it returned me messages only then, when i registered Facebook e-mail, before this i had result : "[]". Also it return not full information: 1) return deleted messages 2) do not return messages from inbox that i receive from friends e-mail. 3) do not return some incoming messages from friend If who had same problem or find solution, explain please, what i have done wrong. Thanks. P.S. Excuse me for my english. I continue learning. A: The problem is, Facebook has rolled out their fancy new messages system without giving developers the proper API to take advantage of it. Once they decide to release the new "unified_thread" table, it will solve your problem. They've been saying they were going to release it for months, but I'm not holding my breath. Until they release it...it's impossible to provide data to your users that is consistent with what they will find in their inbox.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: having issues downloading xls file using procmail Any ideas why my xls attachment files aren't being downloaded? thanks This is a perl wrapper creating the procmailrc file for me. my $procmailrc =<<EOL; MAILDIR=$workDir VERBOSE=on LOGFILE=$workDir/procmail.log :0 B * ^Content-Type.*application.*name=.*\.(xls|rtf) { MAILDIR } :0 mail/ EOL A: The generated recipe is syntactically correct, but semantically bogus; this is almost certainly not what you want. The MAILDIR between the braces is equivalent to MAILDIR='' i.e. you are setting the MAILDIR variable's value to nothing. This causes the matching messages to be delivered to a different directory than your other messages, most likely a place you need to dig out from the log files so you can restore the misplaced messages. Perhaps you do not have write access to the directory where you end up trying to deliver those messages, which will most likely cause the calling process to bounce them back to the sender. Anyway, since you have a log file, please post a pertinent snippet (three-four lines should be all we need) if you still cannot figure this out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: New SQL Server Install Mixed Mode authentication not allowing Windows Authentication I have a new instance of SQL Server 2008 RS Standard Edition. I enabled Mixed-Mode Authentication but I can't get Windows Authentication to work. I get the Error: 18456, Login Failed for user 'MyDomain\jreddy'. I can log in with the sa account so I can make changes, but I'm not sure what to change. Any help would be greatly appreciated. I've checked the event log and found this error relating to the login failure: Reason: Token-based server access validation failed with an infrastructure error. A: When you enable Windows Authentication for Sql Server, it won't just automatically resolve authentication requests with Active Directory. You still have to set up an account for each user, and assign Sql Server permissions to that account for individual databases (often done via roles). The good news is that you can often do this for an entire Active Directory group at a time — for example, an unusually permissive database might allow the entire MyDomain\Users to log in and use a specific database. A: Apparently the problem was with UAC on the Windows 2008 server. Our network guys were changing some group policies and turned UAC on for all our servers. So, this had nothing to do with switching edition of SQL Server (Ent --> Standard). Turning off UAC fixed the issue I was having.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Understanding classes in ActionScript I have not used Flash in some time, let alone gotten round to using Classes in flash. I need to do some work on a client's site and I am trying to follow the previous developer's code which he/she did using classes in AS2. Am I correct in understanding that these lines of code... import mx.transitions.*; import com.app.*; import com.movie.*; class com.movie.Main extends MovieClip { private var _contentData:Object; private var _contentManager:ContentManager; public var _language:String; * *imports the other classes *extends the abilities of the movie clip called Main and then fires off everything below it. What I am trying to grasp is what fires off the initial code and it looks like this might be it? EDIT: It seems that the initial Main.as is fired off just after the preloader on the timeline: import com.movie.Main; A: In your Main class there should be a line such as: public function Main():void That's the constructor of the class and where most of the initialization code should be. If the Main class is the fla's document class, the class will be created automatically. A: It is a Document Class, of which an instance is created automatically and added to the stage. Not everything is fired off, just the constructor (same name as the class) will run, whatever that is doing from then on. The document class can be chosen when compiling. Take a look here. The document class can probably also be chosen in the project configuration in an IDEs. A: if you are using flash IDE, include com.movie to the list of source file locations & set Document class to Main.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to add a vertical scrollview i ve got a view which contains buttons and textview .what i want is to scroll vertically...cud u guys help me out below is the code... - (id)initWithItem:(NSString *)theItem Title:(NSString *)title Description:(NSString *)detaildesc{ if (self = [super initWithNibName:@"Secondetailview" bundle:nil]) { self.theItem1=theItem; self.theTitle=title; UILabel *tit = [[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 25)] autorelease]; [tit setBackgroundColor:[UIColor clearColor]]; [tit setTextColor:[UIColor whiteColor]]; [tit setText:self.theTitle]; [tit setFont:[UIFont boldSystemFontOfSize:16]]; NSLog(@" wii this is cool:%@",detaildesc); [self.view addSubview:tit]; label1.text=detaildesc; label1.numberOfLines=4; label1.textColor=[UIColor grayColor]; } return self; } A: Put a UIScrollview inside the tab and then adjust the contentSize of the UIScrollView to the size of the total height of all your controls. A: In contentSize you have to increase the Y value
{ "language": "en", "url": "https://stackoverflow.com/questions/7556204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SVG / Raphael, how does one implement the DOT algorithm in javascript? (Graph organization) My fiddle: http://jsfiddle.net/G5mTx/10/ As you can see, the current way I'm organizing the nodes does no balancing, and there is some overlap when parent nodes have more than 1 child node. For those not familiar with the DOT algorithm, a brief, vague explanation can be found here: http://www.ece.uci.edu/~jhahn/pdf/dot.pdf Basically, DOT organizes the nodes such that the graph is optimal, which means that it is concise, has minimal line crossing, and is balanced. I've heard of some people running the DOT algorithm server side before sending it to the client... which would be consistantly faster... but I need each of the nodes to have hover and click states, as I plan on allowing the user to re-assign where the arrows / lines point. I mean, I COULD do the SVG generation server-side.. but then how would I hook up hover / click events to the nodes, and have the tell the server which Model the node represents upon line re-assignment? Note: My server runs Ruby on Rails 2.3.8 A: I struggled with exactly this situation and ran the DOT algorithm on my server, sending only the new coordinates for the nodes back to the browser. Ultimately I found the setup unsatisfactory. I switched to using D3's force layout algorithm, which is implemented in Javascript and appears to be more modern than DOT's, and now I'm much happier.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: resize / drag usercontrol at runtime How can I resize / drag a usercontrol in silverlight 4 at runtime through a resizehandle in the bottomright corner for example? As a beginner I have no idea how I can do this. A: I've found exactly what I was looking for. I was using a childwindow but it blocked interaction with parent so I thought I had to create a usercontrol and built in resize function and drag function and stuff. This guy took the childwindow and refactored it for non-modal use: * *http://timheuer.com/blog/archive/2009/05/10/silverlight-childwindow-non-modal-refactor.aspx *latest build here: http://floatablewindow.codeplex.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7556209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perl style regular expression for C comments At work, I have a requirement to create a perl-style regular expression for C comments (/*) for comments left in our code. Our business analysts had new requirements, and these were all prefaced with "BA", and I'm supposed to somehow scan the comments to find these instances. I am very unfamiliar with regular expressions and after reading more about them, I'm lost as to how to target comment blocks with only the BA string. Any guidance would be greatly appreciated. A: I'm not aware of any weird escaping rules for C comments, so I think you just want something like this: /\/\*.*?\/\*/s The s flag means that the . will also match carriage returns, so the comments can cross multiple lines. To match only comments starting with "BA", you'd want: /\/\*BA.*?\/\*/s Consider adding the i flag if the "BA" part can be lowercase. A: find . -regex ".*\.[ch]" | xargs grep -regex "/\* *BA" What that does: * *Find all your C source and header files. *Search each of those files for "/*" followed by any amount of whitespace, followed by "BA".
{ "language": "en", "url": "https://stackoverflow.com/questions/7556210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: sessionStorage between parent and child pop-up I have an HTML5 page where I store some data with: window.sessionStorage.setItem('toStore', 'hello world'); Then, I open from this window a pop-up one with: window.open('mobile.html', 'myPopUp'); I have a set of Javascript functions associated to the two pages, where I want to access the local storage data of parent page from the popUp with the getItem('toStore') call. Is that possible? If yes, what's the calling syntax? Thanks A: Converting comment to answer. window.opener.sessionStorage.setItem('toStore', 'hello world');
{ "language": "en", "url": "https://stackoverflow.com/questions/7556214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Click an UIImage and open an UIImageView in Objective-c Suppose I have an UiImage called "thumbnail" on a view, I want to ask how to open an UiImageView when I click on the UiImage(thumbnail)? This effect is similar to an user click on a small image on a webpage, then popup a larger image. Thanks A: Add UITapGestureRecognizer to your UIImageView: UITapGestureRecognizer *tapRecognizer; tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(yourSelector)]; [thumbnail addGestureRecognizer:tapRecognizer]; [tapRecognizer release]; thumbnail.userInteractionEnabled = YES; // very important for UIImageView A: A UIImage can't exist "on a view" as it is just a representation of some image data. So you'd have an appropriately sized and shaped UIButton, with your thumbnail image as it's image, and link this button's action to the creating and presenting of a new UIImageView. A: I would suggest you rather use a UIButton and set its Background image to your image. Then you can wire an IBAction from this button to your view controller.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mac magic mouse horizontal swipe/scroll issue in firefox 6 I have added overflow-x: hidden to my css html tag in order to hide the slides that are floated to the left, each slide fills the whole window. These slides are then accessed using a navigation, this works fine in all browsers hiding the horizontal scroll as it should. I have come across a problem now though where even though the horizontal scrollbar is hidden the hidden pages can be scrolled to using the magic pad swipe/scroll. Is there anyway this can be disabled using a specific webkit css property or by adding javascript? I have seen posts where people have instructed users to disable the swipe/scroll in through terminal etc but that's not what Im after. I have found this problem only to happen in Firefox 6 for mac so far. Thanks Kyle A: If the overflow property isn't working, try using JQuery.scrollTop() or JQuery.scrollLeft() $(document).ready(function(){ $("#element").scroll(function(){ $(this).scrollTop(0); $(this).scrollLeft(0); }); }); That's the only thing that comes to mind, to be honest. I assume of course that the swipe/scroll triggers a scroll event, otherwise that function would fail, in which case I know of no working solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there an open-source implementation of an XPathNavigator for POCOs? I would like to enable XPath navigation over my POCOs (i.e. "plain old CLR objects"). From a brief search, I have found several options: * *Use ObjectXPathNavigator .NET 1.0 implementation. However, since it was written against .NET 1.0, I have concerns about potential issues with generics (and whatever else that wasn't supported back then). *Implementing my own XPathNavigator by extending the .NET XPathNavigator class. The second option appears to be what I want. However, I don't have the time to write my own -- especially since I expect that someone else has already implemented it and made it open source. I just have a difficult time finding this elusive PocoXPathNavigator implementation! Thanks. A: The best approach, it seems, is to use ObjectXPathNavigator (option 1) since it's open source. I plan to extend it to support generics and whatever else I need. A: You can serialize your objects as xml string into memory and then use the standard XPathNavigator to search in it. There are also some native XML database systems which you may use to serialize your objects into. The question is, why do you need an XPathNavigator to search in objects? If you have a large objects graph you may consider using some kind of graph db / nosql db.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to turn GCStress on in Windows 7? I am debugging a GC heap corruption and came to the step where I want to try running the program under WinDbg + PageHeap + AppVerifier + GCStress. I found in the article Software crash: faulting module mscorwks.dll, version 1.1.4322.2379 that I can enable GCStress like this: reg.exe add "HKLM\SOFTWARE\Microsoft\.NETFramework" /f /v HeapVerify /t REG_DWORD /d 1 reg.exe add "HKLM\SOFTWARE\Microsoft\.NETFramework" /f /v StressLog /t REG_DWORD /d 1 reg.exe add "HKLM\SOFTWARE\Microsoft\.NETFramework" /f /v GCStress /t REG_DWORD /d 3 reg.exe add "HKLM\SOFTWARE\Microsoft\.NETFramework" /f /v FastGcStress /t REG_DWORD /d 2 (I am trying this method. It takes the program forever to launch. I deleted the last two entries from the registry to have it work, probably something is wrong with the approach itself.) Or the article Access Violation in .NET 4 Runtime in gc_heap::garbage_collect with no unmanaged modules described the other method: (DWORD) StressLog = 1 (DWORD) LogFacility = 0xffffffff (DWORD) StressLogSize = 65536 Which way is correct or is there another correct way? A: I searched GCStress on Koders. It turned out the best way to understand it is by looking at .NET's source code: enum GCStressFlags { GCSTRESS_NONE = 0, GCSTRESS_ALLOC = 1, // GC on all allocations and 'easy' places GCSTRESS_TRANSITION = 2, // GC on transitions to preemtive GC GCSTRESS_INSTR_JIT = 4, // GC on every allowable JITed instruction GCSTRESS_INSTR_NGEN = 8, // GC on every allowable NGEN instruction GCSTRESS_UNIQUE = 16, // GC only on a unique stack trace };
{ "language": "en", "url": "https://stackoverflow.com/questions/7556224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: django fails to retrieve data using multiple databases Im trying to access one database table which is in several databases. I tried using MytableObject.get.using(databasename) first, but it threw error: django.db.utils.DatabaseError: relation "mytable" does not exist So i set out trying to figure out why. as long as i know im not doing anything different than usual : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': config.get('databaseDefault', 'DATABASE_NAME'), # Or path to database file if using sqlite3. 'USER': config.get('databaseDefault', 'DATABASE_USER'), # Not used with sqlite3. 'PASSWORD': config.get('databaseDefault', 'DATABASE_PASSWORD'), # Not used with sqlite3. 'HOST': config.get('databaseDefault', 'DATABASE_HOST'), # Set to empty string for localhost. Not used with sqlite3. 'PORT': config.get('databaseDefault', 'DATABASE_PORT'), # Set to empty string for default. Not used with sqlite3. }, 'databaseEe': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': config.get('databaseEe', 'DATABASE_NAME'), # Or path to database file if using sqlite3. 'USER': config.get('databaseEe', 'DATABASE_USER'), # Not used with sqlite3. 'PASSWORD': config.get('databaseEe', 'DATABASE_PASSWORD'), # Not used with sqlite3. 'HOST': config.get('databaseEe', 'DATABASE_HOST'), # Set to empty string for localhost. Not used with sqlite3. 'PORT': config.get('databaseEe', 'DATABASE_PORT'), # Set to empty string for default. Not used with sqlite3. }, 'databaseLv': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': config.get('databaseLv', 'DATABASE_NAME'), # Or path to database file if using sqlite3. 'USER': config.get('databaseLv', 'DATABASE_USER'), # Not used with sqlite3. 'PASSWORD': config.get('databaseLv', 'DATABASE_PASSWORD'), # Not used with sqlite3. 'HOST': config.get('databaseLv', 'DATABASE_HOST'), # Set to empty string for localhost. Not used with sqlite3. 'PORT': config.get('databaseLt', 'DATABASE_PORT'), # Set to empty string for default. Not used with sqlite3. }, 'databaseLt': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': config.get('databaseLt', 'DATABASE_NAME'), # Or path to database file if using sqlite3. 'USER': config.get('databaseLt', 'DATABASE_USER'), # Not used with sqlite3. 'PASSWORD': config.get('databaseLt', 'DATABASE_PASSWORD'), # Not used with sqlite3. 'HOST': config.get('databaseLt', 'DATABASE_HOST'), # Set to empty string for localhost. Not used with sqlite3. 'PORT': config.get('databaseLt', 'DATABASE_PORT'), # Set to empty string for default. Not used with sqlite3. } } And i created some testcode: from django.db import connections cursor = connections[database].cursor() cursor.execute("select tablename from pg_tables WHERE tablename !~* 'pg_*'") print cursor.fetchall() which printed out all my tablenames, "mytable" among them. Then i tried this code : from django.db import connections cursor = connections[database].cursor() cursor.execute("select * from mytable") print cursor.fetchall() which produced error again: django.db.utils.DatabaseError: relation "mytable" does not exist LINE 1: select * from mytable So what am i doing wrong? i can read and write into my default database just fine. I tracked things down to this line: cursor = connections[database].cursor() and found that, if i write actual connection name instead of database, like that: cursor = connections['databaseLv'].cursor() then it works just fine. So how can i do this dynamically? Alan A: Django needs DB Routers to be defined to decide what database to use, maybe your definitions are not the right ones.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do Struts2 Results annotations override or add to superclass defined values? The following example: I have a superclass and subclass for a struts action. The superclass defines @Results, and the subclass needs to define additional specific @Result entries. For example: @Results({ @Result(name=BaseAction.ERROR, location="/WEB-INF/jsp/error.jsp") }) public abstract class BaseAction extends ActionSupport implements ServletRequestAware { ... } ..and a subclass @Results({ @Result(name=BaseAction.INDEX, location="/WEB-INF/jsp/reporting/index.jsp") }) public class ReportAction extends BaseAction { ... } My question is, does an instance of ReportAction only have the @Result of INDEX defined, or does it also contain any @Result entries defined in any if it's superclasses. Is my ReportAction aware of the location set for BaseAction.ERROR ?? Thanks, Martin A: Yes, your ReportAction class will have both BaseAction.INDEX and BaseAction.ERROR. General super class or sub class rule will apply in this case also. If you don't find something in your subclass it will go and look into the super class. In your case BaseAction.ERROR not found in your subclass it will go and look into the superclass. A: It will have both. You can verify with the config browser plugin. A: It will be able to identify both BaseAction.INDEX and BaseAction.ERROR. If the result is available in the Subclass (In your case ReportAction class) it will follow that, Otherwise it will look in the superclass (In you case BaseAction class).
{ "language": "en", "url": "https://stackoverflow.com/questions/7556228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Sudoku difficulty rating I want to build a sudoku game with a generator. I have figured out everything how to do it without the difficulty level: easy, medium, hard. My question is how many numbers should I hide depending of the difficulty level? Any ideas. A: I'm pretty sure that the difficulty rating for a sudoku puzzle is assigned not based on the quantity of missing numbers but on the techniques required to solve the puzzle. Take a look at this list of sudoku solving techniques. The Naked Single and Hidden Single techniques are well-known and easy for novices to complete. The harder techniques like X-Wing and Swordfish are much more difficult. To determine the difficulty, you should write a program that iteratively solves your puzzle, each time with more techniques in its toolbox. A: Here are some ideas. You might also be interested in this Sudoku generator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Number of Spring Contexts created by ContextLoaderListener It is easily to know how many contexts have been created if we create ApplicationContext instances programmatically. However, how many context are created if we use ContextLoaderListener? For example Spring's reference as below: <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> It has 2 context xml files. Does it means 2 contexts are created? Thanks. A: Only one context is created - only one root application context exists. Bootstrap listener to start up and shut down Spring's root WebApplicationContext. If you look at the code of ContextLoader - it creates a WebApplicationContext using the contextConfigLocation param (which is later parsed by the context) A: ContextLoaderListener creates only one application context containing all beans from files selected in contextConfigLocation. Bean definitions are merged together and form a single context. However if you use Spring MVC, the framework will create one extra child context per each DispatcherServlet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error in Query String.Whitespaces I am creating a hyperlink to a page The url is determined by the user input,thus by the querystring <a href='+abc+'&country='+country +'&state='+state+' ></a>; The problem is that the variable state consists of two or more words.. so when i try to click the hyperlink proving the input in the form,only the first word of the state variable is fetched.Browser treats the other as another variable. example if i input new york as state. in the state variable only new is saved,asnd the browser treates york as another variable with a blank value &york="" What should I do? A: Escape the illegal characters with encodeURIComponent; '<a href='+ encodeURIComponent(abc) +'&country=' + encodeURIComponent(country) +'&state=' + encodeURIComponent(state) + '></a>; Which would, for example, convert "aaa bbb" to "aaa%20bbb". A: Well, you could always encode the url: Encode URL in JavaScript? Or use some comma-separated string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check admin rights C# How to check is my application starts with admin rights? I use this code now: public static bool IsUserAdministrator() { //bool value to hold our return value bool isAdmin; try { //get the currently logged in user WindowsIdentity user = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(user); isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); } catch (UnauthorizedAccessException ex) { isAdmin = false; } catch (Exception ex) { isAdmin = false; } return isAdmin; } This code checks user rights, I need to check the rights that application has. For example, I'm not the administrator but when the application starts with admin rights this code returns false. Thanks! A: That's the correct approach to performing the check, I use it myself in my PowerShell profile to distinguish elevated sessions. I suspect you're not taking into account the effect of User Access Control (UAC). When a user logs in they get a security token object allocated. This contains both their own security id (SID), the SIDs of groups they belong to and a list of privileges they have (and whether those privileges are enabled). With UAC enabled, when you do an interactive login if you have certain privileges or are a member of the local administrators you get two tokens: one with everything and a second with administrative access SIDs and privileges removed. The latter token is used with each launched process, unless launched elevated when the former token is used. Thus an administrator cannot exercise their full power without an extra step – this helps prevent malware from being started with full control of the system. The best tool for seeing this in action is Process Explorer. The Security tab of the process properties dialogue shows the contents of the process's security token (and adding the "Integrity Level" column to the main display will show what processes are elevated) – run Process Explorer elevated to see the full information. So your code will only return true for a process run by an administrator that is also elevated (run as administrator).
{ "language": "en", "url": "https://stackoverflow.com/questions/7556237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Signing in on a website ? how does the server manage it? I am developing a site where access to certain pages might require the user to sign in. (he/she writes his username and password) if the user has successfully signed in he/she can then access this pages. How does the server know that this is the case ? Does it figure the IP address of the sender when he/she establish the connection ? Does it set up a timeout variable on its side so to say: 'you have been disconnected because your activity was idle for 10 minutes' ??? Many websites have this abilities on I just don't know how this is done. Can somebody explain ? Thanks, A: The most common solution is to use cookies. You could store session data or unique identifiers in the cookies, then your app would check the contents during each request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Templated list with radio buttons I have the following code: @using (Html.BeginForm()) { for (int i = 0; i < Model.Themes.Count; i++) { <div class="theme"> <img src="/Content/img/placeholder/@Model.Themes[i].PreviewImg" class="theme-image" /> <div class="theme-meta"> @Html.RadioButton("Themes", Model.Themes[i].Selected, new { @id = "Themes_" + i + "__Selected" }) @Html.TextBoxFor(x=>x.Themes[i].Id) <label>@Model.Themes[i].Name</label> </div> </div> } <div class="submit"> <input type="submit" class="dash-module-alt-button submit" name="SelectTheme" /> </div> } However submitting this with one of the radio buttons selected does not bind with the selected property set to true. Using Html.RadioButtonFor means that they all have a generated array name so they can all be selected. HOW the eff am i supposed to do this? cheers w:// A: Not sure if this is what you want but Html.RadioButtonFor will take a value argument - @Html.RadioButtonFor(x => x.Themes, "blue") @Html.RadioButtonFor(x => x.Themes, "green") A method for using this in a loop is discussed in this question - When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?
{ "language": "en", "url": "https://stackoverflow.com/questions/7556240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do I need a Guice module for every class to write integration tests? Currently I have 1 Guice module in my project which defines all bindings. Now I want to write integration tests and I need to bind the dependencies of a specific class. If I use the existing module, Guice will bind all dependencies. But I think this in not correct for integration tests. So, do I need a module for every class that only the necessary dependencies will be bind? Thanks. A: Creating one Guice module to bind all bindings in a project isn't optimal, but neither is creating one module per binding. In general, you simply want to "group related bindings into a module". Doing so is somewhat of an art, rather than a science, so I can't give perfect advice. If your project has a solid Java package structure, then creating one Guice module per package is a good place to start (though, if your packages contain lots of classes, you may even want several per package). Using per-package Guice modules also gives you the advantage of letting you make your implementation classes be package-private (which is good for encapsulation!). One specific example: if your project has external dependencies, it's probably good to bind them separately from your application code. For example, if you have a webserver that talks to an RPC service on another server, it's good to bind the service separately from the code that talks to the service (that way, you can mock out the external service without mocking any application code). As a crutch, you can also use Modules.override(...)[1], but doing so is generally a sign that your modules are too big. * *http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/util/Modules.html A: Yes, you can have more than one module, and usually you want a different one for your tests. If you didn't use field injection and it's not too much work, you could have your setup build the classes with constructors that are passed the tested objects, including mocks. Alternatively, and more commonly, remember that your modules' configure methods can install other modules, so if you compartmentalize the stuff that's common between regular operation and integration testing into one module, the remaining two different modules can each install the common one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android JSON Exception I have a little problem with parsing JSON data which I receive via server.I have a two JsonObjects which don't have data always,only in some cases but I need to check if they are null or not everytime.I'm using this code to do that : String jsonData = new String(contentBuffer,"UTF-8"); Log.w("JSONDATA","JSONDATA VALID OR NOT : "+jsonData); json = new JSONObject(jsonData); JSONObject jsonObj =(JSONObject) new JSONTokener(jsonData).nextValue(); if(jsonObj.getString("collection_id")==null){ values.put("collection_id", 0); }else { collectionId = Integer.parseInt(jsonObj.getString("collection_id")); values.put("collection_id", collectionId); } Log.w("COLLECTION ID ","SHOW COLLECTION ID : "+collectionId); if(jsonObj.getString("card_id")!=null){ values.put("card_id", cardId); }else { values.put("card_id", 0); } Log.w("CARD ID ","SHOW CARD ID : "+cardId); And the thing that I want it not to throw an Exception, just to check if collection_id is null, save 0 in the database, and if not save it's value. But using this code it's throwin me JSONException. Any ideas how to fix that? A: use if ( jsonObject.has("collection_id")) this will check if jsonObject has collection_id key present in it. A: You could also use collectionId = jsonObj.optInt("collection_id", 0); This will get the value as an int if it exists, or return 0 if it does not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CakePHP Select Query Is there a way to select all fields from a specific table in CakePHP? So something like: $this->Model1->find('first', array('fields' => 'Model2.*', 'conditions' => 'Model1.id = Model2.Model1_id'), 'contain' => array()); I've been looking all over the place and can't find anything on this. I'm kind of hoping that I don't have to type out all of the fields for Model2 :( Forgive me for my nubishness, I just started learning Cake. Many thanks in advance! A: You don't. The syntax you have (meaning the Model2.* part) will work, as will defining no fields at all. By default, they're all returned. I don't know, though, whether the find call as you have it will work. It seems awkward at best to be executing a find on Model1 in order to get data from Model2. As Henri mentioned in his comment, better to do the find on Model2. A: For some driver, wildcard won't work as expected. So you need the whole list of fields. $ds = $this->Model1->getDataSource(); $this->Model1->find('first', array( 'fields' => $ds->fields($this->Model1), 'conditions' => 'Model1.id = Model2.Model1_id', 'contain' => array() )); A: you can try this $this->Model1->find('first', array( 'fields'=>'Model2.*', 'joins' => array( array( 'table'=>'table', 'alias'=>'Model2', //'type'=>'LEFT', 'conditions'=>array( "Model2.model1_id = Model1.id", ), ), ), 'conditions' => array('Model1.somefields' =>'1' ) ) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7556244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSF 2.0, malformedXML when using ajax on a commandlink I am trying to display a field in a form after an ajax request through a commandlink.However ,i get a malformedXML error when i click the link. The xhtml file looks like : <h:form> . . <tr> <td>Product Image*:</td> <td> <h:graphicImage url="#{addItem.prodFileName}" width="100" height="100"/> <br /><h:commandLink value="change image" > <f:ajax event="click" render="uploadimage" execute="@this" listener="#{addItem.ChangeImage}"/> </h:commandLink> </td> </tr> <tr > <td> <t:inputFileUpload rendered ="#{addItem.editImgChange}" label="editImage" id="uploadimage" value="#{addItem.uploadedFile}" /> <h:messages for="prodimage"/> </td> </tr> . . </h:form> The AddItem bean is RequestScoped and it has the below lines of code: @ManagedBean public class AddItem extends AbstractBean { //.. boolean editImgChange=false; //... public void ChangeImage(){ this.editImgChange=true; } } Inshort,i want to display the t:inputFileUpload field only after user clicks the change image link. I have kept a flag editImgChange in the AddItem bean whose initial value is false and once user clicks the change image link ,the flag is changed to true. The program goes to the ChangeImage() method ,but after that i get the error "malformedXML:During update:j_idt30:uploadimage not found" . I will be happy with a totally different solution also, to achieve the same result ,incase my design is bad. A: The render attribute should point to the ID of a component which is always rendered into the HTML. It's namely JavaScript who is supposed to update/replace its content based on the ajax response. But if the component is never rendered into HTML, then JavaScript won't be able to update/replace its content. You need to wrap it in another component which is always rendered into HTML and then update it instead. E.g. <h:panelGroup id="uploadimage"> <t:inputFileUpload rendered ="#{addItem.editImgChange}" label="editImage" value="#{addItem.uploadedFile}" /> </h:panelGroup>
{ "language": "en", "url": "https://stackoverflow.com/questions/7556245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Following: How to use FTS in SQLite with Monotouch for iOS I'm currently following this small tutorial about MonoTouch, SQLite and FTS3: How to use FTS in SQLite with Monotouch I've sucessfully done step 1 and 2. Unfurtunatelly I'm facing a problem on step 3, because when i try to compile the iPhone monotocuh project I got this error: Error 1: mtouch failed with the following message: Process exited with code 1, command: /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -arch i386 -gdwarf-2 -fobjc-legacy-dispatch -fobjc-abi-version=2 -miphoneos-version-min=4.2 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk /var/folders/lu/luWKJVufEMO0MYd3+T3MJ++++TI/-Tmp-/tmp4f24ee90.tmp/main.x86.o -o /var/folders/lu/luWKJVufEMO0MYd3+T3MJ++++TI/-Tmp-/tmp4f24ee90.tmp/Iusuite -framework CFNetwork -framework AssetsLibrary -framework CoreTelephony -framework EventKit -framework Foundation -framework CoreMotion -framework GameKit -framework MapKit -framework MediaPlayer -framework MessageUI -framework OpenGLES -framework StoreKit -framework UIKit -framework AddressBookUI -framework iAd -framework SystemConfiguration -framework AddressBook -framework AudioToolbox -framework AVFoundation -framework QuartzCore -framework CoreFoundation -framework CoreGraphics -framework CoreLocation -framework ImageIO -framework Security -framework CoreMedia -framework CoreVideo -framework ExternalAccessory -framework EventKitUI -framework QuickLook -framework AudioToolbox -lz -u _mono_pmip -u _CreateZStream -u _CloseZStream -u _Flush -u _ReadZStream -u _WriteZStream -liconv -lmono-2.0 -lmonotouch -L/Developer/MonoTouch/SDKs/MonoTouch.iphonesimulator.sdk/usr/lib -u _catch_exception_raise -L/Users/user/Develop/MonoDevelop/.../ -lSQLite3_iOS -force_load /Users/user/Develop/MonoDevelop/.../Libraries/libSQLite3_iOS.a ld: library not found for -lSQLite3_iOS collect2: ld returned 1 exit status (1) (Iusuite.Application) This is what i use as additional command for monotouch -gcc_flags "-L${ProjectDir} -lSQLite3_iOS -force_load ${ProjectDir}/Libraries/libSQLite3_iOS.a" Any hint or idea? thanks to all Francesco A: You're building your own sqlite library and you need to make sure you're using this library from your MonoTouch project. The extra arguments you're giving mtouch ask gcc to link your new library. The given path is: /Users/francesco/Develop/MonoDevelop/AdMaiora/Applications/src/AdMaiora.Iusuite/Iusuite.App.Apple/Iusuite.Application/Libraries/libSQLite3_iOS.a Does that file exists on your system ? If not then look for the file and either update your extra arguments or move the library to the location you provided. Note: it's uncommon to provide -L${ProjectDir} and then specify -force_load ${ProjectDir}/Libraries/libSQLite3_iOS.a (note the extra /Libraries/ in the path).
{ "language": "en", "url": "https://stackoverflow.com/questions/7556246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ RAII Questions So as I understand it to implement RAII properly, if I where to call CreateFont, I'd wrap that in a class with CreateFont in the constructor and DeleteObject in the destructor, so it cleans it up when it goes out of scope. First question is, won't I end up with ALOT of classes doing that? Especially since the class only has a constructor and destructor. Second question is, what if I'm calling the CreateFont class in the WndProc, that goes out of scope constantly. So am I supposed to do all my calls to CreateFont or like LoadBitmap in the WndMain? I'm used to calling those functions in WM_CREATE and cleaning them up in WM_DESTROY. A: First question is, won't I end up with ALOT of classes doing that? Especially since the class only has a constructor and destructor. Yes, but there are few points to consider: * *is it a problem? The classes will be small and easy to read and understand, *you might be able to reuse many of them (for example, there are a lot of Win32 functions which create HANDLE objects, and they're all closed the same way (with CloseHandle), so you could reuse the same class for those. *you can use a smart pointer or some other generic wrapper to fill in most of the boilerplate code. The most popular smart pointer classes allow you to specify a custom deleter function. Second question is, what if I'm calling the CreateFont class in the WndProc, that goes out of scope constantly. Store it in a location where it won't go out of scope prematurely. :) Here, smart pointers might be useful again. For example, shared_ptr could be used to keep the font alive as long as there's at least one shared_ptr pointing to it. Then you can simply pass it out of the function to some common longer-lived location. Otherwise, as long as you implement copy constructor and assignment operator (in C++11 you might want to implement move constructor and move assignment instead) for your RAII class, it can be copied (or moved) safely to wherever you want to put it, even if it was created in a smaller scope. A: You can avoid a lot of repetitious work by using a template to help you. For example if you use boost::shared_ptr you can do: #include <boost/shared_ptr.hpp> #include <functional> struct Font; Font *createFont(); void deleteFont(Font*); int main() { boost::shared_ptr<Font> font(createFont(), std::ptr_fun(deleteFont)); } Which saves you writing a custom class to manage the resource. If boost and TR1 or newer aren't available to you it's still possible to implement something similar and generic yourself to assist. boost::shared_ptr is reference counted properly, so if you want to create it somewhere and "promote" it to live longer later you can do so by copying it somewhere longer lived before it dies. A: First question is, won't I end up with ALOT of classes doing that? Especialy since the class only has a constructor and deconstructor If you don't like the number of classes you'd need to create for each different type of object, you can create a single RAII class that takes a HGDIOBJ parameter in the constructor and calls DeleteObject in the destructor. This class can then be used for all the different GDI objects. For example: class GDIObject { public: HGDIOBJ GdiObject; GDIObject( HGDIOBJ object ) : GdiObject( object ) { } ~GDIObject() { DeleteObject( GdiObject ); } } ... GDIObject font( CreateFont( 48, 0, 0, 0, FW_DONTCARE, false, true, false, DEFAULT_CHARSET, OUT_OUTLINE_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, VARIABLE_PITCH, TEXT("Impact") ) ); Second question is, what if I'm calling the CreateFont class in the WndProc, that goes out of scope constantly. So am i supposed to do all my calls to CreateFont or like LoadBitmap in the WndMain? I'm used to calling those functions in WM_CREATE and cleaning them up in WM_DESTROY. For items that need to remain in-memory for longer than the function scope, you'll have to put these at the global level. A: If you're going for solid RAII, there are some options for reducing the number of classes you'll need - for example, some boost smart pointers (shared_ptr specifically) allow you to provide your own function to call when the pointer goes out of scope. Otherwise, yes - you'll have a class for any resource which requires explicit freeing - and while it's a pain in the butt code-wise, it will save you massive time in debugging in the long run (especially in group projects). I'd still say to use RAII based on your own feelings on the situation though - it's a wonderful idea to use it everywhere, but some times when converting old code it can be a massive amount of work to fix all the call-chains up to use it. One more thing - I'm not overly familiar with the GUI logic you're working with, so I won't go there specifically... but you'll have to look into how your resources should be copied and how long they should be maintained. Will your RAII containers be reference counting, or will they have value (copy) semantics? Reference counting smart-pointers like shared_ptr may solve your problem about recreation of resources frequently as long as you can pass a reference to the original around your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How can I get command arguments with D-trace on OSX I'm trying to preview run commands with the args with D-trace. I tried something like this: sudo dtrace -n 'syscall::execve:return {printf("%s\n", curpsinfo->pr_psargs);}' But on OSX this code returns only commands names not their args. I find this forum thread but code in last answer doesn't works for me. A: with a little help of my colleague we manage to fix script mentioned in question. This is correct one. The problem was that forum markup removed some * and _ chars.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Asp Mvc 3 with NinjectHttpApplication and MEF I am using Ninject as my MVC controller factory, but I also load in certain routes and controllers via MEF, these controllers need to be able to register themselves with Ninject: Bind<SomePluginController>.ToSelf(); So the dynamically added routes can be picked up. So far the only way to do this I can think of is to expose the internal kernel outside of the web application, however this seems a bit nasty and the NinjectHttpApplication.Kernel seems to be obsolete. Has anyone else managed to do this? A: The problem you've got is that MEF is designed to compose a set of unknown parts, whereas Ninject is dealing with explicit component registration. You can't easily grab type information from MEF because it is all handled at runtime, not compile time. What I think you may have to do, is build a composite controller factory that supports both Ninject and MEF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to free c++ memory vector * arr? I have a vector<int>* arr, which is actually a 2D array. arr = new vector<int> [size]; Is it ok that I just do delete arr; Will arr[i] be automatically be deleted, since it is a standard vector? A: Your code is broken. You should be using delete[] with new[]: delete[] arr; Once you fix this, your code will work correctly. I have to agree with the commenters that a C-style array of vectors looks a bit crazy. Why not use a vector of vectors instead? That'll take care of memory management for you. A: You're allocating an array of vectors there. So you'll need array delete: delete [] arr; If you were intending to allocate a vector of 'size' elements, you need: arr = new vector<int>(size); // don't use array delete for this though! A: No, you should be using delete[] when you used new[]. But this is madness. You're using nice happy friendly containers for one dimension, then undoing all the goodness by resorting to manual dynamic allocation for the outer dimension. Instead, just use a std::vector<std::vector<int> >, or flatten the two dimensions into a single vector.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Display datetime in actionscript with no timezone or daylight savings time changes? In actionscript I am trying to format datetime fields coming in from a webservice call which takes into account the timezone and daylight savings time. Basically we need to display times for events, here in our TZ at the time it will be on that day. The following function works for timezones but we recently found that all of the upcoming times after the daylight savings time are being shifted an hour forward. Is there a better way to handle this? public function getTimeZoneFix(fixDate:Date):Date { var GMTHour:Number = 4; // our timzone offset var gmtDate:Date = new Date(fixDate); var hourOffset:Number = gmtDate.getTimezoneOffset() / 60 - GMTHour; gmtDate.setHours(gmtDate.getHours() + hourOffset ); return gmtDate; } A: Have a look on the following: http://thanksmister.com/2011/10/06/determining-local-timezone-in-actionscript-air-flex-as3/ It may help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: scss style sheets issue rails 3.1 my projects.css.scss file looks like the bellow one, // Place all the styles related to the Projects controller here. // They will automatically be included in application.css. // You can use Sass (SCSS) here: http://sass-lang.com/ $right-container-background: #3BBFCE; $right-container-padding: 2px; .right-container{ background-color: $right-container-background; color: white; padding-left: $right-container-padding; padding-right: $right-container-padding; } It says that all styles will be automatically added to your application.css. But I am not able to use it without importing to application.css i.e. @charset "utf-8"; @import "projects.css.scss"; @import "partners.css.scss"; So, while i'm in the projects section of my view, is it not going to load all the .scss file imported in application.css ? A: The default application.css in rails 3.1 contains the following lines: /* * This is a manifest file that'll automatically include all the stylesheets available in this directory * and any sub-directories. You're free to add application-wide styles to this file and they'll appear at * the top of the compiled file, but it's generally better to create a new file per style scope. *= require_self *= require_tree . */ You should re-add them if you want the default behaviour of including everything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Passing Dynamic Loaded Type to SomeFunction I am trying to pass the type of a dynamically loaded dll (it uses an interface, but I need the conectrete implementation of this) to a function and am missing something. var data = LoadAssemblyFromParamenter(pathToDataDll); Type dataType = data.GetType().MakeGenericType(data.GetType()); SomeTest<dataType>(); public void SomeTest<T>() { //do something with T } Error is "The Type or Namespace 'dataType' coulnd not be found..." The concrete type is for a FileHelpers object (that uses fields), so I need the concrete implmentation. p.s. This has to be .net 3.5 .... To elaborate SomeMethod<T>( IEnumerable<T> items ) calls public static void WriteRecords<T>(IEnumerable<T> records, string fileName ) where T: ICMSDataDictionary { if (records == null || String.IsNullOrEmpty(fileName)) return; if (records.Any()) { FileHelpers.DelimitedFileEngine<T> engine = new FileHelpers.DelimitedFileEngine<T>(); engine.WriteFile(fileName, records); } } A: You can not do this, using Method syntax, because, for this you would know the type at compile time. You can, however, invoke your method using reflection. This code should help you started: static void Main(string[] args) { //Get method Method[T] var method = typeof(Program).GetMethod("Method", BindingFlags.NonPublic | BindingFlags.Static); //Create generic method with given type (here - int, but you could use any time that you would have at runtime, not only at compile time) var genericMethod = method.MakeGenericMethod(typeof(int)); //Invoke the method genericMethod.Invoke(null, null); } static void Method<T>() { Console.WriteLine(typeof(T).Name); } With object, it's similar, but you have to construct object dynamically, using reflection. A: Use the "dynamic" keyword: public void Doit() { dynamic data=LoadAssemblyFromParamenter(pathToDataDll); SomeTest(data); } public void SomeTest<T>(T arg) { Debug.WriteLine("typeof(T) is "+typeof(T)); } !!!EDIT!!!: sorry, I missed that you needed the 3.5 Framework. If so, use this: public void Doit() { var data=LoadAssemblyFromParamenter(pathToDataDll); var mi=this.GetType().GetMethod("SomeTest").MakeGenericMethod(data.GetType()); mi.Invoke(this, new object[0]); } public void SomeTest<T>() { Debug.WriteLine("typeof(T) is "+typeof(T)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Program Executing Differently From CMD I have made a C# app that, when opened, reads a text file and outputs the lines into the list view. I have set this to run at startup with a reg key which does open it but the app just shows an empty list view. Same thing happens when I run it from cmd but everything works fine when I just double click on the file in explorer, there are no parameters/arguments to the app so this has really confused me, any ideas are much appreciated! Thanks. A: Hard to tell without looking at the code that reads the file. I suspect the current dir is the problem. Make sure to specificity full path to your text file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: building several targets using for loops in gnu make (only symbol definitions change) i need to build 4 targets from the same set of source files. The only thing that changes are a couple of symbol definitios at compile time (-D DEBUG_OUTPUT, -D TIME_OUTPUT) how can I accomplish that in a GNU makefile? I thought of running a gnu make 'for loop' and re-declare the $(SYMBOLS) and $(TARGETNAME) each time, then run make $(TARGETNAME) from within the for loop. Is that possible? Is there a better way (preferrably using gnu make and not automake, or some other variant) Thank you, nass A: How about this: foo: DEBUG_OUTPUT=yes foo: TIME_OUTPUT=2 bar: DEBUG_OUTPUT=no bar: TIME_OUTPUT=3 baz: DEBUG_OUTPUT=maybe baz: TIME_OUTPUT=5 qux: DEBUG_OUTPUT=dunno qux: TIME_OUTPUT=7 TARGETS = foo bar baz qux all: $(TARGETS) $(TARGETS): $(SOURCE_FILES) @echo compile $^ into $@ using $(DEBUG_OUTPUT) and $(TIME_OUTPUT)
{ "language": "en", "url": "https://stackoverflow.com/questions/7556271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rails 3.1 - auto compile SASS before browser refresh I used to run compass -watch to ensure my Sass files compiled as soon as they were modified. Now though, thanks to the asset pipeline, code auto-compiles (if changes are detected) when the view is refreshed in the browser. There's a time-cost associated with this, especially if you frequently modify your Sass files. I'm spending half my development time waiting on views to refresh. I'm wondering if there's a way to compile sass before a page refresh in rails 3.1. I tried the sass-guard gem but it doesn't seem to do what I want in rails 3.1. Perhaps there's another way? A: fixed this using guard-livereload - now my code changes take effect before I've even switched from text-editor to browser, which cuts down on RSI-inducing mouse movements considerably
{ "language": "en", "url": "https://stackoverflow.com/questions/7556272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }