text
stringlengths
8
267k
meta
dict
Q: Qt program with Shell I want to write a testing program. It will open a special *.tests file and test direct program with tests from the file. I need to: * *Run some program. e.g ./main -testing 45 563 67 *Listen to result. How I can to do it? I want to run program main with some tests and listen to its result. A: You should ues the QProcess class to start your program. QString program = "./main"; QStringList arguments; arguments << "-testing" << "45" << "563" << ...; QProcess *myProcess = new QProcess(parent); myProcess->start(program, arguments); Then you can use the waitForFinished to wait for it to finish. exitCode will give you the return code. The readAllStandardOutput (or *Error) methods allow you to read what the process has output to the console.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cygwin displays error messages in Hebrew and garbled I have been using Cygwin to build my Android library using the NDK's ndk-build script and Cygwin's make tool. It started giving me errors with a bunch of Latin non-English characters. When copying the text to Google, it was pasted as Hebrew (which I can read). Is there any way to force it to output errors in English? Any idea why this happens? A: Check your environment variables for the correct locale. LANG or LC_MESSAGES are probably responsible. Set those to an English locale (in your profile to have that in future sessions as well) to get English error messages. Sorry, I'm a Windows person and know nearly nothing of Unix so you'd have to look up the specifics elsewhere, but this should be the general direction to go. Some programs/libraries try to be overly smart by guessing the locale from the keyboard layout or the user's locale. And oftentimes ignoring the fact that on Windows locale and UI language are two different concepts (and that different languages on the console are even harder to get right). As for why the messages appear garbled that's likely because the console window uses the wrong code page. The easiest fix is usually to use a TrueType font for the console window, but in this case neither Consolas nor Lucida Console include glyphs for Hebrew, so you'd only see boxes anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Is there is any way to increase the java heap size in nokia c2 mobiles? I'm developing a mobile app in J2ME. I'm facing memory issues. I'm using Nokia c2 mobile.Please tell me Is there is any way to increase the java heap size in Nokia c2 mobiles? Thanks & Regards, A: As far as I know there is no way to extend VM memory heap size on mobile devices. There are significant constraints and mobile developers have to deal with them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Bit depth issues on bitmaps and screens (white is not white) I have a transparent PNG image representing a bluetooth icon with a blue glow, exported from photoshop: On a HTC Desire, a simple imageview is created, and the PNG is used as a bitmap. If the background arround the imageview is white, there are differences between nuances. If the background is black, than the differences are hidden. If I use ADB to do a screen capture, the problem is not visible: Possible causes: The screen uses a higher bit depth rate than what is used for the bitmap. Eg. RGB24 vs RGB16. By doing so, the screen has a wider number of nuances for white than what is possible for the bitmap encoding. When displayed, the bitmap's pixels are approximated to the new bit depth requirements, but fail to properly match the background nuance because of the approximations used. Eg. RGB16->RGB24 would mean C24 = 255*C16/31 . If I use the screen capture software, the bit depths are probably downscaled to a narrower bit depth value (RGB16) so all the nuances merge together and are approximated to the simpler, 16bit colors. This is why I used a photo camera to illustrate the problem. The Question is how to fix this? I already tried loading the bitmap with parameters such as: resample.inPreferredConfig = Config.ARGB_8888; But to no use. I simply need to display a transparent image, such as an icon with GFX effects: shadows, glows, etc. I would be happy to use a grayscale mask as well (Black=>White mask to indicate the pixel transparency, but didn't find a way for that either). Thanks for your time! A: You can just set the Window format before setting the contentView in an Activity. getWindow().setFormat(PixelFormat.RGBA_8888); A: This probably has nothing to do with bit depth. The "whitish square" you described is in your screenshot as well. It is possible you can't see it on your computer monitor if your monitor is not properly calibrated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Attempted to read or write protected memory when accessing dll I try to access zip32.dll version 3.0 when my code got this error : System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at projectName.clsName.ZpArchive(ZCL& zcl, ZPOPT& zopts) at projectName.clsName.functionName() in <location>:<line> This is what i done with the code : //ZCL Structures [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] protected struct ZCL { public int argc; /* Count of files to zip */ [MarshalAs(UnmanagedType.LPStr)] public string fzname; /* name of archive to create/update */ public string[] zipnames; /* zip file name */ [MarshalAs(UnmanagedType.LPStr)] public string fzlist; /* name of archive to create/update */ } //ZPOPT Structures [ StructLayout( LayoutKind.Sequential )] protected struct ZPOPT { [MarshalAs(UnmanagedType.LPTStr)] public string Date; // US Date (8 Bytes Long) "12/31/98"? [MarshalAs(UnmanagedType.LPTStr)] public string szRootDir; // Root Directory Pathname (Up To 256 Bytes Long) [MarshalAs(UnmanagedType.LPTStr)] public string szTempDir; // Temp Directory Pathname (Up To 256 Bytes Long) public int fTemp; // 1 If Temp dir Wanted, Else 0 public int fSuffix; // Include Suffixes (Not Yet Implemented!) public int fEncrypt; // 1 If Encryption Wanted, Else 0 public int fSystem; // 1 To Include System/Hidden Files, Else 0 public int fVolume; // 1 If Storing Volume Label, Else 0 public int fExtra; // 1 If Excluding Extra Attributes, Else 0 public int fNoDirEntries; // 1 If Ignoring Directory Entries, Else 0 public int fExcludeDate; // 1 If Excluding Files Earlier Than Specified Date, Else 0 public int fIncludeDate; // 1 If Including Files Earlier Than Specified Date, Else 0 public int fVerbose; // 1 If Full Messages Wanted, Else 0 public int fQuiet; // 1 If Minimum Messages Wanted, Else 0 public int fCRLF_LF; // 1 If Translate CR/LF To LF, Else 0 public int fLF_CRLF; // 1 If Translate LF To CR/LF, Else 0 public int fJunkDir; // 1 If Junking Directory Names, Else 0 public int fGrow; // 1 If Allow Appending To Zip File, Else 0 public int fForce; // 1 If Making Entries Using DOS File Names, Else 0 public int fMove; // 1 If Deleting Files Added Or Updated, Else 0 public int fDeleteEntries; // 1 If Files Passed Have To Be Deleted, Else 0 public int fUpdate; // 1 If Updating Zip File-Overwrite Only If Newer, Else 0 public int fFreshen; // 1 If Freshing Zip File-Overwrite Only, Else 0 public int fJunkSFX; // 1 If Junking SFX Prefix, Else 0 public int fLatestTime; // 1 If Setting Zip File Time To Time Of Latest File In Archive, Else 0 public int fComment; // 1 If Putting Comment In Zip File, Else 0 public int fOffsets; // 1 If Updating Archive Offsets For SFX Files, Else 0 public int fPrivilege; // 1 If Not Saving Privileges, Else 0 public int fEncryption; // Read Only Property!!! public int fRecurse; // 1 (-r), 2 (-R) If Recursing Into Sub-Directories, Else 0 public int fRepair; // 1 = Fix Archive, 2 = Try Harder To Fix, Else 0 public byte flevel; // Compression Level - 0 = Stored 6 = Default 9 = Max [MarshalAs(UnmanagedType.LPTStr)] public string fSplitSize; //Null for no spliting size //addition for ZCL public int m_CountFile; //For total file on backup file. } //Import Dll: [DllImport("zip32.dll", SetLastError=true)] protected static extern int ZpArchive(ref ZCL zcl,ref ZPOPT zopts); And here's the function that call the ZpArchive : //set the zip options m_zopts = CreateZPOPTOptions(); ZCL zcl = new ZCL(); zcl.argc = m_CountFile; //Total file zcl.fzname = m_ZipFileName; zcl.zipnames = m_FilesToZip; zcl.fzlist = null; //zip the files try { ret = ZpArchive(ref zcl,ref m_zopts); } catch(Exception e) { //<catch> } The exception threw when i try to call the ZpArchive function. I'm using Visual Studio 2010 with compatibility for .Net 2.0 Any idea / advise regarding to this issue? Thanks in advance :) -FDI Update : Here's the structure from library source code : typedef struct { /* zip options */ LPSTR Date; /* Date to include after */ LPSTR szRootDir; /* Directory to use as base for zipping */ LPSTR szTempDir; /* Temporary directory used during zipping */ BOOL fTemp; /* Use temporary directory '-b' during zipping */ BOOL fSuffix; /* include suffixes (not implemented) */ BOOL fEncrypt; /* encrypt files */ BOOL fSystem; /* include system and hidden files */ BOOL fVolume; /* Include volume label */ BOOL fExtra; /* Exclude extra attributes */ BOOL fNoDirEntries; /* Do not add directory entries */ BOOL fExcludeDate; /* Exclude files newer than specified date */ BOOL fIncludeDate; /* Include only files newer than specified date */ BOOL fVerbose; /* Mention oddities in zip file structure */ BOOL fQuiet; /* Quiet operation */ BOOL fCRLF_LF; /* Translate CR/LF to LF */ BOOL fLF_CRLF; /* Translate LF to CR/LF */ BOOL fJunkDir; /* Junk directory names */ BOOL fGrow; /* Allow appending to a zip file */ BOOL fForce; /* Make entries using DOS names (k for Katz) */ BOOL fMove; /* Delete files added or updated in zip file */ BOOL fDeleteEntries; /* Delete files from zip file */ BOOL fUpdate; /* Update zip file--overwrite only if newer */ BOOL fFreshen; /* Freshen zip file--overwrite only */ BOOL fJunkSFX; /* Junk SFX prefix */ BOOL fLatestTime; /* Set zip file time to time of latest file in it */ BOOL fComment; /* Put comment in zip file */ BOOL fOffsets; /* Update archive offsets for SFX files */ BOOL fPrivilege; /* Use privileges (WIN32 only) */ BOOL fEncryption; /* TRUE if encryption supported, else FALSE. this is a read only flag */ LPSTR szSplitSize; /* This string contains the size that you want to split the archive into. i.e. 100 for 100 bytes, 2K for 2 k bytes, where K is 1024, m for meg and g for gig. If this string is not NULL it will automatically be assumed that you wish to split an archive. */ LPSTR szIncludeList; /* Pointer to include file list string (for VB) */ long IncludeListCount; /* Count of file names in the include list array */ char **IncludeList; /* Pointer to include file list array. Note that the last entry in the array must be NULL */ LPSTR szExcludeList; /* Pointer to exclude file list (for VB) */ long ExcludeListCount; /* Count of file names in the include list array */ char **ExcludeList; /* Pointer to exclude file list array. Note that the last entry in the array must be NULL */ int fRecurse; /* Recurse into subdirectories. 1 => -r, 2 => -R */ int fRepair; /* Repair archive. 1 => -F, 2 => -FF */ char fLevel; /* Compression level (0 - 9) */ } ZPOPT, _far *LPZPOPT; typedef struct { int argc; /* Count of files to zip */ LPSTR lpszZipFN; /* name of archive to create/update */ char **FNV; /* array of file names to zip up */ LPSTR lpszAltFNL; /* pointer to a string containing a list of file names to zip up, separated by whitespace. Intended for use only by VB users, all others should set this to NULL. */ } ZCL, _far *LPZCL; and the function declaration : int EXPENTRY ZpArchive(ZCL C, LPZPOPT Opts); some forum said it's because of umanageable code. I already use MarshalAs but still not working..
{ "language": "en", "url": "https://stackoverflow.com/questions/7626134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: emacs:how can I look for a function with source code? Possible Duplicate: Emacs: how to jump to function definition in .el file? with C-h f emacs can tell the function document,How can it be function with source code? A: When C-h f shows the function documentation then the first line of the help is "... function in " and there is an underlined part. If you switch to the Help window and press Enter or click the middle mouse button on the underlined part then it opens the relevant part of the source code if you have the source files in your Emacs install.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Solution for graphing application events metrics in real time We have an application that parses tweets and we want to see the activity in real time. We have tried several solution without success. Our main problems is that the graphing solution (example:graphite), needs a continious flow of metrics. When the db aggregates the metrics it's an average operation which is done, not a a sum. We recently saw cube from square which would fit our requirement but it's too new. Any alternatives? A: I found the solution in the last version of graphite: http://graphite.readthedocs.org/en/latest/config-carbon.html#storage-aggregation-conf A: If I understood correctly, you cannot feed graphite in realtime, for instance as soon as you discover a new tweet? If that's the case, it looks like you can specify a unix timestamp when updating graphite metric_path value timestamp\n so you could pass in the time of discovery/publication/whatever, regardless of when you process it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Auto generate class properties by binding to database lookup table I'm not sure if this is feasible or not but is there a way in C# that will allow me to generate static members or enumrator of all the lookup values in a database table? For example, if I have a table for countries with 2 columns: code, countryname. I want a way to convert all the rows in this table into a class with properity for each row so I can do the following: string countryCode = Country.Egypt.Code Where Egypt is a generated property from the database table. A: When you say "to convert all the rows", do you actually mean "to convert all the columns"? I so, and if your ADO.NET provider supports it, you can use LINQ to SQL to auto-generate a class that has properties that match the columns in your table. You can follow this procedure: * *Right-click on your project and Add / New Item / LINQ to SQL Classes. By default, this will generate a DataClasses1.dbml file with DataClasses1DataContext class. *Expand the database connection of interest in the Server Explorer, under Data Connections (you may need to add it there first through right-click on Data Connections). *Pick the table of interest and drag'n'drop it onto the surface of DataClasses1.dbml. Assuming your table name was COUNRTY with fields NAME and CODE, you can then use it from your code like this: using (var db = new DataClasses1DataContext()) { COUNRTY egypt = db.COUNRTies.Where(row => row.NAME == "Egypt").SingleOrDefault(); if (egypt == null) { // "Egypt" is not in the database. } else { var egypt_code = egypt.CODE; // Use egypt_code... } } If you actually meant "rows", I'm not aware of an automated way to do that (which doesn't mean it doesn't exist!). Writing a small program that goes through all rows, extracts the actual values and generates some C# text should be a fairly simple exercise though. But even if you do that, how would you handle database changes? Say, a value is deleted from the database yet it still exists in your program because it existed at the time of compilation? Or is added to the database but is missing from your program? A: This cannot be done because Country.Egypt has to be available at compile time. I think your options are: * *Generate code for Country class from database. Of course, the question then is how will clients use it? *Keep the Properties statically declared and read their Code from database during application start-up *Keep the properties as well as code statically declared and check them against database during application start-up. Further to #1 above, if the client code does not depend on individual property names then these are not types but data and you could just as well use a Country.AllCountries property for that is initialized at start-up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: linking background image I have an css background-image that needs to be linked to the site index. However I cannot seem to be able to link it. I have tried using: #header-bg { background-image: url("./styles/duffcraft/theme/images/bg_header.png"); } Then using: <a href="./" id="header-bg"></a> But it didn't work. The url for the site is: http://bindmind.net/dev/ Its the image in the middle with the DuffCraft and etc on it. The file name for the image is header.png. Basically it has to link to the site index but because ill be transferring this to another domain soon I can't have it linking to http://www.bindmind.net/dev/. EDIT: I have managed to get it to link, but now there is a massive gap bewteen the image and the actual content. (fixed that.) A: You should use instead of a background image a read image in your HTML code. It should look like that: <a href="/"> <img src="./styles/duffcraft/theme/images/bg_header.png"/> </a> This should show your link as an image only, with the size of the image, and by clicking on the image, your index page will be shown. A: you can do this: <a href="http://bindmind.net/dev/"><div id="header-bg"></div></a> or probably you can do it with JavaScript
{ "language": "en", "url": "https://stackoverflow.com/questions/7626152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is my footer div wrapping everything? Please check this page: http://www.playtrickz.com/basic/basic.html with Firebug. Please tell me why the #pagefooter is wrapping everything. Is it bug? A: You need to add a clear property to your footer : #pagefooter { clear: both; } A: You need to add a clearing div after your #main_wrapper <style> .clear { clear: both; } </style> Then add: <div class="clear"></div> after your #main_wrapper
{ "language": "en", "url": "https://stackoverflow.com/questions/7626154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create a web page as 2 parts I want to develop a registration form with 2 panels. One panel is personal information and another is address details. In these panels the user fills in all details of personal information and after completion of this, the user clicks on Add Address Details. If the user clicks on that, the second panel should be visible without page refresh. How can I accomplish this? A: you would use javascript to append the append the second form to to the div of the first form. Or however you have it setup. So in jquery it would look something like this: <script type="text/javascript"> $('#buttonid').click(function() { $('#divid').append("<form><input />etc etc etc</form>"); }); </script> A: You should use the ASP.NET Wizard control. It is the perfect tool for these scenarios. Scott Gu has a post with some links explaining how to use it. I recommend you look at it.There's a video linked that walks you through a full example. I don't know, but hiding/showing panels based on certain conditions on the same page feels inelegant and hacky to me. A: You should look into using an UpdatePanel. Within there you could place to Panels with different form information. Tie in a few button clicks and hide/show the different panels. Edit with a simple example <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager> <asp:UpdatePanel id="upnl" runat="server" ChildrenAsTriggers="true"> <ContentTemplate> <asp:Panel ID="pnl1" runat="server"> <!--personal info--> <asp:Button ID="btn1" runat="server" Text="this button could validate personal info, hide pnl1 and show pnl2" /> </asp:Panel> <asp:Panel ID="pn2" runat="server" Visible="false"> <!--address info--> <asp:Button id="btn2" runat="server" Text="this button could validate address information and finally submit the form." /> </asp:Panel> </ContentTemplate> </asp:UpdatePanel>
{ "language": "en", "url": "https://stackoverflow.com/questions/7626162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: excel vba - efficiently loop 2d array I'm hopelessly trying to find a better way of filling a range contents. This way produces the correct results but is very slow. Can anyone point me in the correct direction in terms of how to fill a 2d array or otherwise to speed up the algorithm? I would love a code snippet someone has had success with or even just links that show a cleaner method. here is my OLD code: ---------------- f = 1 maxcol = 'func call to get last non blank col ref .ie could return T, R, H.etc For f = 1 To UBound(filenames) Set aDoc = LoadXmlDoc(filenames(f)) For Each c In Worksheets("Results").Range("A1:" & maxcol & "1") c.Offset(f, 0).Value = aNode.Text Next c Worksheets("Results").Range(maxcol & "1").Offset(f, 0).Value = filenames(f) Next f UPDATED CODE: ---------- Dim aDoc As DOMDocument Dim aNode As IXMLDOMNode Dim numOfXpaths As Integer Dim filenames As Variant Dim f As Integer Dim maxcol As String Dim rngStart As Range Dim nColIndex As Long Dim lngCalc As Long 'Dim numOfFiles As Integer Dim aXpaths As Variant numOfFiles = UBound(filenames) colToRow aXpaths, numOfXpaths maxcol = Number2Char(numOfXpaths) ReDim aValues(1 To numOfFiles, 1 To numOfXpaths + 1) As Variant For f = 1 To numOfFiles Set aDoc = LoadXmlDoc(filenames(f)) For nColIndex = 1 To numOfXpaths If aDoc.parseError Then aValues(f, nColIndex) = "XML parse error:" Else Set aNode = aDoc.selectSingleNode(aXpaths(nColIndex)) aValues(f, nColIndex) = aNode.Text End If Next nColIndex aValues(f, numOfXpaths + 1) = filenames(f) Next f Worksheets("Results").Range("A1").Offset(1, 0).Resize(numOfFiles, numOfXpaths + 1).Value = aValues Function colToRow(ByRef aXpaths As Variant, ByRef numOfXpaths As Integer) Dim xpathcount As Integer Dim c As Integer 'Dim aXpaths As Variant xpathcount = Worksheets("Xpaths").Cells(Rows.Count, "A").End(xlUp).Row - 1 ReDim aXpaths(1 To xpathcount + 1) As Variant For c = 0 To xpathcount Worksheets("Results").Range("A1").Offset(0, c) = Worksheets("Xpaths").Range("A1").Offset(c, 0) Worksheets("Results").Range("A1").Offset(0, c).Columns.AutoFit aXpaths(c + 1) = Worksheets("Xpaths").Range("A1").Offset(c, 0) Next c Worksheets("Results").Range("A1").Offset(0, xpathcount + 1) = "Filename" 'colToRow = xpathcount + 1 numOfXpaths = xpathcount + 1 End Function Function Number2Char(ByVal c) As String Number2Char = Split(Cells(1, c).Address, "$")(1) End Function A: To do this efficiently you should generate a 2-dimensional data with the data you want to write, then write it all in one go. Something like the following. I prefer 0-based arrays for compatibility with other languages whereas you seem to be using a 1-based array (1 to UBound(filenames). So there may be off-by-one errors in the following untested code: f = 1 maxcol = 'func call to get last non blank col ref .ie could return T, R, H.etc ' 2D array to hold results ' 0-based indexing: UBound(filenames) rows and maxcol columns Dim aValues(0 to UBound(filenames)-1, 0 To maxcol-1) As Variant Dim rngStart As Range Dim nColIndex As Long For f = 1 To UBound(filenames) Set aDoc = LoadXmlDoc(filenames(f)) aValues(f-1, 0) = filenames(f) For nColIndex = 1 To maxCol-1 aValues(f-1, nColIndex) = aNode.Text Next nColIndex Next f ' Copy the 2D array in one go Worksheets("Results").Offset(1,0).Resize(UBound(filenames),maxCol).Value = aValues A: As you're getting you results from XML, have you looked into using XML Maps to display the information - might not be suitable for your situation, but worth a try. This link below shows some stuff about using XML maps in Excel. The syntax of the line to load an XML string into a define map is similar to this: ActiveWorkbook.XmlMaps("MyMap").ImportXml(MyXMLDoc,True) A: You might want to look at my code in "Using Variant Arrays in Excel VBA for Large Scale Data Manipulation", http://www.experts-exchange.com/A_2684.html (further detail provided in the hyperlink) Note that as I don't have your data above to work with the article provides a sample solution (in this case efficiently deleting leading zeroes) to meet you filling a range from a 2d array requirement. Key points to note * *The code handles non contigious ranges by use of Areas *When using variant arrays alwasy test that the range setting the array size is bigger than 1 cell - if not you cant use a variant *The code readas from a range, runs a manipulation, then dumps back to the same range *Using Value2 is slightly moe efficient than Value Here is the code: 'Press Alt + F11 to open the Visual Basic Editor (VBE) 'From the Menu, choose Insert-Module. 'Paste the code into the right-hand code window. 'Press Alt + F11 to close the VBE 'In Xl2003 Goto Tools … Macro … Macros and double-click KillLeadingZeros Sub KillLeadingZeros() Dim rng1 As Range Dim rngArea As Range Dim lngRow As Long Dim lngCol As Long Dim lngCalc As Long Dim objReg As Object Dim X() On Error Resume Next Set rng1 = Application.InputBox("Select range for the replacement of leading zeros", "User select", Selection.Address, , , , , 8) If rng1 Is Nothing Then Exit Sub On Error GoTo 0 'See Patrick Matthews excellent article on using Regular Expressions with VBA Set objReg = CreateObject("vbscript.regexp") objReg.Pattern = "^0+" 'Speed up the code by turning off screenupdating and setting calculation to manual 'Disable any code events that may occur when writing to cells With Application lngCalc = .Calculation .ScreenUpdating = False .Calculation = xlCalculationManual .EnableEvents = False End With 'Test each area in the user selected range 'Non contiguous range areas are common when using SpecialCells to define specific cell types to work on For Each rngArea In rng1.Areas 'The most common outcome is used for the True outcome to optimise code speed If rngArea.Cells.Count > 1 Then 'If there is more than once cell then set the variant array to the dimensions of the range area 'Using Value2 provides a useful speed improvement over Value. On my testing it was 2% on blank cells, up to 10% on non-blanks X = rngArea.Value2 For lngRow = 1 To rngArea.Rows.Count For lngCol = 1 To rngArea.Columns.Count 'replace the leading zeroes X(lngRow, lngCol) = objReg.Replace(X(lngRow, lngCol), vbNullString) Next lngCol Next lngRow 'Dump the updated array sans leading zeroes back over the initial range rngArea.Value2 = X Else 'caters for a single cell range area. No variant array required rngArea.Value = objReg.Replace(rngArea.Value, vbNullString) End If Next rngArea 'cleanup the Application settings With Application .ScreenUpdating = True .Calculation = lngCalc .EnableEvents = True End With Set objReg = Nothing End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7626163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: looping through url I want to do a loop, normally it is done with while do for etc but when the process is big I came up with a solution to refresh the page by echoing a javascript to refresh the page for the next loop. for example: The page is http://localhost/index.php --> this preforms the first iteration with $i=1; at the end of the script it will be redirected to http://localhost/index.php?i=$i++ if (!$_GET['i']){ $i = 1; }else{ $i = $_GET['i']; } if ($i<500){ // proceed with $i = $_GET['i'] //then redirect to http://localhost/index.php?i=$i++ }else{ echo "done"; } Now, consider a situation that the imput parameters come from a FORM to this script. (i.e. $parameter1 , $parameter2, $parameter3) Then I have to pass them every time to new url (next iteration). At normal work I can pass them as GET variable to new url but how can I pass them if I don't want the user be able to see the value of parameters in url? A: At normal work I can pass them as GET variable to new url but how can I pass them if I don't want the user be able to see the value of parameters in url? You can not with the bare redirect, but if you're talking about a specific user, you can do so by assigning those parameters as session variables Docs and then passing the session id as an additional parameter (or trust the user has cookies enabled). function do_redirect($i, Array $parameters) { $i = (int) $i; $parameters['i'] = $i; // save to session as well $_SESSION['parameters'] = $parameters; // redirect to http://localhost/index.php?i=$i&SID } if (is_form_request()) { $parameters = get_form_parameters(); do_redirect(1, $parameters); } elseif (is_redirect_loop_request()) { $parameters = $_SESSION['parameters']; $i = $parameters['i']; if ($i < 500) { do_redirect($i++, $parameters); } else { echo "done."; } } A: Not to be rude, but both answers above are quite prone to security issues (but the session solution is the best one). As for the 'encryption' solution of @itamar: that's not exactly encryption... This is called 'Caesar cypher' (http://en.wikipedia.org/wiki/Caesar_cipher), which is indeed as safe as a paper nuclear bunker... It can be much easier and safe as can be; do not save the iteration in the session, but in the database. For the next request, the only thing you have to do is get the iterator from the database and go on with whatever you want to do. Sessions can be stolen, meaning someone could let you iterate from, say, $i=10 a thousand times. It cannot be done when the iterator is stored in a secure database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: right way to specify the src for an image in MVC3 I have the following code: <img src="images/img2.jpg" alt="" title="" /> Is this correct for Layout.cshtml and partial views? Should I instead specify the source using something like @URl? A: This will probably gonna break. The below one is the right way of doing it : <img src="@Url.Content("~/images/img2.jpg")" alt="" title="" /> A: Use the ImageExtensions Helper function from the Mvc3Futures\Microsoft.Web.Mvc.dll. You can find it in NuGet repository. public static class ImageExtensions { public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl); public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl, string alt); public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl, string alt, object htmlAttributes); public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl, object htmlAttributes); public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl, IDictionary<string, object> htmlAttributes); public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl, string alt, IDictionary<string, object> htmlAttributes); public static TagBuilder Image(string imageUrl, string alt, IDictionary<string, object> htmlAttributes); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7626167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: my json response keys contains "$" and it gives me undefined value i am receiving json response when i alert the data i see those values but when i alert data.$tracking it gives me undefined i also tried data.tracking but no hope function GetVideos(URI, PageSize) { alert("in GetVideos: " + URI + PageSize); $.ajax({ type: "GET", url: URI, async: false, dataType: "application/json", success: function(data) { alert(data.$tracking); }, error: function(err) { alert("error" + err.toString()); } }); } { "$tracking": "uuids", "$execTime": "0", "video": [ { "$publishState": "UpdatePending", "$lcid": "1033", "$options": "0", "$version": "158", "$filterFlags": "9103", "uuid": { "$ref": "3rzh6xt5", "$seoMetaData": "\x2fvideo\x2fvenice-beach\x2f", "$": "2ec4173b-47ab-4bed-b694-9fd966f5b5b3" }, "providerId": { "$": "VeniceBeach_201337" }, "csId": { "$": "Turnhere" }, "source": { "$friendlyName": "TurnHere", "$": "TurnHere" }, "pageGroup": { "$": "MSVLIF" }, "title": { "$": "Venice Beach" }, "description": { "$": "Dude. Catch some hippie vibes strolling down Ocean Front Walk-- smoke a hooka, exercise your free speech and let the eclectic street performers inspire your inner muse." }, "durationSecs": { "$": 269 }, "startDate": { "$": "2007-09-13T00\x3a00\x3a00Z" }, "activeEndDate": { "$": "2013-09-14T00\x3a00\x3a00Z" }, "searchableEndDate": { "$": "2013-09-14T00\x3a00\x3a00Z" }, "archiveEndDate": { "$": "2099-12-31T00\x3a00\x3a00Z" }, "tags": { "tag": [ { "$market": "us", "$namespace": "Duration", "$source": "2", "$premium": "1", "$": "short" }, { "$market": "us", "$namespace": "Genre", "$source": "5", "$premium": "1", "$": "entertainment" }, { "$market": "us", "$namespace": "MSNVideo_Top", "$source": "5", "$premium": "0", "$": "MSNVideo_Top_Lifestyles" }, { "$market": "us", "$namespace": "MSNVideo_Top_Cat", "$source": "5", "$premium": "0", "$": "Most Watched Life" }, { "$market": "us", "$namespace": "MSNVideo_Top_Cat", "$source": "2", "$premium": "0", "$": "Source_TurnHere" }, { "$market": "us", "$namespace": "MSNVideo_Top_Cat", "$source": "5", "$premium": "0", "$": "Travel_General" }, { "$market": "us", "$namespace": "Public", "$source": "4", "$premium": "0", "$": "Venice" }, { "$market": "us", "$namespace": "VC_Source", "$source": "2", "$premium": "1", "$": "Turnhere\x3aTurnHere" }, { "$market": "us", "$namespace": "VC_Supplier", "$source": "2", "$premium": "1", "$": "Turnhere" } ] }, "videoFiles": { "videoFile": [ { "$formatCode": "1002", "$msnFileId": "0304FE9B-4BCE-4955-AC3C-A34C2203F3C1", "$height": "240", "$width": "320", "$bitrate": "446", "uri": { "$": "http\x3a\x2f\x2fcontent3.catalog.video.msn.com\x2fe2\x2fds\x2fus\x2fTurnhere\x2fTurnHere\x2fCC4C4482-B5A8-4829-9CAB-CC104AE628C1.wmv" } }, { "$formatCode": "1003", "uri": { "$": "http\x3a\x2f\x2fcontent3.catalog.video.msn.com\x2fe2\x2fhttp\x3a\x2f\x2fcdn.videos.turnhere.com\x2fflv8\x2fvenicebeach.flv" } } ] }, "files": { "file": [ { "$formatCode": "2007", "uri": { "$": "http\x3a\x2f\x2fcdn.videos.turnhere.com\x2fimages92x69\x2fVENICEBEACH.jpg" } } ] }, "extendedXml": { "$": "" }, "subTitle": { "$": null }, "copyright": { "$": null }, "usage": { "usageItem": [ { "$counterType": "1", "$hourlyCount": "0", "$hourlyChange": "0", "$dailyCount": "0", "$weeklyCount": "0", "$monthlyCount": "2", "$totalCount": "1977", "$totalAverage": "1.05" } ] } }, { "$publishState": "Published", "$lcid": "1033", "$options": "0", "$version": "29", "$filterFlags": "9103", "uuid": { "$ref": "6ms12ek", "$seoMetaData": "\x2fvideo\x2fbush-meets-teen-sensation\x2f", "$": "695fc4de-0cee-495c-b3df-31c0b0e5d574" }, "providerId": { "$": "n_bush_basketball_060314" }, "csId": { "$": "Msnbc" }, "source": { "$friendlyName": "NBC Sports", "$": "NBC Sports" }, "pageGroup": { "$": "MSVROM" }, "title": { "$": "Bush meets teen sensation" }, "description": { "$": "March 14\x3a President Bush meets with Jason McElwain, the autistic 17-year-old high schooler who became an instant star by scoring 20 points and making six three-pointers in his first game last month." }, "durationSecs": { "$": 10 }, "startDate": { "$": "2006-03-13T16\x3a00\x3a00Z" }, "activeEndDate": { "$": "2099-12-31T00\x3a00\x3a00Z" }, "searchableEndDate": { "$": "2099-12-31T00\x3a00\x3a00Z" }, "archiveEndDate": { "$": "2099-12-31T00\x3a00\x3a00Z" }, "tags": { "tag": [ { "$market": "us", "$namespace": "Duration", "$source": "2", "$premium": "1", "$": "short" }, { "$market": "us", "$namespace": "Genre", "$source": "5", "$premium": "1", "$": "Sports" }, { "$market": "us", "$namespace": "mobile", "$source": "5", "$premium": "0", "$": "mobile_rights" }, { "$market": "us", "$namespace": "msnbcid", "$source": "2", "$premium": "0", "$": "11825895" }, { "$market": "us", "$namespace": "MSNVideo_Cat", "$source": "2", "$premium": "0", "$": "NBC Sports" }, { "$market": "us", "$namespace": "MSNVideo_Cat", "$source": "2", "$premium": "0", "$": "Other" }, { "$market": "us", "$namespace": "MSNVideo_Top", "$source": "2", "$premium": "0", "$": "News" }, { "$market": "us", "$namespace": "MSNVideo_Top_Cat", "$source": "2", "$premium": "0", "$": "News_Other" }, { "$market": "us", "$namespace": "MSNVideo_Top_Cat", "$source": "5", "$premium": "0", "$": "Source_NBC Sports" }, { "$market": "us", "$namespace": "Public", "$source": "4", "$premium": "0", "$": "bush meets" }, { "$market": "us", "$namespace": "Public", "$source": "2", "$premium": "0", "$": "Msnbc" }, { "$market": "us", "$namespace": "Public", "$source": "2", "$premium": "0", "$": "MSNBC News" }, { "$market": "us", "$namespace": "Public", "$source": "2", "$premium": "0", "$": "News" }, { "$market": "us", "$namespace": "Public", "$source": "2", "$premium": "0", "$": "sports" }, { "$market": "us", "$namespace": "Public", "$source": "2", "$premium": "0", "$": "Sports news" }, { "$market": "us", "$namespace": "Public", "$source": "2", "$premium": "0", "$": "Video" }, { "$market": "us", "$namespace": "VC_Source", "$source": "2", "$premium": "1", "$": "Msnbc\x3aNBC Sports" }, { "$market": "us", "$namespace": "VC_Supplier", "$source": "2", "$premium": "1", "$": "Msnbc" } ] }, "videoFiles": { "videoFile": [ { "$formatCode": "1002", "$height": "240", "$width": "320", "$bitrate": "200", "uri": { "$": "http\x3a\x2f\x2fwww.msnbc.msn.com\x2fdefault.cdnx\x2fid\x2f11825895\x2fdisplaymode\x2f1157\x2f" } }, { "$formatCode": "1003", "uri": { "$": "http\x3a\x2f\x2fwww.msnbc.msn.com\x2fdefault.cdnx\x2fid\x2f11825895\x2fdisplaymode\x2f1157\x2f\x3ft\x3d.FLV" } } ] }, "files": { "file": [ { "$formatCode": "2007", "uri": { "$": "http\x3a\x2f\x2fmsnbcmedia.msn.com\x2fj\x2fmsnbc\x2fComponents\x2fVideo\x2f060314\x2fn_bush_basketball_060314.vmod.jpg" } } ] }, "extendedXml": { "relatedLinks": { "link": [ { "$url": "http\x3a\x2f\x2fwww.msnbc.msn.com\x2fid\x2f3032113\x2f", "$": "NBC Sports Front Page" }, { "$url": "http\x3a\x2f\x2fwww.msnbc.msn.com\x2f", "$": "Latest news from MSNBC.com" }, { "$url": "http\x3a\x2f\x2fwww.msnbc.msn.com\x2fid\x2f3032092\x2f", "$": "MSNBC.com\x27s News Section" } ] } }, "subTitle": { "$": null }, "copyright": { "$": null }, "usage": { "usageItem": [ { "$counterType": "1", "$hourlyCount": "0", "$hourlyChange": "0", "$dailyCount": "0", "$weeklyCount": "0", "$monthlyCount": "1", "$totalCount": "635", "$totalAverage": "1.13" } ] } } ], "$": "" } A: have u tried dataType: "json", instead of dataType: "application/json", because there is nothing wrong with your json code. http://jsfiddle.net/HWUvj/2/ A: Just tried a little local example: $(function(){ $.get('test.php', function(data) { alert(data.$test); }); }); With test.php being the json output: <?php header("Content-type: application/json");?> { "$test": "test", "$lala": { "$rofl": "$copter", "blubb": "test" } } Works like a charm. WIthout the content type header i receive the same error as you do, as it is only a text and not json :) A: $ is not a reason for undefined value, because it is correct JSON naming char. I believe data.$tracking should work. Your can try also data['$tracking']. Or try data.d.$tracking. Also set your dataType to 'json' and contentType to 'application/json'. In my opinion, you should debug this code and simply track data and find all the problems. Members of StackOverflow shouldn't track all our json-dump and look for errors, it is hard to read such amount of useless data. A: I think you are ot settting the datatype correctly because the JSON is correct. It should be dataType: "json" as stated in the documentation. EDIT - since you are calling another server you must use jsonp so set: dataType: "json", crossDomain: "true"
{ "language": "en", "url": "https://stackoverflow.com/questions/7626168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to launch the Android Download Manager How do I start default phone's download manager, like the one builtin in default browser? I need to create an intent that contains url of file to download. I know it's possible, as I saw some applications doing it in the past. A: What you want is DownloadManager. Browsing the Android source code reveals that the default browser is using this as well. EDIT You can browse the source code for DownloadManager here and try to use the code to make it work on 7. Bare in mind the dependencies of the class might also be not available on 7 (most probably) but it might be worth a look. A: As easy as: startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
{ "language": "en", "url": "https://stackoverflow.com/questions/7626174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I change the values in this array? Here's my code: var array = [{"number":"500","title":"whatever 500"},{"number":"400","title":"whatever 400"}]; alert(array[0].number); //should output 500 $.each(array, function(index, val) { array[index].number = val * 5; }); alert(array[0].number); //should output 2500 I'm trying to multiply all the numbers in my array by 5. But for some reason it's not working. It outputs NaN (Not-a-Number). And when I try to add 50, it outputs [object Object]50. Can someone please tell me what I'm doing wrong here? A: The problem is that val is the object, not a specific value from it. So you're trying to multiply {"number":"500","title":"whatever 500"} by 5, which unsurprisingly doesn't work. You can just use this to refer to the current element in the loop. Your code might look like this: $.each(array, function() { this.number = this.number * 5; }); You could, in fact, make this even shorter, by using the *= assignment operator: $.each(array, function() { this.number *= 5; }); A: Here is correct each: $.each(array, function(index, val) { array[index].number = val.number * 5; }); You're iterating over the objects in array, because array contains objects. First val in your example equals to {"number":"500","title":"whatever 500"} A: "500" is not a number (NaN), it's a string. Try with this array : var array = [{"number":500,"title":"whatever 500"},{"number":400,"title":"whatever 400"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7626177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Comparing Strings in IronPython I am trying to compare two strings while searching for WSUS groups to update. However, my comparison is failing even though they appear to be the same visually, and are of the same type. Since this is IronPython, I don't have a debugger available in Komodo (anyone know of one for IP?) Anyway, can someone spot what I am doing wrong? #---------------------------------------------------------------------- # Search for a matching patch group, and approve them. #---------------------------------------------------------------------- def WSUSApprove(apprvGrpName): clr.AddReference('Microsoft.UpdateServices.Administration') import Microsoft.UpdateServices.Administration wsus = Microsoft.UpdateServices.Administration.AdminProxy.GetUpdateServer('wsus01',False,8530) parentGroupCollection = wsus.GetComputerTargetGroups() for computerTarget in parentGroupCollection: if computerTarget.Name.ToString() == 'Servers': parent = computerTarget childGroupCollection = parent.GetChildTargetGroups() for computerTarget in childGroupCollection: print type(computerTarget.Name.ToString()) print type(apprvGrpName) if apprvGrpName == computerTarget.Name.ToString(): print 'success', computerTarget.Name.ToString() else: print 'a', computerTarget.Name.ToString() print 'b', apprvGrpName #--output that should be equal--# <type 'str'> <type 'str'> a 3 Tuesday b 3 Tuesday A: On Python 2.x, Use repr() to see visually if two strings are the same. print basically calls str, so you can't see unprintable characters and it's hard to see differences in whitespace. So, do: print repr(computerTarget.Name.ToString()) print repr(apprvGrpName) to find out why they aren't equivalent. See John Manchin's comment for what to use on Python 3.x, where repr() doesn't escape unicode characters. A: Most likely one of your strings has a trailing whitespace character such as a newline, carriage return or space.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any possibility to declare indexers in C# as an abstract member? As the title states, I would like to declare an indexer object this[int index] in an abstract class as an abstract member. Is this possible in any way? Is it possible to declare this in an interface too? A: A simple example: public interface ITest { int this[int index] { get; } } public class Test : ITest { public int this[int index] { get { ... } private set { .... } } } Several combinations of private/protected/abstract are possible for get and set A: Of course: public abstract class ClassWithAbstractIndexer { public abstract int this[int index] { get; set; } } A: You may declare it like this: internal abstract class Hello { public abstract int Indexer[int index] { get; } } Then you'll have the option to override only get or override both get and set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: how to select elements with more attributes? How can you select elements with more attributes? $('input[type="checkbox"]') This will select all checkboxes, but how can you specify one more attribute in the selector? <input type="checkbox" data-test="1" /> How can you select all checkboxes with the data-test attribute set too? A: You can chain them like this: $('input[type="checkbox"][data-test="1"]') A: Just write them one after another: $('input[type="checkbox"][data-test="1"]') A: jQuery supports multiple attribute selectors. So you could have something like so: $('input[type="checkbox"][data-test="1"]') Or you could shorten it some with the :checkbox selector. $(':checkbox[data-test="1"]') Test: http://jsfiddle.net/NYX9p/
{ "language": "en", "url": "https://stackoverflow.com/questions/7626197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android - Open YouTube video via Link in TextView I have an app that I wish to put links in that will open the youtube player, the link will be located within a text view. Can anyone help me achieve this as simply using Link text does not work ?? Thanks for any help ! A: Guess this is what you're looking for: http://xjaphx.wordpress.com/2011/09/12/auto-link-for-textview/ Cheers, Pete Houston
{ "language": "en", "url": "https://stackoverflow.com/questions/7626199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create a simple private message system in rails with inbox, send, and reply's? There are some gems out there to instantly have a simple messaging system for users which I have looked at but they don't really fit the bill in terms of having a way to easy customize them. Therefore I would like to ask some suggestions of gems that you consider be good for an instant messaging on a site, or discuss how one could implement this functionality. I have built a simple system before that consisted of a messages table like this: * *inbox *outbox *friend request *replies id|message_id|sender_id|receiver_id|is_reply|is_friendreq|message I'm thinking of storing everything in this one table and get all messages of a certain user where the user_id == receiver_id. This is very basic. I'm learning Rails and try to learn how to implement this on best Rails practice, so any tips/suggestions/ideas are more than welcome.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does a shell guess the PATH when spawned in an empty environment? Using the following code to run the ls command via /bin/shnworks fine: #include <unistd.h> int main(int argc, char **argv, char **envp) { execle("/bin/sh", "sh", "-c", "ls", (char*)NULL, envp); } However if I launch the shell in an empty environment, changing the execle line to read like this: execle("/bin/sh", "sh", "-c", "ls", (char*)NULL, NULL); It works too. How does the shell know the path to ls even though I didn't pass any enviroment? A: Lets re-write your program as following: #include <stdio.h> #include <unistd.h> int main(int argc, char **argv, char **envp) { execle("/bin/sh", "sh", "-c", "ls", (char*)NULL, NULL); return 0; } Now, once you compile and run with ltrace, you'll find the following snippet in the output: <... bsearch resumed> ) = NULL strlen("ls") = 2 memcpy(0x0061cbe0, "/usr/local/sbin", 15) = 0x0061cbe0 strcpy(0x0061cbf0, "ls") = 0x0061cbf0 __xstat64(1, "/usr/local/sbin/ls", 0x7fffb173e120) = -1 strlen("ls") = 2 memcpy(0x0061cbe0, "/usr/local/bin", 14) = 0x0061cbe0 strcpy(0x0061cbef, "ls") = 0x0061cbef __xstat64(1, "/usr/local/bin/ls", 0x7fffb173e120) = -1 strlen("ls") = 2 memcpy(0x0061cbe0, "/usr/sbin", 9) = 0x0061cbe0 strcpy(0x0061cbea, "ls") = 0x0061cbea __xstat64(1, "/usr/sbin/ls", 0x7fffb173e120) = -1 strlen("ls") = 2 memcpy(0x0061cbe0, "/usr/bin", 8) = 0x0061cbe0 strcpy(0x0061cbe9, "ls") = 0x0061cbe9 __xstat64(1, "/usr/bin/ls", 0x7fffb173e120) = -1 strlen("ls") = 2 memcpy(0x0061cbe0, "/sbin", 5) strcpy(0x0061cbe6, "ls") = 0x0061cbe6 __xstat64(1, "/sbin/ls", 0x7fffb173e120) = -1 strlen("ls") = 2 memcpy(0x0061cbe0, "/bin", 4) = 0x0061cbe0 strcpy(0x0061cbe5, "ls") = 0x0061cbe5 __xstat64(1, "/bin/ls", 0x7fffb173e120) = 0 strlen("ls") = 2 malloc(26) = 0x025fa110 strcpy(0x025fa123, "ls") = 0x025fa123 realloc(NULL, 160) = 0x025fa140 fork() As you can see, it's clearly looking for the right path before doing the fork() with '/bin/ls' which is the right path for 'ls'. If there was $PATH variable given, sh would try those paths to find the location of ls. Since there is no $PATH provided in this case, plausible paths (e.g. /bin, /usr/bin, /sbin) are tried nevertheless. From execle man-page: If this PATH variable isn't specified, the default path is set according to the _PATH_DEFPATH definition in , which is set to /usr/bin:/bin. A: From the execle man page: On some other systems the default path (used when the environment does not contain the variable PATH) has the current working directory listed after /bin and /usr/bin, as an anti-Trojan-horse measure. Linux uses here the traditional "current directory first" default path. So I guess your default path is ./:/bin:/usr/bin if on Linux, /bin:/usr/bin otherwise. A: /bin/sh sets a lot of variables on its own if they're undefined by the time it starts. You can see the full list easily by running env -i sh -c set For example, on my system: $ env -i sh -c set IFS=' ' OPTIND='1' PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' PPID='2299' PS1='$ ' PS2='> ' PS4='+ ' PWD='/home/jb' Note how this includes PATH. Also note that PATH gets a status of variable only; it does not get promoted to the exported environment. Cross-check that with env -i sh -c env. $ env -i sh -c env PWD=/home/jb A: The reason this can work is that POSIX says this about PATH: If PATH is unset or is set to null, the path search is implementation-defined. Your /bin/sh uses a default PATH for this case, which happens to include the directory with the ls executable. On my system (FreeBSD) I can inspect this with $ strings -a /bin/sh | grep /bin: /usr/bin:/bin:/usr/sbin:/sbin PATH=/usr/bin:/bin
{ "language": "en", "url": "https://stackoverflow.com/questions/7626208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Telerik MVC Controls and JQuery Closure I have a telerik grid in an asp.net mvc3 (RAZOR) View. While designing I had also bind OnDataBound client event. @{ Html.Telerik().Grid() .Name("someGrid") .clientEvents(e=>e.OnDataBound("someGrid_onDataBound")) .Render(); } <script> function someGrid_onDataBound(e){ //.. some code which needs to access a function from a JavaScript closure. } </script> In the view I have linked a JavaScript file which contains a Closure for performing different actions. and in the function above I need to call some function from the closure, for this I need to declare this function inside the closure. Can anybody tell me please how could I make "someGrid_onDataBound" [grid event handler] to access some function from the closure. A: As i understand from your question, you wanna put your JS files at the end of the page. And you wanna be able to access them from your Views!. If so then you should add references to all your JS files and libraries at the end of your _Layout.cshtml right before </body> tag then after these references add new render section @RenderSection("Scripts") Then put your scripts in suitable section in your Views: @section Scripts{ <script type="text/javascript"> ......... </script> } A: in the closure you have to add the said javascript function to window as follows. (function($){ // here is your out of closure function window.someGrid_onDataBound = function(e){ //.. some code which needs to access a function from a javascript closure. } })(jQuery);
{ "language": "en", "url": "https://stackoverflow.com/questions/7626209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transferring c# List to another list with a method inbetween Was'nt sure of the title, but I have this task which I am having trouble with. I have a List downloaded from a WCF service. ie: List<Stops_edited_small> StopsList = new List<Stops_edited_small>(e.Result); The list has several items two being: LatitudeField LongitudeField Basically, what I need to do is make a Geocoordinate value for each record in the list by doing this: GeoCoordinate(Convert.ToDouble(LatitudeField), Convert.ToDouble(LongitudeField)); Then add the Geocoordinate value in each record in a new List which I can then use. Make sense? I am not sure on how I would go about this. Would i need some kind of foreach loop to do the Geocoordinate conversion on my original list someone? Would i have to convert it into a class first to do this? Thanks, any help or thinking welcome. (EDIT: just to add this is on windows phone, so .net 4 is available) A: You can use the ConvertAll method that goes back to .NET 2.0 before Linq has been introduced. Here is an example: Cast List<int> to List<string> in .NET 2.0 And MSDN Article: http://msdn.microsoft.com/en-us/library/73fe8cwf.aspx A: If you are using .NET 3.5 or later you can use LINQ2Objects var coordinateList = StopsList.Select(stop => new GeoCoordinate(Convert.ToDouble(stop.LatitudeField), Convert.ToDouble(stop.LongitudeField))).ToList(); If you are using an older .NET version you need to use an explicit loop. var coordinateList = new List<GeoCoordinate>(); foreach(var stop in StopsList) { coordinateList.Add( new GeoCoordinate(Convert.ToDouble(stop.LatitudeField), Convert.ToDouble(stop.LongitudeField))); } Edit If you want to combine both the new GeoCoordinate with the stops you have a couple of options. Either create a list with an anonymous type var combinedList = StopsList.Select(stop => new { s = stop, coord = new GeoCoordinate(Convert.ToDouble(stop.LatitudeField), Convert.ToDouble(stop.LongitudeField)), }).ToList(); You can also do the same with a class you create, replace new { with new YourClass {. You can also use the Zip method using both above lists var combinedList = StopsList.Zip(coordinateList, Tuple.Create).ToList(); This gives you a List<Tuple<Stop, GeoCoordinate>>. Note that most of the time you can skip .ToList(), you don't get a List<T>, but an IEnumerable<T>. That will work as good as a List in most cases but your program don't have to copy everything to lists all the time. Usually a little bit more efficient and you don't need to type .ToList() all the time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the way of correct way in using calloc for an array? I want to create a pointer to an array of pointers (with 10 pointers in the array), then I want to give a pointer a value. This is what I have so far: char **arraypointer = calloc (10, sizeof (char*)); How will I give value to this array? I've tried: arraypointer[0] = "string" But I get a seg fault. Edit: I want to create a pointer that points to an array of pointers. Each of these pointers will have a struct property. How is it possible to access the struct property for this pointer? I have no code to post because I am still trying to figure out how it should look. The struct for this pointer will contain a string which is a char *string and an int number. I am thinking of it working like this: arraypointer[0]->string = "this"; arraypointer[0]->number = 3; A: Update: struct mystruct* pointer = calloc(N, sizeof(struct mystruct)); pointer[0].string = "this"; //notice . instead of -> ^ pointer[0].number = 3; ^ Original answer: char **arraypointer = calloc (10, sizeof (char*)); arraypointer[0] = "string"; These two lines are perfectly fine. You'd get a segfault(Undefined behavior, actually) if you tried to do something like arraypointer[0][3] = 's'; later. Also, you'd get in trouble if you did strcpy(arraypointer[0], "string"); because you haven't actually allocated any memory that arraypointer[i] point to A: You have to type : char **arraypointer = (char**) calloc (10, sizeof (char*)); As calloc is meant for void* A: //READING STRINGS USING POINTERS (CALLOC) #include<stdio.h> #include<stdlib.h> int main() { int n; printf("Enter number of Strings : \n"); scanf("%d", &n); char** a = (char**) calloc(n, sizeof(char*)); int i=0; printf("Enter Strings : \n"); for (i=0;i<n;i++) { a[i]= (char*) malloc(100*sizeof(char)); scanf("%s", a[i]); } i=0; printf("**************\n"); for (i;i<n;i++) { printf("%s\n", a[i]); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7626214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I make punch-through transparent text in HTML/CSS? I have a div which has css background: rgba(0, 0, 0, 0.85);. Centered in that div is the title of the page. I want to make the title see through (knockout, punch-through, however you want to call it. i.e. see past the div's background black to the background image of the page). The only method of doing that that I have come up with is using an image with the div's background and transparent text and seperate the header part into blocks. /////////////////////////////////////////////// // (empty) // TITLE IMAGE // (empty) // /////////////////////////////////////////////// The problem is that I dont know how to create the empty divs such that the image will remain centered (the empty divs need to be there to add the black background). Is there a different way to either do the see through text that doesnt have this problem or a way to center the image div with the empty divs? EDIT: For an example of the effect that I am trying to achieve, look here: http://www.showandtell-graphics.com/layer-knockout.html A: you can not do this directly; You should use an image for this, or svg might do the trick but that's a hell of a lot more complicated and browsers do not all support it that well. A: You should just be able to do this <div> <h1>Title</h1> </div> Place the background-image on the div The h1 will be transparent by default. To center the title, use text-align:center To center the background image, you can use background-position:center Example: http://jsfiddle.net/jasongennaro/EQDZd/
{ "language": "en", "url": "https://stackoverflow.com/questions/7626219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why Progress Indicator is not starting from View Controller class? I have a progress indicator in one of my classes, that is subclass of NSViewController.It is connected with Outlet. When I'm trying to start indicator in initialization time of that class, and show content in main Window, from App Delegate, indicator is not starting what the reason?What I tried is here [indicator startAnimiton:[self view]]; //in initWithNib function , but it's not starting But when I try to start it from App Delegate [MyClass.indicator startAnimation:self]; is working. Did I miss something? How can I start Indicator from my Controller , when I initialize it. A: You should start the progress indicator in awakeFromNib because only then all outlets are guaranteed to be connected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I stop this div from sitting on top of the scrollbar without breaking my JQuery ScrollTo plug-in? I am having a little bit of trouble with a website I'm building. I am using the jQuery plug-in "scroll to" as the website is one complete page with different sections. Now I am trying to keep the navigation bar fixed at the top of the page when the user scrolls down, but at the moment it is sitting over the top of the scrollbar. I found an answer for how to stop it sitting on top of the scrollbar, which said that I should remove "overflow:auto;" from the 'wrapper' div, but somehow, this killed my ScrollTo plug in, and the links no longer worked. I want one scrollbar on the right hand side of the page, that users can use to scroll down, but I want the big white navigation bar to stay at fixed at the top. My website can be downloaded from this link > http://dl.dropbox.com/u/14917277/YW4YW%20Website.zip - It is only a small website so will not take two seconds to download. Any help is HUGELY appreciated, thanks a load guys and girls! A: Why are putting your content in a wrapper overflowing div? This is happening because the wrapper has a z-index that is lower than the top bar. Remove the wrapper. Just let the content overflow normally! Replace your index file with this: <html lang="en"> <head> <meta charset=utf-8> <link rel="stylesheet" type="text/css" href="css/fonts.css" /> <link rel="stylesheet" type="text/css" href="css/main.css" /> <script type="text/javascript" src="jquery/jquery-1.6.2.min.js"></script> <script type="text/javascript" src="jquery/jquery.scrollTo.js"></script> <script> $(document).ready(function() { $('a.panel').click(function () { $('a.panel').removeClass('selected'); $(this).addClass('selected'); current = $(this); $(document).scrollTo($(this).attr('href'), 800); return false; }); $(window).resize(function () { resizePanel(); }); }); function resizePanel() { width = $(window).width(); height = $(window).height(); mask_height = height * $('.item').length; $('#debug').html(width + ' ' + height + ' ' + mask_height); $('body .item').css({width: width, height: height}); $('body').css({width: width, height: mask_height}); $(document).scrollTo($('a.selected').attr('href'), 0); } </script> <title>Young Women 4 Young Women - Breast Cancer Support Group - Southmead Hospital, Bristol</title> </head> <body> <div id="top-wrap"> <div id="top-bar"></div> <!-- CLOSE TOP-BAR --> <div id="navigation-wrapper"> <div id="navigation-bar"> <div id="navigation-main"> <a href="#item1" class="panel">HOME</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#item2" class="panel">ABOUT THE GROUP</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#item3" class="panel">SCHEDULE</a> </div> <!-- CLOSE NAVIGATION-MAIN --> <div id="navigation-main-2"> <a href="#item4" class="panel">IN THE NEWS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#item5" class="panel">LINKS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#item6" class="panel">GET IN TOUCH</a> </div> <!-- CLOSE NAVIGATION-MAIN-2 --> </div> <!-- CLOSE NAVIGATION-BAR --> </div> <!-- CLOSE NAVIGATION-WRAPPER --> <div id="emblem"><a href="index.html"><img src="images/emblem.png" alt="Young Women 4 Young Women" /></a></div> <!-- CLOSE EMBLEM --> </div> <!-- CLOSE TOP-WRAP --> <div id="item1" class="home-area"> <a name="item1"></a> <div class="content"> <div class="home-header-wrap"> <div class="home-pad"></div> <div class="home-header-image"><div class="home-cleardiv"></div><h1>YOUNGWOMEN4YOUNGWOMEN.COM</h1></div> <div class="home-pad"></div> </div> <div class="justify"><span class="text">Young Women 4 Young Women is a </span><span class="red-text">support group</span><span class="text"> for women who have been affected by breast cancer. We meet once a month at Southmead Hospital in </span><span class="red-text">Bristol</span><span class="text"> for a chat and a cup of tea.<br /><br /> Over the past </span><span class="red-text">eleven years</span><span class="text"> we have welcomed women of all ages with a wide range of experiences. Whether you are looking for friendship, understanding, comfort, encouragement, laughter, company, support, compassion, of just </span><span class="red-text">somebody to talk to</span><span class="text"> who knows what it's like, we're here for you.</span> <br /><br /> <div class="center"><span class="text">The kettles on so come on in!</span></div></div> </div> </div> <div id="item2" class="about-area"> <a name="item2"></a> <div class="content"> <div class="about-us-header-wrap"> <div class="about-us-pad"></div> <div class="about-us-header-image"><div class="about-us-cleardiv"></div><h1>WHO ARE WE, AND WHAT DO WE DO?</h1></div> </div> <br /> <ul class="box"> <li><img src="images/portrait.png"></li> </ul> <div class="divide-wrap"> <div class="divide-bar"></div> <div class="scroll"><a href="#item1" class="scroll-arrow panel"></a></div> </div> </div> </div> <div id="item3" class="when-area"> <a name="item3"></a> <div class="content"> <div class="schedule-header-wrap"> <div class="schedule-header-image"><div class="about-us-cleardiv"></div><h1>WHO ARE WE, AND WHAT DO WE DO?</h1></div> <div class="schedule-pad"></div> </div> </div> </div> <div id="item4" class="news-area"> <a name="item4"></a> <div class="content"> <div class="in-the-news-header-wrap"> <div class="in-the-news-pad"></div> <div class="in-the-news-header-image"><div class="in-the-news-cleardiv"></div><h1>DEVELOPMENTS &amp; INNOVATIONS IN SURGERY &amp; TREATMENT</h1></div> </div> </div> </div> <div id="item5" class="links-area"> <a name="item5"></a> <div class="content"> <div class="useful-links-header-wrap"> <div class="useful-links-header-image"><div class="useful-links-cleardiv"></div><h1>SUPPORT, SERVICES & RETAILERS</h1></div> <div class="useful-links-pad"></div> </div> </div> </div> <div id="item6" class="contact-area"> <a name="item6"></a> <div class="content"> <div class="get-in-touch-header-wrap"> <div class="get-in-touch-pad"></div> <div class="get-in-touch-header-image"><div class="get-in-touch-cleardiv"></div><h1>SEND US AN E-MAIL OR POP A LETTER IN THE POST</h1></div> </div> </div> <div class="footer-wrapper">TEST</div> </div> </body> </html> However, I would like to say the site is looking quite nice. Kpsuperplane
{ "language": "en", "url": "https://stackoverflow.com/questions/7626223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery ui datepicker : custom dayname headers general information: I'm using the datpicker to set opening hours for stores.. for an entire year. For this I have buttons to select all mondays etc of the entire year and then i have other buttons that add the classes. for instance you click "monday", which selects all mondays of the year in the calendar. then you click the 'class' button and all mondays get the openening hours '9:00-17:00'. I do this by saving an array of 366 days with the class info for each day. So every selection of one or more day is simply converted to a day of the year and that index of the array is updated. this works nicely but now i want to achieve the same effect on a week basis. so i did the following: i'm trying to achieve custom daynames, turning them into links to select for instance all mondays of that month. what i got so far: //javascript $("#datepicker").datepicker({ ... beforeShowDay: setHollidays, dayNamesMin: ['<a class="weekSelector" href="7">Zo</a>', '<a class="weekSelector" href="1">Ma</a>', '<a class="weekSelector" href="2">Di</a>', '<a class="weekSelector" href="3">Wo</a>', '<a class="weekSelector" href="4">Do</a>', '<a class="weekSelector" href="5">Vr</a>', '<a class="weekSelector" href="6">Za</a>'], monthNames: ['January<span class="invisible">0</span>', 'February<input type="hidden" value="1" class="invisible"/>', 'March<input type="hidden" value="2" class="invisible"/>', 'April<input type="hidden" value="3" class="invisible"/>', 'May<input type="hidden" value="4" class="invisible"/>', 'June<input type="hidden" value="5" class="invisible"/>', 'July<input type="hidden" value="6" class="invisible"/>', 'August<input type="hidden" value="7" class="invisible"/>', 'September<input type="hidden" value="8" class="invisible"/>', 'October<input type="hidden" value="9" class="invisible"/>', 'November<input type="hidden" value="10" class="invisible"/>', 'December<input type="hidden" value="11" class="invisible"/>'], ... }); //selects all days of the month (for one month) that are a given week days. for example: all mondays $("a.weekSelector").click(function () { selDay = $(this).attr("href"); // get the day index markerType = 'month'; //use in beforeShowday function to select the days // added code var container = $(this).parent('.ui-datepicker-group'); alert($(container).find('.invisible').val()); // end of added code $("#datepicker").datepicker("refresh"); resetMultiSelect(); //reset variables used for the selection return false; }); //setHollidays adds the correct classes the the days. this works as well, but if the days always get selected in the first month (ie january). Because i don't have acces to the month. so when i select the header 'monday' for the month 'march' ,all mondays for january are selected. so finally here's my question: how can i get the month (or first date in the month) in the $("a.weekSelector").click function? edit: when it's finished it will be turned into a drupal module and probably a jquery plugin. A: here's my 'dirty' way to fix it (in the click function): var el = $(this); var offset = el.offset(); var elTop = offset.top; var elLeft = offset.left; var arr = $("a.weekSelector[href='"+selDay+"']"); $.each(arr, function(i, val) { var curTop = $(val).offset().top; var curLeft = $(val).offset().left; if((elTop == curTop) && (elLeft == curLeft)) { selmonth = $(".invisible:eq("+i+")").val(); } }); what this basically does is retrieve all the weekselectors with the same href as the one clicked (for example all the 'monday' links), then compare there offset to the offset of the clicked element. then I used the id I get from that, to search for the hidden field. I tried searching through the DOM for the hidden field but it always seemed to return undefined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove all items of an array except the last 5 on PHP Possible Duplicate: Remove elements from array? how would I remove all array elements but last 5 ones? The array is a log, but the log will become extensive so I just want to see the five recent items (a.k.a. last five elements) A: $new = array_slice($old, -5) A: Use array_slice: $a5 = array_slice($arr, -5); A: if you are getting this array from the text file, you shouldn't read the whole file into array. either use a command line utility to get 5 last lines, $last5 = `tail $logfile`; or at least read only last chunk of it, of considerable side of, say 1Kb and than get last 5 out of it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: MySQL apply a value a field of each row based on the order of another field I have a table which I would like to apply a price rank for each record. 1 for the highest, 2 for the next highest, 3 for the next highest. Currently I'm selecting each row and then updating each record individually like so: Usage: function get_list('table','order field','order direction') - returns associative array foreach(get_list('ps2','price','DESC') as $p) { $ct++; $s = "UPDATE `ps2` SET `price_rank` = '".$ct."' WHERE `db_id` = '".$p[db_id]."' LIMIT 1"; mysql_query($s); } As I have many records this is extremely slow, is there another way? Edit: Here's one way which is way faster but is there a better way? ALTER TABLE `ps2` DROP `price_rank` ; ALTER TABLE `ps2` CHANGE `db_id` `db_id` INT( 11 ) NOT NULL ; ALTER TABLE `ps2` DROP PRIMARY KEY ; ALTER TABLE `ps2` ORDER BY `price_per_pax_after_tax` DESC; ALTER TABLE `ps2` ADD `price_rank` INT NOT NULL AUTO_INCREMENT PRIMARY KEY; ALTER TABLE `ps2` ORDER BY `db_id`; ALTER TABLE `ps2` CHANGE `price_rank` `price_rank` INT( 11 ) NOT NULL ; ALTER TABLE `ps2` DROP PRIMARY KEY ; ALTER TABLE `ps2` ADD PRIMARY KEY ( `db_id` ) ; ALTER TABLE `ps2` CHANGE `db_id` `db_id` INT( 11 ) NOT NULL AUTO_INCREMENT ; A: Personally I would handle the ranking in the DML statements using aggregate functions like MAX and limit and offset to get the results I want. Also when the price changes you will have to repopulate the rank values if you store them in the table. The current methods above do not handle identical prices. You can return the rank without storing it with this SELECT p.db_id, COUNT(DISTINCT p2.price) as Rank FROM packages_sorted as p JOIN packages_sorted as p2 ON p.price <= p2.price GROUP BY p.db_id If you still want to store the rank, UPDATE FROM packages_sorted as p JOIN ( SELECT p.db_id, COUNT(DISTINCT p2.price) as PriceRank FROM packages_sorted as p JOIN packages_sorted as p2 ON p.price <= p2.price GROUP BY p.db_id ) as pSub ON p.db_id = pSub.db_id SET p.price_rank = pSub.PriceRank Both of those statements handle identicle prices with the count distinct.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cakephp vs Codeigniter I'm a Cakephp developer but my colleagues say that it is slow compared to Codeigniter and I must say that there shouldn't be too much of a difference since you can use cache to speed things up. Is the speed that noticeable with Cakephp and Codeigniter and is it a significant issue over selecting CI over Cake or should I not bother too much about this? A: Speed, does not suppose to be the key in your decision of your framework. number of features that are built in with the framework should be one of your first priorities. this is for example some thing that will help you speed up things and not develop from scratch Community size and development life cycle of the FW are also important. You should always remember that choosing a framework is very subjective and depend on your needs. So my opinion here that there is not one sharp answer, it is always about trade off's in life.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the concept of default constructor? help me in getting the concept of default constructor with example. i don't know when to use default constructor in the program and when not to. help me coming over this problem.explain it with an example for me. when it is necessary to use it? #include<iostream> using namespace std; class abc { public: abc() { cout<<"hello"; } }; int main() { abc a; system("pause"); return 0; } so actually what is the use of default constructor and when it is necessary to use it? A: A class that conforms to the concept DefaultConstrutible allows the following expressions (paragraph 17.6.3.1 of N3242): T u; // object is default initialized T u{}: // object is value intialized T(); T{}; // value initialized temporary So much for the concept. Paragraph 12.1/5 actually tells us what a default constructor is A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4). An implicitly-declared default constructor is an inline public member of its class. ... With the introduction of deleted special member functions, the standard also defines a list of cases where no implicit default constructor is available and the distinction of trivial and non-trivial default constructors. A: * *Constructor is a special function, without return type. Its name must be as the class\struct name. It doesn't have an actual name as a function, as Kerrek-SB pointed out. *Default constructor is the one that has no parameters, or has parameters all with a default value. *Constructor function is being called only once - when an object is instantiated *Constructor is called through a new expression or an initialization expression. It cannot be called "manually". *Useful for initializing object's fields, usually with a member initializer list. Check this. A: If you don't need to do anything as your class is instantiated. Use the default constructor, any situation else you will have to use your own constructor as the default constructor basically does nothing. You also don't need to write any "default" constructor. class abc { }; int main() { abc a; //don't want to do anything on instatiation system("pause"); return 0; } class abc { private: int a; public: abc(int x) { a = x }; } int main() { abc a(1); //setting x to 1 on instantiation system("pause"); return 0; } A: Default constructor is constructor with no argument and will be called on these situations: * *Instancing or newing an object of a class without any constructor, like: abc a; abc* aptr=new abc; *Declaring an array of a class, like: abc a_array[10]; *When you have a inherited class which does not call one of base class constructors *When you have a feature in your class from another class and you don't call a definite constructor of that feature's class. *When you use some containers of standard library such as vector, for example: vector <abc> abc_list; In these situations you have to have a default constructor, otherwise if you do not have any constructor, the compiler will make an implicit default constructor with no operation, and if you have some constructors the compiler will show you a compile error. If you want to do one of the above things, use a default constructor to make sure every object is being instantiated correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: get row with max from group by results I have sql such as: select c.customerID, sum(o.orderCost) from customer c, order o where c.customerID=o.customerID group by c.customerID; This returns a list of customerID, orderCost where orderCost is the total cost of all orders the customer has made. I want to select the customer who has paid us the most (who has the highest orderCost). Do I need to create a nested query for this? A: You need a nested query, but you don't have to access the tables twice if you use analytic functions. select customerID, sumOrderCost from ( select customerID, sumOrderCost, rank() over (order by sumOrderCost desc) as rn from ( select c.customerID, sum(o.orderCost) as sumOrderCost from customer c, orders o where c.customerID=o.customerID group by c.customerID ) ) where rn = 1; The rank() function ranks the results from your original query by the sum() value, then you only pick those with the highest rank - that is, the row(s) with the highest total order cost. If more than one customer has the same total order cost, this will return both. If that isn't what you want you'll have to decide how to determine which single result to use. If you want the lowest customer ID, for example, add that to the ranking function: select customerID, sumOrderCost, rank() over (order by sumOrderCost desc, customerID) as rn You can adjust you original query to return other data instead, just for the ordering, and not include it in the outer select. A: You need to create nested query for this. Two queries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using NHibernate and Mono.Data.SQLite I read and implemented Trying to using Nhibernate with Mono & SQLite - can't find System.Data.SQLite However, as the last comment there states this seems not to work with NHibernate 3.1 The error is HibernateException: The IDbCommand and IDbConnection implementation in the assembly Mono.Data.Sqlite could not be found. Ensure that the assembly Mono.Data.Sqlite is [...reachable...] I have Mono.Data.Sqlite in the GAC. I have tried both specifying "Mono.Data.Sqlite" as well as typeof(Mono.Data.Sqlite.SqliteConnection).Assembly.FullName as the name of the assembly Has anyone any Ideas how to get this working? A: There is a problem in the answer of Trying to using Nhibernate with Mono & SQLite - can't find System.Data.SQLite . For the given constructor (3 parameters) to work the assembly in question (Mono.Data.Sqlite) needs to be loaded first. This works if the 4-parameter base contructor is used like this: public class MonoSQLiteDriver : NHibernate.Driver.ReflectionBasedDriver { public MonoSQLiteDriver() : base( "Mono.Data.Sqlite", "Mono.Data.Sqlite", "Mono.Data.Sqlite.SqliteConnection", "Mono.Data.Sqlite.SqliteCommand") { } public override bool UseNamedPrefixInParameter { get { return true; } } public override bool UseNamedPrefixInSql { get { return true; } } public override string NamedPrefix { get { return "@"; } } public override bool SupportsMultipleOpenReaders { get { return false; } } } (Still, credit goes to http://intellect.dk/post/Why-I-love-frameworks-with-lots-of-extension-points.aspx for the original idea - thanks.) And if you use FluentNHibernate, then you'll also need: public class MonoSQLiteConfiguration : PersistenceConfiguration<MonoSQLiteConfiguration> { public static MonoSQLiteConfiguration Standard { get { return new MonoSQLiteConfiguration(); } } public MonoSQLiteConfiguration() { Driver<MonoSQLiteDriver>(); Dialect<SQLiteDialect>(); Raw("query.substitutions", "true=1;false=0"); } public MonoSQLiteConfiguration InMemory() { Raw("connection.release_mode", "on_close"); return ConnectionString(c => c .Is("Data Source=:memory:;Version=3;New=True;")); } public MonoSQLiteConfiguration UsingFile(string fileName) { return ConnectionString(c => c .Is(string.Format("Data Source={0};Version=3;New=True;", fileName))); } public MonoSQLiteConfiguration UsingFileWithPassword(string fileName, string password) { return ConnectionString(c => c .Is(string.Format("Data Source={0};Version=3;New=True;Password={1};", fileName, password))); } } I have not encountered any problems so far...
{ "language": "en", "url": "https://stackoverflow.com/questions/7626251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Fast and easy data import tools/libraries I'm looking tools/libraries which allows fast (easy) data import to existing database tables. For example phpmyadmin allows data import from .csv, .xml etc. In Hadoop hue via Beesvax for Hive we can create table from file. I'm looking tools which I can use with postgresql or libraries which allows doing such things fast and easily - I'm looking for way to avoid coding it manualy from reading file to inserting to db via jdbc. A: You can do all that with standard tools in PostgreSQL, without additional libraries. For .csv files you can use the built in COPY command. COPY is fast and simple. The source file has to lie on the same machine as the database for that. If not, you can use the very similar \copy meta-command of psql. For .xml files (or any format really) you can use the built in pg_read_file() inside a plpgsql function. However, I quote: Only files within the database cluster directory and the log_directory can be accessed. So you have to put your source file there or create a symbolic link to your actual file/directory. Then you can parse it with unnest() and xpath() and friends. You need at least PostgreSQL 8.4 for that. A kick start on parsing XML in this blog post by Scott Bailey.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Capacity planning of the Cache size How to do the capacity planning of the cache - for e.g. how much RAM to allocate for ehCache, memcache or dynacache? Is there any industry standard formula? For e.g. I have about 60,000 Records in the database. This is the company data - which contains company name, description and company code. I want to implement a typeahed feature using jQuery and want to store this company name details in the cache. What would be ideal cache size? I know that cache size is limited to the amount of free memory available but interested to know a specific way? or is t a trial and error where you start with some size and test, plot a graph and keep adjusting the cache size. Update Company Id - CHAR(9) Company Name - VARCHAR2 (250 CHAR) Company Desc - NVARCHAR2(1000 CHAR) A: 1) If you have a dedicated cache server then you don't have to worry about how much memory space you have to use. You use can use the maximum amount of free memory available (or close to) and let it do its magic. 2) If the caching server is the same as your web server then you will have to specify how much you allow memcached (dynacache or other) to use. For my point of view, there is not really an ideal cache size. It all depends on how much memory your server have, how much data you have to put in cache etc. As long your memory is properly balances between caching and web server you are good. In this case, you have a little less than 100 MB of data you need to store in cache. Depending how much your server has, it's very small but you will always have to think how much there data grows and also, do you need to add additional data (like clients, products etc...). So if you put less than you need, you will have to stop the service, increase the value of memory allowed, start the service. If your server process a lot of information that requires lots of memory, then you will have to calculate how much memory and resources these processes takes. Quick example: * *1 Server (cache and web server) with 4G of total memory. *System and processes resources including cronjob, database etc.: 3G *60,000 clients with a total of 100Mb (always use more than the actual size just in case) In this example, 1G of memory left (approximately). It is not recommend to total amount left since you will have enough for your system. I would say using 384Mb or less for your cache will be a good start. You allow your cache to grow and you don't affect your system memory. I would recommend to monitor your server to make sure the memory allocation for your system and your cache balance perfectly. Here's a good article about it: http://techgurulive.com/2009/07/22/how-to-allocate-memory-within-memcached/
{ "language": "en", "url": "https://stackoverflow.com/questions/7626260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: session invalidate in JSF2.0 I'm using JSF2.0 with jsp.I'm trying to incorporate session invalidation in my project.I've tried using the following code. <h:commandButton value="Logout" action="#{bean.logout}" </h:commandButton> and my bean class contains the following method public class Bean{ public String logout(){ FacesContext context = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession)context.getExternalContext().getSession(false); session.invalidate(); return "login"; } } where string login redirects to login page. my project has several pages which includes a header page..when i tried the above way...it was working fine when i click on logout from the very first page...If i try the same after going to other pages, its not logging out.Can anyone help me on this...is this the way we invalidate a session here??? UPDATE I also tried using "*" in the navigation rule so that each page can be redirected to Login...but still the issue was same A: Try return "login?faces-redirect=true" as outcome so the browser does not use the same request for the login-page, which has the session still active. A: Did you try this - return "/login?faces-redirect=true"; If the view login is in the root directory. Otherwise if it's in some other folder then as follows - //if it's in the folder - folder1 return "/folder1/login?faces-redirect=true" Notice / at the beginning of the outcome. A: Use remoteCommand tag and on logout call this remoteCommand using JavaScript and provide the implementation in managedBean for the logout and the implmentation is ok that you paste here just need enter code hereto redirct to login page, or you can use again JavaScript to redirect to login page. <h:commandButton value="Logout" onclick="closeSession();" </h:commandButton> <p:remoteCommand name="closeSession" action="#{jobController.logout}"> public class Bean{ public String logout(){ FacesContext context = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession)context.getExternalContext().getSession(false); session.invalidate(); return "login?faces-redirect=true"; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7626263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why the Nullpointerexception? This is the scenario: class A{ int a; } class B{ A objectA[]=new A[10] ; } class C{ B ObjectB; public static void main(String[] args){ ObjectB.ObjectA[0].a=1; } } I get a nullpointerexception in main operation. However if I declare just one object of class A, I don't get the error. Why so? How do I rectify it? A: (1) B ObjectB; does not create a new instance of B, it just crate the variable, to crate an instance; B ObjectB = new B(); (2) Also A objectA[]=new A[10] ; allocates the array, but not elements in the array, and ObjectB.ObjectA[0].a=1; will also cause NPE. A: calling new B() initializes an array of objects of type A, but none of the member objects. You can rectify it first initializing objectB and then calling objectA[i] = new A() for each item in the array. class B{ A objectA[]=new A[10] ; { for (int i = 0; i < 10; i++) objectA[i] = new A(); } } class C{ B ObjectB = new B(); public static void main(String[] args){ ObjectB.ObjectA[0].a=1; } } A: You have not initialized the ObjectB. There is no memory allocated to ObjectB. Hence showing null pointer exception (Nothing is allocated to ObjectB reference). This should work: class C { B ObjectB = new B(); public static void main(String[] args) { ObjectB.ObjectA[0].a = 1; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7626266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove duplicate vectors inside a vector of vector I have a vector of vector (loops) which contains integer values. Some inside vectors are duplicating but their element order is not the same. Now, I want to get a vector of vector without having any duplicate inner vectors. here is an example for my vec of vec; loops = ((9 18 26 11 9), (9 11 26 18 9),(9 18 25 16 9),(11 45 26 11),( 11 26 45 11),( 16 49 25 16),( 16 25 49 16),(18 9 11 26 18),( 18 9 16 25 18),( 25 16 49 25),( 26 11 45 26)) To identify whether any inner vector is a duplicate of another inner vector; I have developed a function IsDuplicate. This tells me, (9 18 26 11 9) and (9 11 26 18 9) are duplicates then I can delete the second or all other duplicates. To remove duplicate vectors inside my vector of vector, I have implemented following codes. Vector<vector<int> > loops; Vector<vector<int> > ::iterator no1, no2; Int setno1, setno2; for (no1=loops.begin(), setno1=0; no1!=loops.end(); no1++, setno1++){ set1 = *no1; for (no2=loops.begin()+setno1, setno2=setno1; no2!=loops.end(); setno2++){ set2 = *no2; if (set2.IsDuplicate(set1)) loops.erase(loops.begin()+setno2); else no2++; } } it took very very long time and i thought my program is crasihing. so, Please help me to rectify this issue. also, i tried with this. this works but i got a wrong answer. any help please. 01 int first=0; bool duplicates=false; 02 do { 03 set1 = loops[first]; 04 for (no2=loops.begin()+1, setno2=1; no2!=loops.end(); setno2++){ 05 set2 = *no2; 06 if (set2.IsPartOf(set1)){ 07 loops.erase(loops.begin()+setno2); 08 duplicates = true; 09 } 10 else no2++; 11 } 12 first++; 13 } while(!duplicates); A: The idiomatic way is to use the Erase/Remove idiom with a custom predicate. To check for duplicate vectors and without modifying the contents of your vectors, write a predicate that takes its arguments by value, sort the vectors and use std::equal. bool equal_vector(std::vector<int> a, std::vector<int> b) { std::sort(a.begin(), a.end()); std::sort(b.begin(), b.end()); return std::equal(a.begin(), a.end(), b.begin()); } // use it like this v.erase( remove_if(v.begin(), v.end(), equal_vector), v.end() ); As to why your current code fails: Erasing an element from a vector invalidates all other iterators to that vector that are currently in existence thus vector::erase returns a valid iterator to the position after the element that has been removed. The stdlib also provides the set and multiset container which look like a much better fit for your purpose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Symmetric multiprocessing and Distributed systems? Are distributed systems a completely independent concept compared to symmetric multiprocessing (since in distributed, we have individual memory/disk storage per CPU whereas in symmetric we have many CPU's utilizing the same memory/disk storage)? A: I wouldn't say they are completely different concepts, because you can get a shared memory in distributed systems (using Distributed shared memory), and multiple processes running on the same machine don't share their address space. So both environments can exists on both architectures, but with a cost. In general, shared memory is easier to program but harder to build (from the hardware point of view), and distributed systems are harder to program but easier to build. So, the different concepts are actually shared memory and non-shared memory, at least from the programming point of view. A: Distributed Computing and SMP are not the same, although DC might use SMP. DC is a way of how to parallelize independant workload-data to heterogenous and loosely coupled different systems. A SMP system is a machine with tightly coupled CPUs and memory, benefiting from low-latency memory-access and sharing data amongst CPUs while the computations happen. Example for distributed computing: Einstein@Home is a project trying to find gravitational waves from experimental data gathered from huge Laser interferometers. The data to be crunched is pretty independent, so distributing the data to several different machines is no problem. * *Storage: Shared storage not needed. *Shared Memory: Not needed, since the FFT routines used to find the desired results work on independant data chunks. *Workload distribution: Is done over a pool of heterogenous machines. Example for Symmetric Multiprocessing: Running computations on large tables/matrices needs a certain proximity of the computing nodes ("CPUs"/"DC-nodes") to be able to finish the computation. If the result of a computation depends on the result of a "neighboring" node, the Distributed Computing paradigm wouldn't help you much. * *Storage: Should be shared and be accessible as fast as possible *Shared Memory: Needed to exchange interim results *Workload distribution: Takes place in a for-loop compound; the programmer has to care to design his loops in a way, that related computations happen at almost the same time Hope that helps... Alex.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Div overlay hue issue only in IE8 Please visit http://www.in2medical.com/ with IE8. There seems to be some sort of lighter hue over the dark blue bar (in which the logo resides) on top. This hue is not visible in IE9, chrome or firefox.. It looks like in IE8 the div in which I place the content and I position on top of the background is automatically changing the color of the div over which it lays. How is this happening? A: Save /images/bg_logobar.png without the embedded colour profile. I did it for you, but you need to learn how to fix it yourself or you'll have the same problem again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVP: How does presenter access view properties? I will give a full example that compiles: using System.Windows.Forms; interface IView { string Param { set; } bool Checked { set; } } class View : UserControl, IView { CheckBox checkBox1; Presenter presenter; public string Param { // SKIP THAT: I know I should raise an event here. set { presenter.Param = value; } } public bool Checked { set { checkBox1.Checked = value; } } public View() { presenter = new Presenter(this); checkBox1 = new CheckBox(); Controls.Add(checkBox1); } } class Presenter { IView view; public string Param { set { view.Checked = value.Length > 5; } } public Presenter(IView view) { this.view = view; } } class MainClass { static void Main() { var f = new Form(); var v = new View(); v.Param = "long text"; // PROBLEM: I do not want Checked to be accessible. v.Checked = false; f.Controls.Add(v); Application.Run(f); } } It's a pretty simple application. It has an MVP user control. This user control has a public property Param which controls its appearance. My problem is that I want to hide the Checked property from users. It should be accessible only by the presenter. Is that possible? Am I doing something completely incorrect? Please advise! A: You can't completely hide it from the end user, and truthfully, you don't need to. If someone wants to use you user control directly, your control should be dumb enough to just display the properties that are set on it, regardless if they were set through a presenter or not. The best you can do however (if you still insist on hiding those properties from your user), is to implement the IView explicitly: class View : UserControl, IView { CheckBox checkBox1; Presenter presenter; string IView.Param { // SKIP THAT: I know I should raise an event here. set { presenter.Param = value; } } bool IView.Checked { set { checkBox1.Checked = value; } } public View() { presenter = new Presenter(this); checkBox1 = new CheckBox(); Controls.Add(checkBox1); } This way, if someone just does: var ctl = new View(); they won't have access to those properties.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to write event logs into xml files with SLF4J or Logback? I want to create a customized log viewer and I need to integrate log files generated in .Net and Java platforms. First of All I want to know if I could write log events into a well-formed xml format with SLF4J or logback. Any Idea? A: logback-classic supports the log4j XML layout. See here: http://logback.qos.ch/manual/layouts.html Regarding SLF4J: it is a logging facade, rather than a logger. It provides a convenient way to decouple your logging API from the implementation, allowing you to change the actual logging library later. However, it won't log anything else itself, so you can't configure it to use XML. If you want to use The SLF4J API and logback to perform the actual logging, you will need the appropriate logback binding jar. You can find it on the SLF4J web site. A: You might take a look at one of my answers to a similar problem. It's about log4j, but it's valid for logback as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use C# 4.0 tasks feature with these properties - assigning variables on run time - keep certain number of tasks alive Alright i have been searching for days but there is no example of what i am trying to achieve. Currently i am able to use tasks for multi-threaded crawling but it is very bad written. You can see the whole code from here : http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/6fa6fd12-85c5-4489-81b1-25bc0126d406 Now coming my question. I want to use System.Threading.Tasks.Task for multi-threading. Development is microsoft visual studio 2010 and C# 4.0. What i need is 1-) I want to keep certain number of tasks running for all the time. So when a thread finished its job another thread should start working immediately. With this way always certain number of threads will be actively running. 2-) I need to be able to give tasks variables on run time. So think as i have a links pool. I started with first 100 but lets say 45 th task finished first. So another task will be created and this task will take number 101 th link. When another one finished it will continue as this way and always certain number of tasks will be alive. 3-) I need to be able to collect results of tasks. After a task finished somehow collect the result. This part seems like the easiest part. Whichever task example i found just shows 2 task or 3 task , getting certain variables not changing on run time and not keeping certain numbers alive. Multi-threaded applications are the future but there is so bad documentation. A: Have you looked into the TPL-DataFlow CPL yet: TPL Dataflow (TDF) is a new .NET library for building concurrent applications. It promotes actor/agent-oriented designs through primitives for in-process message passing, dataflow, and pipelining. TDF builds upon the APIs and scheduling infrastructure provided by the Task Parallel Library (TPL) in .NET 4, and integrates with the language support for asynchrony provided by C#, Visual Basic, and F#. It's beta but I think your problem are not the threads. Seems you are trying to build some kind of Agent-based programming model and this DataFlow gives you some really nice tools for this. Here is the Homepage and here is a nice video on this. A: Why do you NEED a certain number of tasks? Let the pool/API decide. Passing data to tasks is just like passing data to threads: share a data structure. Use Task to return a result from a task EDIT You cannot set the number of worker threads or the number of I/O completion threads to a number smaller than the number of processors in the computer. If the common language runtime is hosted, for example by Internet Information Services (IIS) or SQL Server, the host can limit or prevent changes to the thread pool size. Use caution when changing the maximum number of threads in the thread pool. While your code might benefit, the changes might have an adverse effect on code libraries you use. Setting the thread pool size too large can cause performance problems. If too many threads are executing at the same time, the task switching overhead becomes a significant factor. (from the MSDN) Really, you can never force a specific number of tasks to be active. Just create the tasks and allow the run-time to decide which ones should/can run. If you don't like that, do not use the TPL and bring your own threads.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Google OAuth on localhost I started to use OAuth with Python and Django. I need it for Google APIs. I working on localhost, so I can't register a domain for url-callback. I've read about that Google OAuth could be used with anonymous domain. Can't find, how and where I can do that? Edit: I have this view: def authentication(request): CONSUMER_KEY = 'xxxxx' CONSUMER_SECRET = 'xxxxx' SCOPES = ['https://docs.google.com/feeds/', ] client = gdata.docs.client.DocsClient(source='apiapp') oauth_callback_url = 'http://%s/get_access_token' % request.META.get('HTTP_HOST') request_token = client.GetOAuthToken( SCOPES, oauth_callback_url, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET) domain = '127.0.0.1:8000' return HttpResponseRedirect( request_token.generate_authorization_url(google_apps_domain=domain)) And this error: Sorry, you've reached a login page for a domain that isn't using Google Apps. Please check the web address and try again. Registered via https://code.google.com/apis/console/ Edit: CONSUMER_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx' CONSUMER_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxx' SCOPES = ['https://docs.google.com/feeds/', ] DOMAIN = 'localhost:8000' def authentication(request): client = gdata.docs.client.DocsClient(source='apiapp') oauth_callback_url = 'http://%s/get_access_token' % DOMAIN request_token = client.GetOAuthToken(SCOPES, oauth_callback_url, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET) return HttpResponseRedirect( request_token.generate_authorization_url()) def verify(request): client = gdata.docs.client.DocsClient(source='apiapp') f = open('/home/i159/.ssh/id_rsa') RSA_KEY = f.read() f.close() oauth_callback_url = 'http://%s/get_access_token' % DOMAIN request_token = client.GetOAuthToken(SCOPES, oauth_callback_url, CONSUMER_KEY, rsa_private_key=RSA_KEY) return HttpResponseRedirect( request_token.generate_authorization_url(google_apps_domain=DOMAIN)) The error: Unable to obtain OAuth request token: 400, Consumer does not have a cert: xxxxxxxxxxxxxxx.apps.googleusercontent.com A: OAuth 1.0 for Installed Applications Besides that, you probably don't want to include your actual CONSUMER_KEY and CONSUMER_SECRET in the example code. A: Just to be clear, you can use the web application flow with localhost while developing on either OAuth 1.0 or OAuth 2.0. OAuth 2.0 should be preferred as it's the mechanism we are focussed on. The user experience for OAuth 2.0 is going to be substantially better. There's nothing stopping you from using localhost as your callback URL. I do this myself all the time. You just need to make sure the callback URL matches exactly, including any port numbers, and you can't deploy your application that way for obvious reasons. Installed applications are more complicated, but if you're doing something with Django, it's possible to take advantage of the fact that OAuth 2.0 is a bearer-token system. As long as you're keeping the refresh token server-side, you can authenticate with your own application out-of-band and then send the bearer token to the installed application. Your installed application will have roughly a one-hour window in which to make calls before you'll need to repeat the process. This can happen transparently to the user in most cases. Transmission of the bearer token should happen over an encrypted channel. A: Try your code without arguments: return HttpResponseRedirect(request_token.generate_authorization_url())
{ "language": "en", "url": "https://stackoverflow.com/questions/7626299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: make castle widsor not load all modules I am using castle windsor to dynamically load some modules. is it possible to ask castle widsor to not load a specific module? I want to instantiate that module manually and then add it to the list of modules A: Based on the comment (I think you meant components, not modules?) you can use IHandlersFilter in Windsor 3. See this blogpost for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get current date and time in XSLT 1.0 I am using xslt 1.0, I am trying to print current date and time to my node. Below is the sample xslt <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:tcm="http://www.tridion.com/ContentManager/5.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:em="http://www.emirates.com/tridion/schemas" xmlns:tcmse="http://www.tridion.com/ContentManager/5.1/TcmScriptAssistant" exclude-result-prefixes="em xlink tcmse tcm"> <xsl:output method="xml" version="1.0" encoding="UTF-16" indent="yes"/> <!-- Common XSLT Templates--> <xsl:include href="tcm:228-190524-2048"/> <!-- root match--> <xsl:template match="root"> <sitedata> <resources> <PublishedDate> <xsl:value-of select="$publishedDate"/> </PublishedDate> </resources> </sitedata> </xsl:template> In above XSLT, in the place of $publishedDate I want system current date and time please suggest!! A: XSLT 1.0 does not provide any standard way to get the current date/time. You can call an extension function to do it (depends on your processor), or you can pass it to the stylesheet as the value of a parameter. A: Here is how to do this with the msxsl.exe command-line utility (for MSXML): XSLT code (testParams.xsl): <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:param name="vDate" select="xyz"/> <xsl:template match="/"> "<xsl:value-of select="$vDate"/>" </xsl:template> </xsl:stylesheet> XML document (t.xml) (fake, ignored): <t/> Command-line: msxsl t.xml testParams.xsl -o con vDate='%date%' Result: "Sun 10/02/2011"
{ "language": "en", "url": "https://stackoverflow.com/questions/7626309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Handling an exception properly I am not good at handling exceptions, so I need a hint at this occasion: I want to put arrays in a collection (ArrayList) all of which should be of the same length. Otherwise errors emerge in computations. When an array of not desired length is to be inserted in the ArrayList, I would like to throw an exception with a message. What kind of exception is suitable for this occasion? What worries me is that I have to check the size of the array which is to be inserted (with an if statement). Is it reasonable to have an if statement inside a try block? Here is the relevant fragment code: inputdata: the arrayList arraylength: the length of the array specified by the first array inserted Could somebody modify the try - catch block? public void insertData(double[] arraydata){ if(this.inputdata.isEmpty()){ inputdata.add(arraydata); this.arraylength = arraydata.length; }else{ try { if(this.arraylength == arraydata.length) inputdata.add(arraydata); }catch(Exception exception){ System.err.printf("Missmatch array dimensions in %d place",inputdata.size()+1); } } } A: Exceptions should only be for exceptional cases. If this is a frequent occurrence, you might want to handle it another way, with standard logic in the workflow. For example, you could retur n true if you can insert the data, and false if the array to insert is not the right length. Or you could check when the user enters the array values, and tell them then that the length has to be x. If this does represent an exceptional case throw an IllegalArgumentException, as in if(this.arraylength == arraydata.length) inputdata.add(arraydata); } else { throw new IllegalArgumentException("Ever array needs same length..."); } something like that. As written, your code right now is catching any exception thrown in the add operation. You should throw, instead of catch, an exception in your insertData method, as my example demonstrates. The exception should be caught outside of the insert data method. This means you don't need a try/catch statement in insertData. Also note that IllegalArgumentException is a Runtime exception, so it does not need to be thrown or caught if you don't want to. You still can catch it, if you want. A: What you are doing in try { if(this.arraylength == arraydata.length) inputdata.add(arraydata); }catch(Exception exception){ System.err.printf("Missmatch array dimensions in %d place",inputdata.size()+1); } Is catching an exception. But inputdata.add is not going throw any exception. Instead, you should throw an exception so that the callers know something is wrong: if(this.arraylength != arraydata.length) throw new IllegalArgumentException("Array length " + arraydata.length + " is not same as previous length " + this.arraylength); inputdata.add(arraydata); The exception includes a helpful message to let the caller know what the mismatch is. Note that I have reversed the test, if the legnth is not acceptable then Exception is thrown; otherwise the execution proceeds to next line. A: What exception is suitable? Depends. Here are some things to consider. * *Is this code part of a method, and was it the intent that the user have the responsibility to pass an array of the right size? The caller made a mistake, so use an IllegalArgumentException. *Is this code part of a larger line of code, and was it the intent that the code would have constructed correctly sized arrays? One of your assumptions is wrong, so use an IllegalStateException. *The situation of wrong-sized arrays is legitimate in some way, and your handler will repair the situation at some level, then continue. I would roll my own Exception for this case. Your code seems to be case (1). The answers provided show some good ways to handle this. I like to use Guava Preconditions myself, since they are self-documenting and less error-prone (no if-statements just to direct the execution around error conditions that require maintenance -- just add new checkSomething calls where they make sense): import static com.google.common.base.Preconditions.checkArgument; <snip> public void insertData(double[] arraydata) { checkArgument(this.arraylength == arraydata.length, "Ever array needs same length..."); inputdata.add(arraydata); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7626317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Update using Active Record in CodeIgniter I have a strange problem, maybe I just don't understand how Active Record works well enough, but here it is. I'm trying to update a record with a particular id. For simplicity and testing I'm just supplying the id directly instead of a variable. Now, if I have understood Active Record correctly, it seems to work very differently from what I'm used to in Asp.Net where I used the Entity Framework ORM. But as far as I have understood it you can select the record first in one line and then when you run update in the next line, that particular record will be updated. At least that's how it looks in the documentation. Here's the example from the docs: $data = array( 'title' => $title, 'name' => $name, 'date' => $date ); $this->db->where('id', $id); $this->db->update('mytable', $data); So I tried doing the same thing in my code: $updateData = array( 'description' => 'My localhost' ); $this->myDb->where('id', 2832); $this->db->update('Users', $updateData); Well, that didn't work as expected at all! It did in fact update the database, but it updated each and every record so that all records got the description field updated to "My localhost"! Good thing I'm still just using a test database... I saw in the docs that there was an alternative way as well, by supplying the id in the update statement: $this->db->update('Users', $updateData, array('id' => 2832)); This worked fine, so great. But... I still want to know why the first alternative didn't work, because if I don't understand this I might make other devastating mistakes in the database... I would really appreciate some clarification on how this works, and why all records got updated. A: $updateData = array( 'description' => 'My localhost' ); $this->myDb->where('id', 2832); $this->db->update('Users', $updateData); This is not working because you are applying the "where" clause to $this->myDb and then calling update on $this->db. Since there are no restrictions on $this->db all records are getting updated. Change it to: $this->db->where('id', 2832); $this->db->update('Users', $updateData);
{ "language": "en", "url": "https://stackoverflow.com/questions/7626318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to prevent an textfield losing focus using jQuery and JavaScript? I have a textfield <input type="text"/> that I want to validate when the focus is lost. If the input is not valid, I want to prevent the focus moving to the next element, or in other words keep the focus at the invalid input until it's valid. How can I do that using jQuery and JavaScript? I have tried with this code, but it doesn't work (jsFiddle): <!DOCTYPE html> <html> <head> <script src="jquery-1.6.2.min.js"></script> <script> $(function() { $('.hello').bind('focusout', function(e) { if(!isValid($(this).val())) { e.preventDefault(); $(this).foucus(); } }); }); function isValid(str) { if(str === "hello") { return true; } else { return false; } } </script> </head> <body> Only valid content: <b>hello</b><br> <input type="text" class="hello"/> <button>Dummy</button> </body> </html> A: The event should be blur you're looking for. And your original jsfiddle had a typo (.foucus instead of focus) And as a commenter said, visitors won't like this behavior. http://jsfiddle.net/qdT8M/4/ A: $("#input").focus(); $("#input").blur(function() { setTimeout(function() { $("#input").focus(); }, 0); }); A: It's just a typo. Change: $(this).foucus(); To: $(this).focus(); Also, you might want to make it easier for your users to correct their mistake by also calling select on the textbox. That way, they can just begin typing again to change the value: $(this).focus().select(); Here is a working example. Note: This answer fixes the problem at hand, i.e. the question that was asked. On a broader scale, I do agree with the others who are saying that one shouldn't lock the user into a field. A better way of doing this would be to validate the whole form on submit, letting the users see all the problems and fixing them all at once, instead of bugging them throughout. A: Instead of $(this).focus(), use $(this).trigger('focus');. And the event should be blur, not focusout. Edit: oh well, focus() will work as well :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7626319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do I change an image when it passes a certain point on a page, and then change it back when it is above that point? I am completely new to javascript, but I want to learn it rather than jQuery to get some fundamental knowledge. The function I want to create should animate an arrow to turn upwards when it passes 50% of the page. In addition to this, the function that it calls when upside down should change. So: upArrow onClick(scrollUp) downArrow onClick(scrollDown) I'm sure I sound stupid, but maybe someone can understand what I'm trying to explain. A: You can either write the imageelement.src property to point to a different arrow, or, for extra smoothness, use a CSS sprite containing both arrows and write element.style.backgroundPosition to change the displayed image without having to load a new image. You can assign a new function to imageelement.onclick to change what happens when you click on it, but usually it is simpler to have one click-function that decides what to do based on state. eg: <div id="arrow" class="arrow-down"></div> #arrow { position: fixed; top: 0; left: 0; z-index: 10; width: 32px; height: 32px; background-image: url(/img/arrow.png); } .arrow-down { background-position: 0 0; } .arrow-up { background-position: 0 -32px; } var arrow= document.getElementById('arrow'); window.onscroll=window.onresize= function() { arrow.className= isHalfwayDown()? 'arrow-up' : 'arrow-down'; }; arrow.onclick= function() { var h= document.documentElement.scrollHeight; scrollTo(0, isHalfwayDown()? 0 : h); window.onscroll(); }; function isHalfwayDown() { var y= document.documentElement.scrollTop+document.body.scrollTop; var h= document.documentElement.scrollHeight; return y>=h/2; } Browser compatibility notes: window.onscroll() is because IE doesn't fire the scroll event when scrollTo() is used. Both html and body's scroll offsets have to be added together in isHalfwayDown() because the browsers unfortunately don't agree on which element represents the viewport.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Dynamic form validation in symfony2 Before receiving $_POST information from form submission, I didn't know anything about the number of fields, types or validation rules (whether the field is required, whether it should be a valid email, etc.) In ohter words, the validation rules and fields depend on what i receive in $_POST: user creates form fields and defines validation rules by himself. So I need to set validation rules after I'll receive $_POST What will be most right method to do this in symfony2? A: The solution was simple: http://symfony.com/doc/current/book/forms.html#adding-validation (It seems this paragraph was added not long time ago, or i don't know) A: This is exactly the same thing that happens in CollectionType. There the ResizeFormListener instance listens to the preBind event to dynamically add or remove fields. You should do the same.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone Core Location startMonitoringSignificantLocationChanges I need to know when the user approaches a certain location. On the iPhone 4 I'm using startMonitoringForRegion:desiredAccuracy: but this is not supported on the 3GS (which I want to support), so in this case I'm forced to use startMonitoringSignificantLocationChanges. The thing is, startMonitoringSignificantLocationChanges causes the delegate to be called (and the app to be launched into the background if it is not) for every significant location change, even if it is totally unrelated to my needs. It is easy for me to detect whether the delegate call is relevant for me, but I'm wondering about another thing: If I am launched into the background and then I detect that the call is not relevant, should I stay quietly in the background, or should I abort the app somehow and remove myself from the background until next time? A: If you don't need to do anything with a location update, just return from the method call, and stay idle in the background. Don't try to abort the app, that will just cause unnecessary reloading (using battery) of your app next time you get a significant location change. The OS will terminate background app(s) if and when it decides it needs the memory space. A: I would think that in your callback to the AppDelegate, if you determine the call is not needed, you just return; out and be done. The callback on location change would be called, but unless you decide to stop monitoring, the location monitoring will continue. The app is not brought into the foreground, just method calls from inside the AppDelegate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITableView cell not diplaying images horizontally I want to have only one uitableview cell which can display horizontally as many images as it receives from server. But the problem is currently I receive say 15 images from the server and the cell only displays first 6 images and does not display rest 9 images. However, I can see the horizontal scroller scrolling till the end as i have made the contentsize according to size of 15 images. Following is the code (for testing purpose I am retrieving image from resource folder instead of getting from server ). -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } CGFloat imageXCordinate = 0.0; int i =0; for(i=0; i < 15; i++) { NSString *filePathForIconPhotoImage = [[NSBundle mainBundle] pathForResource:@"icon_photo" ofType:@"png"]; UIImage *iconPhoto = [[UIImage alloc] initWithContentsOfFile:filePathForIconPhotoImage]; UIImageView *vwIcon=[[UIImageView alloc] initWithFrame:CGRectMake(imageXCordinate,2,iconPhoto.size.width,iconPhoto.size.height) ] ; vwIcon.image =iconPhoto; [cell.contentView addSubview:vwIcon]; [vwIcon release]; [iconPhoto release]; imageXCordinate = imageXCordinate + basePhoto.size.width; } [tableView setContentSize:CGSizeMake((basePhoto.size.width * i, tableView.frame.size.height)]; } NOTE: 1. I know I can use a UIScrollView instead but still want to use UITableView for some specific reasons. 2. I have created a UITableView programmatically and placed it in the [self.view addSuvView:myTableView]. Thanks in advance. A: following link will definitely help you how-to-make-an-interface-with-horizontal-tables-like-the-pulse-news-app-part-2
{ "language": "en", "url": "https://stackoverflow.com/questions/7626327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting the character from keyup event I'm handling the keyup event, and need to get the character being typed. When I type a dot, data.keyCode is 190, but when I'm trying to convert it using String.fromCharCode(190), I'm getting the "¾" symbol. This reference tells me 190 is the period symbol. That one says I don't have any chance for cross-browser keypress handling. So, how do I handle this properly? A: I'm handling the keyup event, and need to get the character being typed. That's not reliably available. On keyup you only get the keyCode and not the charCode. (If you think about it this makes sense: the charCode is associated with the character being typed in a keypress, which might be shifted with a modifier key and so generate a different character to the base key; on keyup and keydown, since those events are not immediately associated with a new character being typed, there isn't a known character to generate.) So if you are doing something that relies on knowing whether a . character was typed, you will need to use the keypress event instead. If you want to know when the abstract key that is labelled ./> on some common keyboard layouts is released, you can do that with keyup, using the keyCode listed on the unixpapa link. Using keyCode like this is typically used for games and other features where the actual key position matters rather than the character it generates when typed. Unfortunately the browsers have made an inconsistent mess of some keyCodes including this one, so you'd have to check it for all possible values listed above, and you can't reliably tell the difference between the main keyboard period, the numpad period/delete key and the main delete key.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to Access Elements in FancyBox iframe There is an iframe, opened in fancybox window. The content of the iframe is external. Is there a way to access this content and to change the style of one of the elements? A: If the iFrame is on another domain you can't access it in any way due to browser restriction. This is called same origin policy. One thing that can get around it is the greasmonkey extension for firefox (this has no actual utility, it's just to let you know this fact if you are interested) A: Since the iframe has contents from the same domain, access the iframe using contents() like this: $('#fancybox-content iframe').contents().find('.selector')
{ "language": "en", "url": "https://stackoverflow.com/questions/7626329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Zend AutoLoader not functioning properly under Shared hosting I recently lauched a zend framework project on a shared hosting. With much struggle, I got the first index page working, but pass it all the autoloadable classes like models, forms, mappers are not found. Here is the version of .htaccess i am using outside the public directory on the root folder. RewriteEngine On RewriteRule ^\.htaccess$ - [F] RewriteCond %{REQUEST_URI} ="" RewriteRule ^.*$ /public/index.php [NC,L] RewriteCond %{REQUEST_URI} !^/public/.*$ RewriteRule ^(.*)$ /public/$1 RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^.*$ - [NC,L] RewriteRule ^public/.*$ /public/index.php [NC,L] A bit surprising fact is that same mappers and forms are recognised in the front page, or the baseURL, but surpass it, nothing is working. What am i doing wrong or missing? A: I think if you copy index.php and .htaccess from the Zend Framework "public" folder and put it in your public_html or equivalent directory. If your Zend Framework application directory is in the same directory as public_html then the default .htaccess file and index.php file should work. /home/yoursite --application/ ---- controllers ---- forms/ ---- models/ ---- views/ -- library/ -- public_html/ (public) ---- .htaccess ---- index.php A: Use this instead RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] Basic idea is if a file exist for requested url on server then send it to the client browser otherwise forward the request to ZF application to deal with it. To make your public dir accessible under root domain edit Apache httpd.conf file instead . Map your virtual host to public dir directly . A: Can you try the solution that i looked for and apply. It's worked for me. http://blog.motane.lu/2009/11/24/zend-framework-and-web-hosting-services/ You fill all content of /public_html/.htaccess (not /public_html/public/.htaccess) by RewriteEngine On RewriteRule ^(.*)$ public/$1 [L]
{ "language": "en", "url": "https://stackoverflow.com/questions/7626330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery files selector conflicting I am using two libraries of jQuery. One is main library from site(I named it as mainlibrary.js) other as limitkeypress.js(named as same). I think both files are conflicting. I used code in sadd.php at line 24 as <script type="text/javascript"> $.noConflict(); $(document).ready(function() { $("#title").limitkeypress ({ rexp:/^[A-Za-z.\-\s]*$/ }); }); </script> I got chrome error as * *limitkeypress.js:125 Uncaught ReferenceError: jQuery is not defined (anonymous function) *sadd.php:24 Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function (anonymous function) Where as my limitkeypress file at line 125 end with code.. })(jQuery); Firefox extension firebug issues same error as.. * *$ is not a function *sadd.php(). sadd.php (line 24) *$(document).ready(function() { What should I do in order avoid this error permanently. I mean if I use any other library. I won't have this error further. A: You use $.noConflict(), which unbinds $, then try to use it on the next line. jQuery should be available, if you're loading jQuery. A: If you are loading two versions of jquery you should have extra care because you need to use noconflict before loading the other. Look at this article an this example <!-- load jQuery 1.1.3 --> <script type="text/javascript" src="http://code.jquery.com/jquery-1.1.3.js"></script> <script type="text/javascript" src="jquery.dimensions.min.js"></script> <!-- revert global jQuery and $ variables and store jQuery in a new variable --> <script type="text/javascript"> var jQuery_1_1_3 = $.noConflict(true); </script> <!-- load jQuery 1.3.2 --> <script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.js"></script> <!-- revert global jQuery and $ variables and store jQuery in a new variable --> <script type="text/javascript"> var jQuery_1_3_2 = $.noConflict(true); </script> If you just want to use $ instead of jQuery, don't call noConflict
{ "language": "en", "url": "https://stackoverflow.com/questions/7626332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight double color lines I need to draw a line with two adjacent color. The only solution i found is based on two lines, with a TranslateTransform on the second. But the translate value have to change according to line orientation (angle). Is the any way to do it more easily? Thanks for help. A: You can draw a two-colour line using a LinearGradientBrush with four GradientStops. For example, the following XAML draws a horizontal line that is half red and half yellow: <Line X1="0" Y1="20" X2="200" Y2="20" StrokeThickness="14"> <Line.Stroke> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Offset="0" Color="Red" /> <GradientStop Offset="0.5" Color="Red" /> <GradientStop Offset="0.5" Color="Yellow" /> <GradientStop Offset="1" Color="Yellow" /> </LinearGradientBrush> </Line.Stroke> </Line> If you attempt to use the same LinearGradientBrush with a line that is not horizontal, you will quickly find that it won't do what you want. The two colours are always separated by a horizontal line whatever gradient the line has, whereas you want the line that separates the two colours to run down the middle of your Line. To achieve this, you need to change the StartPoint and EndPoint for the LinearGradientBrush. These depend on the gradient of the line, and they are a little awkward to calculate. To demonstrate how this can be done, I've put together a templated control (below) that draws two-colour lines. Color1 is the colour that would be on your left if you stood at (X1, Y1) and looked towards (X2, Y2), and Color2 would be on your right. Note that this control assumes that the start and end caps of the line are Flat. If you wish to use other types of start or end cap (e.g. Square or Round), you will need to adjust the calculation of overallWidth and overallHeight. TwoColorLine.cs: public class TwoColorLine : Control { public static readonly DependencyProperty X1Property = DependencyProperty.Register("X1", typeof(double), typeof(TwoColorLine), new PropertyMetadata(Coordinates_Changed)); public static readonly DependencyProperty Y1Property = DependencyProperty.Register("Y1", typeof(double), typeof(TwoColorLine), new PropertyMetadata(Coordinates_Changed)); public static readonly DependencyProperty X2Property = DependencyProperty.Register("X2", typeof(double), typeof(TwoColorLine), new PropertyMetadata(Coordinates_Changed)); public static readonly DependencyProperty Y2Property = DependencyProperty.Register("Y2", typeof(double), typeof(TwoColorLine), new PropertyMetadata(Coordinates_Changed)); public static readonly DependencyProperty Color1Property = DependencyProperty.Register("Color1", typeof(Color), typeof(TwoColorLine), new PropertyMetadata(Colors_Changed)); public static readonly DependencyProperty Color2Property = DependencyProperty.Register("Color2", typeof(Color), typeof(TwoColorLine), new PropertyMetadata(Colors_Changed)); public static readonly DependencyProperty StrokeThicknessProperty = DependencyProperty.Register("StrokeThickness", typeof(double), typeof(TwoColorLine), null); private LinearGradientBrush lineBrush; public TwoColorLine() { this.DefaultStyleKey = typeof(TwoColorLine); } public double X1 { get { return (double)GetValue(X1Property); } set { SetValue(X1Property, value); } } public double Y1 { get { return (double)GetValue(Y1Property); } set { SetValue(Y1Property, value); } } public double X2 { get { return (double)GetValue(X2Property); } set { SetValue(X2Property, value); } } public double Y2 { get { return (double)GetValue(Y2Property); } set { SetValue(Y2Property, value); } } public Color Color1 { get { return (Color)GetValue(Color1Property); } set { SetValue(Color1Property, value); } } public Color Color2 { get { return (Color)GetValue(Color2Property); } set { SetValue(Color2Property, value); } } public double StrokeThickness { get { return (double)GetValue(StrokeThicknessProperty); } set { SetValue(StrokeThicknessProperty, value); } } private static void Coordinates_Changed(DependencyObject obj, DependencyPropertyChangedEventArgs e) { var line = obj as TwoColorLine; if (line != null) { line.OnCoordinatesChanged(); } } private static void Colors_Changed(DependencyObject obj, DependencyPropertyChangedEventArgs e) { var line = obj as TwoColorLine; if (line != null) { line.OnColorsChanged(); } } private void OnCoordinatesChanged() { if (lineBrush != null) { RecalculateEndPoints(); } } public void OnColorsChanged() { if (lineBrush != null) { UpdateColors(); } } public void UpdateColors() { lineBrush.GradientStops[0].Color = Color1; lineBrush.GradientStops[1].Color = Color1; lineBrush.GradientStops[2].Color = Color2; lineBrush.GradientStops[3].Color = Color2; } public override void OnApplyTemplate() { base.OnApplyTemplate(); Line line = GetTemplateChild("line") as Line; if (line == null) { throw new InvalidOperationException("No line found in the template"); } lineBrush = line.Stroke as LinearGradientBrush; if (lineBrush == null) { throw new InvalidOperationException("Line does not have a LinearGradientBrush as its stroke"); } UpdateColors(); RecalculateEndPoints(); } private void RecalculateEndPoints() { double cos, sin; if (X2 == X1) { cos = 0; sin = (Y2 > Y1) ? 1 : -1; } else { double gradient = (Y2 - Y1) / (X2 - X1); cos = Math.Sqrt(1 / (1 + gradient * gradient)); sin = gradient * cos; } // These two lines assume flat start and end cap. double overallWidth = Math.Abs(X2 - X1) + StrokeThickness * Math.Abs(sin); double overallHeight = Math.Abs(Y2 - Y1) + StrokeThickness * Math.Abs(cos); int sign = (X2 < X1) ? -1 : 1; double xOffset = (sign * StrokeThickness * sin / 2) / overallWidth; double yOffset = (sign * StrokeThickness * cos / 2) / overallHeight; lineBrush.StartPoint = new Point(0.5 + xOffset, 0.5 - yOffset); lineBrush.EndPoint = new Point(0.5 - xOffset, 0.5 + yOffset); } } Themes\Generic.xaml: <Style TargetType="local:TwoColorLine"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="local:TwoColorLine"> <Line x:Name="line" X1="{TemplateBinding X1}" Y1="{TemplateBinding Y1}" X2="{TemplateBinding X2}" Y2="{TemplateBinding Y2}" StrokeThickness="{TemplateBinding StrokeThickness}"> <Line.Stroke> <LinearGradientBrush> <GradientStop Offset="0" /> <GradientStop Offset="0.5" /> <GradientStop Offset="0.5" /> <GradientStop Offset="1" /> </LinearGradientBrush> </Line.Stroke> </Line> </ControlTemplate> </Setter.Value> </Setter> </Style> Example usage: <Grid> <local:TwoColorLine X1="190" Y1="170" X2="150" Y2="50" Color1="Red" Color2="Green" StrokeThickness="14" /> <local:TwoColorLine X1="210" Y1="170" X2="250" Y2="50" Color1="Red" Color2="Green" StrokeThickness="14" /> <local:TwoColorLine X1="230" Y1="190" X2="350" Y2="150" Color1="Red" Color2="Green" StrokeThickness="14" /> <local:TwoColorLine X1="230" Y1="210" X2="350" Y2="250" Color1="Red" Color2="Green" StrokeThickness="14" /> <local:TwoColorLine X1="210" Y1="230" X2="250" Y2="350" Color1="Red" Color2="Green" StrokeThickness="14" /> <local:TwoColorLine X1="190" Y1="230" X2="150" Y2="350" Color1="Red" Color2="Green" StrokeThickness="14" /> <local:TwoColorLine X1="170" Y1="210" X2="50" Y2="250" Color1="Red" Color2="Green" StrokeThickness="14" /> <local:TwoColorLine X1="170" Y1="190" X2="50" Y2="150" Color1="Red" Color2="Green" StrokeThickness="14" /> </Grid> EDIT: revise RecalculateEndPoints() method to put the StartPoint and EndPoint on the edge of the line rather than on the line's bounding rectangle. The revised method is much simpler and makes it easier to use the control with more than two colours. A: You can create a small ImageBrush with the colors, and draw a single line using it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove background color of ShellFile “icons”, but not of “real” thumbnails I’m using WindowsAPICodePack, getting ShellFile’s Thumbnail’s. But some of those which look like the generic icons – have a black background. I therefore make it a Bitmap and set Black as transparent. The problem is that when it’s a thumbnail of a picture – it shouldn’t do it. How can I tell a real thumbnail from an “icon”? My code: ShellFile sf = ShellFile.FromFilePath(path); Bitmap bm = sf.Thumbnail.MediumBitmap; bm.MakeTransparent(Color.Black); Thanks A: You can approach this problem from another angle. It is possible to force the ShellFile.Thumbnail to only extract the thumbnail picture if it exists or to force it to extract the associated application icon. So your code would look something like this: Bitmap bm; using (ShellFile shellFile = ShellFile.FromFilePath(filePath)) { ShellThumbnail thumbnail = shellFile.Thumbnail; thumbnail.FormatOption = ShellThumbnailFormatOption.ThumbnailOnly; try { bm = thumbnail.MediumBitmap; } catch // errors can occur with windows api calls so just skip { bm = null; } if (bm == null) { thumbnail.FormatOption = ShellThumbnailFormatOption.IconOnly; bm = thumbnail.MediumBitmap; // make icon transparent bm.MakeTransparent(Color.Black); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7626336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Difference between ~lp() or simply ~ in R's locfit This is cross-posted after having first posted on stats.stackexchange.com, as I thought it involves more the use of R and statistics than coding, but now I see that I might find a more lively community of R users here. https://stats.stackexchange.com/questions/16346/difference-between-lp-or-simply-in-rs-locfit I am not sure I see the difference between different examples for local logistic regression in the documentation of the gold standard locfit package for R: http://cran.r-project.org/web/packages/locfit/locfit.pdf I get starkingly different results with fit2<-scb(closed_rule ~ lp(bl),deg=1,xlim=c(0,1),ev=lfgrid(100), family='binomial',alpha=cbind(0,0.3),kern="parm") from fit2<-scb(closed_rule ~ bl,deg=1,xlim=c(0,1),ev=lfgrid(100), family='binomial',alpha=cbind(0,0.3),kern="parm") . What is the nature of the difference? Maybe that can help me phrase which I wanted. I had in mind an index linear in bl within a logistic link function predicting the probability of closed_rule. The documentation of lp says that it fits a local polynomial -- which is great, but I thought that would happen even if I leave it out. And in any case, the documentation has examples for "local logistic regression" either way... A: The author of the locfit package, Catherine Loader, kindly answered my email. She says that instead of the alpha argument of scb, separate h and nn arguments need to go inside lp if I specify it within the formula for scb. I could not get the code work that way though. And I am still unsure about why there should a difference from the case without specifying lp() and simply giving the alpha and deg arguments to the scb function. And she also noted an important error my code as posted: with the 'parm' kernel, there is no local smoothing, but a parametric (in my case, logic) estimate. Finally, note that the literature seems to suggest specifying type=4 as an argument for scb for logistic regressions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: where are member-vars of a class on the heap stored? As a class is instantiated on the heap. Are all member vars then also allocated on the heap, or somewhere else. Is there then any good in allocating member vars explicit on the heap? struct abc { std::vector<int> vec; } int main() { abc* ptr = new abc(); //the "class" is on the heap but where is vec? ptr->vec.push_back(42); //where will the 42 be stored? return 0; } will this make any difference struct abc { std::vector<int>* vec_ptr; abc() { vec_ptr = nev std::vector<int>(); } int main() { abc* ptr = new abc(); ptr->vec->push_back(42); } A: Non-static data members are stored inside the object (class instance) they're part of. If you create an object as a local with automatic storage duration, its members are inside it. If you allocate an object dynamically, they're inside it. If you allocate an object using some entirely different allocation scheme, its members will still be inside it wherever it is. An object's members are part of that object. Note that here the vector instance here is inside your structure, but vector itself manages its own dynamic storage for the items you push into it. So, the abc instance is dynamically allocated in the usual free store with its vector member inside it, and 42 is in a separate dynamic allocation managed by the vector instance. For example, say vector is implemented like this: template <typename T, typename Allocator = std::allocator<T>> class vector { T *data_ = nullptr; size_t capacity_ = 0; size_t used_ = 0; // ... }; then capacity_ and used_ are both part of your vector object. The data_ pointer is part of the object as well, but the memory managed by the vector (and pointed at by data_) is not. A note on terminology: * *with automatic storage duration was originally on the stack. As Loki points out (and I mentioned myself elsewhere), automatic local storage is often implemented using the call stack, but it's an implementation detail. *dynamically was originally on the heap - the same objection applies. *When I say usual free store, I just mean whatever resource is managed by ::operator new. There could be anything in there, it's another implementation detail. A: Your question could be simplified. Consider: int main() { std::vector<int> v; v.push_back(42); } "Where is 42 stored?" In this example, v is an automatic variable, so it is stored in the local scope's store (usually the stack). But note that v has a fixed, small size -- it's just the handler object. The actual memory for the contained elements is separately allocated by the vector's internal logic, using the specified allocator (in this case, std::allocator), which in turn takes all its memory from the free store. All the (non-static) data members of a class form part of that class's data type and consume space -- this is essentially the same as a dumb C struct. However, the magic of most C++ library classes lies in the fact that their data members are only tiny pointers, and all the payload data is allocated separately and managed by the class's internal logic. So when you make a class with lots of vector members, the class itself still won't be very big. Any instance of that class will be allocated in its entirety wherever and however you want it (automatically, dynamically, statically), but be aware that each member object will request additional, separate memory all by itself to do its work. A: the newed object is treated as a contiguous allocation. creating a new instance of abc creates an allocation with a minimum size of sizeof(abc). the system does not allocate members of the class separately when you create via new. to illustrate: new does not call new for each member, sub-member. therefore, the data members are stored in the contiguous allocation created by new, which is a single allocation. in the case of the vector, the vector internally uses dynamic allocation for its elements -- this is accomplished using a separate allocation. this allocation is made within vector's implementation. therefore the members do reside on the heap, but they exist as part of the abc instance and that instance uses one allocation, excluding any allocations the data members create. Is there then any good in allocating member vars explicit on the heap? yes. there are many reasons you might choose to do this. considering the context of the question: you should favor declaring your members as values until there is a very good reason not to (details here). when you need to declare your member as a heap allocation, always use an appropriate container (e.g. auto pointer, shared pointer) because this will save you tons of effort, time, and complexity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using roboguice without extending Activity Is there a way to use roboguice without extending Activity class with RoboActivity. A: Yes. It's easier with the 1.2-SNAPSHOT which isn't yet in beta. To use 1.2, just add the following to your onCreate(), onContentChanged(), and onDestroy(). You don't need the bits about the EventManager if you're not using roboguice events: @Override protected void onCreate(Bundle savedInstanceState) { RoboGuice.getInjector(this).injectMembersWithoutViews(this); super.onCreate(savedInstanceState); } @Override public void onContentChanged() { super.onContentChanged(); RoboGuice.getInjector(this).injectViewMembers(this); } @Override protected void onDestroy() { try { RoboGuice.destroyInjector(this); } finally { super.onDestroy(); } } If you're using RoboGuice 1.1.x (the latest stable build), then the principle is the same but the calls are slightly different. Take a look at the 1.1 RoboActivity source to see which calls you need to make. A: It works, but you must implement RoboContext and declare this protected HashMap<Key<?>,Object> scopedObjects = new HashMap<>();
{ "language": "en", "url": "https://stackoverflow.com/questions/7626359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to build the gsl-1.8(GNU Statistical Library) on Win 64bit I'm a newbie in compiling GNU libraries(Never did it before). I have VS 2010 but don't mind downloading other ANSI C Compiler. If you can assist me in the steps I need to do to run the make file that build the library. A: As far as I can see the win32 port of the gsl got stuck with version 1.8 (current is 1.15), this is quiet old and I'm not sure if a build on win64 will work. Anyhow if you want to give it a try download the sources from here http://gnuwin32.sourceforge.net/downlinks/gsl-src-zip.php, unpack everything into a new and empty directory and start by reading src\gsl\1.8\gsl-1.8\VC8\Readme_VC8.htm. The VC10 compiler should do. A: I've recently built, deployed and used the GSL 1.15 for Win 64 with the MinGW gcc of debian, so I can assure you it's possible to build the GSL on Win64. However, I'm absolutely not experienced with VS and can't help you there, sorry. If you can make any use of binaries and a building debian package, please look into our repository.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to minify Javascript if you use SBT 0.10 or later How do you minify or obfuscate your Javascript files, if you build your Scala projects with Simple Build Tool (SBT) 0.10.x? Edit: Or later SBT versions, e.g. 0.11, 0.12. (For earlier versions of SBT there are some plugins that minify/obfuscate Javascript, but as far as I can tell they haven't been upgraded to work with SBT 0.10.x. Two examples: Yui Compressor Plugin for SBT, and sbt-closure) (Here's a list of SBT 0.10.x plugins; I didn't find any plugin that minifies Javascript.) A: sbt-closure has a recently active branch that is targetting SBT 0.11 compatibility. You could wait for that to be completed, or, better yet, contribute! The SBT Mailing List or #sbt on Freenode IRC are good places to find help for plugin development. A: In the interests of staying up to date, here's an actively-developed fork of the 'sbt-closure' plugin: https://github.com/eltimn/sbt-closure It's published to TypeSafe's Community Ivy Repository and is currently has builds against sbt versions 0.11.2, 0.11.3 and 0.12.0. This question was originally about sbt 0.10.x, but I think later versions are probably of more interest by now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does there have to be a mode switch for something to qualify as a context switch? Does there have to be a mode switch ie. from user to kernel mode in order for the action to be called a context switch? A: No. Not all processors even have privilege levels. A context switch usually means restoring an execution state from a Process Control Block. However, the notion of a context is implementation-defined. From Wikipedia: What constitutes the context is determined by the processor and the operating system. ... When a transition between user mode and kernel mode is required in an operating system, a context switch is not necessary; a mode transition is not by itself a context switch. However, depending on the operating system, a context switch may also take place at this time. A: context switch happens only in kernel mode. If context switching happens between two user mode processes, first cpu has to change to kernel mode, perform context switch, return back to user mode and so on. So there has to be a mode switch associated with a context switch. A: Mode Switch - When a single process mode is switched from user-level to kernel-level or the other way around. It happens through the system calls. When a process call the system call, the process mode will change to kernel-mode and the kernel will start acting on behalf of the user process. And once the system call returns the process mode will change from kernel-mode to user-mode. "Mode" is a property associated with the process. So, a mode switch is switch of the mode of a single process. Context Switch - It is when the running process current state is stored some place and a new process is chosen for running and its already stored state is loaded in the CPU registers. And now the new process starts running. This whole "context switch" procedure is done by the "Process Scheduler".
{ "language": "en", "url": "https://stackoverflow.com/questions/7626363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Draw triangle cutout for selection indication in UIView I'm creating a view that serves as a category selector for my app. I'd like it to have a cutout triangle as the selection indication, as in this image: I'm not sure how to draw the triangle so that it is a cutout, revealing the main view underneath. The main view underneath will most likely have a custom, possibly non-repeating (I haven't decided yet) image as its background. In addition, I would like the triangle to animate to a new location when the selection changes, which further complicates things a bit. I realize a subview would make the animation easier, but would complicate the drawing; direct drawing would probably make the animation a bit harder. And I'm not too familiar with Quartz, so I'm not sure how to go with the direct drawing route. Thanks in advance! Update: I've looked at Matt Gallagher's post on drawing shapes with holes, but it doesn't really answer my question. Is there a way for me to "see" what's underneath a certain path within my shape, and copy that? …And then support animating it? Update 2: I've done a partial job by simply drawing an additional path. The result looks like this: http://dl.dropbox.com/u/7828009/Category%20Selector.mov The code: CGRect cellRect = [self rectForCategoryNumber:(selectedCategoryIndex + 1)]; [[UIColor scrollViewTexturedBackgroundColor] setFill]; CGContextMoveToPoint(currentContext, self.frame.size.width, (cellRect.origin.y + cellRect.size.height * 0.15)); CGContextAddLineToPoint(currentContext, self.frame.size.width, (cellRect.origin.y + cellRect.size.height * 0.65)); CGContextAddLineToPoint(currentContext, self.frame.size.width * 0.8, (cellRect.origin.y + cellRect.size.height * 0.4)); CGContextClosePath(currentContext); CGContextFillPath(currentContext); [[UIColor darkGrayColor] setStroke]; CGContextSetLineCap(currentContext, kCGLineCapRound); CGContextMoveToPoint(currentContext, self.frame.size.width, (cellRect.origin.y + cellRect.size.height * 0.15)); CGContextAddLineToPoint(currentContext, self.frame.size.width * 0.8, (cellRect.origin.y + cellRect.size.height * 0.4)); CGContextSetLineWidth(currentContext, 2.5); CGContextStrokePath(currentContext); [[UIColor lightGrayColor] setStroke]; CGContextMoveToPoint(currentContext,self.frame.size.width * 0.8, (cellRect.origin.y + cellRect.size.height * 0.4)); CGContextAddLineToPoint(currentContext, self.frame.size.width, (cellRect.origin.y + cellRect.size.height * 0.65)); CGContextSetLineWidth(currentContext, 1.0); CGContextStrokePath(currentContext); Obviously, in this case it only works because I'm using the same fill color in both cases; I'd like to eliminate this dependency if possible. Also, of course I'd like to animate the position of that triangle. Update 3: What I tried to do to animate: static CALayer *previousLayer = nil; static CGMutablePathRef previousPath = nil; // … Get context, etc. CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init]; shapeLayer.path = shapePath; [shapeLayer setFillColor:[[UIColor redColor] CGColor]]; [shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]]; [shapeLayer setBounds:self.bounds]; [shapeLayer setAnchorPoint:self.bounds.origin]; [shapeLayer setPosition:self.bounds.origin]; if (previousPath) { // Animate change CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"changePath"]; animation.duration = 0.5; animation.fromValue = (id)previousPath; animation.toValue = (id)shapePath; [shapeLayer addAnimation:animation forKey:@"animatePath"]; previousPath = shapePath; } if (previousLayer) [previousLayer removeFromSuperlayer]; previousLayer = shapeLayer; [self.layer addSublayer:shapeLayer]; A: Have you looked at the CAShapeLayer? You can create a path for your selection pane that defines the whole outline including the exclusion of the triangle for each state you need to mask. You can then stroke the layer if you want the outline you're showing in your image by setting the lineWidth and strokeColor properties. That should be able to give you what you need. The path property in the CAShapeLayer is animatable which means that all you have to do is set the path property and it will animate (assuming your layers are sublayers of the view and not the root layer). Update With Code This code: - (void)viewDidLoad { [super viewDidLoad]; [[self view] setBackgroundColor:[UIColor blueColor]]; CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path,NULL,0.0,0.0); CGPathAddLineToPoint(path, NULL, 160.0f, 0.0f); CGPathAddLineToPoint(path, NULL, 160.0f, 100.0f); CGPathAddLineToPoint(path, NULL, 110.0f, 150.0f); CGPathAddLineToPoint(path, NULL, 160.0f, 200.0f); CGPathAddLineToPoint(path, NULL, 160.0f, 480.0f); CGPathAddLineToPoint(path, NULL, 0.0f, 480.0f); CGPathAddLineToPoint(path, NULL, 0.0f, 0.0f); CAShapeLayer *shapeLayer = [CAShapeLayer layer]; [shapeLayer setPath:path]; [shapeLayer setFillColor:[[UIColor redColor] CGColor]]; [shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]]; [shapeLayer setBounds:CGRectMake(0.0f, 0.0f, 160.0f, 480)]; [shapeLayer setAnchorPoint:CGPointMake(0.0f, 0.0f)]; [shapeLayer setPosition:CGPointMake(0.0f, 0.0f)]; [[[self view] layer] addSublayer:shapeLayer]; CGPathRelease(path); } results in this display: And you can download the sample project here: https://dzwonsemrish7.cloudfront.net/items/180s2a200N2i3b0y1g37/ArrowIndicator.zip
{ "language": "en", "url": "https://stackoverflow.com/questions/7626364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Solutions for Storing Data XML, Databases and...? I have a piece of software for reviewing cigars, the user enters the stats (name, price, brand, country, length etc) and a review (maybe a paragraph or two). Theres a menu for searching for previously reviewed cigars which will pull the stats and review for that cigar. At the moment its easy to search for the cigars because the data is all stored in a mysql db on a local server (for example i have a button 'country' which will fill the menu with the countries of the cigars stored in the db(cuba, nicuragua etc...then clicking on the country will fill the menu with the names of the cigars from that country - clicking on the names obviously brings up the stats and review)) I want to convert it so that the data is stored in xml files that the software will create. Is this easy to do? Bearing in mind that the xml files will need to be updated everytime a new review is written? I started trying out XStream but im thinking perhaps JAXB might be better? My question is, is there another way to store data that would be more appropriate? Am i thinking along the right lines using xml files and JAXB? Thanks for any input A: Sorry to side-step a bit from your question. As the above comments already mentioned, the best solution is what you have right now, store it in a database. There will be many problems arising from using only XML files to store and maintain all that information (and you application will be alot slower and limited on the queries you can do). If I understood correctly, your considering XML because you want the application to be completly self contained. If this is so, I suggest another approach. Try another database engine, like SQLite3 or H2. You can simply add a jar to your application and if you read a bit of the documentation, it's really easy to maintain the database in a simple file, no installations required. SQLite3 is currently used in most web frameworks like Django, RoR, etc as an out of the box database, so you can start implementing away. There's also the plus side that your current logic will probably work "as is", since both these databases support standard SQL. Think this might solve your problem? Best Regards, Pedro
{ "language": "en", "url": "https://stackoverflow.com/questions/7626365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lost in the listbox data binding I am trying to do something which I thought would be really simple, but.. I have created a pivot application and inserted a listbox in MainPage.xaml < ListBox x:Name = "partyList" Margin = "0,0,-12,0" > < ListBox.ItemTemplate > < DataTemplate > < StackPanel Orientation = "Horizontal" Margin = "0,0,0,17" > < StackPanel Width = "311" > < TextBlock Text = "{Binding throwLocation}" TextWrapping = "Wrap" Style = "{StaticResource PhoneTextExtraLargeStyle}" /> < TextBlock Text = "{Binding throwText}" TextWrapping = "Wrap" Margin = "12,-6,12,0" Style = "{StaticResource PhoneTextSubtleStyle}" /> </ StackPanel > </ StackPanel > </ DataTemplate > </ ListBox.ItemTemplate > </ ListBox > I want to fill something in that listbox.. and have created an ObservableCollection in mainpage.xaml.cs and figured I could just point ItemsSource to that, but nothing shows up in the list. public class ListItems { public string throwText; public string throwLocation; } List<ListItems> listItems = new List<ListItems>(); public ObservableCollection<ListItems> oblItems = new ObservableCollection<ListItems>(); // Load data for the ViewModel Items private void MainPage_Loaded(object sender, RoutedEventArgs e) { ListItems li = new ListItems(); //li.thumb = new BitmapImage(); li.throwLocation = "Denmark. Åbenrå"; li.throwText = "Throw text"; oblItems.Add(li); partyList.DataContext = oblItems; // Don't know if this makes any sense? partyList.ItemsSource = oblItems; MessageBox.Show(oblItems[0].throwLocation); } I get the messagebox and I can see that the data has reached the oblItems collection, but nothing in the listbox. What I am doing wrong? I thought this should be quite simple. A: OK, the answer to your question comes in two parts, one the reason why your binding fails and then a tip. The reason your data doesn't display is because the two properties in your "ListItems" class are not declared properly, they need to be fully declared properties using Getters and Setters, like this: public class ListItems { public string throwText { get; set; } public string throwLocation { get; set; } } Simply put unless you expose the values properly then Silverlight is unable to Bind and request the data properly. Now for a hint If you fire up the DataBound template with the Windows Phone SDK you will see a better way of doing this by using MVVM (a framework fro proper data binding) where you separate out the view (the XAML), the Model (what you data looks like, e.g. your properties) and the data. MVVM is a more data / type safe way of designing applications that display data through data binding. Once you've looked through that I also suggest looking at frameworks such as MVVMLight (http://mvvmlight.codeplex.com) or Calburn.Micro (http://caliburnmicro.codeplex.com)to set you in good stead for the future. Hope this helps. A: You need to call databind on the list: partyList.DataBind(). This is what cUses the items to actually be added to the list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading Components/Classes into an ArrayList via some component Name Pattern I have a number of classes of the same type (com.project.abc.abs.Agent) annotated like so; @Component("WEB.Agent-1"), @Component("WEB.Agent-2"), @Component("WEB.Agent-3")... etc. For now assume that all classes are in the same package (com.project.abc.web.Agent1...). These classes are all singletons, and I want to load them dynamically into a central 'Agent manager' class. I.e. every time a new agent class is added with the @Component("WEB.Agent-#") annotation it is picked up without having to make changes to the Agent Manager. In the AgentManager class I need some method to load any component that matches the name "WEB.Agent-#" (where # is a number or some unique ID) is this possible using any methods in Spring? If not I'm assuming that I would need to go about loading all classes from a particular folder/package? A: You can do this with ClassPathScanningCandidateComponentProvider and add an exclude filter that gets rid of things that don't match your pattern: ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(); scanner.addIncludeFilter(new AnnotationTypeFilter(Component.class)); scanner.addExcludeFilter(new TypeFilter(){ public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory){ return metadataReader.getAnnotationMetadata() .getAnnotationAttributes(Component.class.getName()) .get("value").matches("WEB.Agent-[0-9]+"); } }); for (BeanDefinition bd : scanner.findCandidateComponents("com.project.abc.web.Agent1")) System.out.println(bd.getBeanClassName());
{ "language": "en", "url": "https://stackoverflow.com/questions/7626368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Easier way of writing null or empty? I'm sure I've missed something here. With a certain project I need to check if a string is empty or null. Is there an easier way of writing this? if(myString == "" || myString == null) { ... A: if (string.IsNullOrEmpty(myString)) { ... } Or you could take advantage of a quirk in extension methods, they allow this to be null: static class Extensions { public static bool IsEmpty(this string s) { return string.IsNullOrEmpty(s); } } which then lets you write: if (myString.IsEmpty()) { ... } Although you probably should pick another name than 'empty'. A: Yes, there's the String.IsNullOrEmpty helper method for exactly this already: if (String.IsNullOrEmpty(myString)) { ... } A: If you are on .NET 4, you can use if(string.IsNullOrWhiteSpace(myString)){ } else: if(string.IsNullOrEmpty(myString)){ } A: To avoid null checks you can use ?? operator. var result = value ?? ""; I often use it as guards to avoid sending in data that I don't want in methods. JoinStrings(value1 ?? "", value2 ?? "") It can also be used to avoid unwanted formatting. string ToString() { return "[" + (value1 ?? 0.0) + ", " + (value2 ?? 0.0) + "]"; } This can also be used in if statements, it's not so nice but can be handy sometimes. if (value ?? "" != "") // Not the best example. { } A: In c# 9 by using pattern matching you could do the following myString is not {Length: > 0}; // Equivalent to string.IsNullOrEmpty(myString) A: C# 9's pattern matching allows you to write: myString is null or "" A: // if the string is not defined to null then IsNullOrEmpty it works great but if string is defined null then trim will throw exception. if(string.IsNullOrEmpty(myString.Trim()){ ... } //you can use IsNullOrWhiteSpace which work well for multiple white space in string .i.e it return true for multiple white space also if(string.IsNullOrWhiteSpace (myString.Trim()){ ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7626375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Why my python mechanize script cannot work for this specific site I need to simulate the process of inputting an item name and clicking the search button on http://ccclub.cmbchina.com/ccclubnew/. if I inspect directly in HTML, the search form is described with name "searchKey" <span class="searchinput"> <input type="text" name="searchKey" id="searchKey" maxlength="25"> </span> here below is the script: import mechanize import cookielib # Browser br = mechanize.Browser() # Cookie Jar cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Browser options br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Follows refresh 0 but not hangs on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # Want debugging messages? br.set_debug_http(True) br.set_debug_redirects(True) br.set_debug_responses(True) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] br.open("http://ccclub.cmbchina.com/ccclubnew/") I get br.select_form('searchKey') Traceback (most recent call last): File "<input>", line 1, in <module> File "build\bdist.win32\egg\mechanize\_mechanize.py", line 524, in select_form raise FormNotFoundError("no form matching "+description) FormNotFoundError: no form matching name 'searchKey' and the br.forms() is empty. my question is: why mechanize cannot select the form which exists in html? what's the possible solution to handle this? thanks A: The input with name searchKey itself is no form. A form comes with the <form> tag, but honestly, this searchbox appears not to be part of a form; you'll have to simulate setting the text of the input and pressing it. A: How about using lxml or BeatifulSoup?
{ "language": "en", "url": "https://stackoverflow.com/questions/7626381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to open pgsql file on Windows? I downloaded a 7 Gigabyte .pgsql file. What do I need to download in order to open this file on my Windows 7 machine? I tried installing PostgreSQL 9.1 for Windows, but when I open the pgAdmin it keeps asking me for a server, and I don't have any. All I want is to open an existing file, how can I configure it? A: 7 GB - this is probably a backup file either of a (big) database or a whole db cluster. To restore it, you need a working Postgres server installation (and possibly a database to restore to). You would have to tell us more about the file. Be aware that a 7 GB backup in uncompressed text format typically results in a database with somewhere around 20 GB disk space. But that can vary wildly. If it is plain SQL (indicated by the file extension .pgsql) you can restore it by feeding it to the standard command line client psql: psql -p $PORT $db -U $username -f /path/to/file.pgsql pgAdmin is a graphical administration tool (you seem to confuse it with the RDBMS itself). It offers restore capabilities, too. If it is an archive file created with pg_dump, you need to use pg_restore. For a file that big it might pay to optimize restore performance. Here is a Postgres Wiki entry on that. Postgres version, encoding and locale of the dump and the database (cluster) have to be compatible. If you don't know any of that, I recommend you start by reading about backup and restore. Or more generally, about PostgreSQL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# grade array with histogram I am studying fundamental programming in C# in Sweden and I was wondering if you could give me a hand with understanding an easy example. My goal is to fill an array with random numbers and then to show asterisk (*) or any symbol that many times as is the random generated number. This what I mean: Student 1 has a grade: 4 : * * * * Student 2 has a grade: 9 : * * * * * * * * * etc. This is the code I came up with so far: using System; using System.Text; namespace Array_1_10 { class Program { static void Main(string[] args) { //declar and create an int array object with 5 elements string tempStars = ""; int[] grades = new int[11]; // initiate the array using Random class methods Random grade = new Random(); for (int j = 1; j < 11; j++) grades[j] = grade.Next(1, 9); //Read and display the array's elements for (int j = 1; j < 11; j++) { tempStars += "*" + " "; tempStars += ""; Console.WriteLine("Student {0} has got: {1} : {2} ", j, grades[j], tempStars); } } } } It fills the array but the asterisks go from 1 to 10 no matter what number is generated, like this: Student 1 has a grade 5 : * Student 2 has a grade 1 : * * etc. Can you please help me with this? Thank you very much. Vojtech A: using System; using System.Text; namespace Array_1_10 { class Program { static void Main(string[] args) { //declar and create an int array object with 5 elements int[] grades = new int[11]; // initiate the array using Random class methods Random grade = new Random(); for (int j = 1; j < 11; j++) grades[j] = grade.Next(1, 9); //Read and display the array's elements for (int j = 1; j < 11; j++) { string tempStars = ""; //initialize string each time for (int lp = 0 ; lp < grades[j] ; lp++)) { // build the string tempStars += "*" + " "; } Console.WriteLine("Student {0} has got: {1} : {2} ", j, grades[j], tempStars); } } } } Here's a more concise version which uses StringBuilder: using System; using System.Text; namespace SO7626386 { class Program { static void Main(string[] args) { var grades = new int[11]; // initiate the array using Random class methods var grade = new Random(); for (int j = 1; j < 11; j++) { grades[j] = grade.Next(1, 10); } //Read and display the array's elements for (int j = 1; j < 11; j++) { Console.WriteLine("Student {0} has got: {1} : {2} ", j, grades[j], new StringBuilder().Insert(0,"* ",grades[j]).ToString()); } } } } A: As an additional solution, that you can research freely: for (int j = 1; j < 11; j++) { string tempStars = new String('*', grades[j]).Replace("*", "* "); Console.WriteLine .... I WON'T explain it to you, because it's quite easy to research it on MSDN. It's interesting because it shows what is the precedence between new and . (to be more clear, in C# you don't need to write this: (new String('*', grades[j])).Replace("*", "* "), in other languages you would have to add the brackets.) A: Trace this part of your code: for (int j = 1; j < 11; j++) { tempStars += "*" + " "; tempStars += ""; Console.WriteLine("Student {0} has got: {1} : {2} ", j, grades[j], tempStars); } In each iteration you will add new asterisk to tempStars no matter how many * should be assign, So you change it. for example first define tempStars in your for loop, second add * as the size of grades[j] to your tempStars variable then print it. A: You need to change your code where you display the number oF stars to take into account the grade. So the code from for loop down would be: For(j=1; j<11; j++) { StringBuilder ab = new StringBuilder(grades[j]); For(int i=0; i<grades[j]; i++) { sb.Append(" *"); } Console.WriteLine("Student {0} has grade {1} : {2}", j, grades[j], sb.ToString()); } The extra for loop is to build a string with the amount of stars the student has got. You should use a stringbuilder for these kinds of operations as it's much more efficient than creating lots of strings. One of thing to note is that the code initialises the stringbuilder to the correct string length. This saves the string builder class the work of resizing it's array under the hood that it uses to build the string. A: The way you've written your code, you're only printing a single asterisk in the first loop, and then adding an additional asterisk in each iteration of the loop. You need an inner loop that prints the correct amount of asterisks, and then you need to clear the tempStars variable in the outer loop after printing it. Try changing the portion of your code that displays the asterisks accordingly: (untested) string tempStars = ""; for (int j = 1; j < 11; j++) { for (int i = 0; i < grades[j]; i++) tempStars += "*" + " "; Console.WriteLine("Student {0} has got: {1} : {2} ", j, grades[j], tempStars); tempStars = ""; } A: This should be better: using System; using System.Text; namespace Array_1_10 { class Program { string stars(int count) { if (count == 0) return ""; string st = "*"; for (int i = 1; i < count; i++) { st += " *"; } return st; } static void Main(string[] args) { //declar and create an int array object with 10 elements int[] grades = new int[10]; // initiate the array using Random class methods Random grade = new Random(); for (int j = 0; j < 10; j++) grades[j] = grade.Next(1, 9); //Read and display the array's elements for (int j = 0; j < 10; j++) Console.WriteLine("Student {0} has got: {1} : {2} ", j, grades[j], stars(grades[j])); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7626386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: json_decode not interpreting array I have a following JSON string, arriving via AJAX to server: {"Names":"[{0:'asdasd'}]","Values":"[{0:'ad'}]"} As you see, Names and Values were intended to hold an array. Problem is, when I call $data = json_decode(stripslashes($_POST['data']), true); $data['Names'][0] I don't get 'asdasd' as I wanted, but "[" symbol. Where the problem lies? P.S. JS code, sending JSON string: var arr_names = "["; names.each(function(i){ arr_names += "{" + i + ":'" + $(this).val() + "'}"; if (i < names.length-1) arr_names += ","; }); arr_names += "]"; var arr_val = "["; values.each(function(i){ arr_val += "{" + i + ":'" + $(this).val() + "'}"; if (i < values.length-1) arr_val += ","; }); arr_val += "]"; var el = { "Names" : arr_names, "Values" : arr_val }; el = encodeURIComponent(JSON.stringify(el)); $.ajax({ type:"POST", dataType:"html", data:"m=1&t="+type+"&data="+el, url:plugin_path+"option-proc.php", success: function(rsp){ $("#result").html(rsp); } }); names and values are a bunch of text fields, selected by the class. m and t variables being sent, are completely irrelevant to the case :) A: The string is encoded incorrectly. $data['Names'] is a string, so by accessing [0] you'll get the first character. If you also json_decode $data['Names'] again you should get something working, although also that is actually incorrectly ecoded (as an object with numeric indexes rather than an array.) I'm pretty sure strict json parsers will fail on that inner-string. I'd suggest fixing whatever generates it, rather than on the decoding side.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python web.py template, how to escape (.) dot In web.py template: index.html I wrote: $def with(s) <img src="$s.filename.png" /> s.filename's value is "picuture" so I want to print <img src="picture.png" /> but how can I tell web.py templating system do not to use $s.filename.png just use $s.filename and add ".png" to it? A: See the Templetor docs: Expression can be enclosed in () or {} for explicit grouping. So, in your case, <img src="${s.filename}.png" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7626394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL query doesn't find cities that begin with č, ć, š, ž, etc My SQL query doesn't find cities that begin with for instance č, but does find cities which have č in their name but begin with regular English letters. The City column in the database is of nvarchar type. What is the solution for this problem? I am using an SQLite database. cmdSQLite = new SQLiteCommand("SELECT RegistrationNumber, DocumentName, Performer, BuiltYear, ReferatCardNumber , City, Municipalities , StreetName FROM Geotest WHERE LOWER (City) = @City", connectionSQLite); SQLiteParameter parameterCity = new SQLiteParameter(); parameterCity.Value = comboBoxCitySearch.Text.ToLower(); parameterCity.ParameterName = "@City"; cmdSQLite.Parameters.Add(parameterCity); A: I think your problem might be related to unicode string in SQL Server. This might help http://support.microsoft.com/kb/239530 When dealing with Unicode string constants in SQL Server you must precede all Unicode strings with a capital letter N, as documented in the SQL Server Books Online topic "Using Unicode Data". The "N" prefix stands for National Language in the SQL-92 standard, and must be uppercase. If you do not prefix a Unicode string constant with N, SQL Server will convert it to the non-Unicode code page of the current database before it uses the string. UPDATE: My mistake, I did not read the question correctly, I thought we were talking about SQL Server. Reading the SQL Lite documentation, http://www.sqlite.org/faq.html#q18 The default configuration of SQLite only supports case-insensitive comparisons of ASCII characters. The reason for this is that doing full Unicode case-insensitive comparisons and case conversions requires tables and logic that would nearly double the size of the SQLite library. The SQLite developers reason that any application that needs full Unicode case support probably already has the necessary tables and functions and so SQLite should not take up space to duplicate this ability. A: Here is solution: parameterCity.Value = comboBoxCitySearch.Text; Dont use C# function comboBoxCitySearch.Text.ToLower(); Just in SQL use: WHERE LOWER(City) = LOWER(@City)
{ "language": "en", "url": "https://stackoverflow.com/questions/7626403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to write a small (socket) server in iOS I saw this in some official iOS apps, so I know it's possible and permitted. I want to write a small socket server in iOS that some other application, that I will write for a desktop machine, can connect to and read data from. Anyone did something like this and can help me with some clues or knows a good starting point ? A: You should read the Stream Programming Guide, the WiTap sample, and many other Programming Guides, Samples and Documentation in Apple's Doc, you will find everything there (including detailed explanations and code) If you simply go to the home page of iOS SDK documentation and go in the "Networking & Internet Topics" you have plenty of resources too, including the Network & Internet Starting Point guide and much more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Checking Request Attribute in JSP I am trying to check a request attribute in a jsp to show/hide certain html. request.setAttribute("submitted", "true"); jsp: <c:if test="${submitted == 'false'}"> // some html </c:if> But no matter what value I set in the attribute, the condition always evaluates to false. Is the attribute not visible inside the condition? Sahil A: Try this instead: request.setAttribute("submitted", true); and in your JSP: <c:if test="${submitted}"> // some html </c:if>
{ "language": "en", "url": "https://stackoverflow.com/questions/7626406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ListView is not responding to clicks whats wrong with this class? the clicks in the listview arent registered, i tried to do a log, but it doesnt go into the setItemOnClickListener public class Chosen extends Activity{ SimpleCursorAdapter adapter; String[] getResult; Cursor c; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chosen); Intent i=getIntent(); Bundle extras=i.getExtras(); final TextView t=(TextView) findViewById(R.id.tv1); int num=extras.getInt("category"); ArrayList al=new ArrayList<String>(); switch(num) { case 0:c=Splash.db.getSocial(Login.uname);break; case 1:c=Splash.db.getMail(Login.uname);break; case 2:c=Splash.db.getBank(Login.uname);break; case 3:c=Splash.db.getMisc(Login.uname);break; } if(c.moveToFirst()) { do { al.add(c.getString(1)); }while(c.moveToNext()); } getResult=new String[al.size()]; al.toArray(getResult); ListView lv=(ListView) findViewById(R.id.list); lv.setClickable(true); ArrayAdapter ad=new ArrayAdapter(this,R.layout.chosenitemlist,R.id.client,getResult); lv.setAdapter(ad); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) { // TODO Auto-generated method stub Log.w("akash", "in list item click"); t.setText("clicked"); Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show(); } }); } } A: Interesting. First, try on several scenarios I've checked myself: http://xjaphx.wordpress.com/2011/07/14/listview-doesnt-respond-to-onitemclicklistener/ If problem still, you might want to share your source code, I'd like to analyze if it's a new scenario. In case you cant' share full source, then try to create a new project and put all necessary code, and share :) A: One more scenario I have found (not listed by xjaphx): my row layout has had a textview and two images, and some of them has had "clickable = true". Setting it to "false" fixed the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference between int, NSInteger and NSUInteger What is the main difference between int, NSInteger and NSUInteger in Objective-C? Which one is better to use in an application and why? A: In such cases you might right click and go to definition: #if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 typedef long NSInteger; typedef unsigned long NSUInteger; #else typedef int NSInteger; typedef unsigned int NSUInteger; #endif A: The difference is for abstract types and their associates sized from hardware. In a manner that now we don't have to worry about what size an int is or how big it's pointer is on any particular hardware. "C" is bad at this, only stating that a long is at least as big as an int, that an int is the "natural" integer size of the hardware (whatever that means), that an int is at least as long as a short--a (big mess). This seemed like a good idea at the time coming from Fortran, but did not age well. One could use the POSIX defines, things like uint32_t, int16_t, etc. But this does not address how big a pointer needs to be on any particular hardware either. So, if Apple defines the return type to be an NSUInteger you just use that and you don't need to know if it is 16, 32 or 64 bits in size for your particular hardware. (I picked those values out-of-the-air just for an example). As you can see in @Bastian the actual size depends on hardware. The documentation answers the "letter of the question" but does not provide an understanding of "why"?
{ "language": "en", "url": "https://stackoverflow.com/questions/7626412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: CoreData - how to create fetchrequest to get array of random attribute values I have simple model with 2 entities House and Flat. House has to many relation to Flat. Flat has attributes like number and description. I would like to get a list of random eight flat numbers. I'm trying to go this way, but it seems that' wrong NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"House" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; [fetchRequest setFetchBatchSize:20]; NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; NSArray *houses = [aFetchedResultsController fetchedObjects]; Then I need to get appropriate values. Please show me a right approach. I try to answer myself. Perhaps my brains are dry:) Just need NSEntityDescription *entity = [NSEntityDescription entityForName:@"Flat" inManagedObjectContext:self.managedObjectContext]; and then work with array of fetched objects. But I'm steel believe that there is more elegant solution. I have further question related to the first one. How to get random objects if number of flats is about 10000? In general it works but slows down noticeable. A: LimitSort the records randomly and set [fetchRequest setFetchLimit:8]; to get the first eight. For random sorting make a NSSortDescriptor with selector or comparator that returns NSComparisonResult randomly and add this descriptor to the fetch request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIImageView consumes memory when hidden? (iOS) Does UIImageView requires memory when it is hidden? Same question for alpha=0.0 I work a lot with hidden images, and I wonder if those still consume memory. More specifically I would like to know that for tableview. Thanks A: Of course if it has an image loaded into the view, it does, because UIImageView is simply a UIView that has a UIImage @property with the retain attribute so it retains the image. The fact that the view is visible or not does not change anything of course, and hopefully because otherwise iOS couldn't load the UIImage again if you set the UIImageView visible again (once the image property is affected to the UIImageView, the UIImageView can't know the source of the image, was it loaded from a file, an URL, generated programatically, ...?), and even if it did know it would be a pain to reload it (could take some time to load and decode) If you don't use an UIImageView's image, at least set its image property to nil to hide it (and reload/reaffect the image again yourself if you need to redisplay it, but if it is used in a UITableView because of the recycling/reuse mechanism of the UITableViewCells it will probably never be the same image to set anyway)
{ "language": "en", "url": "https://stackoverflow.com/questions/7626429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generics and returning class objects I am trying to return an object of a class using the generics. This is the generic class public class ClientBase <S> { protected S CreateObject() { return default(S) ; } } This is how I am trying to use it... public class ClientUser : ClientBase <SomeClass> { public void call() { var client = this.CreateObject(); client.SomeClassMethod(); } } While I get the SomeClassMethod() in the client object, when running the code it gives an error at the line: client.SomeClassMethod(); Error is 'Object reference not set to an instance of an object'. I know there is something missing in the generic class ClientBase's CreateObject() method; just cant figure that bit out. Could someone help me here please? Thanks for your time... A: default(S) where S is a reference type is null. In your case, default(SomeClass) returns null. When you try to invoke a method on a null reference, that's when you get your exception. Are you trying to return a default instance of SomeClass? You may want to use a new() constraint and return new S() in your generic class instead, like so: public class ClientBase<S> where S : new() { protected S CreateObject() { return new S(); } } If S needs to be a reference type you can also constrain it to class: public class ClientBase<S> where S : class, new() { protected S CreateObject() { return new S(); } } A: See what default(T) does: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx In your case, default(S) is going to return null (because it's a class) - this is not an instance of the class. You either need to call new S() or some other S constructor or override CreateObject in your derived class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: web config clear What is the use of the <clear/> in the web.config file? I have it under connectionStrings: <connectionStrings> <clear /> </connectionStrings> A: It clears all inherited keys, that's it. Here is the MSDN Article: http://msdn.microsoft.com/en-us/library/aa903345(v=vs.71).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7626440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Issues with mmap of Complex Types I have an issue attempting to access shared memory using mmap for complex types. So I allocate my memory as so in my parent process: /* Create mmap file */ fid = open(TMP_FILE_NAME, O_RDWR | O_CREAT | O_EXCL, (mode_t) 0755); if (fid < 0) { printf("Bad Open of mmap file <%s>\n", TMP_FILE_NAME); die(-1); } /* Make mmap file Buffer Size */ status = ftruncate(fid, INPUT_BUFFER_SIZE); if (status) { printf("Failed to ftruncate the file <%s>, status = %d\n", TMP_FILE_NAME, status); die(-1); } /* Initialize Shared Memory */ mmap_ptr = mmap((caddr_t) 0, INPUT_BUFFER_SIZE, // Default Buffer Size PROT_WRITE | PROT_READ, // R/W Permissions MAP_SHARED, // No file backing fid, (off_t) 0); if (mmap_ptr == MAP_FAILED) { printf("Failed to perform mmap, Exiting\n"); die(-1); } Now the Struct that I'm passing in memory to my child process is as follows: /* Data structue for IPC */ typedef struct { int current_active_id; int consume_remaining; Queue buffer; } input_buffer; where Queue is a data structure class from the following: http://www.idevelopment.info/data/Programming/data_structures/c/Queue/Queue.shtml In my child process it's okay when I do this, it returns the correct value: printf("Got here... Shared Mem: %d\n", input_queue->consume_remaining); but when I do something like: IsEmpty(input_queue->buffer) it crashes and in the code of the Queue it's only doing this: return Q->Size == 0; Any help would be appreciated, thanks!! A: Queue is a pointer to struct QueueRecord, and should be allocated as such, presumably using the same shared memory segment. note that this should also be mapped at the same address in both parent and child, or you will not be able to dereference it. A: The structure you are putting in the map contains pointers. The pointers are all relative to the address space of the process that created them. If the other process doesn't mmap at the same address, or if it does but the allocations made for the queue aren't taken from inside that buffer, the pointers will be invalid in the other process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3.1 - Fields With Errors I'm using Rails helper methods to build a form, and using validations. Whenever one of these validations fails, rails wraps the corresponding inputs and labels in a field_with_errors tag. Which is fine. However, for some reasons rails is wrapping both the input AND the label in different divs, making styling really hard: eg: <div class="field"> <div class="field_with_errors">...label...</div> <div class="field_with_errors">..input ...</div> </div> and what I need is: <div class="field"> <div class="field_with_errors">...label & input...</div> </div> Does anyone know how I would achieve this? A: One way is to replace the divs with spans, which don't break formatting as they're not block level elements. To do so, put this somewhere in an initializer: ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| "<span class=\"field_with_errors\">#{html_tag}</span>".html_safe end Another way would be to simply make the original divs not display as block level elements, with this line in your CSS file: .field_with_errors { display: inline-block; } but this is not fully supported by some of the older browsers (looking at you IE6 and 7).
{ "language": "en", "url": "https://stackoverflow.com/questions/7626461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: php replace non matches from two arrays How do you replace all non matches from one array that are not defined within the other array, i have kind of got working but its not exactly right. as i will show you. the result is, but wrong. - - £ 8 - - - - - - - - The required result should be £ 8 - - this is how my code is $vals_to_keep = array(8, 'y', '£'); $replace_if_not_found = array('£', 8, '#', 't'); // replace if not in above array $result = ''; foreach ($replace_if_not_found as $d) { foreach ($vals_to_keep as $ok) { if(strcmp($d, $ok) == 0){ $result .= $d . " "; }else $result .= str_replace($d, $ok ,'-') . " "; } } echo $result; A: use in_array http://php.net/manual/en/function.in-array.php foreach ($replace_if_not_found as $d) { if (in_array($d, $vals_to_keep)) $result .= $d . " "; else $result .= str_replace($d, $ok ,'-') . " "; } A: You could loop over all of the items in $replace_if_not_found replacing them with -, or not, as appropriate. Using closure in PHP 5.3 or above $result = array_map(function($item) use ($vals_to_keep) { return in_array($item, $vals_to_keep, TRUE) ? $item : '-'; }, $replace_if_not_found); echo implode(' ', $result); Using a foreach loop $result = array(); foreach ($replace_if_not_found as $item) { if (in_array($item, $vals_to_keep, TRUE)) { $result[] = $item; } else { $result[] = '-'; } } echo implode(' ', $result;
{ "language": "en", "url": "https://stackoverflow.com/questions/7626462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to allow files uploading with WebView in Cocoa? WebView have a method called - (void)webView:(WebView *)sender runOpenPanelForFileButtonWithResultListener:(id < WebOpenPanelResultListener >)resultListener But there is almost 0 doc and details on it. Inside I display an open file dialog and get the selected file name. Like this - (void)webView:(WebView *)sender runOpenPanelForFileButtonWithResultListener:(id < WebOpenPanelResultListener >)resultListener { NSOpenPanel* openDlg = [NSOpenPanel openPanel]; [openDlg setCanChooseFiles:YES]; [openDlg setCanChooseDirectories:NO]; // process the files. if ( [openDlg runModal] == NSOKButton ) { NSString* fileString = [[openDlg URL]absoluteString]; [resultListener chooseFilename:fileString]; } } But then ? What should I do ? On website, it show that I selected a file, but when you click on upload the website just return an error, like if no file is uploaded. Should I write the code that handle the file upload or what ? I'm kinda lost... Edit: In fact I got it working.... By just alter the code from here: Cocoa webkit: how to get file upload / file system access in webkit a bit, as some part was deprecated - (void)webView:(WebView *)sender runOpenPanelForFileButtonWithResultListener:(id < WebOpenPanelResultListener >)resultListener { // Create the File Open Dialog class. NSOpenPanel* openDlg = [NSOpenPanel openPanel]; // Enable the selection of files in the dialog. [openDlg setCanChooseFiles:YES]; // Enable the selection of directories in the dialog. [openDlg setCanChooseDirectories:NO]; if ( [openDlg runModal] == NSOKButton ) { NSArray* URLs = [openDlg URLs]; NSMutableArray *files = [[NSMutableArray alloc]init]; for (int i = 0; i <[URLs count]; i++) { NSString *filename = [[URLs objectAtIndex:i]relativePath]; [files addObject:filename]; } for(int i = 0; i < [files count]; i++ ) { NSString* fileName = [files objectAtIndex:i]; [resultListener chooseFilename:fileName]; } [files release]; } } Enjoy ! A: I followed Peter Hosey comment and wow, my code is now short and works the same - (void)webView:(WebView *)sender runOpenPanelForFileButtonWithResultListener:(id < WebOpenPanelResultListener >)resultListener { // Create the File Open Dialog class. NSOpenPanel* openDlg = [NSOpenPanel openPanel]; // Enable the selection of files in the dialog. [openDlg setCanChooseFiles:YES]; // Enable the selection of directories in the dialog. [openDlg setCanChooseDirectories:NO]; if ( [openDlg runModal] == NSOKButton ) { NSArray* files = [[openDlg URLs]valueForKey:@"relativePath"]; [resultListener chooseFilenames:files]; } } A: There are a couple of ways your code can be improved: * *To loop through an array, use fast enumeration instead of an index loop. It's both faster and easier to read. The only time you should use an index loop is when you really need indexes, and this is not such a situation. *You don't need the first loop at all. Send the URLs array a valueForKey: message, with @"relativePath" for the key. The array will ask each object (each URL) for its relativePath, collect an array of all the results, and return that for you. The code for this is a one-liner. *You don't need the second loop, either. The WebOpenPanelResultListener protocol added chooseFilenames: in 10.6, so you can now just send that message, once, passing the whole array to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What could cause my program to not use all cores after a while? I have written a program that captures and displays video from three video cards. For every frame I spawn a thread that compresses the frame to Jpeg and then puts it in queue for writing to disk. I also have other threads that read from these files and decodes them in their own threads. Usually this works fine, it's a pretty CPU intensive program using about 70-80 percent of all six CPU cores. But after a while the encoding suddenly slows down and the program can't handle the video fast enough and starts dropping frames. If I check the CPU utilization I can see that one core (usually core 5) is not doing much anymore. When this happens, it doesn't matter if I quit and restart my program. CPU 5 will still have a low utilization and the program starts dropping frames immediately. Deleting all saved video doesn't have any effect either. Restarting the computer is the only thing that helps. Oh, and if I set the affinity of my program to use all but the semi-idling core, it works until the same happens to another core. Here is my setup: * *AMD X6 1055T (Cool & Quiet OFF) *GA-790FX-UD5 motherboard *4Gig RAM unganged 1333Mhz' *Blackmagic Decklink DUO capture cards (x2) *Linux - Ubuntu x64 10.10 with kernel 2.6.32.29 My app uses: * *libjpeg-turbo *posix threads *decklink api *Qt *Written in C/C++ *All libraries linked dynamically It seems to me like it would be some kind of problem with the way Linux schedules threads on the cores. Or is there some way my program can mess up so bad that it doesn't help to restart the program? Thank you for reading, any and all input is welcome. I'm stuck :) A: First of all, make sure it's not your program - maybe you are running into a convoluted concurrency bug, even though it's not all that likely with your program architecture and the fact that restarting the kernel helps. I've found that, usually, a good way is a post-mortem debugging. Compile with debugging symbols, kill the program with -SEGV when it is behaving strangely, and examine the core dump with gdb. A: I would try to choose a core round-robin a when new frame processing thread is spawned and pin the thread to this core. Keep statistics on how long it takes for the thread to run. If this in in fact a bug in Linux scheduler - your threads will take roughly the same time to run on any core. If the core is actually busy with something else - your threads pinned to this core will get less CPU time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Assign some data fields to DropDownList item I want to assign 2 data fields to a DropDownList item because I want to display 2 values at click at an item in different elements (for example, 2 textboxes). For example: at click on a DDL item, that a value of data field named "example" displayed in one TXTBOX and other of a data field named "definition" displayed in other TXTBOX. A: If you have do something like this, you can just separate the two values with some sort of delimiter (, or | or whatever), and then parse them out when it's selected and you have to display them. Item.Value = "VALUE1,VALUE2"; string[] Values = Item.Value.Split(','); txt1.Text = Values[0]; txt2.Text = Values[1];
{ "language": "en", "url": "https://stackoverflow.com/questions/7626472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mahout collaborative-filtering input binary dataset i am new to mahout. I have already used mahout's item based algorithm with a loglikelihood similarity measure. I read in past threads that it is better to use loglikelihood similarity when the recommender handles binary values (like or dislike). I also read that mahout uses three values (like, dislike, non exist ). So i get confused a little bit, about the format of the input dataset file. Does the input file format have to be like this ? userId, itemID where the preference by default is 1? I would like to know if there is a way to put the dislike info in the dataset. I would except for example the input dataset file, be something like this : userid, itemid, binaryPreference 1, 15, 1.0 2, 35, 0 1, 25, 1.0 ...... Help me please! Thanx in advance! A: I am not sure where you read that, but it's wrong. There is no three-state "boolean" preference in Mahout. You either have ratings in your data, or you don't, in which case you have boolean preferences, which either exist or do not exist. There is no third state. As strange as it may seem, I'd encourage you try to treating "like" and "dislike" as the same, to start. It might work well. You can later try incorporating artificial ratings on a scale of -1 to 1 or something to represent like, dislike and shades in between. You could then try other similarity metrics like Euclidean distance to see how it does. A third possibility is to build two recommenders: one has the "like" associations and the other has a data model with "dislike" associations. You could use the output of the "like" recommender, and filter or modify the results by the results of the 'dislike' recommender. This would require some coding, but isn't hard. [email protected] would be a good place to follow up on this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using CSS translateY() I am moving some element from (browser height + element height)px towards the top of the browser at -50px of the browser using CSS keyframes and that works but the problem is it's lagging and I am well aware that using translateY would resolve this issue. Now assume I have a CSS as follows. .bubble { -webkit-transition: -webkit-transform 1s ease-in-out; } .bubble.move { -webkit-transform: translateY(-50px); } As the element is below the browser screen (browser height + element height)px and I want it to move at the top of the screen at -50px, that doesn't work. It just moves the element from its current position to the -50px of that current position which is not intended. How can I ask transitions to go at -50px of the browser and not he element? A: Translate isn't what you're looking for. You want to position the element absolutely and put the transition on the top property. Something like: .bubble { position:absolute; top:100%; transition:top 1s ease-in-out; } .bubble.move { top:50px; } Only bad part about this approach is that the body will need to be the relative parent of the .bubble. I left out vendor prefixes because I hate them. A: Use javascript to calculate it and set the css using javascript too A: Have you tried positioning the element absolutely instead of relatively?
{ "language": "en", "url": "https://stackoverflow.com/questions/7626474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Working with a Model class that has a foreign/navigation key to itself I am trying to develop a catalog project in ASP.NET MVC 3 and using EF Code first with an existing Database. There is a Categories table in my database that points to itself. For that, I have written the following model class. --"Correct me if the model is wrong"-- public class Category { public int CategoryID { get; set; } public string CategoryName { get; set; } public int? ParentCategoryID { get; set; } public string CategoryDesc { get; set; } [ForeignKey("ParentCategoryID")] public virtual Category ParentCategory { get; set; } public virtual ICollection<Product> Products { get; set; } } Question : I am unable to understand as to how can i work with this class. While using and passing the following code to the view var cat = dbStore.Categories.Include("ParentCategory").ToList(). I got this error : Object reference not set to an instance of an object. This is happening because the root category has null ParentCategoryID. Please tell me how will you work with this code or any resource that can help me understand working in such scenarios. Just any sort of code will be helpful that uses the above the model, like displaying a list or a menu or anything, just anything. A: Usually what you do is travel from top level categories to bottom level categories. Inorder to do that first you need to define SubCategories collection in your class public class Category { public int CategoryID { get; set; } public string CategoryName { get; set; } public int? ParentCategoryID { get; set; } public string CategoryDesc { get; set; } [ForeignKey("ParentCategoryID")] public virtual Category ParentCategory { get; set; } [InverseProperty("ParentCategory")] public virtual ICollection<Category> SubCategories{ get; set; } public virtual ICollection<Product> Products { get; set; } } Then you retrieve the top level categories var topCategories = dbStore.Categories .Where(category => category.ParentCategoryID == null) .Include(category => category.SubCategories).ToList(); After that you can traverse the hierachey foreach(var topCategory in topCategories) { //use top category foreach(var subCategory in topCategory.SubCategories) { } } A: If you do not have very many categories you can solve this by loading the whole collection of categories. I think EF will handle the fixup for you so all relations are properly populated. As far as I know there are no SQL'ish databases/ORM's that can handle this scenario well. An approach I often use is to load the whole collection as I said above and then manually fix the relations. But I do think EF will do that for you. Basically you should do: var topCategories = dbStore.Categories.ToList().Where(category => category.ParentCategoryID == null);
{ "language": "en", "url": "https://stackoverflow.com/questions/7626475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to multiply values from different rows and different columns? This what the table looks like. Code Items Unit QTY Price Total ------- --------- ---- ---- ----- ----- HTM001 Cable Tie pcs null 1.00 ? HTM001s Cable Tie null 20 null and I tried a query like this... SELECT VRIJ1 FROM dbo.INVELE WHERE FK_BODEFINITOIN_USERDEFINED IN (894) AS QTY, SELECT RESTWRDE FROM dbo.INVELE WHERE FK_BODEFINITOIN_USERDEFINED IN (898) AS PRICE, (QTY*PRICE) AS TOTAL FROM dbo.INVELE then I got these: Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'AS'. Msg 156, Level 15, State 1, Line 5 Incorrect syntax near the keyword 'AS'. what I want is to like this 20*1.00=Total. Anyone Please help!!! A: ;WITH T1(QTY, CODE) AS ( SELECT VRIJ1, LEFT(CODE, 7) FROM dbo.INVELE WHERE FK_BODEFINITION_USERDEFINED IN (894) ), T2(PRICE, CODE) AS ( SELECT RESTWRDE, CODE FROM dbo.INVELE WHERE FK_BODEFINITION_USERDEFINED IN (898) ) SELECT T1.QTY, T2.PRICE, T1.QTY*T2.PRICE AS TOTAL FROM T1 INNER JOIN T2 ON T1.CODE = T2.CODE
{ "language": "en", "url": "https://stackoverflow.com/questions/7626476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stop a timeout function in this code: $("a").live("click", function(e) { e.preventDefault(); setTimeout(function () { $.get( "someOtherUrl", {someVariable: "someValue"}, function(result) { $(".result").html(render(result)); } ); }, 1000); $('a').live("touchmove", function(e) {clearTimeout()}); }); I want to stop the timeout when the user moves his finger on the screen. The thing is that clearTimeout() doesn't work because it is not linked to the timeout. How would I name the timeout and clear it quickly? Am I using the right method? A: Save the return value from "setTimeout()" in a variable, and then pass that value to "clearTimeout()" to clear it. $("a").live("click", function(e) { e.preventDefault(); var t = setTimeout(function () { $.get( "someOtherUrl", {someVariable: "someValue"}, function(result) { $(".result").html(render(result)); } ); }, 1000); $('a').live("touchmove", function(e) {clearTimeout(t);}); }); Now I would actually write that quite differently; as it is, you're adding a redundant "touchmove" handler on every click. Maybe something like this: function setupAnchorClicks() { var timer = null; $("a").live("click", function(e) { e.preventDefault(); timer = setTimeout(function() { // ... }, 1000); }).live("touchmove", function() { clearTimeout(timer); }); } setupAnchorClicks(); A: You'll have to save the handle received from setTimeout (it's a plain integer), and then pass it to clearTimeout as the argument. var functionToCancel = function() {console.log("hello");} var timeoutHandle = setTimeout(functionToCancel, 1000); clearTimeout(timeoutHandle);
{ "language": "en", "url": "https://stackoverflow.com/questions/7626479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Require_once triggering on page load and when submit? I have a php page (horses.php) that includes: <?php require_once('send_email.php');?> What happens is I have some scripting to send an email (and do some other things) in the send_email.php file. Now when horses.php loads the send_email.php page triggers and sends an email. It works perfectly. But on horses.php I also have a submit button that updates a db and goes to anoher page.. But what happens is that the send_email.php seems to be triggered on page load and also on submit? Because I get an email on page load (as I should), but then also when I press submit?? Ideas around this? Thanks A: You could try only sending the email if the form hasn't been submitted: if (!isset($_POST['name_of_an_element_in_the_form'])) { require_once('send_email.php'); } A: You have some code to send a mail while loading send_email.php ? I don't think it's a good practice, just define a function (or a class) to send a mail in send_email.php and call it when you actually need to send a mail...
{ "language": "en", "url": "https://stackoverflow.com/questions/7626480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP explode(), delimiter being returned? I'm not sure why but the explode function doesn't seem to be working for me. I have a string which contains one or more sets of comma-seperated values. These sets are delimied by starting / ending square brackets. After stripping off the ending "[" and "]", I thought it would be simple to then use the explode function to get the results seperated by "][". Instead, I get something weird. $rawInserts = '[1,2,3,4,5][2,3,4,5,6][3,4,5,6,7]'; $the_inserts = substr($rawInserts,1,strlen($rawInserts)-2); echo "$the_inserts \n"; //returns "1,2,3,4,5][2,3,4,5,6][3,4,5,6,7" $inserts = explode($the_inserts , "]["); echo print_r($inserts)."\n"; // returns one item array containing "]["; why is it returning "]["? (FYI, I tried this exact example and it fails). Thanks in advance. A: array explode ( string $delimiter , string $string [, int $limit ] ) Delimiter first, string second. A: Switch the parameters. It's delimiter first and string as second parameter: $inserts = explode('][', $the_inserts); A: it should be $inserts = explode("][",$the_inserts ); A: I myself cannot remember the parameters for every function, so just go to the php.net website and search for the explode function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7626481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }