text
stringlengths
8
267k
meta
dict
Q: Java Socket Programming Login as Anonymous on FTP I'm a newbie in Java socket programming and right now, I have a hard time. I would like to make a simple java program which can connect a socket in port 21, log as anonymous user, and put a password on it, so I can log as an anonymous in a proper way. I turn on my FTP on XAMPP, and run my application on eclipse. here the code : public class ftpClient { Socket socket; PrintWriter pw; BufferedReader input; String info = ""; public ftpClient(){ try{ socket = new Socket("localhost", 21); System.out.println("Masuk port 21"); logUsername(); sendPassword(); closeEverything(); } catch(IOException ioe){ System.out.println("Kesalahan dalam Socket"); } } public void logUsername()throws IOException{ input = new BufferedReader(new InputStreamReader(socket.getInputStream())); pw = new PrintWriter(socket.getOutputStream()); pw.write("USER anonymous\n"); pw.flush(); System.out.println(input.readLine()); } public void sendPassword()throws IOException{ pw.write("PASS faris@gmail.com\n"); pw.flush(); System.out.println(input.readLine()); System.out.println(input.readLine()); } public void closeEverything() throws IOException{ input.close(); pw.close(); socket.close(); } public static void main(String[]args){ new ftpClient(); System.out.println("done"); } } I was told that on FTP while log as anonymous you need enter an email address as a password, and here the output. Masuk port 21 220 ProFTPD 1.3.3 Server (ProFTPD Default Installation) [127.0.0.1] 331 Password required for anonymous 530 Login incorrect. done Would you mind telling the wrong part? I'm sorry for my bad coding style. Thanks A: Promoted OP's comment to Answer: Yes you are right. I haven't configure it yet. Thank you :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7515537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MYSQL - Problems using a string as primary key Possible Duplicate: Alphanumeric Order By in Mysql My tables are sorting my records incorrectly. The primary key is a string that as one char and its combined with a number starting from 1 ex: F1. It becomes problematic when it got to two digit numbers ex: F10. The database only check the first two characters and discard the rest. Ex: It should look like this F1,F2,F3,...F9,F10,F11,etc. It looks like this F1, F10, F11, F12,....,F2,F3,F4,etc. So if you have any ideas please share it. Note: using MySql 5 server and MySql Workbench 5.2 Here is the script code for one table in the database: SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL'; DROP SCHEMA IF EXISTS `RimpexDB` ; CREATE SCHEMA IF NOT EXISTS `RimpexDB` DEFAULT CHARACTER SET latin1 COLLATE latin1_general_ci ; USE `RimpexDB` ; -- ----------------------------------------------------- -- Table `RimpexDB`.`RpxFornecedor` -- ----------------------------------------------------- DROP TABLE IF EXISTS `RimpexDB`.`RpxFornecedor` ; CREATE TABLE IF NOT EXISTS `RimpexDB`.`RpxFornecedor` ( `FID` VARCHAR(80) NOT NULL , `FNome` VARCHAR(80) NOT NULL , `FDescricao` VARCHAR(1000) NULL , `FNTel` VARCHAR(45) NULL , `FNCel` VARCHAR(45) NULL , `FEndereco` VARCHAR(200) NOT NULL , `FEmail` VARCHAR(100) NULL , `FFax` VARCHAR(45) NULL , `FActivo` CHAR NOT NULL , `FDataAct` VARCHAR(200) NOT NULL , `FDataNAct` VARCHAR(200) NULL , PRIMARY KEY (`FID`) , INDEX `FID` (`FID` ASC, `FNome` ASC, `FDescricao` ASC, `FNTel` ASC, `FNCel` ASC, `FEndereco` ASC, `FEmail` ASC, `FFax` ASC, `FActivo` ASC, `FDataAct` ASC, `FDataNAct` ASC) ) ENGINE = InnoDB COMMENT = 'Fornecedor Table' ; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; A: MySQL is not just looking at the first two characters and discarding the rest but rather sorting in lexical ordering (ie alphabetic) ordering. The type of ordering you need is sometimes referred to as natural ordering. If you have the option of changing the PK from the string to just a number column dropping off the 'F' character for each record, you'll be much better off. A: Assuming the first character is always a letter (and only the first character is), this is what you need to do with your current data structure: select FID from RpxFornecedor order by cast(substring(FID, 2) as integer) But you should really consider changing your PK to a numeric one. A: One workaround could be to use F00001, F00002, ... F12345 strings as your primary key.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I assume that the order I send values over POST will be model bound to an array in the same order in Asp.net MVC? I'm am working on having a screen that allows the user to change the order of items, and when the user clicks on the "Save" button my javascript will look at the order of <li> items, and in the order it finds them it will form an array with an id value and send it back to my application. I expect the POST data to look like: stepIds=5&stepIds=2&stepIds=1 This means that the steps are in the order of #5, then #2, and lastly #1. In my Asp.Net MVC application I plan to catch it with: public virtual ActionResult Reorder(short[] stepIds) { } My question is, will Asp.net MVC ALWAYS form the stepIds array in the same order that values are specified in the POST string, or do I need to do a more complicated POST in order to ensure the order the user picks is the order the server sees? A: No, you cannot rely on the order. The way this is implemented in ASP.NET 4.0 it will indeed preserve the order but this might change in future versions. You may look at the HttpValueCollection.FillFromString private method with Reflector to see how it is implemented. The only reliable way to guarantee order is this: stepIds[0]=5&stepIds[1]=2&stepIds[2]=1
{ "language": "en", "url": "https://stackoverflow.com/questions/7515540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: how to remove keyup event listeners by javascript I'm using the Google autocomplete api on a text field to suggest locations as you type. The main problem I have with this is that Google does not let you limit results to a specific country, it just lets you bias results to area bounds which is kind of useless. So seaching for term "ru" will give you Russia in suggestions even your region is set to somewhere in Europe. I realized though that if you put for example "france ru" it gives you france locations only matching ru which is perfect. So my problem is that the autocomple is completely built by google javascript. autocomplete = new google.maps.places.Autocomplete(input, options); So I cannot easily fiddle with search string to add in to it constantly "france" I can see what is bound to the onkeyup event on that field and can take it and call it myself however I cannot unbind it from keyup. I tried several solutions how to do it but can't find a way. jQuery unbind won't work as this is not bound through it obviously. Native functions want a reference to a function bind to listener but this is annonymous function in it. Found some examples using loops over element.data['events'] but I get data undefined error. Has anyone solution to unbind all what is register in onkeyup ? A: You mentioned jQuery, so I'll use that: $(input).data('events').keyup is the array that will contain all the keyup handlers. If there is only one keyup event used by Autocomplete, you can hijack the handler to first run whatever function you need, then run the original: var originalKeyup = $(input).data('events').keyup[0].handler; $(input).data('events').keyup[0].handler = function(){ // your code here, where you can add 'france' to input.value // fire the old function originalKeyup.apply(this,arguments); }; You could also just remove the original event handler from the keyup array, and bind new ones that will do what you want. UPDATE: You could hijack Element.prototype.addEventListener (BEFORE ALL OTHER CODE) to add an events property to the Element which will contain any handlers added by any code: var oldAddEventListener = Element.prototype.addEventListener || Element.prototype.attachEvent; Element.prototype.addEventListener = Element.prototype.attachEvent = function(type, handler){ this.events = this.events || {}; this.events[type] = this.events[type] || []; this.events[type].push({handler: handler}) oldAddEventListener.apply(this,arguments); }; Now, every time addEventListener is called, by jQuery or otherwise, the Element's events property should be updated with the current events. You may also want to hijack removeEventListener to remove the corresponding event from the events object when removeEventListener is called: var oldREL = Element.prototype.removeEventListener || Element.prototype.detachEvent; Element.prototype.removeEventListener = Element.prototype.detachEvent = function(type, handler){ this.oldREL.apply(this,arguments); if(this.events && this.events[type]){ for(var i=this.events[type].length-1; i>=0; i--){ if(this.events[type][i].handler == handler){ this.events[type].splice(i,1); break; // remove only the first occurrence from the end } } if(this.events[type].length==0){ delete this.events[type]; } } }; Now you should be able to inspect all events registered on any element. You can remove all 'keyup' events by iterating over the input.events.keyup object and using input.removeEventListener. The attachEvent and detachEvent are used by IE<9. I don't have IE, so it hasn't been tested there. It works well in Safari 5. Let me know if you have issues in other browsers. NOTE: These mods need to be in place BEFORE any other code is executed on the page. Update: Apparently, this will not work in FF or Opera. Changing Element to HTMLInputElement in the code will fix the problem. A: Have you tried binding the autocomplete to the current map bounds, as shown in the documentation: autocomplete.bindTo('bounds', map) ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7515557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a user without an associated login is not supported in SQL Server 2008 R2 When scripting a SQL Server 2000 database, on an SQL Server 2000 version of SQL Server, with SQL Server Management Studio 2008 R2 (10.50.1617.0) i get the error: Creating a user without an associated login is not supported in SQL Server 2008 R2. With the full stack trace: Microsoft.SqlServer.Management.Smo.SmoException: Creating a user without an associated login is not supported in SQL Server 2008 R2.; at Microsoft.SqlServer.Management.SqlScriptPublish.GeneratePublishPage.worker_DoWork(Object sender, DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument) What is a good way to resolve this issue. i've considered: * *creating a login (and incur the wrath high atop the thing) *deleting the user (and incur the wrath from high atop the place) *select some rather than all objects to script, and don't script the user that offends SQL Server 2008 R2 But i'll let people on SO post answers, get answers upvoted, and accept an answer that best solves the problem. A: As instructed. Just don't script the database users that have no associated login. You can do this in the Tasks > Generate Scripts wizard (pointing 2008 or later SSMS at your 2000 instance) by choosing to select specific database objects and unchecking any troublesome users: A: I suspect that your SQL Server 2000 database has user aliases: these were required in SQL Server 6.5 in some circumstances because it was, er, crap, Note what MSDN says: sp_addalias is provided for backward compatibility. Microsoft® SQL Server™ version 7.0 provides roles and the ability to grant permissions to roles as an alternative to using aliases. Run sp_helpuser on the SQL Server 2000 box and review the output and remove them
{ "language": "en", "url": "https://stackoverflow.com/questions/7515558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bit shift in Java May be I am too tired. Why dont't the following display the same value? int x = 42405; System.out.println(x << 8); System.out.println((x &0x00ff) << 8); The lower bits should be clear in both cases A: EDIT: Okay, I'm leaving the bottom part for posterity... If x is int, then it's pretty simple: x << 8 will have the same value as x & 0xff if and only if none of the "middle" 16 bits are set: * *The top 8 bits of x will be rendered irrelevant by the left shift *The bottom 8 bits of x are preserved by the masking If there are any of the "middle" 16 bits set, then x & 0xff will differ from x in a bit which is still preserved by the shift, therefore the results will be different. I don't understand why you'd expect them to always give the same results... I'm going to assume that the type of x is byte, and that it's actually negative. There's no shift operation defined for byte, so first there's a transformation to int... and that's what can change depending on whether or not you've got the mask. So let's take the case where x is -1. Then (int) x is also -1 - i.e. the bit pattern is all 1s. Shift that left by 8 bits and you end up with a bit pattern of 24 1s followed by 8 0s: 11111111111111111111111100000000 = -256 Now consider the second line of code - that's taking x & 0xff, which will only take the bottom 8 bits of the promoted value of x - i.e. 255. You shift that left by 8 bits and you end up with 16 0s, 8 1s, then 8 0s: 00000000000000001111111100000000 = 65280 A: Below, x is > 0xff , and in one case you mask away the upper 3 bytes, meaning you you do (0x123 & 0x00ff) << 8 , which will be 0x23 << 8 And that is quite different from 0x123 << 8 int x = 0x123; System.out.println(x << 8); //prints 74496 System.out.println((x &0x00ff) << 8); //prints 8960 And if x is a byte, it will get "promoted" to int before the shift, and if it's negative, it'll sign extend, and you get a whole lot of 1 bits set in the integer, which is masked away with &0xff in one case, and not masked away in the other i.e. byte x = (byte)0xAA; //x is negative System.out.println(x << 8); //prints -22016 System.out.println((x &0x00ff) << 8); //prints 43520
{ "language": "en", "url": "https://stackoverflow.com/questions/7515566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: JQuery draggable - allow containment to multiple containers? I'd like to allow users to drag an element from one container to another while still being constrained from being able to drag the element outside of either of those two containers. I have everything working perfectly except the part where they can drag to another container. View code and result on JSFiddle.net I thought this post seemed like the answer but it doesn't appear to work for me. A: I added a jQuery UI droppable to your fiddle. With a little bit of tweaking I'm sure you'd be able to get this exactly how you want it. http://jsfiddle.net/U2nKh/20/ A: just add these lines inside your draggable function like this: $("#drop").draggable({revert: 'invalid', start: function(){ currentParent = $(this).parent().attr('id'); }});
{ "language": "en", "url": "https://stackoverflow.com/questions/7515569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: parser creation in perl that extract xml tags from source code? i have to extract xml comments from c code .I tried using perl regexp but i am unable to extract the comments. can any one help me. my code as shown below. Dima_chkTimeValidation(&dacl_ts_pumpPWMLowNoDos_str, &dacl_ti_pumpPWMLowNoDos_U16, ti_valid_U16, ti_inval_U16, (tB)(dacl_r_pumpPwmResidualFilt_S16 < r_testlimit_S16), (tB)((testCond_B == TRUE) && (dosingActive_B == FALSE)), TRUE); /*****************************************/ /*xml comments*/ /****************************************/ <DTC> <TroubleCode>1101</TroubleCode> <Classification>FAULT</Classification> <SelfHealing>No selfhealing</SelfHealing> <WarningLamp>No Warning Lamp</WarningLamp> <DirectDegradation>No Action</DirectDegradation> <Order>PRIMARY</Order> </DTC> /*******************************/ /* Dosing clogg test */ /*******************************/ /* special test when run i sequence test mode SMHD_DOSVALVE_E */ if ((s_seqTestCtrlStatus_E == SMHD_RUNNING_E) && (s_seqTestMainState_SMHD_DOSVALVE_E)) { /* Use result from DDOS test */ Dima_chkValidation(&dacl_ts_pumpPWMLowDos_str, (tB)(s_dosValveTest_E == SMHD_TESTFAILED_E), (tB)(s_dosValveTest_E != SMHD_TESTNOTFINISHED_E)); } as show above i have lot of c code lines before and after xml comments but i posted just little c code, i added some comments in the c code, i need to extract the comments as it is. so any body can help me how to extract using perl. A: Your data is bizarre, to say the least. I'm making two assumptions here: the ' is the starting delimiter of the example string, and you want to extract the stuff between the angle brackets (which are neither XML nor XML comments according to, you know, the standard). No guarantee against misparsing embedded C code. use 5.010; use Data::Dumper qw(Dumper); say Dumper \%+ while '<dtcnumber>1223<dtcnumber> <discription>battery short circuited<discription> <cause>due to unproper connections<cause> main(); { .......... ... c code. ... };' =~ /<(?<key>[^>]+)>(?<value>[^<]+)<\g{key}>/g; Output $VAR1 = { 'value' => '1223', 'key' => 'dtcnumber' }; $VAR1 = { 'value' => 'battery short circuited', 'key' => 'discription' }; $VAR1 = { 'value' => 'due to unproper connections', 'key' => 'cause' }; A: Its not a good idea to write the whole code for your work, but I am still doing it so that you can get an idea of how to approach a particular problem. Here, I am providing you the simplest approach (might not be efficient) 1. Keep you input data simple and make your life more simpler. Identify a particular pattern using which your code can identify the beginning and end of XML. Dima_chkTimeValidation(&dacl_ts_pumpPWMLowNoDos_str, &dacl_ti_pumpPWMLowNoDos_U16, ti_valid_U16, ti_inval_U16, (tB)(dacl_r_pumpPwmResidualFilt_S16 &lt r_testlimit_S16), (tB)((testCond_B == TRUE) && (dosingActive_B == FALSE)), TRUE); /*****************************************/ /*[[[ Start XML &lt DTC &gt &lt TroubleCode &gt 1101 &lt /TroubleCode &gt &lt Classification &gt FAULT &lt /Classification &gt &lt SelfHealing &gt No selfhealing &lt /SelfHealing &gt &lt WarningLamp &gt No Warning Lamp lt /WarningLamp &gt &lt DirectDegradation &gt No Action &lt /DirectDegradation &gt &lt Order &gt PRIMARY &lt /Order &gt &lt /DTC &gt End XML]]]*/ /*******************************/ /* special test when run i sequence test mode SMHD_DOSVALVE_E */ if ((s_seqTestCtrlStatus_E == SMHD_RUNNING_E) && (s_seqTestMainState_SMHD_DOSVALVE_E)) { /* Use result from DDOS test */ Dima_chkValidation(&dacl_ts_pumpPWMLowDos_str, (tB)(s_dosValveTest_E == SMHD_TESTFAILED_E), (tB)(s_dosValveTest_E != SMHD_TESTNOTFINISHED_E)); } Here, you can identify the pattern I have kept to detect starting of xml and end of xml 2. Next, is the code. Now i have tried to write it as much in the "C" way except for the regex. #!/usr/bin/perl # # open(FD,"&lt Code.cpp") or die "unable to open file: $!\n"; my $start_xml = 0 ; ## 0 indicates false condition ..i.e either XML not started or XML ended ## 1 means xml has started. while(&lt FD &gt){ chomp($_); ## Handling only single Line comments my $temp = $_; if($temp =~ m/\[\[\[\s*start\s*xml/ig && $start_xml == 0){ ## Check if start xml pattern found $start_xml = 1; next; ## equivalent to continue of C } if(($temp =~ m/&lt [a-z0-9 -&!@]+ &gt.*/ig) && ($start_xml == 1)){ ## You can add additional letters that may come ## In such cases pattern matching wont be necessary as you know # you have got XML data between start and end xml pattern. But still... # some case you might need it print "$temp\n"; ## I am printing it out , but you may write it to file }elsif($temp =~ m/end\s*xml\s*\]\]\]/ig){ $start_xml = 0; last; ## equivalent to break in C } } close FD; NOTE :: There is no &lt space &gt after "&lt" and after the "&gt" tag in the text and in the code. So, remove that space when you are running the code. The kind of pattern chosen to detect xml taken from "Python cog" :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7515573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Call subclass's method from its superclass I have two classes, named Parent and Child, as below. Parent is the superclass of Child I can call a method of the superclass from its subclass by using the keyword super. Is it possible to call a method of subclass from its superclass? Child.h #import <Foundation/Foundation.h> #import "Parent.h" @interface Child : Parent { } - (void) methodOfChild; @end Child.m #import "Child.h" @implementation Child - (void) methodOfChild { NSLog(@"I'm child"); } @end Parent.h: #import <Foundation/Foundation.h> @interface Parent : NSObject { } - (void) methodOfParent; @end Parent.m: #import "Parent.h" @implementation Parent - (void) methodOfParent { //How to call Child's methodOfChild here? } @end Import "Parent.h" in app delegate's .m file header. App delegate's application:didFinishLaunchingWithOptions: method.. Parent *parent = [ [Parent alloc] init]; [parent methodOfParent]; [parent release]; A: You can, as Objective C method dispatch is all dynamic. Just call it with [self methodOfChild], which will probably generate a compiler warning (which you can silence by casting self to id). But, for the love of goodness, don't do it. Parents are supposed to provide for their children, not the children for their parents. A parent knowing about a sub-classes new methods is a huge design issue, creating a strong coupling the wrong way up the inheritance chain. If the parent needs it, why isn't it a method on the parent? A: Technically you can do it. But I suggest you to alter your design. You can declare a protocol and make your child class adopt that protocol. Then you can have to check whether the child adopts that protocol from the super class and call the method from the super class. A: You could use this: Parent.m #import "Parent.h" @implementation Parent - (void) methodOfChild { // this should be override by child classes NSAssert(NO, @"This is an abstract method and should be overridden"); } @end The parent knows about the child and child has a choice on how to implement the function. A: super means "invoke a method dispatching on the parent class", so can use super in the subclass because a subclass only has one parent class. A class can have many _sub_classes though, so how would you know which method implementation to call, in the general case? (Hence there is no such thing as a sub keyword.) However, in your example you have two separate methods. There's nothing stopping you (assuming you have very good reasons for doing something like this!) from saying, in the parent, - (void) methodOfParent { [self methodOfChild]; } A: if your super has multiple subs then go for this one for the specific sub's method if ([super isKindOfClass:[specificsub class]]) { [specificsub methodName]; } if your super is dealing with that object (that sub) so sub's method loggedin will be called an other way is in you super class super *some = [[sub alloc] init]; [some methodName]; A: This can be done by over riding the method in subclass. That is create a method in parent class and over ride the same in subclass.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Reading and Plotting from text files I have some problems in reading data from text file and plotting it.The text file contains Date; Time; Temp °C 05.08.2011; 11:00:47;23.75 05.08.2011; 11:01:21;23.69 05.08.2011; 11:01:56;25.69 05.08.2011; 11:02:16;23.63 05.08.2011; 11:02:50;23.63 05.08.2011; 11:03:24;23.63 I want to plot the Temperature values with elapsed minutes. firstly i used [a,b]=textread('file1.txt','%s %s','headerlines',1) to read the data in a string and I get '17:09:16;21.75' After that I used a= strread('17:08:00;21.81','%s','delimiter', ';') to get '17:08:00' '21.81' But after this I am not been able to figure out how to move forward to deal with both these strings, especially time. I want to plot temperature with time on xaxis..but not this time the elapsed time..in this case 2 mins 37 secs. Help needed Thanks Aabaz.thats really a big favor..I dun why I could figure it out ..I spent so much time on it I have some 50 files comprising this data..If i want to loop it under this code , how can accomplish it, cz i have names of the file under ROM IDs..alike 1AHJDDHUD1224.txt. How wud pass the file names in the loop.Do I have to change the names of the files then pass them under loop.I dun knw I have one more question that if I wanted the values to be plotted after every 60 seconds..alike as soon the data is available in text files graph is plotted , and then graph is updated after every 60 sec until some more values are available in text file A: Consider the following code. It will cycle through all .DAT files in a specific directory, read the data files, then plots with a the x-axis formatted as date/time: %# get a list of files BASE_DIR = 'C:\Users\Amro\Desktop'; files = dir( fullfile(BASE_DIR,'*.dat') ); files = {files.name}; %# read all files first dt = cell(numel(files),1); temps = cell(numel(files),1); for i=1:numel(files) %# read data file fname = fullfile(BASE_DIR,files{i}); fid = fopen(fname); C = textscan(fid, '%s %s %f', 'delimiter',';', 'HeaderLines',1); fclose(fid); %# datetime and temperature dt{i} = datenum( strcat(C{1},{' '},C{2}) ); temps{i} = C{3}; end Now we can plot the data (say we had 16 files, thus layout subplots as 4-by-4) figure for i=1:16 subplot(4,4,i), plot(dt{i}, temps{i}, '.-') xlabel('DateTime'), ylabel('Temp °C') datetick('x','HH:MM:SS') end A: You can merge the time strings with sprintf and translate them to seconds with datenum. Then the rest will be easy. Here is how it could work: fid=fopen('data','r'); header=fgetl(fid); data=textscan(fid,'%s','delimiter',';'); fclose(fid); data=data{:}; day=data(1:3:end); hour=data(2:3:end); temp=str2double(data(3:3:end)); time=cellfun(@(x) sprintf('%s %s',day{strcmpi(hour,x)},x),hour,'uniformoutput',0); % timev=datevec(time,'mm.dd.yyyy HH:MM:SS'); timen=datenum(time,'mm.dd.yyyy HH:MM:SS'); seconds=timen*86400; plot(seconds-seconds(1),temp); You may want to check the date format as I did not know which format you were using, so I guessed it was mm.dd.yyyy HH:MM:SS (see Matlab date specifiers)
{ "language": "en", "url": "https://stackoverflow.com/questions/7515584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How should I implement Transaction database EJB 3.0 In the CustomerTransactions entity, I have the following field to record what the customer bought: @ManyToMany private List<Item> listOfItemsBought; When I think more about this field, there's a chance it may not work because merchants are allowed to change item's information (e.g. price, discount, etc...). Hence, this field will not be able to record what the customer actually bought when the transaction occurred. At the moment, I can only think of 2 ways to make it work. * *I will record the transaction details into a String field. I feel that this way would be messy if I need to extract some information about the transaction later on. *Whenever the merchant changes an item's information, I will not update directly to that item's fields. Instead, I will create another new item with all the new information and keep the old item untouched. I feel that this way is better because I can easily extract information about the transaction later on. However, the bad side is that my Item table may contain a lot of rows. I'd be very grateful if someone could give me an advice on how I should tackle this problem. A: I would try a third option something like this. public class Item { private String sku; private double currentPrice; } public class Customer { private String name; private List<Transaction> transactions; } public class Transaction { private Item item; private Customer customer; private double pricePerItem; private double quantity; private String discountCode; } I will leave you to work out the JPA mappings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Duplicate subdomain mapping on Google App Engine with www prefix Some of my clients are having problems accessing my Google App Engine website from typing in the URL. Despite it being written down - it's on a printed invite - as http://subdomain.domain.com (which works), people insist on putting in http://www.subdomain.domain.com Is there some way of adding another mapping to make www.subdomain.domain.com point at subdomain.domain.com?? Help greatly appreciated. A: You should be able to simply add that subdomain in Google Apps (following the instructions here). Failing that, you could use a third-party redirection service to send a 302 to your 'real' subdomain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I reference the outer "$(this)" in jquery? Let's say I have code like this: $('.myClass').each(function(){ $('#' + $(this).attr('id') + "_Suffix").livequery('click', function(){ doSomething($(this)); }); }); The $(this) that I pass to the doSomething function is what's in the second jquery parenthesis - $('#' + $(this).attr('id') + "_Suffix"). How do I reference what's in the first parenthesis - what the original this referred to? ( $('.myClass').each ) I assume I could save it into a variable, and then use that variable: $('.myClass').each(function(){ outerThis = $(this); $('#' + $(this).attr('id') + "_Suffix").livequery('click', function(){ doSomething($(outerThis)); }); }); But is there any way to reference it without doing this? A: You need to put it in a separate variable: $('.myClass').each(function(){ var outer = $(this); $('#' + $(this).attr('id') + "_Suffix").livequery('click', function(){ doSomething(outer); }); }); Also, livequery is deprecated; you should use live instead. A: Just save the scope in local variable: $('.myClass').each(function(){ var self = $(this); $('#' + $(this).attr('id') + "_Suffix").livequery('click', function(){ doSomething($(this)); }); }); A: Try to use local variable $('.myClass').each(function(){ var myclassObj = $(this); $('#' + myclassObj.attr('id') + "_Suffix").livequery('click', function(){ doSomething($(this)); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7515597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can we declare global variable in QML file? I want to do something similer to following code: //test.qml import QtQuick 1.0 Item { var globalforJs =10; function increment() // JavaScript function { globalforJs++; } .... QML Code Can we have global variable in QML file and access it from the JavaScript function? A: Using int or variant properties do not create a javascript variable, but rather a semantically different generic QML property (see here) Before Qt 5, global javascript variables were recommended to be defined in a separately imported javascript file, however Qt 5 adds a var type property support. A: Try property int globalForJs: 10; If you want a variable that can take any type: property var globalForJs: 10 Prior to QML 2, use the variant keyword instead of var. A: the thing which you want to make global should be done like in this example property variant name:"john"//i want this to be global onCreationCompleted(){ Qt.name = name } whereever you want to use the name property use like Qt.name instead of just name.this also applicable for any ids of controls
{ "language": "en", "url": "https://stackoverflow.com/questions/7515598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Best way to change a form action upon submit Basically I have a form with a few drop-downs, but the page I'd like to be set as the action of the form submit would be based on the option chosen in one of the drop downs. I'd like to stick with one submit button, so it seems a little tricky. Can anyone point me in the right direction? A: You could use some jQuery. $("#yourDropDown").change(function() { var text = $(this).children(':selected').text(); $("#yourForm").attr('action', text); }); Where "yourDropDown" is the ID of your dropdown, and "yourForm" is the ID of your form, and where the text in the dropdown-options are fully qualified URLs to post to. Edit: Also I agree with Quentin's comment on your post. A: Another way is to add an onsubmit event handler on the form. If your form looks something like: <form id="myForm" action="action1.php"> <select id="myDropdown"> <option value="1">Option 1</option> <option value="2">Option 1</option> </select> <input type="submit" value="Submit" /> </form> add the following javascript (using jQuery here): $(document).ready(function() { $('#myForm').submit(function() { var dropdownVal = $("#myDropdown").val(); switch( dropdownVal ) { case 1: $(this).attr('action', 'action1.php'); // do other stuff if you want break; case 2: $(this).attr('action', 'action2.php'); // do other stuff if you want break; } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7515600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to Structure a Table where *some* Columns can have Multiple Values? Possible Duplicate: How to Store Multiple Options selected by User in a Table I am very confused by this. I want my users to be able to restrict who may contact them. So I need to create a new table of RESTRICTIONS for each user and their selected criteria, which will have a column for each user's restriction criteria. Those columns will include age, income, looking for, drugs, etc. Some of those columns (looking for, drugs, etc.) might contain multiple choices, and therein lies my problem. How do I structure the table in this way, considering some criteria (columns) can have multiple values while others do not? I've been told about join tables and enum values (both of which I've never worked with before), but I am really confused as to how I would structure a table in which some columns (not all), can contain multiple choices. How do I store those multiple choices in those specific columns of the table and how do I structure the overall table of RESTRICTIONS? A: A DB column (at least theorethically) should NOT hold multiple values. Unfortunately, there are some programmers that store multiple values in a single column (values separated by comma for examples) - those programmers (in most cases) destroy the concept of DB and SQL. I suggest you to read about Database Normalization to get a start in organizing your tables. And, do your best to achieve the Codd's Third Normal Form A: You probably need more than one table. You have a "users" table already, right? If one of your "restrictions" criteria can have just one value per user, then that column belongs in the "users" table. So you might have columns "min_age" and "max_age" in the users table, because presumably each user has only one, contiguous range of ages they are looking for. On the other hand, for each restriction criterion that can have multiple values, you need a new table. So you might have a table "users_restrictions_drugs" in which the primary key is (user, drug). But you might also have a table "users_restrictions_lookingfor" in which the primary key is (user, lookingfor). Whatever "looking for" is. For some of these tables it may make sense either * *to define the second column (the one that isn't "user") as an enum *or (better) to have an additional table that sets out the possible values of that second column and is referenced by a foreign key. A: This is the simplest way. Multiple attributes become rows in a second table. CREATE TABLE restrictions ( user_id INTEGER PRIMARY KEY, -- references users (user_id), not shown age_restriction VARCHAR(10) NULL, income_restriction VARCHAR(20) NULL ); CREATE TABLE looking_for ( user_id INTEGER NOT NULL REFERENCES restrictions (user_id), looking_for VARCHAR(35) NOT NULL, -- could also be a foreign key. PRIMARY KEY (user_id, looking_for) ); INSERT INTO restrictions (user_id) VALUES (1); INSERT INTO restrictions (user_id, age_restriction) VALUES (2, '> 25'); INSERT INTO looking_for VALUES (1, 'boat'); INSERT INTO looking_for VALUES (1, 'dunky fazoo'); If you wanted to accept multiple restrictions on age, such as '> 25' and '< 55', you could build another table for that, too. To retrieve all the restrictions, use an OUTER JOIN. SELECT r.user_id, r.age_restriction, r.income_restriction, lf.looking_for FROM restrictions r LEFT JOIN looking_for lf ON lf.user_id = r.user_id A: table restrictions user_id smoker_ok min_height max_height min_age max_age ------------------------------------------------------- 1 Y 150 200 24 34 2 N 100 180 32 57 table drug_restrictions user_id drug_id drug_allowed ---------------------------------- 1 H N 1 M Y 2 E Y Would be an example. In the restrictions table, you can store explicit, singular values - smokers yes or no, or min and max requirements. For each table where there are multiple choices, you can create a join table - I've given an example for drugs. In the drug_restrictions table, user 1 says she doesn't want people using H, but does want people using M. This solution allows you to use the "drug_id" as a foreign key to whatever table in your database populates the "drugs" field on the user interface. It allows you to use regular, standard SQL conventions for those foreign keys, and to enforce them at the database level by declaring them as foreign keys. The drawback is, of course, that you have to query lots of tables to find matching records, and that's not much fun. So, you could also follow Catcall's recommendation - this dramatically reduces the number of tables, but makes it impossible to use "standard" foreign key integrity constraints. This might be okay - it's certainly going to be faster. I'd be reluctant to use enums - they tend to lead to complex queries, and are not "standard" SQL. A: There's no problem to have tables where some columns have duplicate values. Consider a tbale with users; there's no problem if two users have the same birthday? The only problem is a table where a primary key occurs more than once. For instance, a user table may very well have username as its primary key, and you wouldn't want two users with the same username. So, make one table that lists users, one that lists restrictions, and one that joins the two. The latter will have one entry for every combination of user/permission.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Client Webservice in java - proxy authentication I have made a web service client importing a third party wsdl in eclipse. But I got this exception: javax.xml.ws.WebServiceException: Connection IO Exception. Check nested exception for details. (Unable to connect to 1X.XXX.X.XX:X0 - Connection timed out). I hope this exception occurred for the proxy only. There is a proxy server between me and that third party. I don't know how to do the proxy authentication and where in coding I need to this proxy authentication. A: Is your end point on HTTPS? There different ways proxies support HTTPS - one ways is SSL bridging and the other is SSL Tunneling.. May be your client side libraries you used to connect may not support the one being used by the proxy... A: You must explicitly set the proxy server in Java, the JRE does not retrieve it from the OS configuration. You can find the detailed explanation here. As per the link, a standard configuration may look like this: System.setProperty("http.proxyHost", "myproxy.com"); System.setPropery("http.proxyPort", "8080"); Obviously, you can also define the system properties as VM arguments during startup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to disable a submit button until other button has been pressed? I have a simple JSF form: <h:form> <h:inputText value="#{textBean.firstName}"/> <h:inputText value="#{textBean.lastName}"/> <h:commandButton value="confirm" action="textBean.confirm"/> <h:commandButton value="submit" action="textBean.submit"/> </h:form> It is necessary that before you click "submit" user must press the button "confirm". Otherwise, next to the button "submit" display an error message. A user can not click the submit button, if not pre-pressed to confirm. It is very desirable to do it on a layer of the UI. Some might suggest something about this? A: You might want to change the logic so that on click of the submit button a confirmation dialog box is presented to the user. Something simple like this: <h:form> <h:inputText value="#{textBean.firstName}"/> <h:inputText value="#{textBean.lastName}"/> <h:commandButton value="submit" action="#{textBean.submit}" onclick="return confirm('Confirm form submit?');"/> </h:form> Otherwise if you want to get the behaviour mentioned above you could disable / hide the submit button until the user has clicked the confirm button, something like: <h:form> <h:inputText value="#{textBean.firstName}"/> <h:inputText value="#{textBean.lastName}"/> <h:commandButton value="confirm" action="#{textBean.confirm}"/> <h:commandButton value="submit" action="#{textBean.submit}" disabled="#{textBean.btnDisabled}"/> </h:form> The disabled attribute can be replaced with the rendered attribute if you want to hide the button. It takes a boolean. This boolean variable can be set in your confirm method to true so that when the request comes back the button will be enabled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting XAuth to work with Node.JS & OAuth I'm building my first node.js app, and trying to integrate it with the Instapaper API. Instapaper only uses XAuth, and I'm a little confused how it works. Should I use the node-oauth module and try to customize it for xauth? Or should I roll my own xauth? Or something else, maybe? A: I'd checkout something like EveryAuth, see how they are handling the various options out there, forking it, and then contributing back with a new implementation. Good luck man. A: Here is how to get it working with the oauth module. https://stackoverflow.com/a/9645033/186101 You'd still need to handle storing the tokens for your users, but that answer should get you u and running for testing the API in node.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Quartz.Net as windows service with jobstore in DB The java version of Quartz has a validation-query property which is used to check whether the database service is available. I cannot find this in the .NET version of Quartz. How does the .NET version check if the database is available after a service has been restarted or when the system is booted? A: Java has different way of checking whether a connection in the pool is still usable. The .NET connection pool does not have the concept of validation query, it's done internally within the connection pool. So you don't need to worry about providing the validation query yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: copy-and-swap idiom, with inheritance I read interesting things about the copy-and-swap idiom. My question is concerning the implementation of the swap method when inheriting from another class. class Foo : public Bar { int _m1; string _m2; .../... public: void swap(Foo &a, Foo &b) { using std::swap; swap(a._m1, b._m1); swap(a._m2, b._m2); // what about the Bar private members ??? } .../... }; A: Just cast it up to the base and let the compiler work it out: swap(static_cast<Bar&>(a), static_cast<Bar&)(b)); A: You would swap the subobjects: swap(static_cast<Bar&>(a), static_cast<Bar&>(b)); You may need to implement the swap function for Bar, if std::swap doesn't do the job. Also note that swap should be a non-member (and a friend if necessary). A: You would typically be doing it like this: class Foo : public Bar { int _m1; string _m2; .../... public: void swap(Foo &b) { using std::swap; swap(_m1, b._m1); swap(_m2, b._m2); Bar::swap(b); } .../... };
{ "language": "en", "url": "https://stackoverflow.com/questions/7515617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: blackberry browser - video format It looks like the browser on a Blackberry doesn't support either HTML 5 or Flash... What's the best format to display video in it? Thanks A: BrowserSession is useful to paly video and audio formats in Blackberry.Visit following links useful for you. BlackBerry - Play mp4 video from remote server. If you need information about Browser session the following link might help you. http://docs.blackberry.com/en/developers/deliverables/11844/Browser_session_management_438294_11.jsp A: You would use the object tag e.g. <object data=FILENAME type=MIMETYPE> You can see the supported video formats on different phones here (PDF). Source A: Latest version of blackberry (from 6.0). but however it is not that intelligent to play videos efficiently. Is your application using native code ? If yes, then go for manual player or invoke default browser which has capability to play videos. I have done the same way for you tube videos.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTML p tag takes the height of its parent, not its content guys! I'm using the tinyscrollbar plugin (jQuery), and I have to scroll paragraphs in a div with it. The problem is that the div (parent of the paragraphs) is 296px high and every paragraph takes 296px for its height and in the div I can view only one paragraph. I think, that it has to be done with css hack or something, but I don't know how to do it. Thanks in advance! A: The paragraphs have a height set to "inherit" Here's an example
{ "language": "en", "url": "https://stackoverflow.com/questions/7515620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how do I output the rowName based on a linking table? I need to output A_Name, B_Name, and C_Name. from tableA, tableB, tableC. I have a linking table containing all the ID's of the above, e.g: CREATE TABLE `tableLink` ( `tableLinkID` int(5) NOT NULL auto_increment, `A_ID` int(11) NOT NULL, `B_ID` int(5) NOT NULL, `C_ID` int(5) NOT NULL, PRIMARY KEY (`tableLinkID`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 AUTO_INCREMENT=17 ; My question: I need to know how to SELECT based on having C_ID, how to select and output A_ID's [A_Name], B_ID's [B_Name], and C_ID's [C_Name]. I hope this is clear enough. (I have the C_ID in a variable) A: Try using JOINs: SELECT tableA.A_Name, tableB.B_Name, tableC.C_Name FROM tableLink JOIN tableA ON tableLink.A_ID = A.ID JOIN tableB ON tableLink.B_ID = B.ID JOIN tableC ON tableLink.C_ID = C.ID WHERE tableLink.C_ID = 42
{ "language": "en", "url": "https://stackoverflow.com/questions/7515624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I select all elements of a class with a visible parent? EDIT: This selector is correct. There bug must be elsewhere in the code. So this question is no longer relevant. EDIT2: The real problem was that my parent class had the inline style "display:inline" attached to it, apparently the visible selector doesn't like display:inline. After I took that out it started working. EDIT3: An inline element with an unset height. JQuery says, anything with a height of zero, is considered invisible, I suppose my element with an unknown height was defaulted to zero. This is what I have but it doesn't seem to be working.. $('.parent-class:visible .my-class[state!="done"]') I want to select all .my-class elements that their .parent-class element is visible. Thank you! A: try $(".parent-class:visible").children(".my-class[state!='done']").html("i am gone"); here is the fiddle http://jsfiddle.net/XAnqB/7/ A: Your selector should work, and it does work. In your fiddle, you have not included the jQuery library, so it doesn't work there! See this updated fiddle. A: if you change the framework in jsfiddle to jquery instead of mootools it works A: You have it so all descendents of the parent are selected. The space is the "ancestor operator". If you want only the direct children, use the > operator: .parent-class:visible > .my-class[state!="done"]'
{ "language": "en", "url": "https://stackoverflow.com/questions/7515627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Program can't find libboost_program_options.so.1.47.0 at runtime Since I don't have root permission to install Boost C++ library, I installed it under my home local. When compiling, I used: g++ -I/home/name/local/boost_1_47_0 -L/home/name/local/boost_1_47_0/stage/lib foo.cc -o foo -lboost_program_options but at runtime, it goes: error while loading shared libraries: libboost_program_options.so.1.47.0: cannot open shared object file: No such file or directory and ldd gives: libboost_program_options.so.1.47.0 => not found I also tried to specify the absolute path of the library, but it doesn't work either: g++ /home/name/local/boost_1_47_0/stage/lib/libboost_program_options.so.1.47.0 -I/home/name/local/boost_1_47_0 -L/home/name/local/boost_1_47_0/stage/lib foo.cc -o foo A: Try using the LD_LIBRARY_PATH environment variable to instruct the run-time linker where to find the library: export LD_LIBRARY_PATH=/home/name/local/boost_1_47_0/stage/lib Then rerun your application. A: I'm a newbie, so don't take my words too seriously. Furthermore, this question is several months old and I guess solved long ago. Nevertheless, here's what I think. You specify the library path to the linker, so the program compiles and links fine. However, when you try to execute the binary, it looks for the libs in the environment defined path. I guess this can be fixed by typing into bash export PATH=$PATH:path_to_your_library_folder Best Regards Miroslav
{ "language": "en", "url": "https://stackoverflow.com/questions/7515631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP : Parser asp page Googd morning, can I parser an asp page with php for to take the html tag code ? How can I take this value <a href="xxx">**VALUE TO TAKE**</a> from an asp page ? A: Yes you can use file_get_contents('http://www.example.com/myasp.asp'); to get the file in a string and then use some RegEx to get the data you need. Somthing like <?php /*GET ALL LINKS FROM http://www.w3schools.com/asp/default.asp*/ $page = file_get_contents('http://www.w3schools.com/asp/default.asp'); preg_match_all("/<a.*>(.*?)<\/a>/", $page, $matches, PREG_SET_ORDER); echo "All links : <br/>"; foreach($matches as $match){ echo $match[1]."<br/>"; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7515634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving source string of image in richtextbox after moving or pasting from clipboard I'm working on richtextbox, which can handle images. I'm saving xaml content of richtextbox to database as string. Images are saved in the folder tree. And I have one problem: When I insert image to richtextbox (in InlineUIContainer) all is working, saving and loading makes no problem. But when I drag image or cut and paste image again, source path of image is changed: <Image> <Image.Source> <BitmapImage BaseUri="pack://payload:,,wpf1,/Xaml/Document.xaml" UriSource="./Image1.jpeg" CacheOption="OnLoad" /> </Image.Source> </Image> original source was: <Image Source="pack://siteoforigin:,,,/path_to_image/some_image.jpg" /> And therefore, when I save xaml again (still everything ok), I can't load images again, because in the xaml there are wrong paths to them (not ok :-)). I searched for it, but I haven't found any solution. Could You help me please? A: I found another way, I am saving it to the XAML package, Images are copied into it and everything works perfect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tableview, Sections, Rows and coreData - Rows are displayed multiple(duplicate) i am saving Data in coreData to show it in a Table. I have 3 Entitys: EntitySet <------>> EntityRow <------>> EntityDetails (To Many Relationships) While reading and showing the Data in the Table, Sections and Rows, it works fine. But the problem is, ALL Data from EntityRow is displayed in ALL Sections, but i want to display ONLY the rows which belongs to the Section X. What can be wrong here? I dont know how to solve this problem. In my tableView:cellForRowAtIndexPath: method it looks like this: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } EntityRows *rows = [_rowsX objectAtIndex:indexPath.row]; cell.textLabel.text = rows.title; return cell; } Or may can be my mistake in coreData? Wrong relationship? Thanks for any help, brush51 A: hum.. verify: * *(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; *(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; if you have more than one section, you must use indexPath.section as well indexPath.row in your * *(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
{ "language": "en", "url": "https://stackoverflow.com/questions/7515640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Infinite URL Parameters for ASP.NET MVC Route I need an implementation where I can get infinite parameters on my ASP.NET Controller. It will be better if I give you an example : Let's assume that I will have following urls : example.com/tag/poo/bar/poobar example.com/tag/poo/bar/poobar/poo2/poo4 example.com/tag/poo/bar/poobar/poo89 As you can see, it will get infinite number of tags after example.com/tag/ and slash will be a delimiter here. On the controller I would like to do this : foreach(string item in paramaters) { //this is one of the url paramaters string poo = item; } Is there any known way to achieve this? How can I get reach the values from controller? With Dictionary<string, string> or List<string>? NOTE : The question is not well explained IMO but I tried my best to fit it. in. Feel free to tweak it A: Like this: routes.MapRoute("Name", "tag/{*tags}", new { controller = ..., action = ... }); ActionResult MyAction(string tags) { foreach(string tag in tags.Split("/")) { ... } } A: Just in case anyone is coming to this with MVC in .NET 4.0, you need to be careful where you define your routes. I was happily going to global.asax and adding routes as suggested in these answers (and in other tutorials) and getting nowhere. My routes all just defaulted to {controller}/{action}/{id}. Adding further segments to the URL gave me a 404 error. Then I discovered the RouteConfig.cs file in the App_Start folder. It turns out this file is called by global.asax in the Application_Start() method. So, in .NET 4.0, make sure you add your custom routes there. This article covers it beautifully. A: The catch all will give you the raw string. If you want a more elegant way to handle the data, you could always use a custom route handler. public class AllPathRouteHandler : MvcRouteHandler { private readonly string key; public AllPathRouteHandler(string key) { this.key = key; } protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { var allPaths = requestContext.RouteData.Values[key] as string; if (!string.IsNullOrEmpty(allPaths)) { requestContext.RouteData.Values[key] = allPaths.Split('/'); } return base.GetHttpHandler(requestContext); } } Register the route handler. routes.Add(new Route("tag/{*tags}", new RouteValueDictionary( new { controller = "Tag", action = "Index", }), new AllPathRouteHandler("tags"))); Get the tags as a array in the controller. public ActionResult Index(string[] tags) { // do something with tags return View(); } A: That's called catch-all: tag/{*tags} A: in asp .net core you can use * in routing for example [HTTPGet({*id})] this code can multi parameter or when using send string with slash use them to get all parameters
{ "language": "en", "url": "https://stackoverflow.com/questions/7515644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: AS3 Not Adding Sprite to MovieClip My code is simply looping through an xml file and creating 'pages' (which are later animated). This has all worked fine but now I want to add a sprite over the entire contents of the page if the contents of the xml contain a URL. At run-time I can see that the checks for the URL are being processed correctly and that the overlay is being generated, but I cannot "see" it on the page. The following code is located in a for loop for every page in the xml file: var page:Page = new Page(); //MovieClip in my library // ... other stuff var textMC:FadeText = new FadeText(xml); //load the text from the xml fragment for this page //if the text contains a URL (using RegExp) if(textMC.hasLink()) { var button:Sprite = new Sprite(); button.graphics.beginFill(0x000000); button.graphics.drawRect(0, 0, 1, 1); button.name= textMC.getLink(); button.x = button.y = button.alpha = 0; button.width = rectangle.width; button.height = rectangle.height; button.buttonMode = true; button.addEventListener(MouseEvent.CLICK, goToUrl, false, 0, true); page.addChildAt(button, page.numChildren); } //... more code - such as add page to stage. From the console (using FireBug and FlashBug) the button is being created, but I cannot see it on screen so I am guessing the addChild bit is at fault. What is wrong and how do I fix it? [edit] Having set the alpha to 1 I can see that the overlay IS being added to the page, but it is not changing my cursor or responding to mouse clicks. I now believe it is something wrong with the XML. It is correctly parsed XML (otherwise FlashPlayer would throw exceptions in my face) and it appears that this code works on every page except the second. Further more, if the second page is set as visible (a flag in the XML determins if the page is created or not) then none of the other pages overlay works. A: Sorry to necro this thread but one thing I can think of is that because you specify a z-position to place your page it might be that the z-position generated by (i+1) is not the next one in line. AS3 doesn't allow display-objects to be placed on 'layers' with empty 'layers' between them which was allowed in AS2. My guess is that during the loop at one point or another the loop doesn't generate a page which leaves an empty layer. The reason why the stage.addChild(page) actually works is because it simply searches for the next empty layer in that stack because you don't specify it. A: button.x = button.y = button.alpha = 0; set alpha to 1 button.alpha = 1; and check for rectangle.width , rectangle.height last thing, check for textMC.hasLink() if its true or not. If its true, there is another problem with your code that is not related to this sample code. A: Illogical answer: Replaced stage.addChildAt(page,i+1); with stage.addChild(page);. I was clutching at straws. Have spent FAR too long working on this blip, but it works! I don't know WHY it works, and at this point I don't care; IT WORKS!!! (sorry for the unprofessionalism however I have spent two and a half days working on this and have just got it working!) If someone wants to explain why it works, feel free. I would VERY much prefer to learn why this occurs that struggle to work around it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Join between a sqlsever table and an oracle table I have been using SQL Server 2008 for a short time now and have never used Oracle before. I am able to access an Oracle table through SQL Server with the syntax select * from [OracleDB1]..[OracleDB1].[Zips] (where OracleDB1 is the oracle database and Zips is the table I require) Is it possible to join a SQL Server table with this one in a Table-valued Function? Just using a normal join as I would with SQL Server tables gives an Invalid object name error on the Oracle table. Can this be done directly (or at all) or is it possible to do this some other way such as table variables? example query: select * from dbo.Table1 t INNER JOIN [OracleDB1]..[OracleDB1].[Zips] z where t.zip = z.zip A: I was performing the join wrong since I missed the ON clause. I was able to get it to work by declaring a temptable and joining on that. declare @tempTable table{ ZIP nvarchar(5), COUNTY nvarchar(10) } insert @tempTable select ZIP, COUNTY, from [OracleDB1]..[OracleDB1].[ZIPS] select * from dbo.Table1 t INNER JOIN @tempTable z on t.ZIP = v.ZIP where t.AdmissionOn >= '08-08-2011' AND t.AdmissionOn <= ''09-08-2011' This also worked in line as I had in the original question once I added the ON clause but the table variable suits my needs better since it only has to access the Oracle table once and not each comparison.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSData memory leak Instruments is showing that i get a memory leak right there: -(id) copyWithZone: (NSZone *) zone { Layer *copy = [[Layer allocWithZone:zone]init]; NSData *imageData = [[NSData alloc]initWithData:_image]; copy.image = imageData; [imageData release]; return copy; } The image property is declared as it follows: @property (nonatomic, retain) NSData *image; Here is a screenshot of instruments, to prove that i am not lying. Anyone see a problem in there? A: The Leaks instruments shows you where an object originated, not where it "leaked". So somewhere in your code you'll have something like this: MyClass *obj = [otherObj copy]; // or copyWithZone: But you're not releasing or autoreleasing obj and thus create a leak. In Objective-C, convention tells you a method should return an autoreleased object, except for methods that start with alloc, new, copy or mutableCopy. These method must return a retained object instead and the receiver is the owner and thus responsible for releasing them. See Memory Management Policy in Apple's memory management guide. A: Here is how we solved it, following the instructions given here. -(id) copyWithZone: (NSZone *) zone { Layer *copy = [[Layer allocWithZone:zone]init]; copy->_image=nil; [copy setImage:[self image]]; return copy; } A: - (id)copyWithZone:(NSZone *)zone{ Layer *copy = [[[self class] allocWithZone: zone] init]; [copy setImage:[self image]]; return copy; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7515658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tuple NumPy Data Type I currently am reading in colors from an SQLite database in the following way: import numpy as np, apsw connection = apsw.Connection(db_name) cursor = connection.cursor() desc = {'names':('name','R','G','B'),'formats':('a3','float','float','float')} colorlist = np.array(cursor.execute("SELECT name, R, G, B FROM Colors").fetchall(),desc) But I was hoping to read in this data in a NumPy array with only two columns, where the second column is a tuple containing (R,G,B), i.e. something like: desc = {'names':('name','Color'),'formats':('a3','float_tuple')} colorlist = np.array(cursor.execute("SELECT name, R, G, B FROM Colors").fetchall(),desc) I want to do this to simplify some of my later statements where I extract the color from the array as a tuple and to eliminate my need to create a dictionary to do this for me: colorlist[colorlist['name']=='BOS']['Color'][0] A: Do you literally need a tuple? Or do you just want the values to be grouped? You can create a numpy record array with arbitrary shapes for each of the fields... >>> np.array([('ABC', (1, 2, 3)), ('CBA', (3, 2, 1))], dtype='3a, 3i') array([('ABC', [1, 2, 3]), ('CBA', [3, 2, 1])], dtype=[('f0', '|S3'), ('f1', '<i4', 3)]) This works even for n-dimensional arrays: >>> np.array([('ABC', ((1, 2, 3), (1, 2, 3))), ('CBA', ((3, 2, 1), (3, 2, 1)))], dtype='a3, (2, 3)i') array([('ABC', [[1, 2, 3], [1, 2, 3]]), ('CBA', [[3, 2, 1], [3, 2, 1]])], dtype=[('f0', '|S3'), ('f1', '<i4', (2, 3))]) Partially applied to your specific problem: >>> desc = {'names':('name','Color'),'formats':('a3','3f')} >>> colorlist = np.array([('ABC', (1, 2, 3)), ('CBA', (3, 2, 1))], desc) >>> colorlist[colorlist['name']=='ABC']['Color'][0] array([ 1., 2., 3.], dtype=float32) Using rec.fromarrays to generate a record array from two regular arrays: >>> desc = {'names':('name','Color'),'formats':('a3','3f')} >>> np.rec.fromarrays([['ABC', 'CBA'], [(1, 2, 3), (3, 2, 1)]], desc)[0][1] array([ 1., 2., 3.], dtype=float32) A full solution: color_query = cursor.execute("SELECT R, G, B FROM Colors").fetchall() name_query = cursor.execute("SELECT name FROM Colors").fetchall() desc = {'names':('name','Color'),'formats':('a3','3f')} colorlist = np.rec.fromarrays([color_query, name_query], desc) If for some reason you can't split the query like that, you'll just have to split the results of the query, perhaps using a list comprehension: colorlist = np.rec.fromarrays([[row[0] for row in query], [row[1:] for row in query]], desc)
{ "language": "en", "url": "https://stackoverflow.com/questions/7515659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iPhone App: images for retina display not showing In my iPhone app I'm including high resolution image with naming convention imagename@2x.png, but it is not showing higher resolution images for retina display. What could be wrong? A: If you are calling the images programmality try to use: [UIImage imageNamed:@"image.png"]; Make sure you are on a project that supports the retina display. []'s A: in my case problem was case Sensitivity of @2x
{ "language": "en", "url": "https://stackoverflow.com/questions/7515665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GridCalculatedColumn has a Property called "Expression", what can it contain? GridCalculatedColumn has a Property called "Expression", what could it contain? These are valid: iif(condition, trueResult, falseResult) {0}*{1} Convert.ToString({0}) How to format the result of the expression? e.g. this doesn't work: iif(condition, String.Format"{0:0.00}%", {0}), "NA") Any idea what Expression can contain? A: I believe this has the same/similar rules as DataColumn.Expression, see: http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx ----Added based on comments---- See this thread on stackoverflow: How to bind a telerik grid column to a child data object that is a list? It links to: http://www.telerik.com/help/aspnet-ajax/grdbindingtosubobjects.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7515670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Modal blocking dialog in Javascript I'm developing Openlayers toolbar in Javascript with jQuery and jQuery UI. One feature that I want to implement is Adding points to the map. In openLayers you have to listen for event called 'sketchcomplete'. layer.events.on({ 'sketchcomplete': onPointAdded }); The problem is in onPointAdded callback. This callback should return true or false. True mean that the point should be added to the map and false means cancel adding this point to the map. Now the callback looks like this: onPointAdded = function(feature) { var f = feature.feature; var result = false; $('#dialog-point-add').dialog({ modal : true, buttons : { 'Add point' : function() { result = true; $(this).dialog("close"); }, 'Cancel' : function() { result = false; $(this).dialog("close"); } } }); return result; }; The problem is that this dialog doesn't block the executing code. I'm asking You How to handle this situation? I want to show dialog to the user with confirmation for adding the point. A: If I understand the question correctly, you are not going to be able to do this with the jquery ui dialog. The vanilla js confirm box should work though. A: The function can not block, because JavaScript is single threaded and nothing else could be executed. Why don't you just add the logic, you want to call if the the function returns true, to the 'Add point' callback? EDIT: a "normal" JavaScript confirm dialog would block: onPointAdded = function(feature) { return confirm("Sure?"); };
{ "language": "en", "url": "https://stackoverflow.com/questions/7515672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: byte representation in BINARY_CHECKSUM()? according to this article http://decipherinfosys.wordpress.com/2007/05/18/checksum-functions-in-sql-server-2005/ they say that BINARY_CHECKSUM() returns the same value if the elements of two expressions have the same type and byte representation. So, “2Volvo Director 20″ and “3Volvo Director 30″ will yield the same value my question is what is byte representation? and why SELECT BINARY_CHECKSUM('2Volvo Director 20' )// -1356512636 SELECT BINARY_CHECKSUM('3Volvo Director 30' )// -1356512636 gives the same results ? the byte of '2' is not as the byte of '3' A: I don't know exactly what that article means by that phrasing, but from googling around I see that a SQL Server MVP has reverse-engineered the full algorithm (eg here) and others have noticed that the algorithm has weird problems around a 16-character cycle. Notice that in that sample, the changes occur at position 1 and position 17: SELECT BINARY_CHECKSUM('2Volvo Director 20' )-- -1356512636 SELECT BINARY_CHECKSUM('3Volvo Director 30' )-- -1356512636 -- 12345678901234567 which are 16 apart - if the space is removed so the changes occur at positions 1 and 16, you get different checksums: SELECT BINARY_CHECKSUM('2Volvo Director20' )-- 1257395465 SELECT BINARY_CHECKSUM('3Volvo Director30' )-- 1257395480 -- 12345678901234567 The internet consensus appears to be that the hash function offered by BINARY_CHECKSUM is of low quality, and that you should use HASHBYTES in preference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Widget Preferences "delay" problem I have a Widget with his android.appwidget.action.APPWIDGET_CONFIGURE Activity with some preferences witch I can set before adding it to the "desktop". My problem is that the preferences does not get applied because I noticed that as soon as the APPWIDGET_CONFIGURE is called, the widget is created and never refresh after the widget is actually applied to the screen and it actually never reads the updated preferences. Any thoughts? Thanks Oh, I think I found what it seems to be an easy solution but I don't like it much so I like to have a "second opinion". I don't say what it is to not influence the answers. PS. The configuration activity works fine, the problem is only when the widget is applied for the first time. A: The (easy) solution I found is to call an update on the widget after closing the APPWIDGET_CONFIGURE Activity. The "dirty" thing I don't like is that you actually "draw" the widget one extra time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Json.NET to parse result returned by Google Maps API I am trying to use google map api's web service to make a web request, and get the json string, and then get the latitude and longitude I need for the input address. Everything is fine. I got the json string I need. Now I am using Json.net to parse the string. I don't know why, but I simply cannot convert it into a JArray. Here is the json string Can anyone teach me how to write the c# code to get the lat and lng in geometry > location? Thanks Here is my codes and the bug screenshot A: You have a few options when using JSON.NET to Parse the JSON. The best option, IMHO, is to use Serialization to pull the object back into a structured type that you can manipulate as you could any other class. For this you can see serialization in the JSON.NET documentation (I can also post more details if that isn't clear enough). If all you want is to grab the address, as you listed in your question, you can also use the LINQ feature to pull that information back. You could use code similar to the following to pull it off (the key lies in the SelectToken method to pull back the details you need). Dim json As Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(jsonString) json.SelectToken("results.formatted_address").ToString() You can also use all the normal power of Linq to traverse the JSON as you'd expect. See the LINQ documentation as well. A: [I realize this is an old question, but in the off chance it helps someone else...] The problem here is that json["results"] is a JArray, but you are not querying it like one. You need to use an array index to get the first (and only, in this case) element, then you can access the objects inside it. string address = json["results"][0]["formatted_address"].Value<string>(); To get the latitude and longitude you can do: JToken location = json["results"][0]["geometry"]["location"]; double lat = location["lat"].Value<double>(); double lng = location["lng"].Value<double>();
{ "language": "en", "url": "https://stackoverflow.com/questions/7515679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using printf awk function to output nth arguments Given the following file's content: alias command with whitespace-separated argument list anotheralias othercommand and its arguments how i can to print something like: alias = command with whitespace-separated argument list anotheralias = othercommand and its arguments Currently I'am using the below command, but it's wrong. cat aliases | awk '{printf "%20s = %s\n", $1, $0}' A: cat aliases | awk '{$1=sprintf("%20s =",$1);print}' A: cat aliases | awk '{ printf("%20s =", $1); $1=""; printf("%s\n", $0) }' A: another way: sed 's/ /=/1' yourFile|awk -F= '{printf ("%20s = %s\n",$1,$2)}' A: Just use the shell: while read line; do set -- $line cmd=$1 shift printf "%20s = %s\n" "$cmd" "$*" done < filename
{ "language": "en", "url": "https://stackoverflow.com/questions/7515688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: make doesn't find rules to make target (newbie on manual makefile generation) I have the following makefile that I tried to construct out of a tutorial. Then I (thought) i added the necessary sources in order to fit it for my code.. but it doesn't find the target. I think It may have to do with the folder structure of the sources, but I can't figure it out. SVN_REV=(svnversion -cn | sed -e 's/.*://' -e 's/\([0-9]*\).*/\1/' | grep '[0-9]') DEBUG_OPTS:=-g -DSVN_REV \ -DDEBUG_MODE \ -UTIME_MODE \ -UREADFROMFILE CFLAGS:=$(DEBUG_OPTS) -c -Wall LDFLAGS:=$(DEBUG_OPTS) -lpthread EXECUTABLE:=fw_board COMPILER:=arm-linux-gcc (makefile cont'd below, there are the src files locations as seen from the TOPDIR) SOURCES:=main_process/main.c \ ezxml/ezxml.c \ info_file_parser/info_file_parser.c \ info_file_parser/array_management.c \ info_file_parser/protocol_file_parser.c \ info_file_parser/sequence_file_parser.c \ info_file_parser/topology_file_parser.c \ seq_exec_module/seq_execution.c \ i2c_device_drivers/pca950x.c \ i2c_device_drivers/ltc2495.c \ i2c_device_drivers/ltc2609.c \ i2c_device_drivers/temperature_uc.c \ i2c_device_drivers/pcf8574.c \ i2c_device_drivers/stepper_motor_control.c \ i2c_device_drivers/test_functions.c \ i2c_device_drivers/stepper_pca.c \ i2c_device_drivers/stepper_atmega.c \ i2c_device_drivers/general_i2c.c \ i2c_device_drivers/zx_mbd_pwr.c \ i2c_device_drivers/virtual_switch_handler.c \ i2c_device_drivers/pressure_sensor_ASDXAV030PG7A5.c \ hashing/ConfigData.c \ hashing/Hash.c \ hashing/LinkedList.c \ init_file_parser/init_file_parser.c \ usb_communication/serial_comm.c \ protocol_parser/protocol_parser.c BINDIR:=bin OBJDIR:=.obj OBJECTS:=$(addprefix $(OBJDIR)/,$(SOURCES:%.c=%.o)) .PHONY: all all: $(SOURCES) $(EXECUTABLE) @echo all_start this is the linking stage $(EXECUTABLE): $(OBJECTS) | $(BINDIR) @echo link $(COMPILER) $(LDFLAGS) $(OBJECTS) -o $(BINDIR)/$@ and the compilation stage. but main.c can't be located as you'll see $(OBJECTS): $(OBJDIR)/%.o : %.c | $(OBJDIR) @echo compile $(COMPILER) $(CFLAGS) $< -o $@ $(OBJDIR): mkdir $(OBJDIR) $(BINDIR): mkdir $(BINDIR) .PHONY: clean clean: @echo removing_files rm -rf $(OBJECTS) $(BINDIR)/$(EXECUTABLE) running make returns the following: make: *** No rule to make target `main_process/main.c', needed by `all'. Stop. A: Don't list the sources as a dependency of all. all: depends on $(EXECUTABLE). Incidentally, the echo will only get output (if at all) AFTER $(EXECUTABLE) has been built. $(EXECUTABLE): depends on $(OBJECTS) I'm not quite sure what the syntax on your $(OBJECTS) rule is doing, but there is no need to have an explicit rule on $(OBJECTS). Just having the $(OBJECTS) list all the object files, and then having a rule to generate them from the C files is sufficient. With all those rules, "all:" is implictly dependant on the sources anyway. Also, "all:" is a "phony" rule, so will rebuild all dependencies every time anyway. The path main_process/main.c needs to exist relative to the directory that contains the makefile. Fix all that and you should be good to go. A: I can't see where exactly your make went wrong without a lot of information about your build environment, but your best bets are: * *Use make -d to show you where things went wrong. If you don't use implicit rules, make -rd is more concise. *Use automake to avoid writing a Makefile at all. In principle, if there is such a thing as the file main_process/main.c, it should be compiled. Have you tried an ls with the exact same name?
{ "language": "en", "url": "https://stackoverflow.com/questions/7515695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can one convert 64 character size of the devToken got in didRegisterForRemoteNotificationsWithDeviceToken to the 32 characters size string? While implementing Push Notification service in my application, I am facing very strange problem. In my case, I am using Server model of In-App purchase (and hence the content provider server is custom server provided by the client). The server is providing an API that is used to register the device to the APNS. In that API, device token expected to be of 32 characters long (as written in apple documentation that the device token used to be send with the notification need to be of 32 bytes, I suppose). My problem is, since we are getting 64 characters of String in didRegisterForRemoteNotificationsWithDeviceToken method, how can one convert it to 32 characters? I mean will there not be a lost of data? I am currently trimming the NSData to get the NSString only. Update: Can I use memcpy in iPhone? I got to know that it is only available in Mac OSx and not in iOS, is it correct? Kindly suggest the way to do this. Thanks in advance. A: Is the 64 byte sting hex encoded perhaps?
{ "language": "en", "url": "https://stackoverflow.com/questions/7515696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery .numeric and pasting content The .numeric function (http://www.texotela.co.uk/code/jquery/numeric/) works great, but when you paste content into the txtOrderName field and you exit the field it doesnt validate. Does anyone know any modifications that will allow the .numeric function to be run again after content has been pasted? For example, if I paste '4,00' into the txtOrderPrice field, I dont want the comma (,) to be displayed. The numeric function ignores this if you type '4,00' in the field (changes to '400'). But knowing people they might just paste '4,00' into the field and stuff things up. <script type="text/javascript" src="jquery.numeric.js"></script> $(document).ready(function() { $(".numeric").numeric(); }); </script> <input class="numeric" type="text" id="txtOrderPrice" name="txtOrderPrice_name" maxlength="128" /> A: it says it's the limitation: Limitations / Bugs CTRL+A does not select all text. Text pasted via the mouse is not auto-corrected, though a callback can be defined to work around this. so, the workaround would be to hook it up to either .blur() or .focusout() event: $(document).ready(function() { $(".numeric").numeric(); $(".numeric").focusout(function() { $(this).keyup(); }); }) http://jsfiddle.net/xFJfP/ A: You could replace the , with a . like so: value.replace(/,/g,".");
{ "language": "en", "url": "https://stackoverflow.com/questions/7515704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculate a sum from information contained in a variable How do I process a calculation using information stored in one variable? I want to let people enter a calculation into a form, and then they will get the answer. If someone enters 25 * 10, they will be told the answer is 250. A: What you are looking for is "php math parser". This might help you: http://www.phpclasses.org/browse/package/2695.html. Didn't use it yet, looks ok though. Please spare yourself a lot of trouble and don't use eval(). ;-) UPDATE: I will need something like this too, so I took the time and found another one: http://www.bestcode.com/html/math_parser_for_php.html. It is not free though. A: you can do your own parser, or use the eval function. But please make sure to not allow random code execution on your server. some people would love to do a shell_exec('rm *') or something like that. alternativly you could use wolfram-alha api or something equivalent, if you don't need to store the result. (even then, you could send the result back to your server with ajax)
{ "language": "en", "url": "https://stackoverflow.com/questions/7515706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Post programmatically to Facebook Market Is there an API to create new posts on the Facebook Market?
{ "language": "en", "url": "https://stackoverflow.com/questions/7515708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ListView onClick event doesn't fire with Linkified email address I have a straight forward ListView with a ListAdapter and custom onItemClick method for the list. My ListView items are clickable to perform other functions. However, some of my ListView elements contain an email address that should be clickable too. I found Linkify, and added it to the email address textview per the docs. After doing so, the ListView item containing such a "clickable" textview is now no longer clickable to perform the other functions. I have tried adding the OnItemClickListener after I create the entire view, to no avail :( Any idea's on how to have my ListView items clickable eventhough they contain a Linkified textView? My deepest appologies for not searching further before asking the question to begin with. I have found the answer to my question, and posted it as an answer. A: Solution: After a lot of more searching (which I already did, but not far enough apparently), I finally found this page. Example code: My page (LinearLayout containing the listView) assigns a ListViewAdapter which creates the various ListView items, assigns itself as the OnClick listener and adds the ListView: list.setAdapter(adapter); list.setOnItemClickListener(this); addView(list); The ListViewAdapter creates each ListView item and assigns it's content, linkifying email addresses when needed: public View getView(int position, View convertView, ViewGroup parent) { View view = layoutInflater.inflate(R.layout.list_item_layout, null); TextView textView = (TextView) view.findViewById(R.id.item_text); textView.setText(<some email address>); Linkify.addLinks(textView, Linkify.EMAIL_ADDRESSES); } The solution is easy, using the code on the page I found. I created a LinkTextView class descending from TextView and added the method described on the page. After the Linkify.addLinks call above I added the statement: textView.setMovementMethod(null); The ListView item and linkified text are now both clickable once again. Again, my deepest appologies for not searching further before asking the question to begin with. A: Just add android:descendantFocusability="blocksDescendants" to xml definition of list item. Source: http://www.thekeyconsultant.com/2013/06/android-quick-tip-linkify-and-listviews.html?m=1
{ "language": "en", "url": "https://stackoverflow.com/questions/7515710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Call Method By Event width JS OOP (prototype) i hope anybody can help me =) I try to keep the example simple: function myClass(){ //some Code } myClass.prototype.func1 = function(){ //some Code } myClass.prototype.func2 = function(){ document.getElementById("myEl").onclick = function(){ this.func1 //does not work, this is only the Element... } } How does it works to call func1? I want to bind the onclick-event in func2. A: First, you have to keep a reference to the current object. As you already noticed, inside the event handler, this refers to the DOM element. You can do this with var self = this; Second, you have to actually call the function: self.func1(); Complete example: myClass.prototype.func2 = function(){ var self = this; document.getElementById("myEl").onclick = function(){ self.func1(); }; } In the newer browsers you can also use .bind() [MDN] to explicitly define what this should refer to (see the MDN docs for a shim for other browsers): document.getElementById("myEl").onclick = this.func1.bind(this); A: Inside the onclick function, the this value is bound to the element being clicked. You need to keep a copy (a reference) to the this inside of func2: myClass.prototype.func2 = function(){ var self = this; //keep a reference to the this value document.getElementById("myEl").onclick = function(){ self.func1(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7515716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python:JS: How to parse multiple kml node in one xml file? <xml> <mapshape title="Bar" extras=""> <kml></kml> </mapshape> <mapshape title="Foo" extras=""> <kml></kml> </mapshape> </xml> I've got a xml doc like that, multiple mapshape nodes in one xml, and each contains one valid kml file. I need to plot them all on google maps. I have tried libraries like geoxml(3), they can parse one kml file, but my document has many kmls, how can I deal with this? A: You can use lxml to extract the kml sections and then pass them on to the other library: doc = """<xml> <mapshape title="Bar" extras=""> <kml></kml> </mapshape> <mapshape title="Foo" extras=""> <kml></kml> </mapshape> </xml>""" import lxml.etree as etree xml = etree.fromstring(doc) for mapshape in xml: kml = etree.tostring(mapshape.getchildren()[0]) parseKML(kml)
{ "language": "en", "url": "https://stackoverflow.com/questions/7515718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get cookies value on another page with jQuery? I have called one PHP page inside an iframe I have stored some values in cookies. I want to read those cookies values from that page to other page. I used jQuery to read the cookie. var value = $.cookie('artname'); 'artname' is the cookie name. But it is displaying null because the cookie path is different. The path is /v/abcfile/frontend/. But the path for the other cookies on the page i am trying to get is /. I tried with this: top.jQuery.cookie('artname'); But it's still showing me the same. For path ii have tried with: var value = $.cookie("artname", { path:'/v/vspfiles/frontend/' }); Its still showing me the null value. How can I get value of cookie? A: When you save your cookies, set path to "/". Cookie will be available on all pages $.cookie('artname', 'value', { path:'/'}); A: This worked for me: $.cookie.defaults = { path: '/' }; $.cookie("foo", "value" );
{ "language": "en", "url": "https://stackoverflow.com/questions/7515720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Raising a function by timer I want to raise a function periodically . When I finish one function cycle to wait some period of time and only them to start the second run. I thought to make it like : timer = new System.Timers.Timer(); timer.Interval = 1000; timer.Enabled = true; timer.Start(); timer.Elapsed += TimerTick; private void TimerTick(object sender, EventArgs e) { //My functionality } But seems that TimerTick is raised every secound and not secound from my last TimerTick run . How i can solve this one ? A: You can use threads: var thread = new Thread(o => { while(true) { DoTick(); Thread.Sleep(1000); } }); A: You can stop your timer before doing your processing and start it again after it's done: private void TimerTick(object sender, EventArgs e) { timer.Stop(); //My functionality timer.Start(); } it's also a good idea to put your functionality in a try-catch and call Start() in the finally section. (if this suits you) A: Try the following: private void TimerTick(object sender, EventArgs e) { // get the timer that raised this event (you can have multiple // timers, or the timer obj is out of scope here, so use this): Timer timer = (Timer) sender; // disable (or use timer.Stop()) timer.Enabled = false; // ... // your code // ... // at end, re-enable timer.Enabled = true; } you will find that the timer will now run 1000ms after your code finished. You can also use timer.Stop() and timer.Start(). A: you could always do something like this: while (true) { // your functions Thread.Sleep(1000) } you'd have to find a way to stop this through an external mechanism, but it should work. A: You're right: the timer will run every second: it won't care what you're doing in the TimerTick. What you can do is to stop the timer on entering the TimerTick methode. private void TimerTick(object sender, EventArgs e) { timer.Stop(); //My functionality timer.Start(); } A: Try this: DateTime lastDT = DateTime.MinValue; private void TimerTick(object sender, EventArgs e) { DateTime now = DateTime.Now; if (now - last).TotalSeconds > what_you_want { //My functionality } last = now; } Using this, your form (main thread) is not locked and you/user can do what you please. A: Try private void TimerTick(object sender, EventArgs e) { timer.Stop(); // My Functionality timer.Stop(); } However, you may have an extra even fired. As per MSDN Docs: The signal to raise the Elapsed event is always queued for execution on a ThreadPool thread, so the event-handling method might run on one thread at the same time that a call to the Stop method runs on another thread. This might result in the Elapsed event being raised after the Stop method is called. The code example in the next section shows one way to work around this race condition. You might want to consider Thread.Sleep() instead
{ "language": "en", "url": "https://stackoverflow.com/questions/7515721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Callback after posting message to Twitter I am posting messgae to twiter via link: http://twitter.com/intent/tweet?source=webclient&text=Hello I am interested in if it is possible to be redirected to some url after posting message? For example Facebook has "redirect_uri" parameter added to the URL. User is redirected to this URL after the meesage is posted on the wall. A: You can use events binding for Web Intents to redirect to a url after tweeting. window.twttr = (function (d,s,id) { var t, js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js=d.createElement(s); js.id=id; js.src="https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } }); }(document, "script", "twitter-wjs")); twttr.ready(function (twttr) { twttr.events.bind('tweet', function (event) { //redirect to your url } ); }); Following links might help : https://dev.twitter.com/docs/intents/events#events https://dev.twitter.com/discussions/671 A: According to the documentation, the tweet web intent does not have a parameter that allows the user to return to your website after the tweet is posted. Most websites that I've seen present the web intent in a popup instead of sending the user away from their site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Jenkins and multi-configuration (matrix) jobs Why are there two kinds of jobs for Jenkins, both the multi-configuration project and the free-style project project? I read somewhere that once you choose one of them, you can't convert to the other (easily). Why wouldn't I always pick the multi-configuration project in order to be safe for future changes? I would like to setup a build for a project building both on Windows and Unix (and other platforms as well). I found this question), which asks the same thing, but I don't really get the answer. Why would I need three matrix projects (and not three free-style projects), one for each platform? Why can't I keep them all in one matrix, with platforms AND (for example) gcc version on one axis and (my) software versions on the other? I also read this blog post, but that builds everything on the same machine, with just different Python versions. So, in short: how do most people configure a multi-configuration project targeting many different platforms? A: Another option is to use a python build step to check the current OS and then call an appropriate setup or build script. In the python script, you can save the updated environment to a file and inject the environment again using the EnvInject plugin for subsequent build steps. Depending on the size of your build environment, you could also use a multi-platform build tool like SCons. A: The two types of jobs have separate functions: * *Free-style jobs: these allow you to build your project on a single computer or label (group of computers, for eg "Windows-XP-32"). *Multi-configuration jobs: these allow you to build your project on multiple computers or labels, or a mix of the two, for eg Windows-XP, Windows-Vista, Windows-7 and RedHat - useful for checking compatibility or building for multiple platforms (qt programs?) If you have a project which you want to build on Windows & Unix, you have two options: * *Create a separate free-style job for each configuration, in which case you have to maintain each one individually *You have one multi-configuration job, and you select 2 (or more) labels/computers/slaves - 1 for Windows and 1 for Unix. In this case, you only have to maintain one job for the build You can keep the your gcc versions on one axis, and software versions on another. There is no reason you should not be able to. The question that you link has a fair point, but one that does not relate to your question directly: in his case, he had a multi-configuration job A, which - on success - triggered another job B. Now, in a multi-configuration job, if one of the configuration fails, the entire job fails (obviously, since you want your project to build successfully on all your configurations). IMHO, for building the same project on multiple platforms, the better way to go is to use a multi-configuration style job. A: You could create a script (e.g. build) and a batch file (e.g. build.bat) that get checked in with your source code. In Jenkins in your build step you can call $WORKSPACE/build - Windows will execute build.bat whereas Linux will run build. A: An option is to use user-defined axis combined with slaves(windows, linux, ...), so you need to add a filter for each combination and use the Conditional BuildStep Plugin to set the build step specific for each plataform(Executar shell, Windows command, ...) This link has a tutorial but it is in portuguese, but it's easy to work it out based on image... http://manhadalasanha.wordpress.com/2013/06/20/projeto-de-multiplas-configuracoes-matrix-no-jenkins/ A: You could use the variable that jenkins create when you define a configuration matrix axis. For example: You create a slave axis with name OSTYPE and check the two slaves (Windows and Linux). Then you create two separate build steps and check for the OSTYPE environment variable. You could use a improved script language instead, like python, which is multi-platform and can achieve the same functionality independent of the slaves' name and in just one build step. A: If you go the matrix route with Windows and something else, you'll want the XShell plugin. You just create your two build scripts such as "build.bat" for cmd and "build" for bash, and tell XShell to run "build". The right one will be run in each case. A: A hack to have batch files run on Windows and shell scripts on Unix: On Unix, make batch files exit with 0 exit status: ln -s /bin/true /bin/cmd On Windows, either find a true.exe, name it sh.exe and place it somewhere in the PATH. Alternatively, if you have any sh.exe installed on Windows (From Cygwin, Git, or other source), add this to the top of the shell script in Jenkins: [ -n "$WINDIR" ] && exit 0 A: Why wouldn't you always pick the multi-configuration job type? Some reasons come to mind: * *Because jobs should be easy to create and configure. If it is hard to configure any job in your environment, you are probably doing something wrong outside the scope of the jenkins job. If you are happy that you managed to create that one job and it finally runs, and you are reluctant to do this whole work again, that's where you should try to improve. *Because multi configuration jobs are more complex. They usually require you to think about both the main job and the different sub job variables, and they tend to grow in complexity to a level beyond being manageable. So in a single job scenario, you'd probably waste thoughts on not using that complexity, and when extending the build variables, things might grow in the wrong direction. I'd suggest using the simple jobs as default, and the multi configuration jobs only if there is a need for multiple configurations. *Because executing multi configuration jobs might need more job slots on the slaves than single jobs. There will always be a master job that is executed on a special, invisible slot (that's no problem by itself) and triggers the sub jobs, but if these sub jobs do themselves trigger sub jobs, you might easily end in a deadlock if there are more sub jobs than slots, and some sub jobs trigger again sub jobs that then cannot execute because there are no more open slots. This problem might be circumvented by using some configuration setup on the slaves, but it is present and might only occur if several multi jobs run concurrently. So in essence: The multi configuration job is a more complex thing, and because complexity should be avoided unless necessary, the regular freestyle job is a better default. A: If you want to select on which slave you run the job, you need to use multi-configuration project (otherwise you won't be able to select/limit slaves on which you run it – there are three ways to do it, however I've tried them all (Tie plugin works only for master job, Restrict in Advanced Project Options is not rock-safe trigger as well so you want to use Slave axis that is proven to work correctly today.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7515730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: TSQL - Exclusion Condition I am trying to build a SQL script that will produce a list of fields for forward-conversion. By this i mean when the application was initially deployed, we had to migrate old data into the new database, as such the old data does not comply with the new standard. I didnt do the migration, only cleaning it up. Design: select * from tblclient where LEN(clientmatter) <> 11 and clientmatter not in (select * from tblclient where ISNUMERIC(clientmatter) <> 1) I know syntactically this will not work but the design should lend a hand on what i am trying to do. The derived table inside the condition will be used with this secondary table in a Union All. I am trying to exclude the non-numeric results from the length problem results so i can get a complete set of information with both conditions. Tested Design: select 'non-numeric', clientmatter from tblclient where ISNUMERIC(clientmatter) <> 1 UNION ALL select 'length problem', clientmatter from tblclient where LEN(clientmatter) <> 11 Tried this but i get duplication. I remember doing a script where i union'ed two queries but only produced one result but can remember how i did it. A: SELECT clientmatter, CASE WHEN LEN(clientmatter) <> 11 THEN 'length problem' END, CASE WHEN ISNUMERIC(clientmatter) <> 1 THEN 'non-numeric' END FROM tblclient WHERE ISNUMERIC(clientmatter) <> 1 OR LEN(clientmatter) <> 11 A: Try this select 'non-numeric', clientmatter from tblclient where ISNUMERIC(clientmatter) <> 1 and LEN(clientmatter)=11 UNION ALL select 'length problem', clientmatter from tblclient where LEN(clientmatter) <> 11 and IsNumeric(clientMatter)=1 UNION ALL select 'both problems', clientmatter from tblclient where LEN(clientmatter) <> 11 and IsNumeric(clientMatter)=0
{ "language": "en", "url": "https://stackoverflow.com/questions/7515731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using iOS's database on Android I am working on an Android application that will access the database that is already preloaded with data. At the same time, I also have an iOS's sqlite database that has the same data that I need. So I was wondering, can I just use iOS's database and load that into my Android application? I found this website that teaches you how to load your own database into Android but somehow iOS's database is not loading properly in my application. Can someone help me in this situation? Many Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7515732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using C# or PowerShell Automate Username and Password Entry in 'Connect to ServerName' dialog box I have a webpage that requires users to enter their credentials in a 'Connect to "ServerName"' dialog box and click OK. I want to automate this login proccess using C# or PowerShell. Is this possible? If not, is there another way of automating this? A: Looks like you are trying to execute the webpage automatically and that popup is blocking you from doing that, if that the case you can use SendKeys to type in the boxes Also a macro recorder being fired by a scheduler task will do it. you can also instead of trying to open the webpage make a WebRequest from a C# application passing the credentials , that will lead you to the same results... regards A: It is possible, but it is probably far easier to use AutoHotkey. It can be scripted to watch for a window of a certain name and then send keystrokes to that window automatically. Alternatively, you can set up the script so that the user just has to press some key or series of keys in that window and it will be converted to a set of keystrokes. The download also includes a compiler, so once you get your script right you can compile it to an .exe to distribute.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Web service vs JAR - is one approach better than the other? We have multiple web apps on our container (Tomcat) that don't interact with each other but they share the same data model. Some basic data access operations are used in multiple web apps, and of course we don't want the same code duplicated between multiple webapps. For this case is it better to build a library to provide the common functions or to expose the functions as a web service? With the library the user would have to provide the data source to access the database while the web service would be self-contained plus have its own logging. My quesion is similar to this SO question but performance isn't a concern - I think working with a web service on the same container will more than meet our needs. I'm interested to know if there's a standard way to approach this problem and if one way is better than the other - I'm sure I haven't considered all the factors. Thank you. A: I would make them a library. This will reduce any performance hits you would incur from network traffic, and in general would make it easier to reach your applications (because your library can't go 'down' like a webserver). If your applications which use this library otherwise do not require a network connection, then you will be able to totally relieve yourself of network connectivity constraints. If you think you may want to expose some functionality of this library to your users, you should consider making a webservice around this library. A: If it is just a model with some non-persistent operations (non-side effect calculations, etc) I'll use jar library. If it is more like a service (DB/Network/... operations), I'll create a separate webservice. If you have strong performance requirements, local library is the only solution. Also you can implement it using interfaces and change implementation when it will be clear, what to use. A: Webservice will certainly have its own share of overhead, both in terms of cpu and the codebase. If you dont to duplicate the same jar in every project, you can consider moving it to server lib, so that once updated every webapp gets the change. But this approach has a major drawback too, suppose you make some non backward compatible change in the model jar and update one webapp to use the newer model, you will certainly have to update all other webapps to be able to adapt to changes made in the common jar. You cant run multiple version from same server lib. You can package appropriate version of common jar in every webapp, but then for even a minor change in the common (model) jar, you will have to repckage and deploy all the webapps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get image Exif data using OpenCV? Does OpenCV support getting Exif data of images? Is there a program in OpenCV that parses the Exif data and get appropriate fields? A: As of 3.1 opencv imread handles exif orientation perfectly. I know this is an old question, but I struggled to find an answer to this same question recently, so am posting here. Apparently cvLoadImage does not handle exif orientation correctly at this time according to a bug report on github. You can find a nice set of sample images with different exif rotations and a good explanation here A: OpenCV has no Exif support. It's not the purpose of OpenCV.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How to format a Date variable in PLSQL I am new to PL/SQL and have this question. I created a procedure with the following specification: PROCEDURE runschedule (i_RunDate IN DATE) this i_RunDate comes in a specific format, and I need to change it to this format: 'MM/dd/yyyy hh:mi:ss PM' I couldn't find how to re-format a Date variable. A: You need to use the TO_CHAR function. Here's an example: SELECT TO_CHAR(CURRENT_TIMESTAMP, 'MM/DD/YYYY HH12:MI:SS AM') FROM dual; A: The DATE has not especific format, a DATE is a DATE. When stored in the database column, date values include the time of day in seconds since midnight, and a DATE variable has the same, only that when in some point you show the variable is formatted. PL/SQL can convert the datatype of a value implicitly, for example, can convert the CHAR value '02-JUN-92' to a DATE value.. but I don't recommend you rely on this implicit conversiosn. I always use the explicit conversion. For more on this topic, you could read this: http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28370/datatypes.htm#i9118 In your case, if you want to format your DATE to log something, or to show in your UI or wathever in a different format, you need to assig it to a varchar variable as Justin said, something like this: .... v_generated_run_date DATE; v_var_date VARCHAR2(30); BEGIN -- generate sysdate if required IF (i_RunDate is null) THEN v_var_date:=TO_CHAR(sysdate, 'MM/DD/YYYY HH12:MI:SS AM'); ELSE v_var_date:=TO_CHAR(i_RunDate,'MM/DD/YYYY HH12:MI:SS AM'); END IF; pkgschedule.createschedule (v_var_date); commit; END runschedule; END Your createschedule procedure, in this case, will have a varchar2 parameter...
{ "language": "en", "url": "https://stackoverflow.com/questions/7515743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Aspect Oriented Programming with LLVM Is there some way to integrate aspects into LLVM-bytecode? A: If you mean an existing way, I haven't seen anything that's stable/in production, but there are a number of papers, for example: http://www.cs.rochester.edu/meetings/TRANSACT07/papers/felber.pdf http://llvm.org/pubs/2005-03-14-ACP4IS-AspectsKernel.pdf Your best bet would be to find an LLVM-supported language you're interested in, then look for projects that have an AOP framework for that language. Some are pre-compilers, which would work "as-is" (assuming you can run whatever the pre-compiler is written in). Frameworks that directly manipulate compiler output would have to be modified to operate on LLVM code. The general answer is "of course"--any system that allows access to generated code or the compilation process will support aspects, it's just a matter of how much effort you want to put in to it. LLVM has great tools for poking at bytecode, which IMO make things like AOP a lot more fun to play with.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use the sitemap content element to load content of the referenced pages I use the sitemap content element so that the editor can explicitly reference to individual pages in my page tree. Of course those pages do contain content elements (Textpic, Media, all the good stuff...) in their "normal" section. I need advice on how to modify the sitemap content element that it will output the content of the referenced pages. I know there is already a plugin called "kb_sitemap" which basicaley does this job... but it does not handle the output of images or media (flash-, quicktime movies..) elements which is absolute necessary. The rendering relevant stuff is handled by Css Styled Content (CSC) which is necassary for me because it renders the media content element. A: Do you use templavoila ? Ok, go to page properties -> General tab (bottom part of the tab) and then you'll find all containers that possibly contain CEs, click to the lil folder icon and you may select content elements from any other page. EDIT: added screenshot, page properties... Note, showcase, maincontent, right content are just my names for my TV elements, could of course be name differently.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: System.IO.IOException ErrorCodes So I'm getting the following error when trying to print to a Zebra printer from my web application: Type : System.IO.IOException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Message : Printer is \172.16.0.244\Zebra2844. Error code is: 5 Can anybody provide some insight as to what the "Error code is: 5" represents? (Googling so far has yet to yield anything relevent) The offending error doesn't happen when I run the web app locally from my machine, so I'm guessing that either the server the web app is hosted on either can't resolve the IP, or its a permission issue, or something like that. Ideally, i'd like to confirm that it's the case if possible. Anyone have any ideas/suggestions? A: It's a Windows error code. System error codes In the case of error 5, it's an Access Denied error. Which is probably in your stack trace somewhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iphone tableview scrolling issue I have a tableview with imageviews and textviews in each cell. When my view is loaded one of the textviews is invisible. But when I start scrolling the textview appears, so that my view looks as it is supposed to look. Does anyone know why this is happening? P.S. I have read about reusing cells when scrolling so I have been very careful to construct my cells correctly. A: Without code, no one can give you a exact answer. But for a guess.... Is your data is getting populated after your table call cellForRowAtIndexPath? When the cell populates the first time, no data, so the cell is in it's unformatted state. By the time you can interact with the table and scroll it off and on screen (which calls cellForRowAtIndexPath again), the data has been populated and so the cell looks as expected. You can test this by putting a breakpoint in your cellForRowAtIndexPath method and check to see if your data objects are initialized or still set to nil.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to have hash of list in perl Sorry for this syntax question. I fail to find the solution. I want to have an array of hashs in perl, each of them has string and array. I'm trying to write the following code: use strict; my @arr = ( { name => "aaa" , values => ("a1","a2") }, { name => "bbb" , values => ("b1","b2","b3") } ); foreach $a (@arr) { my @cur_values = @{$a->{values}}; print("values of $a->{name} = @cur_values\n"); }; But this does not work for me. I get compilation error and warning (using perl -w) Odd number of elements in anonymous hash at a.pl line 2. Can't use string ("a1") as an ARRAY ref while "strict refs" in use at a.pl line 9. A: I want to have an array of hashs in perl You can't. Arrays only contain scalars in Perl. However, {} will create a hashref, which is a scalar and is fine. But this: { name => "aaa" , values => ("a1","a2") } means the same as: { name => "aaa" , values => "a1", "a2" }, You want an arrayref (which is a scalar), not a list for the value. { name => "aaa" , values => ["a1","a2"] } A: Try the following: use strict; my @arr = ( { name => "aaa" , values => ["a1","a2"] }, { name => "bbb" , values => ["b1","b2","b3"] } ); foreach $a (@arr) { my @cur_values = @{$a->{values}}; print("values of $a->{name}: "); foreach $b (@cur_values){ print $b . ", " } print "\n"; }; You just needed to use square brackets when defining your array on lines 3 and 4. A: my @arr = ( { name => "aaa" , values => ["a1","a2"] }, { name => "bbb" , values => ["b1","b2","b3"] } ); Lists ( made with ()) will get flattened. Arrayrefs ([]) won't. See perldoc perlreftut for more. Also, avoid using $a and $b as variable names as they are intended for special use inside sort blocks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: MSAccess VBA code won't open Excel sheet if Excel is already running When I open excel in MS Access through the following VBA code: Set objApp = GetObject(, "Excel.Application") Set objApp = CreateObject("Excel.Application") objApp.Visible = True Set wb = objApp.Workbooks.Open("\\bk00sql0002\D_Root\Pre-Manufacturing\Excel\CommitmentLetter.xls", True, False) It will not open if the Excel Application is already running. I need to first close the already running Excel Application then I can run the above code and it will open Excel. How do I get Excel to open even if it is already running? Thanks! A: Something like this: On Error Resume Next Set objApp = GetObject(, "Excel.Application") Do While Not objApp Is Nothing objApp.Quit Set objApp = GetObject(, "Excel.Application") Loop On Error GoTo 0 Set objApp = CreateObject("Excel.Application") You probably also need to handle the case when Excel won't quit. UPDATE To use the existing running instance (rather than kill it): On Error Resume Next Set objApp = GetObject(, "Excel.Application") On Error GoTo 0 If objApp Is Nothing Then Set objApp = CreateObject("Excel.Application") End if
{ "language": "en", "url": "https://stackoverflow.com/questions/7515762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Launch gallery with Images and Videos get back the selected image/video - Android I know how to launch default gallery with Images and get back the selected image URI. Now I am looking for how to launch default gallery with Images and Video displaying together and get back the selected image/video uri back to my application. Is this possible with default gallery app? Thanks A: check out this post Android Gallery (view) video (also thumbnail issues) i have used the gallery but only with images. i would imagine though they are all just drawables (meaning putting a video in the array might work) but i really dont know without testing. the only other thing is how many videos? if there are to many your apk will be huge. the way i did videos in my app was to separate them out and use intents but you could also keep track of where you are in the gallery and when u hit the spot where the vids should be fire the intent then after the vid is watched come back to the gallery.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to trigger onclick code after refresh when the state is retained using PHP sessions I'm using php session variables to retain page state, as in the example below, it's to maintain the fact that a element has been clicked and receives a new class. The class is removed later if it is clicked a second time. However I am also setting a global variable so that my client side "knows" the state and executing some other code that affect other elements on the page elsewhere (highlights them). This code uses the "this" of the clicked element to know how to highlight the other elements. <==== this is the important bit. $("listRow").click(function(){ if (globalVariable == "someClass") { // clean global globalVariable = " "; /* call a server side script via ajax to unset php session variable */ }else{ /* call a server side script via ajax to create a php session variable, later used on page refresh to retain page state*/ // also set a global js variable for use elsewhere globalVariable = "someClass"; }; $(this).toggleClass(".someClass"); // alot of code to do something to other elements on the page using some data that is specifically available in this element }); Now imagine this normal scenario: * *User clicks listRow triggering the code. // everything fine so far *User refreshes the page : listRow gets the class it needs BUT.... none of the other elements get highlighted. This happens because the listRow hasn't been clicked, and I get this. So what I want to do is create a small function that contains the code to highlight the other page elements. I have a number of preconditions: All the javascript including global variables are contained in external js files. It is not allowed to put raw js into the markup. i.e. the limitation is that I cannot declare a global variable in the and then use php to populate it from the session variable. I think that I can identify the fact that the item has been affected by php by doing the following. I say I think because I'm not sure if this is asking the question "if any element in the listRow..." or if the expression can identify the specific element somehow. function mySelfStarter() { if ($("listRow").hasClass("someClass")) { // some code }; }; I know I can simply cause the function to execute on refresh like this somewhere in the document onload: mySelfStarter(); What I want to do is find the element that has the class someClassand then find the id and then use this id to set both the global variable and the highlighting of other non- related elements. And this all has to be client side code. Something like: if ($("listRow").hasClass("someClass")) { // find the element that has the class "someclass" // get the id of this element // do something with id }; newly served page before click <div id="listWrapper" class="wrapper"> <div id="value1" class="listRow"></div> <div id="value2" class="listRow"></div> <div id="value3" class="listRow"></div> <div id="value4" class="listRow"></div> </div> after click <div id="listWrapper" class="wrapper"> <div id="value1" class="listRow"></div> <div id="value2" class="listRow someClass"></div> <div id="value3" class="listRow"></div> <div id="value4" class="listRow"></div> </div> after page refresh <div id="listWrapper" class="wrapper"> <div id="value1" class="listRow"></div> <div id="value2" class="listRow someClass"></div> <div id="value3" class="listRow"></div> <div id="value4" class="listRow"></div> </div> A: I'm not sure I follow, but if you're saving the state on your php session, you can check for that before rendering the page and if the session says the element was clicked, then also render a small js script that will trigger the click event on your element. That way, you get all the side efects you need, just as if the user had clicked the element. You can trigger a click event by doing something like: $("#element").trigger("click"); Edit with the final solution How about this: $("listRow.someClass").each(function(){ // - this: Is the element with the class // - $(this).attr("id"): Is the ID of that element // do something with id }); How about now? BTW, doing $("listRow") won't probably find anything, since you're telling JQuery to look for a tag called "listRow", are you sure you're not missing a "." or a "#" there?
{ "language": "en", "url": "https://stackoverflow.com/questions/7515774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: socket.io reconnecting when connecting remotely I copied and deployed the socket.io's demo code (found at http://socket.io/ on the front page). I have a server.js and a index.html with this demo code When I run 'node server.js' locally, and then open index.html locally, everything works fine and I connect to the server. The server outputs: info - handshake authorized XXXXXXXXX However, when I put the server.js on a remote server, but open index.html locally, It keeps reconnecting. The server outputs: info - handshake authorized XXXXXXXXX info - handshake authorized XXXXXXXXX info - handshake authorized XXXXXXXXX info - handshake authorized XXXXXXXXX and so on. I've had a hard time finding any info on this. How am I supposed to build an application that initializes when a client connects, if it's being constantly reconnected? This same reconnect pattern occurs when I run server.js locally, and connect to it from a remote server. Thanks for your help! A: Have you updated the url of the socket you want to connect to on the client-side? var socket = io.connect('http://domain.com:port');
{ "language": "en", "url": "https://stackoverflow.com/questions/7515775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binding a combobox selectedvalue in Grid I have a combobox as a column in a gridview and it is bound to a local property like so: <ComboBox Name="cboMetaDataTypes" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=MetaDataTypes}" DisplayMemberPath="Value" SelectedValuePath="Key"/> The Source MetaDataTypes is a List of KeyValuePairs where the Value property is displayed as you can see. Now I am stuck. I want to bind the selected value to the Key that matches the Key of the Column. And I want the selected value to be bound to a local property. I tried a lot but I cannot make it happen. Can anyone give me directions? Thank You. A: If I'm understanding what you want, you want to bind the SelectedValue property to a property in your Window's class (as defined in the MyWindow.xaml.cs file). The best way to do that, in my experience, is to assign your window class a Name like this: <Window x:Name="myWindow" ... > And then you can do the following with your ComboBox <ComboBox Name="cboMetaDataTypes" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=MetaDataTypes}" DisplayMemberPath="Value" SelectedValuePath="Key" SelectedValue="{Binding ElementName=myWindow, Path=myProperty }" /> You may need to define your myProperty as a dependency property to get two way data-binding to work properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get the latest object using Castle ActiveRecord I've got a Table of OrderDetails objects and I'd like to get OrderNumber of the latest Order in the database i.e. the Order with the highest OrderDetailsID. In SQL I can do the following: select Top 1 OrderNumber from orderdetails order by OrderDetailsID desc How would I go about getting the same thing using ActiveRecord, what Criteria should I be specifying in FindOne(...) call? A: ActiveRecord.AsQueryable<OrderDetails>() .OrderByDescending(o => o.OrderDetailsID).First().OrderNumber I can't make it any shorter :) you could also do: FindFirst(typeof (OrderDetails), new[] {NHibernate.Criterion.Order.Desc("OrderDetailsID")}, null).OrderNumber;
{ "language": "en", "url": "https://stackoverflow.com/questions/7515781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image thumbnail from web for a listview So i have a listview with 10 rows, for each row i have to load a image thumbnail from different url's, is there a way to do this with out downloading all 10 big images and resizing them, i just need the thumbnails from those pictures, and downloading all pictures will take a lot of time and memory, any ideas ? =\ Thanks a lot for all of your answers, great ideas. A: 1, u can download those images then create a thumbnail from that bitmaps, then store it in SD card saved_thumbs 2, on the server side u can create the thumbs with php, then download that images A: You have not much choices: * *You have local copies of the images in your app resource *You need to load the images, scale them yourself cache tem and update your listview when you did that *To decrease amount of traffic and memory use you could prescale those pictures, provide those thumbnails besides the original picture, and request that first *(I don't think that there is something like that for free, but would be great) Use a web API which rescales the picture and returns the thumbnails. This would reduce the traffic but probably not the request time. (Maybe setup a private web service which does that for you, maybe php) A: Here's what you need to do: * *Download the images to a Bitmap. *get access to your applications cache and write the bitmaps to the cache. *Each time the activity is brought into view check the cache for the images, if they are there get them from cache. if not download them. These are the steps you need to take. Let me know if you have any questions or problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fluent NHibernate Automappings generating 2 foreign keys for 1 relationship I have this setup (condensed for brevity) Class Employee virtual IList<ChecklistItem> HasInitialed { get; private set; } Class ChecklistItem virtual Employee InitialedBy { get; set; } When this is generated I get these tables Employee Id ChecklistItem Id InitialedBy_id <---- Employee_id <---- The ChecklistItem has 2 foreign keys for Employee, I'm assuming Employee_id to map ChecklistItem.Employee and InitialedBy_id to map ChecklistItem.InitialedBy. How can I tell NHibernate that this is the same bidirectional relationship and only requires 1 foreign key? I'm kind of new to NHibernate in general, but this seems like it should be pretty standard. This is what I've come up with when I'm configuring my database to generate the right schema, is it right? .Override<Employee>(map => map .HasMany<ChecklistItem>(x => x.HasInitialed) .KeyColumn("InitialedBy_id")) If that is right, is there a way to choose KeyColumn based on the ChecklistItem's property name (a lambda)? A: as a convention for all hasmanies class HasManyConvention : IHasManyConvention { public void Apply(IOneToManyCollectionInstance instance) { instance.Key.Column(((ICollectionInspector)instance).Name + "_id"); } } or only for this class HasManyConvention : IHasManyConvention, IHasManyConventionAcceptance { public void Accept(IAcceptanceCriteria<IOneToManyCollectionInspector> criteria) { criteria.Expect(x => x.Name == "HasInitialed"); // and/or entity type } public void Apply(IOneToManyCollectionInstance instance) { instance.Key.Column(((ICollectionInspector)instance).Name + "_id"); } } convention for Manytoone/References class ReferenceConvention : IReferenceConvention { public void Apply(IManyToOneInstance instance) { instance.Column(instance.Name + "_id"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7515785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redefining and merging two tables in R or SAS I have two tables (matrix) of same dimensions, one contains correlation coefficients and other with p values. I want to combine them into one table. For example let's say I have correlation coefficient between variable A1 and A2 of 0.75 in table 1 and p value of 0.045 in table 2. Now in my combined table 3, I want to use: condition1 for table 1: if a coefficient value in a cell of table 1 is less than 0.4 then "+", 0.4 <= coefficient <0.7 then "++" else "+++", condition2 for table 2: if a pvalue in a cell of table 2 is less than 0.01 then "+++", 0.01 <= pvalue < .05 then "++" else "+". Thus corresponding cell value for A1 and A2 in table 3 should look like: +++/++ where "+++" correspond to table 1 value of 0.75 and ++ correspond to table 2 p value of 0.045 and "/" is just a separator. I would like to do this either is SAS or R. A: Here is a solution with R First, create some dummy data to work with corr <- matrix(runif(16),4,4) ps <- matrix(runif(16)^5,4,4) Each matrix can be formatted separately. Note that this drops them down to vectors. The matrix structure will be restored after pasting together the two formatted versions. corr.fmt <- cut(corr, c(0, 0.4, 0.7, 1), labels=c("+","++","+++")) ps.fmt <- cut(ps, c(0, 0.01, 0.05, 1), labels=c("+++","++","+")) res <- matrix(paste(corr.fmt, ps.fmt, sep="/"), nrow(corr), ncol(corr)) This could be combined into a single statement if you want to put the transformations inline res <- matrix(paste(cut(corr, c(0, 0.4, 0.7, 1), labels=c("+","++","+++")), cut(ps, c(0, 0.01, 0.05, 1), labels=c("+++","++","+")), sep="/"), nrow(corr), ncol(corr))
{ "language": "en", "url": "https://stackoverflow.com/questions/7515786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: differences in compiling normal/template functions, c++ I read this in a tutorial: It turns out that C++ does not compile the template function directly. Instead, at compile time, when the compiler encounters a call to a template function, it replicates the template function and replaces the template type parameters with actual types I though it was the same with regular (non-templated) functions. I am trying to understand how the compiler treats both kinds of function, and where is the main difference. Thanks! A: I though it was the same with regular (non-templated) functions. No. Most compilers, when compiling a (non-static) function, will just emit object code for that function (which they might later change when doing whole-program optimization, but not all compilers do that). This is not done for template functions, since (a) those may not contain enough information to emit all of the object code and (b) they may accept an infinite number of possible values for their template arguments, so the compiler would have to compile an infinite number of functions. Consider template <typename T> T add1(T x) { return x + 1; } This template function can be applied to any type T for which operator+ is defined and can take an int argument, and since you can make such types yourself with operator overloading, there's a potentially infinite number of them. Instead, at compile time, when the compiler encounters a call to a template function, it replicates the template function and replaces the template type parameters with actual types ... but the linker will notice that, if you use add1 on the same type T (say, float) in multiple modules, the compiled object code is the same in every case, and it will remove the duplicates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: top 10 from sql server I want to retrieve the ID and DATE fields for the top 10 upcoming from my table. Without the ID the query below works: select top 10 MAX(FromDate) as upcomingdates from TM_Schedule group by(FromDate) But if I add the ID, it throws an error: select top 10 MAX(FromDate) as upcomingdates, ID from TM_Schedule group by(FromDate) A: I don't know your data, but it looks like you can accomplish that without GROUP BY or MAX. Try this: SELECT TOP 10 ID, FromDate FROM TM_Schedule ORDER BY FromDate DESC It should work, unless you have multiple FromDate values for the same ID. A: Select FromDate as upcomingdates, ID from TM_Schedule WHERE FromDate IN ( select top 10 MAX(FromDate)as upcomingdates from TM_Schedule group by(FromDate) ) ORDER BY FromDate A: Do this: select top 10 MAX(FromDate)as upcomingdates, ID from TM_Schedule group by(FromDate), ID You need to group by ID also
{ "language": "en", "url": "https://stackoverflow.com/questions/7515791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server session What is considered a session in sql server. I'm trying to use sp_getapplock and the documentation states: Locks placed on a resource are associated with either the current transaction or the current session. Locks associated with the current transaction are released when the transaction commits or rolls back. Locks associated with the session are released when the session is logged out. When the server shuts down for any reason, all locks are released. 'Locks associated with the session are released when the session is logged out'. I need to know what is considered a session. connecting using management studio is a session to the database; using asp.net to connect to sql server also creates a session. What if I use ADO .net and connection pool, is every connection in the connection pool is considered to be a different session? A: if I use ADO .net and connection pool, is every connection in the connection pool is considered to be a different session? Sort of. Just about every time you open/close a new connection, that's a single session. However, one of the "features" of the connection pool is that it doesn't always open/close on command, and when it sees you're opening and closing a bunch of connections repeatedly it will use a single connection behind the scenes, which I believe results in a single session on sql server. A: With connection pooling, notice that sp_reset_connection is called in between each reassignment of the reused connection. This SO Post covers the cleanup done by sp_reset_connection in detail. Edit In the context of your question, sp_reset_connection "Frees acquired locks". A: The @LockOwner of sp_getapplock refers to when it is released: * *"Session": at session end *"Transaction": on COMMIT or ROLLBACK Basically, a SPID in sys.sysprocesses is a "session"
{ "language": "en", "url": "https://stackoverflow.com/questions/7515797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Problem at marshalling a standard C++ string to a C# string I'm writing a wrapper for a DLL that manages an OCR device. The DLL has a method whose signature resembles the following: unsigned long aMethod(char **firstParameter, char **secondParameter); aMethod returns string pointers to all parameters. I wrote this signature in C#... it is almost functional: [DllImport(aDll.dll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] static unsafe extern ulong aMethod(ref IntPtr firstParameter, ref IntPtr secondParameter); I do the invocation in this way: aMethod(ref firstParameter, ref secondParameter); Marshalling and unmarshalling related to the strings is done as here: Marshal.PtrToStringAnsi(firstParameter) Marshal.PtrToStringAnsi(secondParameter) Obviously, this marshalling has been selected based on DLL's API conventions. Now, the marshalling process has a problem. Suppose that the device has an input with this string "abcdefg". If I use the DLL from pure C++ code I get "abcdefg" as an output. But, if I use the C# signature I´ve wroted, the string loses its first character and looks like "bcdefg". What´s going wrong? How can I fix the C# method? A: Assuming those parameters are given to you from the application, why not simply use: [DllImport(aDll.dll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] static unsafe extern uint aMethod(out string firstParameter, out string secondParameter); If you want them to go both ways, you could use a ref StringBuilder with a pre-allocated size (you should also use this if the C function expects you to manage your own memory -- you didn't say). A: Try changing the CharSet to CharSet = CharSet.Ansi
{ "language": "en", "url": "https://stackoverflow.com/questions/7515798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TeXlipse error while building workspace We seem to have a strange problem at the moment with TeXlipse. I have just recently setup a project on my machine with folders that contain chapters of a book. I then put everything under source control and earlier today tried to build the same project on another machine. When I first open the project and save it everything builds ok and I have no problems. However once I add a new latex file in the project in that machine I get the following dialog box: Building workspace has encountered a problem Errors occured during the build Errors running builder 'Latex Builder' on project. If I do the same things on my machine I get no errors. Does anyone have an idea as to why we get the errors above on one machine and not other? Eclipse installation is the same, we have the same version of MikTex 2.9 and the same packages. The error that comes up is: Errors running builder 'Latex Builder' on project 'doc_help'. Resource '/doc_help/tmp/main.aux' already exists. Resource '/doc_help/tmp/main.aux' already exists. Thanks in advance. A: I got similar problems in two cases: once, where the folder for temporary files was shared in SVN, and then Texlipse caused some really nasty things during building (it first copies everything from tmp to src; then after building moves the stuff back). So, make sure, that temporary files are not shared through source control. For the second issue, I don't know what has caused it. I copied the project in another workspace, where I got similar errors. If instead of copying locally, I did another checkout (after removing the old files entirely), the builder seemed to be working. A: Thanks to the answer of zoltan I've resolved my issue. I am posting for who puts his project with texlipse under versioning by dropbox and wants to use it while modifying tex files. Basically I went to project properties and I deleted temp directory name from input field labeled Directory for Latex temporary files: Now it doesn't give me again errors and builds successfully. Hope my answer is not inappropriate and it can help somebody who want to use Dropbox and not use only local directories. A: Maybe this error occured because of "cleaning" your project. Running "Project/Clean" removes the tmp folder. Running "Project / Build Project" doesn't restore that folder. Therefore this error message is thrown. The tmp folder is automatically generated (once) when a new project is created.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Core data bug refers to nonexistent core data attribute of reflexive many-to-many relationship I am experiencing a perplexing Core Data bug, in which I receive the following error message when trying to save some data: CoreData: error: (1) I/O error for database at /var/mobile/Applications/5D3C0F3C-E097-43BF-887B-2870B1148226/Documents/Database.sqlite. SQLite error code:1, 'table Z_1RELATEDCARDS has no column named FOK_REFLEXIVE' Core Data: annotation: -executeRequest: encountered exception = I/O error for database at /var/mobile/Applications/5D3C0F3C-E097-43BF-887B-2870B1148226/Documents/Database.sqlite. SQLite error code:1, 'table Z_1RELATEDCARDS has no column named FOK_REFLEXIVE' with userInfo = { NSFilePath = "/var/mobile/Applications/5D3C0F3C-E097-43BF-887B-2870B1148226/Documents/Database.sqlite"; NSSQLiteErrorDomain = 1; } For some context: there is no column "reflexive" in my data model. I have an entity, Cards, which has an attribute, relatedCards, that is a many-to-many relationship between Card items. I am quite confused as to what this error is referring to, and any assistance would be greatly appreciated. UPDATE As per a great suggestion in the comments, I ran the app in the iOS Simulator with the argument -com.apple.CoreData.SQLDebug 3 and received the following response: CoreData: annotation: Connecting to sqlite database file at "/Users/jason/Library/Application Support/iPhone Simulator/5.0/Applications/4EE6D378-A946-4EBF-9849-F7D2E58F2776/Documents/Database.sqlite" CoreData: sql: pragma cache_size=200 CoreData: sql: BEGIN EXCLUSIVE CoreData: sql: UPDATE ZCARD SET ZDATEMODIFIED = ?, Z_OPT = ? WHERE Z_PK = ? AND Z_OPT = ? CoreData: details: SQLite bind[0] = "338478797.092588" CoreData: details: SQLite bind[1] = (int64)7 CoreData: details: SQLite bind[2] = (int64)119 CoreData: details: SQLite bind[3] = (int64)6 CoreData: sql: UPDATE ZCARD SET ZDATEMODIFIED = ?, Z_OPT = ? WHERE Z_PK = ? AND Z_OPT = ? CoreData: details: SQLite bind[0] = "338478797.092577" CoreData: details: SQLite bind[1] = (int64)7 CoreData: details: SQLite bind[2] = (int64)100 CoreData: details: SQLite bind[3] = (int64)6 CoreData: sql: INSERT OR REPLACE INTO Z_1RELATEDCARDS(Z_1RELATEDCARDS, REFLEXIVE, FOK_REFLEXIVE) VALUES (119, 100, 0) CoreData: annotation: Disconnecting from sqlite database due to an error. CoreData: error: (1) I/O error for database at /Users/jason/Library/Application Support/iPhone Simulator/5.0/Applications/4EE6D378-A946-4EBF-9849-F7D2E58F2776/Documents/Database.sqlite. SQLite error code:1, 'table Z_1RELATEDCARDS has no column named FOK_REFLEXIVE' [Switching to process 45402 thread 0x15503] For a little context, I have modified the Card table to keep track of when it is modified. That's what's going on in the upper portion of the debug output. However, the key line in the debug output is clearly the fourth from the bottom: CoreData: sql: INSERT OR REPLACE INTO Z_1RELATEDCARDS(Z_1RELATEDCARDS, REFLEXIVE, FOK_REFLEXIVE) VALUES (119, 100, 0) I went into my SQLite database and checked, there is no column FOK_REFLEXIVE in this table. The schema for this table is: CREATE TABLE Z_1RELATEDCARDS ( Z_1RELATEDCARDS INTEGER, REFLEXIVE INTEGER, PRIMARY KEY (Z_1RELATEDCARDS, REFLEXIVE) ); So clearly, Core Data is trying to insert data into a field which does not exist. What am I supposed to do with this? Update: This is also an issue reported by users. I can't update my app and just tell users "oh well you need to trash your data store and start over." That won't go over very well unfortunately even if it were the cause of this error. A: [Update: Based on the authors comments to this answer, this is not the cause. The issue affects end uses and he does not modify the sqlite file. I'll leave this answer here just for future reference. --TechZen] The reflex here is probably a reflexive join in SQL (also called a self join.) The REFLEXIVE in the SQLDebug output is probably the command to create a join table or similar construct. In this case, your Card entity probably has a relationship to itself Core Data uses a reflexive sql relationship to persist that entity relationship. You say that: I have modified the Card table to keep track of when it is modified… … from which I take it that you have modified the sqlite store file directly. That usually causes problems, including corruption. Core Data uses a proprietary sql schema which is undocumented. Any changes to it or even the sqllite runtime can cause problems. I think the most likely issue is that the store file is corrupt. You very seldom get SQL errors from Core Data objective-c code and when you do, its almost always related to a predicate that SQL can't run. Start over with a clean version of your database without any tinkering and see if it works. A: I had just run into this issue as well. It is an issue for you and your customers. Much more so if your app is on the market. There appears to be an issue with the way core data aliases several many-to-many relationships contained in one entity. Look AT THIS POST and THIS ONE AS WELL. The reported solution in the first hyperlink did not solve my issue. To mitigate, I made a container entity to allow for my many-to-many to look like many-to-one-to-many. But, if our app is already on the market, you would need to migrate to keep user data. It seems like you are getting your exception at the start. If this isn't the case, consider in-memory filtering if you're failing on a predicate, and you are not getting the exception on your root most entity. It also appears that this is only an issue sometimes. I have several entities containing multiple many-to-many relationships. There was only one entity that had this issue. The problem entity had two many-to-many relationships, and one to-one relationship; all of which were optional. The to-one delete rule was cascade, both to-many's: nullify. Another entity that does not cause this issue has relationships: * *1 one-to-many relationship, optional, cascade *2 to-one relationships, optional, cascade *3 many-to-many relationships, optional, nullify What's the difference??? I'm not sure. I'm tempted to create entity containers for these many-to-many's as well to avoid your issue. A: I think this is problem due to old .sqlite file, you need to remove old one by reseting device or simulator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I find the "least common part" among the paths on the same logical drive? My program has several paths to be watched, such as C:\XML C:\MyProg\Raw C:\MyProg\Subset\MTSAT C:\MyProg\Subset\GOESW D:\Dataset\Composite D:\Dataset\Global E:\Dataset\Mosaic I want to add 4 paths, namely C:\XML, C:\MyProg, D:\Dataset and E:\Dataset, to my CFolderWatch class instance for the purpose of folder watching insetad of all 7 above-mentioned paths as long as its "Include Subdirectory" switch is set to TRUE. Suppose all paths of being watched have been added to a vector container. Therefore, my question is: How can I find the "least common part" among the paths on the same logical drive? Thank you in advance! Detailed explanation to my question: 1. I got some user-defined directories. 2. I want to these directories to be watched. 3. Before watching, I want to do some preparatory job, for example, find the common part among the path(s) on the same logical drive to avoid possibly adding so many paths to my watching class. For instance, if there are 3 paths on the logical drive C: as follows: C:\test\Data\R1, C:\test\Data\R2, and C:\test\Data\R3, the common path is "C:\test\Data". So, we should add "C:\test\Data" to the watching module, not the three paths. What I mean the common path here is that it has at least one level of directory. If one path has no common path with the others, just returns unchanged. 4. First thing first, the algorithm should handle different logical drive(s). That is to say, all paths must be classified on the basis of their respective drive letter. Then, find the common path among the passed paths on the same logical drive letter. A: A two-step algorithm: * *Partition your directories by drive letter and first directory level. *For each partition, keep the longest prefix. The longest prefix per partition can be easily obtained by counting how many prefix characters each directory has in common with its next sibling, and keeping the minimum. Using mismatch, for example. A: As JB said I think this is a two step solution and I have tried some basic coding here in C#. If you want it in java I suppose you must be knowing how to use it :) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace So_Try1 { class Program { public static int nthOccurrence(String str, char c, int n) { int pos = str.IndexOf(c, 0); while (n-- > 0 && pos != -1) pos = str.IndexOf(c, pos + 1); return pos; } static void Main(string[] args) { List<String> pathString = new List<string>(); pathString.Add("C:\\XML"); pathString.Add("C:\\MyProg\\Raw"); pathString.Add("C:\\MyProg\\Subset\\MTSAT"); pathString.Add("C:\\MyProg\\Subset\\GOESW"); pathString.Add("D:\\Folder2\\Mosaic"); pathString.Add("D:\\Folder2\\Mosaic\\SubFolder"); pathString.Add("D:\\Dataset\\Composite"); pathString.Add("D:\\Dataset\\Global"); pathString.Add("F:\\Folder1\\Mosaic"); pathString.Add("H:\\Folder2\\Mosaic"); pathString.Add("D:\\Folder2\\Mosaic"); pathString.Add("D:\\Folder2\\Mosaic\\SubFolder"); pathString.Add("E:\\Dataset\\Mosaic"); Dictionary<String, int> PathDict = new Dictionary<string,int>(); foreach (String str in pathString) { int count = 0; foreach (char c in str) if (c == '\\') count++; while (count > 0) { int index = nthOccurrence(str, '\\', count); String tempPath; if (index < 0) { //Console.WriteLine(str); tempPath = str; } else { //Console.WriteLine(str.Substring(0,index)); tempPath = str.Substring(0, index); } if (PathDict.ContainsKey(tempPath)) { PathDict[tempPath]++; } else { foreach (var keys in PathDict.Keys) { if (tempPath.IndexOf(keys) > 0) { PathDict[keys]++; } } PathDict.Add(tempPath, 1); } count--; } } foreach(var keyValue in PathDict){ if(keyValue.Value > 1) Console.WriteLine(keyValue.Key); /*Console.WriteLine(keyValue.Key + " - " + keyValue.Value);*/ } } } } This is a very simple program that assumes that you have your paths in a string and checking for duplicates. If for a large no.of paths you must adopt a much more efficient solution. A: There's no algorithm; you're using inconsistent logic. Consider just the set * *C:\XML *C:\MyProg\Raw *C:\MyProg\Subset\MTSAT *C:\MyProg\Subset\GOESW There are at least 4 different solutions: * *C:\ *C:\XML and C:\MyProg\ *C:\XML , C:\MyProg\Raw and C:\MyProg\Subset *C:\XML , C:\MyProg\Raw, C:\MyProg\Subset\MTSAT and C:\MyProg\Subset\GOESW You fail to explain why 2. is the correct solution. It is possible to write an algorithm that finds solution N-1 given solution N as input, so you can get from the input (4) to (1) in three steps. But we don't understand why we should stop at (2).
{ "language": "en", "url": "https://stackoverflow.com/questions/7515807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: About -(NSDictionary)dictionaryWithObjectsAndKeys: and I got a really interesting question. Inside one of my classes I declared a very simple instance method -(NSDictionary)dictionary; that is implemented in this way: - (NSDictionary *)dictionary { return [NSDictionary dictionaryWithObjectsAndKeys: self.userID, @"id", self.userName, @"name", self.userSurname, @"sName", self.userNickname, @"nName", self.userPassword, @"pwd", [NSNumber numberWithDouble:[self.userBirthday timeIntervalSince1970] * 1000], @"birthday", self.userSex, @"sex", self.userEmail, @"email", self.userLanguage, @"locale", [NSNumber numberWithLongLong:self.userCoin], @"coin", self.userRate, @"rate", [NSNumber numberWithDouble:self.userCoordinate.latitude], @"lat", [NSNumber numberWithDouble:self.userCoordinate.longitude], @"lon", self.userPlaces, @"userPlaces", nil]; } with this method declared there are no @"userPlaces" key inside my return dictionary (self.userPlace is obviously valorized and full of objects). So I changed a little bit my method like this: - (NSDictionary *)dictionary { NSMutableDictionary *toReturn = [NSMutableDictionary dictionary]; [toReturn setValue:self.userID forKey:@"id"]; [toReturn setValue:self.userName forKey:@"name"]; [toReturn setValue:self.userSurname forKey:@"sName"]; [toReturn setValue:self.userNickname forKey:@"nName"]; [toReturn setValue:self.userPassword forKey:@"pwd"]; [toReturn setValue:[NSNumber numberWithDouble:[self.userBirthday timeIntervalSince1970] * 1000] forKey:@"birthday"]; [toReturn setValue:self.userSex forKey:@"sex"]; [toReturn setValue:self.userEmail forKey:@"email"]; [toReturn setValue:self.userLanguage forKey:@"locale"]; [toReturn setValue:[NSNumber numberWithLongLong:self.userCoin] forKey:@"coin"]; [toReturn setValue:self.userRate forKey:@"rate"]; [toReturn setValue:[NSNumber numberWithDouble:self.userCoordinate.latitude] forKey:@"lat"]; [toReturn setValue:[NSNumber numberWithDouble:self.userCoordinate.longitude] forKey:@"lon"]; [toReturn setValue:self.userPlaces forKey:@"userPlaces"]; return [NSDictionary dictionaryWithDictionary:toReturn]; } All the key are now present inside the output dictionary!!! This problem drove me crazy to understand but my question is ... There is any reason couse the second method works better then the first one?? I didn't find a reason for it. A: The something similar to the code below solved my problem with the same exception: (NSMutableDictionary *)dictionary { return [NSMutableDictionary dictionaryWithObjectsAndKeys: self.userID, @"id", self.userName, @"name", self.userSurname, @"sName", self.userNickname, @"nName", self.userPassword, @"pwd", [NSNumber numberWithDouble:[self.userBirthday timeIntervalSince1970] * 1000], @"birthday", self.userSex, @"sex", self.userEmail, @"email", self.userLanguage, @"locale", [NSNumber numberWithLongLong:self.userCoin], @"coin", self.userRate, @"rate", [NSNumber numberWithDouble:self.userCoordinate.latitude], @"lat", [NSNumber numberWithDouble:self.userCoordinate.longitude], @"lon", self.userPlaces, @"userPlaces", nil]; } A: [NSDictionary dictionaryWithObjectsAndKeys: stops to add objects when it finds a nil value. So most likely one of the objects you try to add in the first code is nil.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: How to prevent UI from redrawing every control one by one In my user control I perform a lengthy operation. In order to prevent users from clicking the UI, I show a progress bar and I disable the whole UI, like this: this.Enabled = false; ShowProgressBar(); DoLengthyOperation(); RemoveProgressBar(); this.Enabled = true; This works OK. However, my user control has many other controls on it, which also have controls inside them, which also have controls inside them,... etc. The this.Enabled = false call thus disables many many controls. This is intentional. But the problem I have is that you can actually see the UI disabling every control one by one. It goes pretty fast but since there are so many controls, you can actually see it running through all the controls. This does not look professional, it makes the screen flicker and my eyes hurt. Is there a way so that I can prevent the UI from redrawing until all controls are disabled and then perform a single redrawing? I hope this is not a stupid question ;) Don't know if this is relevant: my controls are derived from DevExpress.XtraEditors.XtraUserControl. A: Have you tried the Form.SuspendLayout and Form.ResumeLayout? It seems like what you need. There is more information on the msdn site here. You call suspendlayout before you want to re-draw and then resume once you have disabled all the controls. this.SuspendLayout(); ShowProgressBar(); DoLengthyOperation(); RemoveProgressBar(); this.ResumeLayout(); If the progress bar is on the form, you will have to 'show' it before you suspend the layout. Sorry, I missed that. A: try this: this.Invalidate(); // Invalidate the whole window this.Enabled = false; this.Refresh(); // Redraw every invalidated part of the window, so everything A: None of the suggestion solutions seems to work. I think part of the problem is that I use DevExpress and every control does not directly contain its subcontrol, but uses LayoutControlGroups and LayoutControls and panels etc. The actual amount of controls used is thus a lot higher than the actual controls that you see on the screen and that need to be disabled. So I just added my own recursive function that disables only controls of certain types, in my case Buttons and Edit boxes. The rest is just ignored. Not only is this a lot faster, it also looks much nicer. No flickering at all any more. I think I'm going to use this solution, but I do appreciate the effort of everyone who put an answer or a comment here, thanks! Now I see that my question seems to be a duplicate of this one: How do I suspend painting for a control and its children? Haven't tried that solution tough. A: You can try and add double buffering to your controls. This will not stop the painting. However, it should help with the visual portion of your issue. System.Reflection.PropertyInfo aProp = typeof(System.Windows.Forms.Control).GetProperty("DoubleBuffered", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); aProp.SetValue(YourControlNameHere, true, null); Note: Most controls already have this set to true by default. Your usercontrol may not, so you can test to see if this helps or not. A: You can place controls into a container (call it groupControls), Turn the container's visible property to false, (have a splash screen appear or equivalent size container with "updating" or whatever become visible - call it groupUpdateSplash) update your controls turn off splash container visible and turn on your control container visible groupControls.visible = false groupUpdateSplash.visible = true /* update controls and everything */ groupUpdateSplash.visible = false groupControls.visible = true
{ "language": "en", "url": "https://stackoverflow.com/questions/7515810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What's the opposite of '!important' in CSS? I'm building a jQuery plugin that uses CSS styles to add colors and margins to nested DIV tags. Since I'd rather keep the plugin as a single file, my code adds these colors and margins directly as CSS attributes to the DIVs using jQuery's .css() method. (The values for these attributes can be customized when the plugin is initialized.) However, I also wanted to give users the power to style these DIVs using their own stylesheets, so I'm also adding classes to each group of DIVs (for which the names can also be customized). This seemed like the best way to provide the best of both worlds. The only drawback seems to be that inline style="..." attributes (generated by jQuery's .css() method) always override class styles set in the external stylesheet. I can, of course, use !important styles in the stylesheet, but doing this again and again is cumbersome. So: what I really want is a way to make the inline styles automatically take a lower priority than the external class styles, without having to make the external class styles !important. I have not read about such a thing. Any suggestions? (Or: is there another approach I should be taking to style my DIVs in the plugin?) A: What you might do is prepend a new style to the head of the page and then call the style in your script. Something like $("<style type='text/css'> .theStyle{ //WHATEVER} </style>").prepend("head"); Then you can use addClass in your script $("whatever").addClass("theStyle"); Because you are adding it as the first thing in the head, other stylesheets should override the styles. So your users could add a .theStyle rule to one of their .css files and it should work. EDIT To clarify based on @zzzzBov's comment below style is an internal stylesheet and the .css files I mentioned are external stylesheets The external will only take precedence if the specificity is greater. For this to happen, you need to continue to call your css in the script .theStyle and you need to have your users assign an element to that style, such as div.theStyle, which has greater specificity and will override the former. BTW: @Spudley is right about !important. A: What's the opposite of !important in CSS? There isn't an exact opposite, but there are lower precedence selectors. w3c spec defines the cascade, might as well read it. inline styles have highest precedence, and you're after a low-precedence style, you'll need to add CSS via a stylesheet or style element. Because you're using jQuery, adding a custom style element is very easy: $('<style type="text/css">.foo {color: #FF0000;}</style>').prependTo('head'); The issue you're then going to find is that a user who has specified .foo in a stylesheet will need a higher specificity to win out over the style element, so I'd recommend using an additional class for each element so that a user can override the defaults: .foo.override { color: #0000FF; } In all cases you're going to want to carefully pick your selectors to have the least specificity possible. A: In general, if you are considering using !important, then there's a good chance you should be thinking about tidying up your stylesheets. !important can be useful to force things to behave, but most of the time it is an indicator of overly-complex CSS. There isn't an opposite of !important (nor even the ability to assign levels of importance), but if there was, the same point would probably apply. CSS rules are applied in a very strict order of precedence, and if you follow the best practices of how to apply your CSS (ie style element names and class names in preference to IDs and inline styles) then it is usually possible to override things as required without resorting to !important. The only times I've found that I've actually needed !important have been where I've been working on a stylesheet which was layered on top of existing styles defined by a CMS template which I didn't have any control over. In your case, you are setting inline styles using jQuery. This is a perfectly good thing to do if you want to achieve spot-effects. However for performing general styling, with the possibility of overriding it, you would be better off if you defined those styles in your CSS, and used jQuery to add or remove the classname in order to apply those styles. This would enable you to apply the styles to groups of elements but still have overrides for them where required. Hope that helps. A: You can't do that. Inline styles will always take precedence over styles in your stylesheet. Using !important is the correct method for having your stylesheet styles take precedence over your inline styles. A: You could always have a conditional statement to see if the CSS has already been set, and if it has, don't set it again with jQuery. A: This is not possible. I'd suggest an extra option in your plugin for turning the styles on or off and only add the css based on that option. A: The way some plugins does it is supply a parameter that the developer can use to override the default class names. So that if they want to override your styles, they can supply maybe a prefix-parameter to make all classnames be prefix.yourdefaultclassname.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: How do I search for two strings on the same line in Eclipse? Mainly I want to search for all lines that contain XXX and YYY on the same line in Eclipse. What would be the correct search expression for that? A: This regex should comply with your request: (XXX.*YYY|YYY.*XXX) Used under File Search, checking Regular expression. A: Use XXX*YYY in file search option. This will mean that any characters can come in between XXX and YYY.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: C++: Is this a valid constant member function? I'm currently working on a c++ class. The purpose of the class is to do some http queries. You create an instance specifying * *destination url *some other parameters With this instance, you can call a method called "getChildren" which connects to the HTTP server, executes a query and returns a list of children. So basically, it looks similar to this: class HttpRequest { public: // omitted constructor, ... const std::list<Child> getChildren() { // do the http query // build a list return(list); } } The list which is returned by "getChildren" might change for each call - depending on other actions done on the HTTP server. Now what's your opinion: How shall I declare the method: * *const std::list<Child> getChildren(); *const std::list<Child> getChildren() const; It will compile in both ways, since "getChildren" doesn't modify HttpRequest. Thanks for your help, Uli A: * *const std::list<Child> getChildren(); *const std::list<Child> getChildren() const; It will compile in both ways, since "getChildren" doesn't modify HttpRequest. * *No, it will not compile both ways. (If it would, what would that difference be there for?) The second form is required to call getChildren() for const HttpRequest objects (or references or pointers): void f(const HttpRequest& req) { const std::list<Child>& list = req.getChildren(); // requires const // ... } This would require the trailing const. *The top-level const on the return type (const std::list<Child>) makes no difference at all. The returned object is an rvalue. All you can do with it is to make a copy or bind it to a const std::list<Child>& - no matter whether it's const or not. *You very likely do not want to copy such lists to be copied each time getChildren() is called, so you should return a reference: const std::list<Child>& getChildren() const; (Of course, if there is asynchrony involved, you might want to copy, rather than hand out references to a potentially asynchronously changing object.) *You can overload based on the trailing const. Given that, you could have two versions: one for changing the list and one for getting a const list reference: const std::list<Child>& getChildren() const; std::list<Child>& getChildren(); I wouldn't know whether this makes any sense in your case. A: My initial gut reaction here is that if it's hard to decide, we should look at the function in more detail. Also since the HttpRequest state isn't mutated, and since it may return a different value each time, perhaps the function shouldn't be a member at all. It seems that it might make more sense as a non-member, non-friend that makes use of the HttpRequest to perform its work and return a value. Then the const-semantics are clear. A: A general rule of thumb is declare a member function to be const if you can. If getChildren makes some modification that appears to change the state of the HttpRequest object it's called on (even if it doesn't actually change the state) it's possible you should declare it non-const to avoid confusing people. But otherwise, it should be const. As an aside, I understand the logic of why you're declaring the return value to be const. I would still suggest you not do that. With C++11 and move constructors and such, it's actually very useful (and more accurate) for it to be non-const. A: If your intent is to make sure that the function does not change the state of the HttpRequest object, then you want std::list<Child> getChildren() const. There is no reason to make the std::list constant, unless you return a reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: creating html by javascript DOM (realy basic question) i'm having some trouble with javascript. Somehow i can't get started (or saying i'm not getting any results) with html elements creation by javascript. i'm not allowed to use: document.writeln("<h1>...</h1>"); i've tried this: document.getElementsByTagName('body').appendChild('h1'); document.getElementsByTagName('h1').innerHTML = 'teeeekst'; and this: var element = document.createElement('h1'); element.appendChild(document.createTextNode('text')); but my browser isn't showing any text. When i put an alert in this code block, it does show. So i know the code is being reached. for this school assignment i need to set the entire html, which normally goes into the body, by javascript. any small working code sample to set a h1 or a div? my complete code: <html> <head> <title>A boring website</title> <link rel="stylesheet" type="text/css" href="createDom.css"> <script type="text/javascript"> var element = document.createElement('h1'); element.innerHTML = "Since when?"; document.body.appendChild(element); </script> </head> <body> </body> </html> A: getElementsByTagName returns a NodeList (which is like an array of elements), not an element. You need to iterate over it, or at least pick an item from it, and access the properties of the elements inside it. (The body element is more easily referenced as document.body though.) appendChild expects an Node, not a string. var h1 = document.createElement('h1'); var content = document.createTextNode('text'); h1.appendChild(content); document.body.appendChild(h1); You also have to make sure that the code does not run before the body exists as it does in your edited question. The simplest way to do this is to wrap it in a function that runs onload. window.onload = function () { var h1 = document.createElement('h1'); var content = document.createTextNode('text'); h1.appendChild(content); document.body.appendChild(h1); } … but it is generally a better idea to use a library that abstracts the various robust event handling systems in browsers. A: Did you append the element to document? Much the same way you're appending text nodes to the newly created element, you must also append the element to a target element of the DOM. So for example, if you want to append the new element to a <div id="target"> somewhere are the page, you must first get the element as target and then append. //where you want the new element to do var target = document.getElementById('target'); // create the new element var element = document.createElement('h1'); element.appendChild(document.createTextNode('text')); // append target.appendChild(element); A: create element, add html content and append to body var element = document.createElement('h1'); element.innerHTML = 'teeeekst'; document.body.appendChild(element);
{ "language": "en", "url": "https://stackoverflow.com/questions/7515830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Query TFS 2010 Database for all of yesterday's checkins, ordered by project I'm trying to write a query for the TFS 2010 database that will return all of yesterday's checkins ordered by Team Project. So far I have: USE [Tfs_DefaultCollection] SELECT ChangeSetId, CreationDate, Comment, CommitterId FROM tbl_ChangeSet WHERE CreationDate > DATEADD([day], -2, GETDATE()) /*not perfect*/ AND CreationDate < GETDATE(); I'm not sure how to map CommitterId to an actual user name, and I'm not really even sure where to begin in getting the name of the Team Project in which the checkin occurred. Any thoughts? A: You are querying the operational datastore of TFS. This is not supported and a bad practice. Instead please use the TfsWarehouse which has a much better aggregated model of querying your data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where does Magento 1.6 Store its CMS Page? I was looking around the admin panel of magento, and I came across the cms menu, which has a pages section. I was not able to locate that pages listed in this section in Magento's file directory structure. Where can i find all the cms pages, especially the home page? A: Magento's pages aren't files on the server. They're stored in the database. In the stock installation you'll find their content in the cms_page table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery change custom attritbute I have an audio player in which a user can click on a play button next to songs in a list and the player begins streaming the audio. The play button swaps out for a pause button so that the user can pause the audio. The issue I am running into is that I can't swap a custom attribute out (data-player-action) from play to pause once the click happens: jQuery: var playerInit; $('.btn-control').live("click", function() { var $action, $song_id, self; self = $(this); $action = self.attr('data-player-action'); $song_id = self.parents("tr").attr('id'); $(document.body).data('song-id', $song_id); playerInit($action, self); return false; }); playerInit = function(action, elem) { var jw_content, playerData, self; self = $(elem); $('.tracks tr td').not(self.parent()).removeClass('currentlyPlaying'); switch (action) { case "play": self.removeClass('play').addClass('pause'); if (self.parent().hasClass('currentlyPlaying')) { jwplayer().play(true); } else { self.parent().addClass('currentlyPlaying'); $('#player_area').slideDown('200'); $('#player_wrapper').show(); jw_content = jQuery.parseJSON(self.attr('data-player-feed')); playerData = { 'streamer': jw_content.Location, 'file': jw_content.Resource }; jwplayer().load(playerData).play(true); } break; case "pause": self.removeClass('pause').addClass('play'); jwplayer().pause(); break; case "playAlbum": jwplayer().play(true); } return jwplayer().onComplete(function() { var $reloadPlayer; $(document.body).data('song-id', null); self.parentsUntil('.tracks').find('.pause').hide(); self.parentsUntil('.tracks').find('.play').show(); self.parent().removeClass('currentlyPlaying'); return $reloadPlayer = true; }); }; HTML: <a href=\"#\" class=\"btn-control play\" data-player-action='play' data-artist-id='" + data["Artist"]["MnetId"] + "' data-album-id='" + data["MnetId"] + "' data-player-feed='" + x["SampleLocations"].first.to_json + "' data-player-position='0'></a> any help is greatly appreciated!! A: jQuery's data() method can be used to modify HTML5 custom attributes. Just remember to omit the data- prefix. action = element.data('player-action'); //Get element.data('player-action', 'pause'); //Set A: The main problem I see is that you're accessing data- attributes with the .attr method rather than the .data method. Im not sure why this should cause an issue but you seem to mix and match the two. I set up a simple jsfiddle example of swapping out that attribute and it seems to not cause too much of a problem. Basically, when you want to change the element from play to pause you can use $(this).data('player-action','pause') and vice versa $(this).data('player-action','play') A: I wound up just using the class names. var $playerActions, playerInit; $playerActions = ["play", "pause", "playAlbum"]; $('.btn-control').live("click", function() { var $action, $classList, $song_id, self; self = $(this); $classList = self.attr('class').split(/\s+/); $action = null; $.each($classList, function(index, item) { if (jQuery.inArray(item, $playerActions) > -1) { return $action = item; } }); $song_id = self.parents("tr").attr('id'); $(document.body).data('song-id', $song_id); playerInit($action, self); return false; }); playerInit = function(action, elem) { var jw_content, playerData, self; self = $(elem); $('.tracks tr td').not(self.parent()).removeClass('currentlyPlaying'); $('.tracks tr td.player-controls a').removeClass('pause').addClass('play'); switch (action) { case "play": self.removeClass('play').addClass('pause'); if (self.parent().hasClass('currentlyPlaying')) { jwplayer().play(true); } else { self.parent().addClass('currentlyPlaying'); $('#player_area').slideDown('200'); $('#player_wrapper').show(); jw_content = jQuery.parseJSON(self.attr('data-player-feed')); playerData = { 'streamer': jw_content.Location, 'file': jw_content.Resource }; jwplayer().load(playerData).play(true); } break; case "pause": self.removeClass('pause').addClass('play'); jwplayer().pause(); break; case "playAlbum": jwplayer().play(true); } return jwplayer().onComplete(function() { var $reloadPlayer; $(document.body).data('song-id', null); self.parentsUntil('.tracks').find('.pause').hide(); self.parentsUntil('.tracks').find('.play').show(); self.parent().removeClass('currentlyPlaying'); return $reloadPlayer = true; }); };
{ "language": "en", "url": "https://stackoverflow.com/questions/7515840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: zend modules default controller Hy guys, how can i set the default modules controller ?? i need that if there isn't controller in module folder, i come at default module controller and view! for example i type into the browser: http://192.168.1.100/Testmoduli/public/givep/ where givep is my module without IndexController.php, now i need to come at my default module (artapp) into IndexController.php resources.frontController.defaultController = "index" resources.frontController.defaultAction = "index" resources.frontController.defaultModule = "artapp" resources.frontController.moduleDirectory = APPLICATION_PATH "/modules" thanks! EDIT: so.. If I try to launch an action that does not exist, it is automatically launched in the same action in the form of default? to launch this action can i only catch the action into controller error?? thanks! A: You can do this in your ErrorController : // in errorAction() if($this->_error->type == 'EXCEPTION_NO_CONTROLLER'){ // redirect or forward where you want }
{ "language": "en", "url": "https://stackoverflow.com/questions/7515849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Uncheck/Disable checked "Same as Billing Address" in magento 1.5 Basically, I've been trying to remove the checked box when I go to the following. Sales > Order > View a completed order > Click Re-Order and then I see the SHIPPING ADDRESS has a checkbox which is already checked SAME AS BILLING ADDRESS. I want to uncheck the box and disable this function. Please let me know how I can do this is the simplest way possible. Magento Version 1.5.0.1 A: I found this and it worked perfect. http://www.12live.de/de/blog/magento/magento-create-order-in-backend-set-default-value-of-delivery-address-checkbox-same-as-billing-to-unchecked/ If you create an order in the backend by default the delivery method checkbox "Same as billing" is checked. If the customer has different billing and shipping address this is problematic. In the dop down the shipping address is shown. But due to the checkbox the shown shipping address is ignored and the billing address wil be used for delivery. If you want the checkbox to be unchecked by default the following modification is needed. Recommended is to copy the file from the core to the local code pool and modifiy it there. The file in question is core/Mage/Sales/Model/Quote/adress.php. You need to change line 124 to: $this->setSameAsBilling(0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7515852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: about embedded pentaho reporting Engine log query I have integrated reporting engine in my Java application. I have recently upgraded petaho reporting to 3.8.2. I am facing a problem with this upgrade so I switched on the pentaho logs to see what is going on. and I got following relevant log. Can somebody please explain what is its meaning? I assumed from these logs that Data factory is not able to find the value of my query parameters and setting null instead. if it is the case, I dont understand, why it is so, because in code, I am setting these parameters values in Master report as shown below. similarly I am setting other parameters values. vReport.getParameterValues().put("propertyId", pPropertyId); the log I am talking about is here. Sep 20 16:00:44,540 DEBUG SimpleSQLReportDataFactory - [ IP=0:0:0:0:0:0:0:1, Property=72, Req=6 ] - Detected parameter:[dateFormat, dateFormat, dateFormat, dateTimeFormat, dateTimeFormat, bookedFrom, bookedTo, propertyId] Sep 20 16:00:44,561 DEBUG SimpleSQLReportDataFactory - [ IP=0:0:0:0:0:0:0:1, Property=72, Req=6 ] - Parametrize: 1 set to <null> Sep 20 16:00:44,561 DEBUG SimpleSQLReportDataFactory - [ IP=0:0:0:0:0:0:0:1, Property=72, Req=6 ] - Parametrize: 2 set to <null> Sep 20 16:00:44,562 DEBUG SimpleSQLReportDataFactory - [ IP=0:0:0:0:0:0:0:1, Property=72, Req=6 ] - Parametrize: 3 set to <null> Sep 20 16:00:44,562 DEBUG SimpleSQLReportDataFactory - [ IP=0:0:0:0:0:0:0:1, Property=72, Req=6 ] - Parametrize: 4 set to <null> Sep 20 16:00:44,563 DEBUG SimpleSQLReportDataFactory - [ IP=0:0:0:0:0:0:0:1, Property=72, Req=6 ] - Parametrize: 5 set to <null> Sep 20 16:00:44,563 DEBUG SimpleSQLReportDataFactory - [ IP=0:0:0:0:0:0:0:1, Property=72, Req=6 ] - Parametrize: 6 set to <null> Sep 20 16:00:44,564 DEBUG SimpleSQLReportDataFactory - [ IP=0:0:0:0:0:0:0:1, Property=72, Req=6 ] - Parametrize: 7 set to <null> Sep 20 16:00:44,564 DEBUG SimpleSQLReportDataFactory - [ IP=0:0:0:0:0:0:0:1, Property=72, Req=6 ] - Parametrize: 8 set to <null> Thanks in Advance. A: Pentaho Reporting will only use your parameter values if you also declare proper parameters on your report. Just adding random name-value pairs will not work. So at least declare all parameter you want to use. In the most generic version, assuming you do proper validation of the user input yourself and that you can guarantee that the values you pass in are safe and valid, use this code with all your parameters: final ModifiableReportParameterDefinition parameterDefinition = (ModifiableReportParameterDefinition) report.getParameterDefinition(); parameterDefinition.addParameterDefinition(new PlainParameter("dataFormat", Object.class));
{ "language": "en", "url": "https://stackoverflow.com/questions/7515859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook JS SDK - Post an image to someone's wall and make it open in the Gallery Lightbox To be clear, I know how to post an image to a user's wall using FB.ui, but what I would like to know, is if it's possible to make that thumbnail in the post open up the image using the Facebook Gallery Lightbox, just like any pictures you see from your friends, etc. Currently I can only make the thumbnail link to either my app or directly to the image. A: No, you can't do that: the gallery lightbox access is not exposed in any way that you can change in a wall post.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ collection class to call children functions The project I'm working on has some pretty nasty collection classes that I feel could use a redesign. I'd really like to make a collection template class that takes model instances and provides a way to call type-specific functions of each child in the collection. For example, something like: MyCollection<Student> BiologyStudents(); // [Fill the collection] BiologyStudents.EnrollInClass(ClassList::Biology); BiologyStudents.Commit(); The idea is that I could easily enroll all students in a class using my collection, then commit those changes to a database. My problem is in how to expose that EnrollInClass() function which belongs to the children Student objects? If my collection contains objects of a different type than Student, I would like those functions to be exposed from the collection. The only way I can think to do that with my semi-limited C++ knowledge would be to make a function that takes a parameter which references a function I know is in the containing child class. This wouldn't provide compilation errors if you call the wrong function or provide the wrong parameters, so I'd like a way to utilize the compiler to provide these checks. Is this possible? If so, how? As a warning, I'm used to generic programming in Java/C#, so my impression of C++ templates might be a bit off. A: One way would be to use a method pointer: template <typename T> struct MyCollection { template <typename U> void ForEach(void (T::*func)(U),U param) { // for each item loop goes here (item.*func)(param); } }; MyCollection<Student> BiologyStudents; // [Fill the collection] BiologyStudents.ForEach(&Student::EnrollInClass,ClassList::Biology); You would have to provide different versions for different numbers of parameters. With C++11, you can do this: template <typename T> struct MyCollection { void ForEach(std::function<void (T &)> func) { // for each item loop goes here func(item); } }; MyCollection<Student> BiologyStudents; // [Fill the collection] BiologyStudents.ForEach([](Student &s){s.EnrollInClass(ClassList::Biology);}); Which would not require making different versions of ForEach for different numbers of parameters.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I get items from current page in PagedCollectionView? I've got my objects in PagedCollectionView bound to DataGrid and DataPager. var pcView = new PagedCollectionView(ObservableCollection<Message>(messages)); How can I easily get items from current page in PagedCollectionView from my ViewModel? I wish there were something like this: var messagesFromCurrentPage = pcView.CurrentPageItems; // error: no such a property There are properties like SourceCollection, PageIndex and Count but I don't find them useful in this case. What am I missing here? A: If you want to get select items you can just use Linq to do it. var items = pcView.Where(i => i.SomeCondition == true); Make sure you add a using statement for System.Linq. Edit: Whenever I have a question as to what is really going on I just look at the code using Reflector (or ILSpy). In this case here is the relevant code inside GetEnumerator() which is how the Select or Where gets the items in the list: List<object> list = new List<object>(); if (this.PageIndex < 0) { return list.GetEnumerator(); } for (int i = this._pageSize * this.PageIndex; i < Math.Min(this._pageSize * (this.PageIndex + 1), this.InternalList.Count); i++) { list.Add(this.InternalList[i]); } return new NewItemAwareEnumerator(this, list.GetEnumerator(), this.CurrentAddItem); So you can see how it is returning only the items in the current page from this code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fetch data in a single Row I have two tables PackageDetail and PackageDuration PackageDuration have the PackageID as Foreign Key i.e. can have multiple records with respect to PackageID The Schema of the PackageDetail is: PackageID INT PK PackageName Nvarchar(50) Schema of the PackageDuration Table is: DurationID INT PK Price Money Duration Nvarchar(50) PackageID INT FPK PackageDetail tables have follwoing records: PackageID PackageName 1 TestPackage 2 MySecondPackage PackageDuration table have following records: DurationID PackageID Price Duration 1 1 100 6 2 1 200 12 3 1 300 24 4 2 500 6 PackageDuration table can have max 3 records with one PackageID not more than this(if have ignore that) Now I want to select the Records as in following Way: PackageId PackageNAme Price1 Price2 Price3 Duration1 Duration2 Duration3 1 TestPackage 100 200 300 6 12 24 2 MySecondPackage 500 null null 6 null null Please suggest me how can I achive this. A: Another approach: WITH Durations AS ( SELECT *, ROW_NUMBER() OVER(PARTITION BY PackageId ORDER BY DurationId) Sequence FROM PackageDuration ) SELECT A.PackageId, B.PackageName, MIN(CASE WHEN Sequence = 1 THEN Price ELSE NULL END) Price1, MIN(CASE WHEN Sequence = 2 THEN Price ELSE NULL END) Price2, MIN(CASE WHEN Sequence = 3 THEN Price ELSE NULL END) Price3, MIN(CASE WHEN Sequence = 1 THEN Duration ELSE NULL END) Duration1, MIN(CASE WHEN Sequence = 2 THEN Duration ELSE NULL END) Duration2, MIN(CASE WHEN Sequence = 3 THEN Duration ELSE NULL END) Duration3 FROM Durations A INNER JOIN PackageDetail B ON A.PackageId = B.PackageId GROUP BY A.PackageId, B.PackageName A: This should work as long as the durations are unique for a package and they are either 6, 12, or 24. SELECT PackageDetail.PackageId, PackageDetail.PackageName, D1.Price as Price1, D2.Price as Price2, D3.Price as Price3, D1.Duration as Duration1, D2.Duration as Duration2, D3.Duration as Duration3 FROM PackageDetail LEFT OUTER JOIN PackageDuration D1 ON D1.PackageId = PackageDetail.PackageId AND D1.Duration = 6 LEFT OUTER JOIN PackageDuration D2 ON D2.PackageId = PackageDetail.PackageId AND D2.Duration = 12 LEFT OUTER JOIN PackageDuration D3 ON D3.PackageId = PackageDetail.PackageId AND D3.Duration = 24 A: ;WITH pvt AS ( SELECT PackageID, Price1 = MAX(CASE WHEN Duration = 6 THEN Price END), Price2 = MAX(CASE WHEN Duration = 12 THEN Price END), Price3 = MAX(CASE WHEN Duration = 24 THEN Price END), Duration1 = MAX(CASE WHEN Duration = 6 THEN 6 END), Duration2 = MAX(CASE WHEN Duration = 12 THEN 12 END), Duration3 = MAX(CASE WHEN Duration = 24 THEN 24 END) FROM dbo.PackageDuration GROUP BY PackageID ) SELECT pvt.PackageID, p.PackageName, pvt.Price1, pvt.Price2, pvt.Price3, pvt.Duration1, pvt.Duration2, pvt.Duration3 FROM dbo.PackageDetail AS p INNER JOIN pvt ON p.PackageID = pvt.PackageID ORDER BY p.PackageID; A: Maybe I'm missing something in the requirements, but it seems like Sql Server's PIVOT is what you're looking for. There are quite a few questions here at SO about PIVOT... Here's a good clean example with references to other questions: How do i transform rows into columns in sql server 2005 The big benefit of a pivot table over the other answers here is that it will scale out with no modifications if you add records to your PackageDuration table in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery .get funciton with insert from input text line So I have the following <div id="myscore"><div> <input type="text" name="score" id="score" /> <script type="text/javascript" language="javascript"> $(document).ready(function() { $('#click').click(function(){ $('#myscore').get('computescore.php', $('#score').val(); )}); }); <div id="click"> <a href="#">click</a> </div> The code will not pick up the value of score. How do you get the value of an input field into the a jquery function? It updates the myscore field with the computed score after the score has been entered and clicked. A: $("#score").val() will get you the current value correctly. I'm assuming you want to do something liek this, i.e. set the value of the text to what computescore.php returns? $(document).ready(function() { $('#click').click(function(){ $('#myscore').get('computescore.php', function(data){ $('#score').val(data); }); }); }); A: assuming computescore.php just returns a single value, change: $('#myscore').get('computescore.php', $('#score').val(); )}); to $('#myscore').get( 'computescore.php', function(data){ $('#score').val(data); } ); you have to use a callback-function. take a look at the documentation for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why one of my Embeded WAR in an EAR deployed on JBoss has a bad context-root? I have two WAR in my EAR, that should be deployed on a JBoss 6.0.0 Application Server with those WEB-INF/jboss-web: in services-1.1-SNAPSHOT.war: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 5.0//EN" "http://www.jboss.org/j2ee/dtd/jboss-web_5_0.dtd"> <jboss-web> <security-domain>java:/jaas/wts</security-domain> <context-root>ws</context-root> </jboss-web> in web-1.1-SNAPSHOT.war: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 5.0//EN" "http://www.jboss.org/j2ee/dtd/jboss-web_5_0.dtd"> <jboss-web> <security-domain>java:/jaas/wts</security-domain> <context-root>web</context-root> </jboss-web> And here is my the META-INF/application.xml of my ear: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN" "http://java.sun.com/dtd/application_1_3.dtd"> <application> <display-name>ear</display-name> <module> <ejb>logging-1.1-SNAPSHOT.jar</ejb> </module> <module> <ejb>logic-1.1-SNAPSHOT.jar</ejb> </module> <module> <web> <web-uri>services-1.1-SNAPSHOT.war</web-uri> <context-root>ws</context-root> </web> </module> <module> <web> <web-uri>web-1.1-SNAPSHOT.war</web-uri> <context-root>web</context-root> </web> </module> </application> I expect to get /web and /ws Context root in Jboss's admin console. Instead I get /web and /in services-1.1-SNAPSHOT Any one knows why? And how to fix it?
{ "language": "en", "url": "https://stackoverflow.com/questions/7515881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Local Database in Silverlight I want to integrate a local database into Windows Phone 7 project. The DB should be allready filled with values from manual input. Therefore I use a wizard to create a local Database in WPF. I can create tables, set their values and fill in them, but I could not find the way how to refere columns from different tables. Is it possible using UI wizard in Visual Studio or only possible by coding the datacontext? A: It is possible what you ask and the easiest way to do it is Linq to Sql. Database Management in Mango There is an easier way to do it but i think ms doesn't support that, you create a new windows WPF project and there you add a LinQ to SQL database model there you can create your database and then just copy it to your wp7 project and include it in the solution. Then you will have to comment out or delete the two constructors which are not supported by the WP7 and your are ready to use your database. The two constructors to comment out use System.Data.IDbConnection connection This solution is explained in detail in Corrado's Blog
{ "language": "en", "url": "https://stackoverflow.com/questions/7515890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: set 5 divs in the same positions jquery How can I set the location of 5 divs (equally in dimension) in the same position after initializing with jQuery. The reason I want to have this is to move them one by one to another div. Thanks in advance. A: It depends largely on the HTML you have, but the general ideal is to set the CSS position attribute of each element to be absolute, and then set their positions to be the same using a combination of the top, left, bottom and right CSS properties. $('yourDivs').css({ position: 'absolute', top: 0, left: 0 }); This assumes that the the div's are in the same parent, or that none of their ancestors has a position: relative attribute. A: Something like this? http://jsfiddle.net/Gab4B/ div { height: 200px; width: 200px; } div div { height: 20px; width: 20px; border: solid 1px black; } div.seperate-equal { position: absolute; top: 0; left: 0; height: 5px; width: 5px; background-color: red; } A: Set CSS position: absolute, with equal top and left... A: You'll need some position absolute. Demo at JS Fiddle $('.class').each(function(){ this.style.top=0; this.style.left=0; this.style.position='absolute' });
{ "language": "en", "url": "https://stackoverflow.com/questions/7515894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }