text
stringlengths
8
267k
meta
dict
Q: calling Windows Phone 7 lockscreen programmatically Possible Duplicate: can you lock screen programmatically in wp7 I'd like to write an application for locking the screen (let's say, to reduce wear on the hardware lock button - locking the phone by pressing on the screen) - how could I accomplish this? (VB.NET or C# prefered) BTW: I'm aware this was asked here before - but the other guy asking this had the intention to run his code in the background while phone was locked. I really want to lock the phone using code!! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7532846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: HTML Unity PlugIn not working in wiki I have a wiki at http://toneme.org I would like to run a unity plug-in on the main page. as a test, I have a simple unity project, which comprises a .html and a .unity3d binary. here is the contents of the .html: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Unity Web Player | thelostcity</title> <script type="text/javascript" src="http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject.js"></script> <script type="text/javascript"> <!-- function GetUnity() { if (typeof unityObject != "undefined") { return unityObject.getObjectById("unityPlayer"); } return null; } if (typeof unityObject != "undefined") { unityObject.embedUnity("unityPlayer", "thelostcity.unity3d", 1024, 768); } --> </script> <style type="text/css"> <!-- body { font-family: Helvetica, Verdana, Arial, sans-serif; background-color: white; color: black; text-align: center; } a:link, a:visited { color: #000; } a:active, a:hover { color: #666; } p.header { font-size: small; } p.header span { font-weight: bold; } p.footer { font-size: x-small; } div.content { margin: auto; width: 1024px; } div.missing { margin: auto; position: relative; top: 50%; width: 193px; } div.missing a { height: 63px; position: relative; top: -31px; } div.missing img { border-width: 0px; } div#unityPlayer { cursor: default; height: 768px; width: 1024px; } --> </style> </head> <body> <p class="header"><span>Unity Web Player | </span>thelostcity</p> <div class="content"> <div id="unityPlayer"> <div class="missing"> <a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now!"> <img alt="Unity Web Player. Install now!" src="http://webplayer.unity3d.com/installation/getunity.png" width="193" height="63" /> </a> </div> </div> </div> <p class="footer">&laquo; created with <a href="http://unity3d.com/unity/" title="Go to unity3d.com">Unity</a> &raquo;</p> </body> </html> now if I double click the .html, Google Chrome loads it up perfectly. but if I copy the binary into the wiki's files, edit the wiki Main Page -> insert HTML widget -> <script type="text/javascript" src="http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject.js"> </script><script type="text/javascript"> // <!-- function GetUnity() { if (typeof unityObject != "undefined") { return unityObject.getObjectById("unityPlayer"); } return null; } if (typeof unityObject != "undefined") { unityObject.embedUnity("unityPlayer", "thelostcity.unity3d", 1024, 768); } --> // </script> <p class="header"><span>Unity Web Player |</span> thelostcity</p> <div class="content"> <div id="unityPlayer"> <div class="missing"><a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now!" rel="nofollow"><img alt="Unity Web Player. Install now!" src="http://webplayer.unity3d.com/installation/getunity.png" width="193" height="63"></img></a></div> </div> </div> <p class="footer">« created with <a href="http://unity3d.com/unity/" title="Go to unity3d.com" rel="nofollow">Unity</a> »</p> ...it refuses to run: What is going on? why is it not working? A: The problem is likely the location you're putting the binary. If the binary isn't at http://toneme.org/thelostcity.unity3d then it's not finding it, hence your error. A: As a follow-up, this page details how to write the necessary HTML to display the widget locally, which is as follows: <html> <head> </head> <body> <script type="text/javascript" src="http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject.js"></script> <script type="text/javascript"> <!-- unityObject.embedUnity( "unityPlayer", "CS.unity3d", 300, 300 ); --> </script> <div id="unityPlayer" /> </body> </html> therefore I just need to create a widget in my wiki with the following HTML: <script type="text/javascript" src="http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject.js"></script> <script type="text/javascript"> <!-- unityObject.embedUnity( "unityPlayer", "/file/view/CS.unity3d", 300, 300 ); --> </script> <div id="unityPlayer" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7532851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL LIMIT with WHERE clause Is it possible to use LIMIT x with the WHERE clause? If so, how? I'm trying to do this: select * from myVIew LIMIT 10 where type=3; But i get the following error: ERROR: syntax error at or near "where" LINE 2: where type=3; ^ ********** Error ********** ERROR: syntax error at or near "where" SQL state: 42601 Character: 44 A: Yes, have you tried this? select * from myVIew where type=3 LIMIT 10; Look here for further reference. LIMIT is after WHERE and ORDER BY clauses, which makes total sense if you stop and think about it: first you have to define your base result set (filters and orders), then you limit/page it. A: select * from myVIew where type=3 LIMIT 10; Limit should be after where clause. Syntax : SELECT column_name(s) FROM table_name [WHERE] LIMIT number; A: select * from myVIew where type=3 LIMIT 10;
{ "language": "en", "url": "https://stackoverflow.com/questions/7532852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Honeycomb gallery sample There is a link on the android dev blog to application example which works on both handsets and tablets, but there is android:minSdkVersion="11" in AndroidManifest.xml which assumes tablets rather than handsets. When I decreased the min version the application just didn't start. What did I miss? A: Without seeing that particular sample app: That post relates to Ice Cream Sandwich, that's the next (currently not published) version of android that will run on phones. It will have a higher API level than 11. The app probably uses features that were introduced on api lvl 11. ICS will support these, current phone versions don't.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wix Not Removing Files on Uninstall I've seen others' questions on this matter, but I can't make it work for me. I'm trying to get used to Wix so we can migrate our vdproj's (I feel like we've taken 1 step forward and 4 steps back here...the most basic of things have become completely non-trivial with Wix...but I do see value in having a fully fledged declarative markup for building installers). I have the following wxs in a wixproj in SharpDevelop. Install works. Uninstall does nothing and leaves the install folder and dll in place. What's the problem? Files.wxs: <?xml version="1.0"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Fragment> <DirectoryRef Id="TARGETDIR"> <Directory Id="ProgramFilesFolder" Name="PFiles"> <Directory Id="INSTALLDIR" Name="Client"> <Component Id="InteropDll" Guid="AD09F8B9-80A0-46E6-9E36-9618E2023D66" DiskId="1"> <File Id="Interop.dll" Name="Interop.dll" Source="..\Interop\bin\$(var.Configuration)\Interop.dll" KeyPath="yes" /> <RemoveFile Id="RemoveInterop.dll" Name="Interop.dll" On="uninstall" /> </Component> </Directory> </Directory> </DirectoryRef> </Fragment> </Wix> Setup.wxs: <?xml version="1.0"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Product Id="*" Name="Client Setup" Language="1033" Version="1.0.0.0" UpgradeCode="4A88A3AD-7CB6-46FB-B2FD-F4EADE0218F8" Manufacturer="Client Setup"> <Package Description="#Description" Comments="Comments" InstallerVersion="200" Compressed="yes"/> <!-- Source media for the installation. Specifies a single cab file to be embedded in the installer's .msi. --> <Media Id="1" Cabinet="contents.cab" EmbedCab="yes" CompressionLevel="high"/> <!-- Installation directory and files are defined in Files.wxs --> <Directory Id="TARGETDIR" Name="SourceDir"/> <Feature Id="Complete" Title="Client Setup" Description="Client Setup" Level="1"> <ComponentRef Id="InteropDll" /> </Feature> <!-- Using the Wix UI library WixUI_InstallDir does not allow the user to choose features but adds a dialog to let the user choose a directory where the product will be installed --> <Property Id="WIXUI_INSTALLDIR">INSTALLDIR</Property> <UI Id="WixUI_InstallDir"> <TextStyle Id="WixUI_Font_Normal" FaceName="Tahoma" Size="8" /> <TextStyle Id="WixUI_Font_Bigger" FaceName="Tahoma" Size="12" /> <TextStyle Id="WixUI_Font_Title" FaceName="Tahoma" Size="9" Bold="yes" /> <Property Id="DefaultUIFont" Value="WixUI_Font_Normal" /> <Property Id="WixUI_Mode" Value="InstallDir" /> <DialogRef Id="BrowseDlg" /> <DialogRef Id="DiskCostDlg" /> <DialogRef Id="ErrorDlg" /> <DialogRef Id="FatalError" /> <DialogRef Id="FilesInUse" /> <DialogRef Id="MsiRMFilesInUse" /> <DialogRef Id="PrepareDlg" /> <DialogRef Id="ProgressDlg" /> <DialogRef Id="ResumeDlg" /> <DialogRef Id="UserExit" /> <Publish Dialog="BrowseDlg" Control="OK" Event="DoAction" Value="WixUIValidatePath" Order="3">1</Publish> <Publish Dialog="BrowseDlg" Control="OK" Event="SpawnDialog" Value="InvalidDirDlg" Order="4"><![CDATA[WIXUI_INSTALLDIR_VALID<>"1"]]></Publish> <Publish Dialog="ExitDialog" Control="Finish" Event="EndDialog" Value="Return" Order="999">1</Publish> <Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="InstallDirDlg">NOT Installed</Publish> <Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg">Installed AND PATCH</Publish> <Publish Dialog="InstallDirDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg">1</Publish> <Publish Dialog="InstallDirDlg" Control="Next" Event="SetTargetPath" Value="[WIXUI_INSTALLDIR]" Order="1">1</Publish> <Publish Dialog="InstallDirDlg" Control="Next" Event="DoAction" Value="WixUIValidatePath" Order="2">NOT WIXUI_DONTVALIDATEPATH</Publish> <Publish Dialog="InstallDirDlg" Control="Next" Event="SpawnDialog" Value="InvalidDirDlg" Order="3"><![CDATA[NOT WIXUI_DONTVALIDATEPATH AND WIXUI_INSTALLDIR_VALID<>"1"]]></Publish> <Publish Dialog="InstallDirDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg" Order="4">WIXUI_DONTVALIDATEPATH OR WIXUI_INSTALLDIR_VALID="1"</Publish> <Publish Dialog="InstallDirDlg" Control="ChangeFolder" Property="_BrowseProperty" Value="[WIXUI_INSTALLDIR]" Order="1">1</Publish> <Publish Dialog="InstallDirDlg" Control="ChangeFolder" Event="SpawnDialog" Value="BrowseDlg" Order="2">1</Publish> <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="InstallDirDlg" Order="1">NOT Installed</Publish> <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="MaintenanceTypeDlg" Order="2">Installed AND NOT PATCH</Publish> <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" Order="2">Installed AND PATCH</Publish> <Publish Dialog="MaintenanceWelcomeDlg" Control="Next" Event="NewDialog" Value="MaintenanceTypeDlg">1</Publish> <Publish Dialog="MaintenanceTypeDlg" Control="RepairButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish> <Publish Dialog="MaintenanceTypeDlg" Control="RemoveButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish> <Publish Dialog="MaintenanceTypeDlg" Control="Back" Event="NewDialog" Value="MaintenanceWelcomeDlg">1</Publish> <Property Id="ARPNOMODIFY" Value="1" /> </UI> <UIRef Id="WixUI_Common" /> </Product> </Wix> A: Make sure that no other MSI packages are keeping your components installed. Specifically, go into Control Panel / Programs and Features, and make sure that there isn't an "old" version of your program still installed. A: Try to change the GUID of the components which are not uninstalling. I tried the same and it worked for me. It may be because the GUID is already registered in the registry by some other product. The cause is generally messed up component reference count in the registry - often it happens on dev-boxes during development. Can also often happen to Installshield packages due to their use of the SharedDllRefCount concept (legacy, non-MSI reference counting). Some technical details: Change my component GUID in wix? Test on a clean virtual to verify the problem is real and not a dev-box issue. Changing component GUIDs can have repercussions (patching problems etc...). A: Would be worth checking the following registry key to see if your files are listed. This can cause the uninstaller to ignore the components as it believes them to be shared. HKLM\Software\Microsoft\Windows\CurrentVersion\SharedDlls A: I somehow got my project in the state where every single one of my components couldn't be uninstalled. I have no idea how. I wrote a program that will take a .wixproj file and change all of the component GUIDs to new GUIDs and that solved the issue (after I manually deleted the files). This is based off of user593287's answer. The argument should be the path to your project file. An example of running this from the command line would be: GuidFixer.exe MyProject.csproj using System; using System.Collections.Generic; using System.IO; using System.Xml; namespace GuidFixer { public class Program { public static void Main(string[] args) { string projectFileName = args[0]; string path = Path.GetDirectoryName(projectFileName); List<string> files = new List<string>(); XmlDocument projectDocument = new XmlDocument(); projectDocument.Load(projectFileName); XmlNamespaceManager manager = new XmlNamespaceManager(projectDocument.NameTable); manager.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003"); // Finds all of the files included in the project. XmlNodeList nodes = projectDocument.SelectNodes("/msbld:Project/msbld:ItemGroup/msbld:Compile", manager); foreach (XmlNode node in nodes) { string fileName = Path.Combine(path, node.Attributes["Include"].Value); files.Add(fileName); } foreach (string fileName in files) { // Lets only do .wxs files if (!Path.GetExtension(fileName).Equals(".wxs", StringComparison.CurrentCulture)) { continue; } // This will only update files that aren't readonly, make sure // you check out your files from source control before running. FileAttributes attributes = File.GetAttributes(fileName); if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { continue; } bool modified = false; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; // space inside tags are still lost doc.Load(fileName); foreach (XmlNode node in doc.GetElementsByTagName("Component")) { Guid guid = Guid.NewGuid(); string value = guid.ToString("B").ToUpper(); node.Attributes["Guid"].Value = value; modified = true; } // Only update files that were modified, to preserve formatting. if (modified) { doc.Save(fileName); } } } } } I made some changes to it without testing it, so good luck, it's pretty straightforward though. A: I encountered a similar problem, which appeard not to be present any more when I converted all guids into uppercase (as required in some specification for compatiblity issues). Did not test exensively whether this was really the solution to the problem. Maybe this is the same as the previous answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Pixel shader to project a texture to an arbitary quadrilateral Just need to figure out a way, using Pixel Shader, to project a texture to an arbitary user-defined quadrilateral. Will be accepting coordinates of the four sides of a quadrilateral: /// <defaultValue>0,0</defaultValue> float2 TopLeft : register(c0); /// <defaultValue>1,0</defaultValue> float2 TopRight : register(c1); /// <defaultValue>0,1</defaultValue> float2 BottomLeft : register(c2); /// <defaultValue>1,1</defaultValue> float2 BottomRight : register(c3); Tried couple of interpolation algorithm, but couldn't manage to get it right. Is there any sample you guys think which I might be able to modify to get the desired result? A: There's a nice paper here describing your options (or this .ppt). Basically you need to define some barycentric coordinates across the quad, then interpolate fragment values as BC-weighted sums of the given vertex values. Sorry, don't know of any code; the lack of direct support for quads on modern triangle-oriented HW (see voidstar69's answer) means they've rather gone out of fashion. A: The issue here is that all modern 3D graphics hardware rasterizes triangles, not quadrilaterals. So if you ask Direct3D or OpenGL to render a quad, the API will internally split the quad into two triangles. This is not usually a problem since all modern rendering is perspective-correct, so the viewer should not be able to tell the difference between one quad and two triangles - the interpolation will be seamless. The correct way to ask the API to perform this interpolation is to pass it the texture coordinates as per-vertex data, which the API/hardware will interpolate across each pixel. Your pixel shader will then have access to this per-pixel texture coordinate. I assume that when you use the term 'project' you mean simply mapping a rectangular texture onto a quad, and you are not referring to texture projection (which is like a spotlight shining a texture onto surfaces). The bottom line here is that passing the quad's texture coordinates to the pixel shader is the wrong approach (unless you have some special reason why this is required).
{ "language": "en", "url": "https://stackoverflow.com/questions/7532867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Eager load Many to Many in EF4 using expressions? I have two Entities: GrmDeploymentAttempt and GrmDeploymentStep. These entities have a many to many relationship through an intermediary POCO GrmDeploymentAttemptStep, which has additional information about the actual many-to-many relationship. I am trying to load an attempt with all step information through eager loading, so right now I have the following code: var attempt = _context.GrmDeploymentAttempts .Where(x => x.Id == attemptId) .Include(x => x.AttemptSteps) .FirstOrDefault(); The problem is this eager load the intermediary table, but doesn't eager load the Steps table. How can I use the Include() with expressions to eager load my Step entity? Using the Include(string) method I could do Include("AttemptSteps.Steps") but I am not sure how to do this with expressions. As a note, I know i could instead load the AttemptSteps entity and eager load off of there, but there are some situations where I am unable to do this and I have been wondering how to handle this. A: var attempt = _context.GrmDeploymentAttempts .Where(x => x.Id == attemptId) .Include(x => x.AttemptSteps.Select(a => a.Step)) .FirstOrDefault(); Include(...Select(...)) generally loads a navigation property of a child collection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there any graph data structure implemented for C# I tried to find a graph data structure to reuse in C# without any success. Of course, I can borrow from data structure books but I want it to be more commercially practical(?) Also I would appreciate if you can tell me what the best way of implementing a graph is. Thanks A: Under active development, there is https://www.nuget.org/packages/QuikGraph You can view source code on GitHub https://github.com/KeRNeLith/QuikGraph and also read the wiki https://github.com/KeRNeLith/QuikGraph/wiki A: QuickGraph QuickGraph is a graph library for .NET that is inspired by Boost Graph Library. QuickGraph provides generic directed/undirected graph datastructures and algorithms for .Net 2.0 and up. QuickGraph comes with algorithms such as depth first seach, breath first search, A* search, shortest path, k-shortest path, maximum flow, minimum spanning tree, least common ancestors, etc... QuickGraph supports MSAGL, GLEE, and Graphviz to render the graphs, serialization to GraphML, etc... There are several ways to build graphs. The C++ Boost Graph Library (BGL) would be your best reference. It implements both adjacency-list, adjacency-matrix and edge-list graphs. Look here for details. A: There is actually a fairly old article in MSDN that covers graph creation in C#, An Extensive Examination of Data Structures Using C# 2.0. Despite its age, it still addresses your question as long as you don't mind creating your own graph class(es).
{ "language": "en", "url": "https://stackoverflow.com/questions/7532882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "71" }
Q: Doctrine 2 Query Builder abs Function This Work: $qb = $this->em->createQueryBuilder(); $qb->select("abs(u.code) as code") ->from("User", "u") ->orderBy("code","ASC") ->getQuery() ->getArrayResult(); This Don't Work: $qb = $this->em->createQueryBuilder(); $qb->select("u.code") ->from("User", "u") ->orderBy("abs(u.code)","ASC") ->getQuery() ->getArrayResult(); The Error: Syntax Error] line 0, col 118: Error: Expected end of string, got '(' The native doctrine function abs work only on a select part of statment and don't work on order by part. Obs: 1-) Im avoiding to use NativeQuery. 2-) u.code is a varchar fild on mysql and need to be varchar ( some times numeric and some times string), and i need to order then like a number in numeric case. Any Help? A: Solved atma thank's abs() realy doesn't work directly in orderBy but as an alias. soluction SELECT field1,field2,abs(field3) AS abs_field3 FROM table ORDER BY abs_field3 ASC Obs: It's a doctrine limitation, not a mysql limitation, mysql suports abs direct on order by part. A: may be a little late after 7 years Inactivity, but maybe it helps somebody. Solution found here: Doctine $qb = $this->em->createQueryBuilder(); $qb->select("u.code") ->from("User", "u") ->orderBy( $qb->expr()->andX( $qb->expr()->abs('u.code'), "ASC" ) ) ->getQuery() ->getArrayResult() ;
{ "language": "en", "url": "https://stackoverflow.com/questions/7532886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remove common english words strategy I want to extract relevant keywords from a html page. I already stipped all html stuff, split the text into words, used a stemmer and removed all words appearing in a stop word list from lucene. But now I still have alot of basic verbs and pronouns as most common words. Is there some method or set of words in lucene or snowball or anywhere else to filter out all these things like "I, is , go, went, am, it, were, we, you, us,...." A: You are looking for the term 'stopwords'. For Lucene, this is built in and you can add them in the StopWordAnalyzer.java (see http://ankitjain.info/ankit/2009/05/27/lucene-search-ignore-word-list/) A: It seems like a pretty simple application of inverse document frequency. If you had even a small corpus of say, 10,000 web pages, you could compute the probability of each word appearing in a document. Then pick a threshold where you think the words start to get interesting or contentful and exclude the words before that threshold. Alternatively, this list looks good. http://www.lextek.com/manuals/onix/stopwords1.html A: The tm package for R provides an interface through R for many common NLP tasks, and has an interface to Weka. It might be worth checking out. The documentation is here Upon looking at your question more colsely, you are probably looking for the removeStopWords() function in the tm package.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle SQL Query with Member and Member_phone table join MEMBER table with primary key MEMBER_ID and MEMBER_PHONE table for MEMBER_ID as foreign key and PHONE_IND as one of column with values 'S' (Secondary Phone) or 'P' (Primary Phone) along with phone number details. 'S' is our key value. I need oracle query to fetch the Member information with phone if 'S' exists, if not 'P' phone number. In MEMBER_PHONE table every member will have two possible rows of 'S' and 'P', if not atleast 'P' as one row. Thanks in advance for your help. A: If I understand correctly, the member can have an optional 'S' phone number, and will always have a 'P' phone number. If the 'S' number exists, you want to return the member info along with that number. If not, you want to fallback and return the member info along with the 'P' number, right? select * from MEMBER m inner join MEMBER_PHONE p on p.MEMBER_ID = m.MEMBER_ID where p.PHONE_IND = 'S' or ( p.PHONE_IND = 'P' and not exists ( select * from MEMBER_PHONE p where p.PHONE_IND = 'S' and p.MEMBER_ID = m.MEMBER_ID) ) [edit] It is a fun kind of query. Here's a complete different approach: select m.*, pp.* from MEMBER m left join MEMBER_PHONE ps on ps.MEMBER_ID = m.MEMBER_ID and ps.PHONE_IND = 'S' inner join MEMBER_PHONE pp on pp.MEMBER_ID = m.MEMBER_ID and pp.PHONE_IND = nvl(ps.PHONE_IND, 'P') Check for yourself which one works/performs best. [edit 2] Drawn to this question again by a comment, so I decided to add another one. As you can see, it's hard not to solve this problem. ;-) select * from (select m.*, p.*, dense_rank() over ( partition by m.MEMBER_ID order by decode(p.PHONE_IND, 'S', 1, 2)) as RANK from MEMBER m inner join MEMBER_PHONE p on pp.MEMBER_ID = m.MEMBER_ID ) where RANK = 1 A: select m.* from MEMBER m where exists ( select 1 from MEMBER_PHONE mp where mp.member_id = m.member_id and mp.phone_ind = 'S' ); EDIT I think know I understood... select m.* , mp.* from member m left outer join member_phone mp on m.member_id = mp.member_id where (mp.phone_ind = 'S' or ( mp.phone_ind = 'P' and not exists( select 1 from member_phone mp1 where mp1.member_id = mp.member_id and mp1.phone_ind = 'S' )))
{ "language": "en", "url": "https://stackoverflow.com/questions/7532890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where is the bug in this jQuery code? I have this code and the part in /**/ has some bug... I can't find it... When I delete that part of the code it works fine. Problem Solution $(window).load(function(){ $('#cTop').toggle( function(){ showC(); }, function() { hideC(); } ); $('#textDownRight').click(function(){ window.location = 'http://nitidus-consto.kilu.org'; hideC(); }); /* The buggy code starts here */ $('.menuCircle').hover( function () { $(this).animate({ width: 55%, height: 55% }, 250); }, function() { $(this).animate({ width: 50%, height: 50% }, 250); }); /*it ends here*/ }); function hideC(){ $('#c').animate({ width: 100, height: 100, 'margin-left': '-50px', 'margin-top': '-50px' },500); $('#cTop').animate({ 'backgroundColor': 'rgb(25,25,25)' }, 500);} function showC(){ $('#c').animate({ width: 200, height: 200, 'margin-left': '-100px', 'margin-top': '-100px' },500); $('#cTop').animate({ 'backgroundColor': 'rgb(50,50,50)' }, 500);} A: Try this one http://jsfiddle.net/qHeMD/1/ you're missing quotes around values with percents $(this).animate({ width: 55% , height: 55% }, 250); }, function() { $(this).animate({ width: 50%, height: 50% }, 250); should be $(this).animate({ width: '55 %' , height: '55 %' }, 250); }, function() { $(this).animate({ width: '50 %', height: '50 %' }, 250); A: Try making the percentages strings, like this: /* The buggy code starts here */ $('.menuCircle').hover( function () { $(this).animate({ width: '55%', height: '55%' }, 250); }, function() { $(this).animate({ width: '50%', height: '50%' }, 250); }); /*it ends here*/ });
{ "language": "en", "url": "https://stackoverflow.com/questions/7532894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java wrapper as daemon I am using this YAJSW to run Java Daemon on my Centos 5.5 machines. The think it runs well but out of suddent I notice I get this sort of error and then it just goes down. Any help what must I do to avoid this sort of problem? Can I use some monitoring tool to monitor and recover it as soon it falls into problem? Below is just part of the error list. NFO|3090/0|11-09-19 20:22:13|Controller State: LOGGED_ON -> PROCESS_KILLED INFO|wrapper|11-09-19 20:22:13|restart process due to default exit code rule INFO|wrapper|11-09-19 20:22:13|set state RUNNING->RESTART INFO|wrapper|11-09-19 20:22:13|set state RESTART->RESTART_STOP INFO|wrapper|11-09-19 20:22:13|stopping process with pid/timeout 3090 45000 INFO|3090/0|11-09-19 20:22:13|Controller State: PROCESS_KILLED -> WAITING_CLOSED FINEST|3090/0|11-09-19 20:22:13|wrapper manager received stop command INFO|3090/0|11-09-19 20:22:14|Controller State: WAITING_CLOSED -> USER_STOP INFO|wrapper|11-09-19 20:22:14|stop config name null INFO|wrapper|11-09-19 20:22:14|externalStop false INFO|wrapper|11-09-19 20:22:14|exit code linux process 0 INFO|wrapper|11-09-19 20:22:14|killing 3090 INFO|3090/0|11-09-19 20:22:14|gobler execption OUTPUT 3090 null INFO|3090/0|11-09-19 20:22:14|gobler execption ERROR 3090 null INFO|3090/0|11-09-19 20:22:14|gobler terminated OUTPUT 3090 INFO|wrapper|11-09-19 20:22:14|process exit code: 0 INFO|3090/0|11-09-19 20:22:14|gobler terminated ERROR 3090 INFO|wrapper|11-09-19 20:22:14|set state RESTART_STOP->RESTART_WAIT INFO|wrapper|11-09-19 20:22:19|set state RESTART_WAIT->RESTART_START INFO|wrapper|11-09-19 20:22:19|starting Process INFO|3090/0|11-09-19 20:22:19|Controller State: USER_STOP -> UNKNOWN INFO|wrapper|11-09-19 20:22:19|Controller State: UNKNOWN -> WAITING INFO|wrapper|11-09-19 20:22:20|working dir /usr/local INFO|wrapper|11-09-19 20:22:20|error initializing script INFO|wrapper|11-09-19 20:22:20|exec:/usr/java/jdk1.6.0_18/bin/java -classpath /usr/local/yajsw-beta-10.2/./wrapperApp.jar:/usr/local -Xrs -Dwrapper.service=true -Dwrapper.console.visible=false -Dwrapper.visible=false -Dwrapper.pidfile=/var/run/wrapper.commServer.pid -Dwrapper.config=/usr/local/yajsw-beta-10.2/conf/wrapper.conf -Dwrapper.port=15003 -Dwrapper.key=-6288918147195966892 -Dwrapper.teeName=-6288918147195966892$1316434940036 -Dwrapper.tmpPath=/tmp org.rzo.yajsw.app.WrapperJVMMain INFO|wrapper|11-09-19 20:22:20|started process 8988 INFO|wrapper|11-09-19 20:22:20|started process with pid 8988 INFO|wrapper|11-09-19 20:22:20|set state RESTART_START->RUNNING INFO|wrapper|11-09-19 20:22:34|Controller State: WAITING -> STARTUP_TIMEOUT INFO|wrapper|11-09-19 20:22:34|restart process due to default exit code rule INFO|wrapper|11-09-19 20:22:34|set state RUNNING->RESTART INFO|wrapper|11-09-19 20:22:34|set state RESTART->RESTART_STOP INFO|wrapper|11-09-19 20:22:34|stopping process with pid/timeout 8988 45000 INFO|wrapper|11-09-19 20:22:34|Controller State: STARTUP_TIMEOUT -> USER_STOP INFO|wrapper|11-09-19 20:22:34|stop config name null INFO|wrapper|11-09-19 20:22:34|externalStop false INFO|wrapper|11-09-19 20:23:19|process did not stop after 45000 sec. -> hard kill INFO|wrapper|11-09-19 20:23:19|killing 8988 INFO|wrapper|11-09-19 20:23:19|send kill sig INFO|wrapper|11-09-19 20:23:19|exit code linux process 9 INFO|wrapper|11-09-19 20:23:19|Controller State: USER_STOP -> PROCESS_KILLED INFO|8988/1|11-09-19 20:23:20|gobler execption OUTPUT 8988 null INFO|8988/1|11-09-19 20:23:20|gobler execption ERROR 8988 null INFO|wrapper|11-09-19 20:23:20|process exit code: 999 INFO|8988/1|11-09-19 20:23:20|gobler terminated OUTPUT 8988 INFO|8988/1|11-09-19 20:23:20|gobler terminated ERROR 8988 INFO|wrapper|11-09-19 20:23:20|set state RESTART_STOP->RESTART_WAIT INFO|wrapper|11-09-19 20:23:25|set state RESTART_WAIT->RESTART_START INFO|wrapper|11-09-19 20:23:25|starting Process INFO|wrapper|11-09-19 20:23:25|Controller State: PROCESS_KILLED -> UNKNOWN INFO|wrapper|11-09-19 20:23:25|Controller State: UNKNOWN -> WAITING INFO|wrapper|11-09-19 20:23:25|working dir /usr/local INFO|wrapper|11-09-19 20:23:25|error initializing script INFO|wrapper|11-09-19 20:23:25|exec:/usr/java/jdk1.6.0_18/bin/java -classpath /usr/local/yajsw-beta-10.2/./wrapperApp.jar:/usr/local -Xrs -Dwrapper.service=true -Dwrapper.console.visible=false -Dwrapper.visible=false -Dwrapper.pidfile=/var/run/wrapper.commServer.pid -Dwrapper.config=/usr/local/yajsw-beta-10.2/conf/wrapper.conf -Dwrapper.port=15003 -Dwrapper.key=-6288918147195966892 -Dwrapper.teeName=-6288918147195966892$1316435005686 -Dwrapper.tmpPath=/tmp org.rzo.yajsw.app.WrapperJVMMain INFO|wrapper|11-09-19 20:23:26|started process 8989 INFO|wrapper|11-09-19 20:23:26|started process with pid 8989 INFO|wrapper|11-09-19 20:23:26|set state RESTART_START->RUNNING INFO|wrapper|11-09-19 20:23:40|Controller State: WAITING -> STARTUP_TIMEOUT INFO|wrapper|11-09-19 20:23:40|restart process due to default exit code rule INFO|wrapper|11-09-19 20:23:40|set state RUNNING->RESTART INFO|wrapper|11-09-19 20:23:40|set state RESTART->RESTART_STOP INFO|wrapper|11-09-19 20:23:40|stopping process with pid/timeout 8989 45000 INFO|wrapper|11-09-19 20:23:40|Controller State: STARTUP_TIMEOUT -> USER_STOP INFO|wrapper|11-09-19 20:23:40|stop config name null INFO|wrapper|11-09-19 20:23:40|externalStop false INFO|wrapper|11-09-19 20:24:25|process did not stop after 45000 sec. -> hard kill INFO|wrapper|11-09-19 20:24:25|killing 8989 INFO|wrapper|11-09-19 20:24:25|send kill sig INFO|wrapper|11-09-19 20:24:25|exit code linux process 9 INFO|wrapper|11-09-19 20:24:25|Controller State: USER_STOP -> PROCESS_KILLED INFO|8989/2|11-09-19 20:24:26|gobler execption OUTPUT 8989 null INFO|8989/2|11-09-19 20:24:26|gobler execption ERROR 8989 null INFO|wrapper|11-09-19 20:24:26|process exit code: 999 INFO|8989/2|11-09-19 20:24:26|gobler terminated OUTPUT 8989 INFO|8989/2|11-09-19 20:24:26|gobler terminated ERROR 8989 A: You can trace what the linux process is doing by attaching an strace to it. If it is a problem with YAJSW itself and if you are looking for a simple wrapper to keep your job up and running, it can be done with a simple bash script. until myjob; do echo "restarting myjob" sleep 10 done Line 1 is a blocking call as long as myjob is running and if it exits with anything other than a 0 then, it will be restarted. A: You could look: here - this could be a resource leak. A: I ran into very similar wrapper log output on Windows. In my case, multiple applications were running through yajsw instances. It appears that in some cases, automatic port selection by yajsw to monitor Java applications doesn't work properly. In the yajsw instance that is failing, adding wrapper.port = 24572 fixes the issue. Recreate the service after modifying the wrapper.conf. I only had to add this to the instance of yajsw that was failing; other instances auto-selected ports successfully. The port number doesn't matter, just choose an unused port.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: FireBug Lite messageQueue null I'm trying to get FireBug Lite working with IE7. Given this code (and nothing else): <script type="text/javascript" src="https://getfirebug.com/firebug-lite.js"></script> <link rel="stylesheet" href="../../css/third-party/jquery.ui.all.css"> This is a test! ...I get an error at Line: 8180, 'this.messageQueue is null or not an object' and the console does not appear. If I remove the CSS file reference, it works fine. Also, this CSS works fine with FireBug under FF and GC. The CSS file is a recent download from jQ's web site and contains nowhere near 8,000 lines (after expanding all @imports), nor does any of the code accessible to my web server contain the token 'messageQueue'. I don't have any IE plugins (that I am aware of) and have never used any sort of MSMQ products on this PC. I also tried random things such as switching the order of statements, loading jQuery's regular .js files, using the FireBug bookmarklet instead, etc., all to no avail. Any advice? A: This is a known bug that affects IE7 (and IE8) and is being tracked on the firebug issue tracker. This is still an issue on all channels (Firebug 1.4 stable/debug/beta/developer). Disclaimer: If you're going to use these methods, please subscribe to the discussion about this bug and make sure you stop using this contrived one either when it's fixed, or Firebug 1.5 comes out. If you need to use firebug now, you could use firebug 1.3. This method I can't find documented anywhere... <script type="text/javascript" src="https://getfirebug.com/releases/lite/1.3/firebug-lite.js"></script> A better approach would be to use Firebug 1.3 as a bookmarklet. I've hacked up this bookmarklet URL based on the firebug release archive: javascript:(function(F,i,r,e,b,u,g,L,I,T,E){if(F.getElementById(b))return;E=F[i+'NS']&&F.documentElement.namespaceURI;E=E?F[i+'NS'](E,'script'):F[i]('script');E[r]('id',b);E[r]('src',I+g+T);E[r](b,u);(F[e]('head')[0]||F[e]('body')[0]).appendChild(E);E=new%20Image;E[r]('src',I+L);})(document,'createElement','setAttribute','getElementsByTagName','FirebugLite','3','releases/lite/1.3/firebug-lite.js','releases/lite/latest/skin/xp/sprite.png','https://getfirebug.com/','#startOpened'); Just dump it into your 'links' bar using the above in the URL field. A: One possible cause of this: if there's no stylesheet or CSS style data. No idea why. If there is no CSS and you're seeing this error, add some and Firebug Lite might just work again. For example, this JSbin, with a token CSS rule, works with Firebug Lite in IE8: http://jsbin.com/etecub/5/ Code: http://jsbin.com/etecub/5/edit This JSbin, identical but with no CSS rules, fails to load Firebug Lite in IE8 with the error 'this.messageQueue' is null or not an object: http://jsbin.com/etecub/6/ Code: http://jsbin.com/etecub/6/edit It seems like it doesn't matter if the rule is actually applied or not (e.g. http://jsbin.com/etecub/9 works fine). If you've got a stylesheet attached and see this error anyway, and the above doesn't work, maybe try adding a <style> block to the document with a CSS rule or two. A: I had the same issue with Firebug Lite not opening with my Meteor App. After reading the bugtracker discussions I tried the debug-version, which is basically only the uncompressed version of the library. And yes, that made the difference and Firebug Lite now starts in both Chrome and Safari. The tag I am using right now: <script type="text/javascript" src="https://getfirebug.com/firebug-lite-debug.js"></script> A: Just saw an answer that helped me, from here: https://github.com/angular/angular.js/issues/3596. The bug-report itself is on the Angular project repo, but it doesn't have anything to do with Angular -- the problem, for me, was manifesting itself on a vanilla HTML/CSS/JS page, and the fix worked there as well. Quoting from there: firebug-lite-beta.js:30905 Uncaught TypeError: Cannot read property 'push' of undefined Adding basic null check: if (typeof this.messageQueue == 'undefined') {        this.messageQueue = []; } Seems to be solving the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: How to change App Profiles Page to match changed Namespace We recently changed the Namespace for our canvas app from 'karmakorn' to 'karmalyze' to get ready for an alpha release. The Facebook platform correctly points to http://apps.facebook.com/karmalyze for the canvas, but continues to point to http://www.facebook.com/KarmaKorn for the app profiles page. We don't see anyplace to edit this. Is it a Facebook bug? Is there some trick we can do to trigger the correct setting? A: The app namespace and the app's profile page URL are completely separate. At some point you set your page's "username" to be KarmaKorn by going to facebook.com/usernames while logged in as an administrator of the page (a developer of the app). The app's namespace is set completely separately in the Developer app. Officially there is no way to change or transfer your Facebook page's username. You could make a second page at the URL you want and set up some links to direct users from one of those pages to the other (or maintain both of them in tandem).
{ "language": "en", "url": "https://stackoverflow.com/questions/7532914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Razor: Get style value from elsewhere on the page I'm trying to hack my way through some ASP.NET pages put together with Razor, having never seen Razor used before today, more or less, and I was wondering if it were possible to grab a CSS style value and use it in Razor code, like this: @foreach (var item in someList.Where(i => someHTMLElement.display == block ? i.property == "value" : i.property == "othervalue")) { ... display filtered list } It's that Where bit I'd like to populate with something useful. Any suggestions? A: Razor runs on the server much earlier a DOM tree is constructed by the client browser. This means that you do not have access to other DOM elements with Razor. The best way to achieve that would be to simply adapt your view model and include the necessary properties to it and have the controller populate them. So in the view all you have to do is a simple test of some property. A: You'd have to leverage some server-side feature for this. Razor views rendered hierarchically , so the value to display must be defined either in the controller (if using MVC), or above where you intend to implement it. But it's up to you to make the determination on the server, or use JavaScript to replicate this logic on the client...
{ "language": "en", "url": "https://stackoverflow.com/questions/7532917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: meta_where code not being recognized I used meta_where on a rails project last summer and it worked. However trying to set up a rails project at a distance using the screen sharing site "join.me" I'm getting errors when the code gets to the first line that uses meta_where ("matches"). I've put "gem 'meta_where'" in the Gemfile and "bundle install" gives the error: Bundler could not find compatible versions for gem "activerecord": In Gemfile: meta_where depends on activerecord(~>3.0.0.rc2) activerecord (3.1.0) and yet when I use the gem server and check the installed gems on the webpage there are 2 versions of activerecord (3.0.9 and 3.1.0) and meta_where-1.0.4 is listed. It seems that the code is looking in the wrong directory, but that's just a wild guess. What's the problem? Thanks, Barney A: the problem is, meta_where depends on Rails 3.0 (NOT 3.1). are you using rvm? you should create a rails 3.0 project, if you need meta_where. if you're using rvm, you can simply create another gemset, and rvm gemset create rails30 rvm gemset use rails30 gem install bundler gem install rails -v=3.0.10 then create a Rails 3.0 project rails new my_project and so on
{ "language": "en", "url": "https://stackoverflow.com/questions/7532918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Building Android Webkit Plugins? I have an application I built (based on OilCan) that modifies some popular webpages with basic enhancements. When I distribute it as a .apk, I can launch my new application called MyApp that emulates the browser, editing the target pages to my liking. Now I'd like to re-package it as a plugin for the default browser, so that if my app is installed, it runs in the base Android Webkit Browser app, instead of requiring the user to launch MyApp every time. Is this possible? I assume so because this appears to be how Adobe Flash works -- install the .apk, extend the browsers functionality -- but also, that's a content-based plugin, rather than an add-on. I can find no documentation regarding what I want to do; any direction at all would be super helpful! Thanks, --L A: I think the browser is prepared to use the flash plugin (expected extension). I also did research before whether I can extend the default browser, but only found posts on google group where the developers say that there is no API included which allows browser extension. I would love to see an API since this would enhance the app so much, but I also can understand their decision since it's a lot of work and wrong extensions could break the efficiency... E.g. dolphin browser plugins are also all self written, closed API (right now at least).
{ "language": "en", "url": "https://stackoverflow.com/questions/7532921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails controller design pattern for My Events I would like to have a My_Events page, which only display events that current user subscribed to, and allow user to manipulate these events, in addition to Index page that displays all events in the system. How should I go about this to comply with RESTful pattern? Should I just create a my_events action and my_event.html.erb, or create a new controller for it? What would be the reason to choose one over another approach? Thank you. A: If you happen to have a user controller, adding an events action to that and routing based on the user for user specific events would seem most RESTful. # app/controllers/users_controller.rb class UsersController < ApplicationController ... def events @user = User.find params[:id] @events = @user.events end end # config/routes.rb resources :users do member do get 'events' end end The benefit to this over something like /events/my_events is that the URL is unique to the data that is being presented. If a user uses the link /users/fubar/events then it will show events for the user fubar, where as with something like /events/my_events the generated page is tied to the session and not the URL. Of course it really depends on what your goal is, and what requirements your application has. A: You can have methods in another controller that load these Events and do all the things that you want/need. But if you want to use the index, edit, delete and create new Event, I would recommend having an events_controller as it will be better for you in the future when lines and lines of codes are added. That's the point of having a controller per model, having everything ordered.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript Objects: What gets returned from an object constructor I wasn't sure how to ask this, and I apologize if it's been asked already, but I could not find it or an answer. What is returned when you assign a function to a var. var obj = function(){ this.name = 'Steve'; } alert( obj.name === '');//true obj.name = 'Mike'; alert( obj.name === '');//true obj.foo = 'fall'; alert( obj.foo );//fall I know obj is now a function/object and I can call obj(). I also know that the function attached to obj is a constructor for new objects of type obj. If I do var newObj = new obj(); alert( newObj.name );//Steve "Steve" is printed. etc. etc. Why does obj seem to have a property called "name" attached to it? And why when I try to assign a value to that property does it not get assigned? A: Because function objects have aname property (which is non-standard by the way) that represents the "name" of the function, your function shows an empty string ("") as the value of this property because it's anonymous. For example, if you declare a function with the name foo: function foo() {} foo.name; // "foo" var anon = function () {}; anon.name; // "", an anonymous function var namedFunctionExpr = function bar () {}; namedFunctionExpr.name; // "bar" Also as you noted, you can't change the value of this property, since in most implementations, it's non-configurable, non-enumerable and non-writable: Object.getOwnPropertyDescriptor(function x(){}, 'name'); /* logs: { configurable: false, enumerable: false, value: "x", writable: false } */ Remember, this property is non-standard and there are some implementations that don't support it (e.g. all IE JScript versions do not support it) Now as @Felix suggest, I would like to add that this.name doesn't have anything to do with your function's name property. In your example, calling the obj function as a constructor (with the new operator), sets the this value to a newly created object, that inherits from your function's prototype, and you are assigning a value to the name property to this new object. A: Without constructing an instance of an object with the function, using obj.name, you're just reading the name property of the function. You can actually explicitly name a function with the syntax function foo(){ } you could do something like: var goo = function foo() {} and goo.name will actually read "foo". Your declaration here is not named: var obj = function(){ this.name = 'Steve'; } so obj.name is always the empty string. You can read up more here: http://bonsaiden.github.com/JavaScript-Garden/#function However, if you invoke the function with new, you get an instance of an object created through the constructor, complete with everything inherited through the prototype chain. It's worth noting however, that you can actually return any object you want from a constructor function. By default it returns an instance of the object, but you could just as easily return a different object, which naturally wouldn't have any of the properties from the prototype. ie: function Dog() { this.bark = "bark!"; return { bark: "quack"}; } var weirdDog = new Dog(); will not have weirdDog.bark === "bark". Again, you can read up more on the Javascript Garden site for more info. A: "name" property returns the name of the function and you can't set it because it's readonly property. It's returning blank because your function is anonymous. Better check this link for more details: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Name
{ "language": "en", "url": "https://stackoverflow.com/questions/7532923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hashtag in url issue I have a querystring parameter that populates another page and the problem happens when the parameter starts with a hashtag # Ex: mysitepage/Details?param=#456 Of course this happens because hashtags in url ends the request. The problem is that these are ids from the database and cant be changed. Instead of using a querystring, is there any work around for this that someone can inform me of. Edit1- I realized I was encoding the whole url wheere the problem was. Now I am only doing the parameter part, but it seems to be making the parameter static instead of dynamic now: example : String.Format("mysite.com?param="+Server.UrlEncode({0}), Eval("param")) basically it encodes the 0 in curly braces and not the actual evaluated value A: You should checkout HttpUtility.UrlEncode(string) It will encode # to %23& and of course you can decode it back with UrlDecode() A: You need to encode and decode the parameter. With ASP.NET MVC, I'm using Url.Encode() and Url.Decode() for this. #456 encoded is %23456 It looks like you can use HttpUtility.UrlEncode() and HttpUtility.UrlDecode() in ASP.NET.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I install Maven with Yum? I'm trying not to learn much about either yum or maven. I've inherited this code and I don't want to spend more time than I have to in this environment. I've got yum. My installation "has" ("is attached too"? "knows about"?) two repos: the Amazon one and JPackage, which I understand is something of a standard. (Actually, each of those repositories consists of two sub-repositories, but I don't think that's causing the problem.) When I asked yum to install maven2, it declined, saying it had never heard of maven2. When I asked yum to install maven2 ignoring Amazon, it does so, but it installs Maven 2.0.9, which is fairly old. The actual pom.xml I have requires a higher version. When I Google for Maven repositories I get repositories that Maven can use to build other things, not repositories that Yum can use to install Maven. (I did find a repository containing thing that let Maven build Yum. I think Google is mocking me at this point.) So, all I need is the repo file that points to a repo that contains whatever I need to install Maven 2.2.1. If it weren't for all these labor-saving devices, I could probably get some work done. A: For future reference and for simplicity sake for the lazy people out there that don't want much explanations but just run things and make it work asap: 1) sudo wget https://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo 2) sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo 3) sudo yum install -y apache-maven 4) mvn --version Hope you enjoyed this copy & paste session. A: Do you need to install it with yum? There's plenty other possibilities: * *Grab the binary from http://maven.apache.org/download.html and put it in your /usr/bn *If you are using Eclipse you can get the m2eclipse plugin (http://m2eclipse.sonatype.org/) which bundles a version of maven A: This is what I went through on Amazon/AWS EMR v5. (Adapted from the previous answers), to have Maven and Java8. sudo wget https://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo sudo yum install -y apache-maven sudo alternatives --config java pick Java8 sudo alternatives --config javac pick Java8 Now, if you run: mvn -version You should get: Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z) Maven home: /usr/share/apache-maven Java version: 1.8.0_171, vendor: Oracle Corporation Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.38.amzn1.x86_64/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "4.14.47-56.37.amzn1.x86_64", arch: "amd64", family: “unix" A: Maven is packaged for Fedora since mid 2014, so it is now pretty easy. Just type sudo dnf install maven Now test the installation, just run maven in a random directory mvn And it will fail, because you did not specify a goal, e.g. mvn package [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 0.102 s [INFO] Finished at: 2017-11-14T13:45:00+01:00 [INFO] Final Memory: 8M/176M [INFO] ------------------------------------------------------------------------ [ERROR] No goals have been specified for this build [...] A: yum install -y yum-utils yum-config-manager --add-repo http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo yum-config-manager --enable epel-apache-maven yum install -y apache-maven for JVM developer, this is a SDK manager for all the tool you need. https://sdkman.io/ Install sdkman: yum install -y zip unzip curl -s "https://get.sdkman.io" | bash source "$HOME/.sdkman/bin/sdkman-init.sh" Install Maven: sdk install maven A: Icarus answered a very similar question for me. Its not using "yum", but should still work for your purposes. Try, wget http://mirror.olnevhost.net/pub/apache/maven/maven-3/3.0.5/binaries/apache-maven-3.0.5-bin.tar.gz basically just go to the maven site. Find the version of maven you want. The file type and use the mirror for the wget statement above. Afterwards the process is easy * *Run the wget command from the dir you want to extract maven too. *run the following to extract the tar, tar xvf apache-maven-3.0.5-bin.tar.gz *move maven to /usr/local/apache-maven mv apache-maven-3.0.5 /usr/local/apache-maven *Next add the env variables to your ~/.bashrc file export M2_HOME=/usr/local/apache-maven export M2=$M2_HOME/bin export PATH=$M2:$PATH *Execute these commands source ~/.bashrc 6:. Verify everything is working with the following command mvn -version A: For those of you that are looking for a way to install Maven in 2018: $ sudo yum install maven is supported these days. A: You can add maven to the yum libraries like this: wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo Now you can install maven like this: yum install apache-maven Once done, maven 3 will be installed and mvn -version will show you which version you've got - I had 3.2.1. This worked perfectly for me on CentOS 6 with one exception. It installed OpenJDK 1.6 and made it the default Java version, even though I'd already manually installed JDK 8 (possibly because I'd manually installed it). To change it back use alternatives: alternatives --config java alternatives --config javac and choose the correct version. A: I've just learned of a handy packaging tool called fpm recently. Stumbling upon this question I thought I might give it a try. Turns out, after reading @OrwellHindenberg's answer, it's easy to package maven into an RPM with fpm. yum install -y gcc make rpm-build ruby-devel rubygems gem install fpm create a project directory and layout the directory structure of the package mkdir maven-build cd maven-build mkdir -p etc/profile.d opt create a file that we'll install to /etc/profile.d/maven.sh, we'll store this under the newly created etc/profile.d directory as maven.sh, with the following contents export M3_HOME=/opt/apache-maven-3.1.0 export M3=$M3_HOME/bin export PATH=$M3:$PATH download and unpack the latest maven in the opt directory wget http://www.eng.lsu.edu/mirrors/apache/maven/maven-3/3.1.0/binaries/apache-maven-3.1.0-bin.tar.gz tar -xzf apache-maven-3.1.0-bin.tar.gz -C opt finally, build the RPM fpm -n maven-3.1.0 -s dir -t rpm etc opt Now you can install maven through rpm $ rpm -Uvh maven-3.1.0-1.0-1.x86_64.rpm Preparing... ########################################### [100%] 1:maven-3.1.0 ########################################### [100%] and viola $ which mvn /opt/apache-maven-3.1.0/bin/mvn not quite yum but closer to home ;) A: Not just mvn, for any util, you can find out yourself by giving yum whatprovides {command_name}
{ "language": "en", "url": "https://stackoverflow.com/questions/7532928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "148" }
Q: facebook credits , how to get php back? i am using the facebook credits example and everything works but this: if ($_GET['order_id'] && $_GET['status']) { $html = "Transaction Completed! </br></br>" ."Data returned from Facebookkkkkk: </br>" ."<b>Order ID: </b>" . $_GET['order_id'] . "</br>" ."<b>Status: </b>" . $_GET['status']; } elseif ($_GET['error_code'] && $_GET['error_message']) { $html = "Transaction Failed! </br></br>" ."Error message returned from Facebook:</br>" .$_GET['error_message']; } looks like $order_id and $status are not passed back. what i actually need is to get the vars from the form passed back into php so i can put them into a database. any ideas? thanks A: To get these you generally need to this: $secret = 'YOUR_APP_SECRET'; $request = parse_signed_request($_REQUEST['signed_request'], $secret); $payload = $request['credits']; $order_id = $payload['order_id']; $func = $_REQUEST['method']; if ($func == 'payments_status_update') $status = $payload['status'];
{ "language": "en", "url": "https://stackoverflow.com/questions/7532929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NO CERTIFICATE problem for a specific user I have a problem I am trying to figure out but seem to have run into a brick wall. I have an APK that I mailed to a user to install. It is signed in release mode. I have installed the same apk on my phone (Motorola Atrix, OS version 2.3.4) successfully. The user has the same phone with the same OS version, but when he tries to install it, he gets "Application not installed" message. The error from adb shows this: INSTALL_PARSE_FAILED_NO_CERTIFICATES I searched around on the net, and there seems to be known issue in Android when the certificate is not generated successfully Issue 830:Some APKs get created with partial signatures. However, if it is unsigned, it should be unsigned for all devices, isn't it? It works fine for me & another user with the same phone. But doesn't work for this Specific user. I am scratching my head & cannot figure out the reason. Anyone run across this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7532932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Removing comma at the end of output java I'm trying code a basic application that will take the amount of numbers the user wants to input and then ask the user for the numbers, save the the numbers in a string array and then print them out in specific format. this is what I have so far the only problem is I need to remove the last comma at the end of the output, I'm sure I'm going about this wrong... any assistance is appreciated. import java.util.Scanner; public class info { public void blue(){ Scanner sc = new Scanner(System.in); Scanner dc = new Scanner(System.in); System.out.println("how many numbers do you have?"); int a = dc.nextInt(); System.out.println("enter your numbers"); String index[]=new String [a]; String i; for(int k = 0;k<index.length;k++){ i = sc.nextLine(); index[k]=i; } System.out.print("query ("); for(int l = 0;l<index.length;l++){ System.out.printf("'%s',",index[l]); } System.out.print(")"); } } A: for(int l = 0;l<index.length;l++){ if(l==index.length-1) System.out.printf("'%s'",index[l]); else System.out.printf("'%s',",index[l]); } A: Arrays.toString(array).replaceAll("[\\[\\]]", ""); A: This requires no if check for each element in your array: if(index.length > 0) { for(int l = 0;l<index.length-1;l++){ System.out.printf("'%s',",index[l]); } System.out.printf("'%s'",index[index.length-1]); } A: Much cleaner approach could be, String comma=""; for(int l = 0; l<index.length; l++) { System.out.printf("'%s''%s'", comma, index[l]); // Now define comma comma = ","; } A: You can use substring method of String to strip the comma in the end. It is also better to use StringBuilder.append when doing concatenation in a loop. A: This is displaying each string on its own line, with a comma at the end. If you want all of the words on one line, separated by commas, then replace for(int l = 0;l<index.length;l++){ System.out.printf("'%s',",index[l]); } with StringBuilder buf = new StringBuilder(); for(int l = 0;l<index.length;l++){ buf.append(index[l]); if (l != (index.length - 1)) { buf.append(","); } } System.out.println(buf.toString()); A: Been in the C# world for a while so the code may not be exact, but this should work StringBuilder sb = new StringBuilder(); for(int l = 0;l<index.length;l++){ sb.Append(index[l] + ";"); } sb.deleteCharAt(sb.Length - 1); System.out.print(sb.ToString()); This will save your code from having to write to the output over and over, so there is less overhead as well. A: } System.out.print("\b");//<--------- System.out.print(")"); Why not use a String buffer and output it in the end? A: import apache StringUtils, then do StringUtils.join( index, "," ); A: Much simpler is: String conj=""; for(int l = 0;l<index.length;l++){ System.out.print(conj); System.out.print(index[l]); conj=","; } You have to do this sort of thing so often, I routinely write a little "joiner" class: public class Joiner { private String curr; private String conj; private StringBuilder value; public Joiner(String prefix, String conj) { this.curr=prefix; this.conj=conj; value=new StringBuilder(); } public Joiner(String conj) { this("", conj); } public Joiner append(String s) { value.append(curr).append(s); curr=conj; return this; } public String toString() { return value.toString(); } } Then you can build a concatenated string with code like: Joiner commalist=new Joiner(","); for (String one : many) { commalist.append(one); } System.out.println(commalist.toString()); // or whatever you want to do with it Or like to build a WHERE clause: Joiner where=new Joiner(" where ", " and "); if (foo!=null) { where.append("foo="+foo); } if (bar!=null) { where.append("bar="+bar); } String sql="select whatever from wherever"+where;
{ "language": "en", "url": "https://stackoverflow.com/questions/7532935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to properly use RegisterNatives I'm trying to register a native function through jni, and to do that, I have to store a pointer to the function in a jninativemethod struct, which has a void* field for the function pointer. In setting that field, I get the error error: invalid conversion from void (*)(JNIEnv*, _jclass*, jlong, _jobject*)' to void* when compiling with GCC on unix. I've looked around, and it seems you aren't allowed to convert function pointers to void pointers, so is this interface just broken? Is there a 'right' way to do it? (other than using javah to generate headers and exporting the functions) A: It's true that casting a function pointer to a void* is frowned upon in C++, because the standard declares it to be undefined behaviour. However, in the case of something like RegisterNatives, there really is no alternative. Fortunately, the compilers you are likely to use with JNI are nice enough to make the cast behave as you would expect, despite the standard's protests. For what it's worth, the Visual C++ documentation for void explicitly mentions that “A void pointer can point to a function”, so you're in good shape on that point. Furthermore, the POSIX function dlsym also requires void-to-function casts to be legal, so it seems unlikely that GCC would trip you up here. You can also check the following two answers for more information about the legality and effectiveness of casting between void pointers and function pointers: * *reinterpret_cast to void* not working with function pointers *Casting a function pointer to another type
{ "language": "en", "url": "https://stackoverflow.com/questions/7532952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Inconsistent line endings warning when line endings are consistent I was opening an auto-generated file in Visual Studio to inspect it, and Visual Studio tells me the line-endings are inconsistent. I know about the difference between LF and CRLF, so I thought I would try making a small change to the generation code to use the proper newline depending on the platform. I tell Visual Studio not to change it, and I close the file. I open it with Python and take a look at each of the lines with this snippet of code. with open(filename, 'r') as f: # uses %r so it prints the non-formatted string (so I can see \r and \n) print '\n'.join(('%r' % x for x in f.xreadlines())) I take a look at the output, and every line (except for the last) ends with a '\r\n'. The last line has no newline, so it contains only the text. I also open the file with Emacs and it doesn't auto-detect to use DOS mode, and shows me the ^M character on every line. Why are the line endings of the file "inconsistent" when I can see that every line is using the same line ending? A: (answering my own question, but maybe it will help others in the future) The line endings weren't "inconsistent", but they also weren't valid. With a little look at hexdump, I found in the file the following at the point where a CRLF should be. 0d 0d 0a When the file was written out, it must have written the \r character twice or potentially, the literal \r\n was used and whatever wrote out the file change the \n character into a \r\n automatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Lib usb how to read character from port I want to write an application that reads data from the USB device and was looking for a library that can make the job easier. I found a library called lib-usb. Unfortunately, it has almost no documentation. Here is what I have tried: #include <stdio.h> #include <stdlib.h> #include <usb.h> int main(){ struct usb_device dev; struct usb_device *device; usb_dev_handle *handle; struct usb_bus bus; usb_init(); usb_find_busses(); int a=usb_find_devices(); bus=usb_get_buses(); handle=usb_open(device); return 0; } But I can't figure out how to select a port that I want to read from. I would like to save read data as a string. Any advice is appreciated. A: USB doesn't really transfer characters -- it transfers packets. Additionally, your code makes no sense at all; there is some pretty good documentation online at http://libusb.sourceforge.net/api-1.0/, which I recommend that you read.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Response.AppendHeader() is broken I'm using Response.AppendHeader("Refresh", "2; url=default.aspx") To send users back to the home page after they log in or log out and it works. But, on the contact us page it fails and this is what it says: The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. Requested URL: /default.aspx, 2; url=default.aspx The weird thing is this doesn't happen in debug, only on the live site. It looks like it's appending the header twice somehow... I don't know. Any ideas? A: If the Contact page is not in the same path as Default.aspx, the relative path will not work. You will need to give it the absolute path like "../Default.aspx" if its one level down. A: I found out what it was. In my aspx I had onclick="btnSubmit_Click" runat="server" You only need the runat="server" directive. The onclick directive was causing the event handler to fire twice. A: One line solution is to replace: Response.AppendHeader("Refresh", "2; url=default.aspx"); with: Response.Headers["Refresh"] = "2; url=default.aspx"; The cause of HTTP 404 errors is due to duplicate "Refresh" header in the HTTP Response-headers. It doesn't affect IE but it does Chrome. This is a tricky issue where you would understand this only when you see the HTTP Response-headers in browser's developer mode. In ASP.NET if you are using Server.Transfer then even though the transfer is complete the page name in the address bar is not changed. For e.g. if you are transferring from Default.aspx to Managers.aspx then the address bar still says Default.aspx. And when Response.AppendHeader is on both Default.aspx and Managers.aspx pages then on transfer the headers gets added twice to Default.aspx.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Encrypting passwords on POST Django aside from using SSL, is there any way to encrypt a password in the Django framework on the first POST to the server? For example, if I have a form that accepts a username and password, then send it to another view, aren't the passwords sent to the backend unencrypted? If so, is there a way to encrypt the passwords before transmitting to the backend? A: SSL is a de facto solution, but if for some reason you can't have it, then you'll find shelter in some javascript libraries that encrypt post data. And there are plenty of them if you search.. But I don't believe that any of them can achieve maximum security.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Finding a gem from the require line in code I currently have an installer that installs a set of ruby scripts (that is an optional install from the main program). I have written a script that after the install, it scans through all of the require statements inside the contained ruby files, and then pulls out all of the "required" files. For example, it will look for require 'curb' require 'rest-client' # require etc... that is in each file, and then include them in a list (removing duplicates) so I have an array that looks like: "curb", "rest-client", etc... For most gems its perfectly fine, as the names match, and I just do a gem install GEMNAME In the case that the names do not match however, I am trying to figure out a way to find out the gem name from the require line, by querying the gem server. For example: xml-simple has a require statement of xmlsimple, but the gem is xml-simple. After much searching, the only "solution" that I can find is to install every gem and check to see if the files are contained inside with the gem specification GEMNAME This is far from optimal, and actually a really bad idea, and I was wondering if there was a way to query rubygems to see what files are contained inside of a gem. A: Rubygems has an API with a search endpoint: /api/v1/search.(json|xml|yaml)?query=[YOUR QUERY] The search endpoint is listed at Gem Methods. I'm sure this search can be used to do what you want, perhaps by providing a partial name and using a regex to filter for the closes matches. Edit: It may also be work having a look at the Bundler gem itself, as they sometimes recommend gems when you make a typo if I remember correctly. Update: I would follow a workflow like this: Try to install gems just are they are required. If there is an error select a few segments of the gemname, say gem_name_str[0..5], gem_name_str[0..4] and gem_name_str[0..3]. Query the API with these strings. Remove duplicates Test the values returned with a dynamically generated regex. Something like: #given @param name = string from 'require' statement values_returned_from_api.each do |value| split_name = name.split(//) split_value = value.split(//) high_mark = 0 #this will find the index of the last character which is the same in both strings for (i in 0..split_name.length) do if split_name[i] == split_value[i] high_mark = i else break end end #this regex will tell you if the names differ by only one character #at the point where they stopped matching. In my experience, this has #been the only way gem names differ from their require statement. #such as 'active_record'/'activerecord', 'xml-simple'/'xmlsimple' etc... #get the shorter name of the two regex_str = split_name.length < split_value.length ? split_name : split_value #get the longer name of the two comparison_str = split_name.length < split_value.length ? value : name #build the regex regex_str.insert((high_mark + 1), '.') #insert a dot where the two strings differ regex = /#{regex_str.join('')}/ return name if comparison_str =~ regex end Note: this code is not tested. Its just to illustrate the point. It can also probably be optimized and condensed. I am assuming that the API returns partial matches. I haven't actually tried it out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to call a test case in Selenium rc with PHP? can you tell me how to run a test case in selenium RC with php? A: Taken from the official guide at http://www.phpunit.de/manual/3.7/en/selenium.html Create a class that extends from PHPUnit_Extensions_SeleniumTestCase which will contain the methods from PHPUnit_Framework_TestCase and the selenium specific methods: <?php require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; class WebTest extends PHPUnit_Extensions_SeleniumTestCase { protected function setUp() { $this->setBrowser('*firefox'); $this->setBrowserUrl('http://www.example.com/'); } public function testTitle() { $this->open('http://www.example.com/'); $this->assertTitle('Example WWW Page'); } } ?> Then browse in your console to where this file is saved and run: phpunit filename.php If you want to run an specific test you could use the --filter options as well. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hudson/Jenkins: Start task simultaneously on multiple slave machines If I have a task (a script) that needs to start on n number of machines at the same time (with some tolerance: ~10 minutes), how do I go about setting this up in Hudson or Jenkins? A: Are they all the same type of machine (OS?) You can use a multi-configuration style job. This will run the script on all the machines you specify under "slaves". If they are not all the same (for eg mix of Linux and Windows), you may need to come up with either a platform independent script - like ant, or install bash on Windows so you can use "Execute Shell"
{ "language": "en", "url": "https://stackoverflow.com/questions/7532982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to enable MS Access VBA debugging? This is really annoying. In MS Access VBA, there should be linebreak and debugging, however it always go through my code without hitting any of my breaks. Is there somewhere where I need to enable it first? I have the following option: Option Compare Database Option Explicit A: I did face this issues in MS Access 2010. All you need to do is uncheck "Use Access Special Keys" Option available under Access Main Menu .. do the following: Select File -> Options -> Select General Database Check or uncheck "Use Access Special Keys" Close and Open file and you are done. A: In VBE options, you need to make sure that the choices on the GENERAL tab are chosen correctly. I recommend these settings: * *BREAK IN CLASS MODULE (not BREAK ON ALL ERRORS, because the latter will not show you which line in a class module has caused the problem) *COMPILE ON DEMAND turned OFF. When you're coding, I recommend turning OFF AUTO SYNTAX CHECK on the EDITOR tab, because I can depend on the code turning red to tell me that it doesn't compile, without the interruption of a dialog popping up. A: I am sure you'd love this question. Check the answers. Mine is quite complete. erl and MZ-tools are the keys to "real" debugging in MS-Access A: You can also write Stop in your code to cause the debugger to break.
{ "language": "en", "url": "https://stackoverflow.com/questions/7532992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting Address Information from Google Places API I've been looking to use the Google Places API in one of my projects, but I had a question about it that I couldn't figure out. Should be very simple, but I can't quite wrap my brain around it. Here's my issue: I'm trying to implement an autocomplete field that uses Google Places to find a location, then I want to pass that information through the form and include a location name and address in the form parameters. I'm assuming I'm going to use Place Details to pass the information on, but how can I look that up given the information from the autocomplete field? Here's my workflow: User enters location in autocomplete -> Autocomplete passes address information through form -> User submits form -> Form processing page displays location name and address information. I'm using PHP for the form processing. Is there a way I can pass the information through JSON to the form processing page? Any example code would be helpful. Thanks! References I've looked up: http://code.google.com/apis/maps/documentation/places/ Getting full address from business name -- Google Maps API A: After doing further research, I was able to figure out how to do it. Using the autocomplete example: http://code.google.com/apis/maps/documentation/javascript/examples/places-autocomplete.html Then, just passing place.name place.formatted_address Through the form after the places API pulled it up, I was able to accomplish my goal. I passed the variables into hidden form fields for processing. For example: document.getElementById('place-name').value = place.name; document.getElementById('place-address').value = place.formatted_address; document.getElementById('place-phone').value = place.formatted_phone_number; document.getElementById('place-id').value = place.id; Hope this helps someone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are there any tools for analyzing my solution for good design practices? Are there any tools included with Visual Studio 2010 (Ultimate) that perform a review of a solution to determine if it follows, for example, SOLID principles? If not in VS, add-ins are okay. Free is best but will consider purchasing something. In a nutshell, I'm looking for a tool to analyze a solution, it's projects, and their relationships. A: FxCop and StyleCop. FxCop will analyze you projects only after they are compiled, so not a direct answer to your question. StyleCop will analyze your C# code files directly for good code and documentation style.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using jQuery UI and .Net Master pages I would like to try and use jQuery UI along side of master pages in ASP.Net 4.0; I like the widgets better than the .Net controls. But I have a question around the accordion control. Is it possible to put an accordion control in the master page and use it like a menu and still allow it to retain it's selected panel? In other words, each time a page is loaded, the ready() event triggers in the master page and resets the accordion. If I have panel 3 open, and select an item in the panel, I would like panel 3 to remain open when the new content is loaded. I was thinking I only want to to the jQuery ready function on the initial load of the master page but I can't seem to make that happen. I hope this makes sense. Thank you A: Apparently you are not alone having this issue and most people are doing it the way this post explains it. A: You could use an asp:Hidden field to hold the "currentOpenAccordionPanel". I'm sure there's a jQuery event you can hook to update that field whenever a different panel is opened. Then your page-init code can check that field and open that panel (or open a default panel if that field is empty or absent). Because its an asp:Hidden field, the value will remain stable through postback operations (it will live in the viewstate), which is what it sounds like you wanted. I like this approach a little better than a Session-based approach or cookie-based approach: if a user has multiple browsers/tabs open on your site, they will stomp each other's values if you store the value in a common location (like session or cookie). Viewstate-stored data will still behave fine if the user has multiple tabs open. A: I'm not sure if this is a great answer or not, but you can probably use session variables and logic in the view to only render the accordion script on the first load. Set a session var to something, and check for that value on subsequent loads. If it's set, don't render the javascript code (?) There might be a better way. A: * *Make a "Content area" iframe. When a link on the accordian is clicked, load a different page in the iframe. *or make a content area div, and on the accordian link click, make an ajax call to and load the new content there A: Do you have to do full page postbacks? If not then you could use ajax from the client to interact with the server and avoid having to keep the accordian's state. Using the UpdatePanel is 1 option for this. Also, you could add a hidden input field to the form and set its value prior to posting back. Then on the server you can use ClientScriptManager to emit the necessary jQuery call to set the accordian's state back to what it was before the postback.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SSRS 2008 R2 - Stop auto generation of report parameters When adding a new Dataset to a report based off a stored procedure that has parameters (say @MileageLow and @MileageHigh) sometimes those stored procedure parameters are propagated into the actual report parameters. Is there an option like "Auto Generate Report Parameters" that I can uncheck to prevent BIDS from performing this action? A: What I do when only having drop boxes is add a <Please Select> with value NULL to the drop down via UNION ALL (if based on query). I then set this to the default, and in the main report dataset add a big fat IF @MileageLow IS NULL RETURN A: The answer is to specify the report parameters during the creation of the DataSet itself. I was in the habit of just creating it and then going in after and setting the parameters. SSRS assigns parameters automatically on a best guess basis.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Button click and ListView click I have a ListView. on click of a list item I start a Activity. Now I have added a Button on that ListView and onclick of a button I want to start a another activity. After adding a Button, I can click on the button and start a Activity but now I can not click a list item. What happened to listview's item click ?? A: Read this excellent blog post: Focus problems with list rows and ImageButtons Essentially you should add the following to your root layout element in the row-item xml. android:descendantFocusability="blocksDescendants" A: that is the concept. If u want to implement both clicks then write button click normally and for list item click did not use the listitem click. Instead that you write onclick listener for converted view that you returned in getview() Then both clicks will work
{ "language": "en", "url": "https://stackoverflow.com/questions/7533027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I make an html5 animation when a button is clicked on a webpage? I have an idea for an interactive animation that I would like to create in html5. I want to have a soccer field with jerseys on it in a formation like 4-4-2 and have different options on the side to change the formation let's say to a 4-5-1 and then when this button is clicked that says 4-5-1 the jersey will rearrange on the field to that shape. Any ideas on how I could do this ?? Thanks in advance A: The simplest and most dependency-free way to do so would be to add a JavaScript function to the onClick attribute of your button or element, and then have JavaScript move the players around by editing their positions, attributes, and so forth. However, I would recommend using jQuery since it's generally easier. You would then bind an action to the button's id (id="..." attribute on your ). For example: $(document).ready(function() { $("mybuttonid").click(function(event){ ... }); }); A: http://jsfiddle.net/rlemon/3YRzS/ like mentioned, jquery and animate. A: Might be possible on certain browsers with the CSS3 Key Frames animations, as seen on the smashing magazine's website, for example - http://coding.smashingmagazine.com/2011/05/17/an-introduction-to-css3-keyframe-animations/
{ "language": "en", "url": "https://stackoverflow.com/questions/7533028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mvc 3 checkbox @value failing in partial view I have the following line of code in a partial view @Html.CheckBox("selectedUnit", new { @value = item.data.Id }) This partial view is a table that allows for selecting of table rows. In my postback i then get a list of my checkboxes in the form with either the Id or "false". My issue is in my original call to the partial view everything works as intended, but when i call it from the second page (conformation page with selectable rows for removing before saving) I get a server exception saying: String was not recognized as a valid Boolean. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.FormatException: String was not recognized as a valid Boolean. Source Error: Line 73: <tr> Line 74: <td class="checkboxColumn"> Line 75: @Html.CheckBox("selectedUnit", new { @value = item.data.Id }) Line 76: </td> Line 77: <td> I've got no idea why it works when called the first time, but not the second time. Its the exact same partial view with the exact same set of data. Any ideas? A: Make sure that item.data.id is returning Boolean value type. Try also following one : @Html.CheckBox("chxPoo", item.data.id)
{ "language": "en", "url": "https://stackoverflow.com/questions/7533029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS in Chrome displaying High? Hi I've just started writing a page and i've hit a snag I've never had before and I'm not sure what i've done. This fiddle http://jsfiddle.net/4Fbpu/ displays fine in FF, Opera and IE 9 (surprisingly). But in Chrome the content starts midway between the header and wrapper. Does anybody know what's causing this and how to fix it please? A: First of all, try reducing the complexity in your test cases. I made a simpler test here: http://jsfiddle.net/guitarzan/PqvKR/4/ I think this is a rendering bug in Chrome. It is treating the floated ul as position:absolute, but only when its height is less than or equal to the negative (top) margin on its containing parent. Increase its height greater than 50px and it pops back into place. See here: http://jsfiddle.net/guitarzan/PqvKR/6/ So I found two solutions: * *Add a height to the ul of 51px or greater. This is probably too tall for your design, so you'd have to adjust other things, or... *Add another element around the ul and give it a height greater than 0px. Test solution here: http://jsfiddle.net/guitarzan/4Fbpu/13/
{ "language": "en", "url": "https://stackoverflow.com/questions/7533031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Memory leaks on DLL unload A C++ console application loads a DLL at run time using LoadLibrary() function and then calls some of the functions exported by the DLL. Once the application is done with the DLL, it calls FreeLibrary() function to unload the DLL. Will the memory leaks caused by the DLL function calls also get removed when the DLL is unloaded or they will remain there untill the application terminates? A: The memory leaks will remain. The OS doesn't care which DLL allocated the memory, it only cares about which process allocated the memory. A: Alright! so here is how you could solve this problem. since its a console application I assume you are creating the application in that case the OS allocates stack/virtualmem and the heap for you where you would create the objects on heap. generally those details are abstracted from us as we simply use operator "new"! here is what might work - get a handle to the deafault heap provided by your OS - GetProcessesHeap(); and free the heap after freelibrary using HeapFree()! this would clear the entire heap allocated to you but this might clear other dynamically allocated stuff as well. this is how you can make it work- before loading the DLL create a private heap required for dynamic allocation of stuff from your DLL using - HeapCreate(). use HeapAlloc and HeapDealloc instead of new/delete to create objects from your dll with your private heap handle. free the heap using heapdestroy() once you are done with using the library!
{ "language": "en", "url": "https://stackoverflow.com/questions/7533033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: converting my WGS 84 co-ordinates into screen x and y I am stuck on a little problem of creating a simple map app. what i am trying to learn is the mathematics behind the conversion of my WGS 84 GPS co-ordinates. this is the problem: I have two WGS 84 co-ordinates; lat:53.7506 Long:-2.3931 + lat:53.7638 Long:-2.4212 I want to convert these values onto points on my screen x = 'a' value between 0 and 200 and y = 'a' value between 0 and 200 i have said a value as this value will be derived from the lat and long figures as mentioned above. can anyone help please? i have tried normalising the figures using the formula N = V/D (N being the normailsed value with V being the co-ordinate value and D being the max value of the screen area which in my case is 200. this didnt work as all the figures generated was all in the 199 - 200 range but I have gotten lost with the thought process on this now so I need some help. I am sure there is a formula for calculating the right but i cannot seem to find it please help as I need to sleep well tonight :) thanks A: It is a simple linear mapping for x, and one for y with a twist: x) as the lower limit is the left hand side, you can simply use x = (long + 180)/360 * x_max y) as long 0 is in the middle, you'll need to substract/add accordingly: y = (y_max/2) - (lat/90) * (y_max/2)
{ "language": "en", "url": "https://stackoverflow.com/questions/7533037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replicate Django Admin's "add" button Let's say I have the following two models, each with their own form to create model records. For example: Business_Client Model: busName field - CharField mainContact field - ForeignKey(Contacts) Contacts Model: firstName field - CharField lastName field - CharField When the user wants to create a new business, they will have to select a "Main Contact" from a drop down menu. However, if the contact is not in the list, they have to create that record first, then come back, and re-start creating the business record again. The admin interface makes this easy by having the little + button beside the drop down menu which takes you to the Contact form, you fill it out, hit Save which then brings you back to the Business form, with the mainContact field already selected to your newly created Contact record. How do I do this!?! I have been searching around Google and am coming up short. Anyone have some good links/tutorials that would get me going? Thanks! A: I've never done it, but thinking about it: You have a view /add/business/ with a field for name, and a field for contact (with a little plus beside it). The plus is simply a link that creates new popup window via javascript that points to /add/contact/ and has a javascript callback. When the form is submitted, validated and put into the DB, the window closes and the id/name is passed back to the original form and auto entered in the field. This seems to be how the django admin does it. You can look at the widget that the django admin uses yourself: https://code.djangoproject.com/browser/django/trunk/django/contrib/admin/widgets.py#L218 The render function that has the html: https://code.djangoproject.com/browser/django/trunk/django/contrib/admin/widgets.py#L249 which shows that it's simply an anchor link with an onlick javascript popup pointing to the relvant add view. Once the form is submitted the values are passed back. https://code.djangoproject.com/browser/django/trunk/django/contrib/admin/static/admin/js/admin/RelatedObjectLookups.js#L55
{ "language": "en", "url": "https://stackoverflow.com/questions/7533041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to obtain if user likes page or not with API 3.0? All what I found is related to old API not 3.0 :\ I need to determine that before an application will display proper message. A: Your app will need to request the user_likes permission in order to do this. Then, you can do the following using the JavaScript SDK: <script type="text/javascript"> FB.getLoginStatus(function(response) { if(response.authResponse) { token = response.authResponse.accessToken; FB.api('/me/likes', function(response) { likes = response.data; for(x in likes) { page_id = likes[x].id; page_name = likes[x].name; // check if user is a fan of Coca-Cola if(page_id == '40796308305') { alert('You like the page:\n ' + page_name); } } }, {access_token: token}); } }); </script> Or the following, using the PHP SDK: <?php $likes = $facebook->api('/me/likes'); foreach($likes[data] as $like) { if(array_key_exists('id', $like)) { $page_id = $like['id']; $page_name = $like['name']; // check if user is a fan of Coca-Cola if($page_id == '40796308305') { print 'You like the page: ' . $page_name; } } } ?> A: If this is for a Facebook fan page, Facebook has a post on how to do this with your iframe page. You need to decode the signed_request http post parameter that gets sent to your site. This page shows you how to decode it in PHP. A: Check this. http://fatalweb.com/articles/how+to+check+if+user+has+liked+facebook+fanpage-24.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7533044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: object synchronization When a synchronized block is used for synchronization on an object instance, then threads compete to get into object's implicit monitor. And once, any particular thread enters into the monitor, any other thread has to wait for entering into it. Then synchronized(object){ // some code here // no function call } must not enforce taking any particular type of object. Thus any object type can be used here because every object has its implicit monitor. Kindly reply me is it true? A: Just keep in mind that if you have a variable that is null, you cannot lock it. Also, while things like Integer are objects, an int or float is not. You can lock an Integer or int[], but not an int. A: Yes, every Java Object can act as a monitor. And since this is such a short answer, for bonus, this is an interesting read: Does the JVM create a mutex for every object in order to implement the 'synchronized' keyword? If not, how? Also note that C# does something similar with their objects, but also have value types (which are not Monitors)
{ "language": "en", "url": "https://stackoverflow.com/questions/7533048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Python style: should I avoid commenting my import statements? I'll try to make this as closed-ended of a question as possible: I often find that I have a group of imports that go together, like a bunch of mathy imports; but later on I might delete or move the section of code which uses those imported items to another file. The problem is that I often forget why I was using a particular import (for example, I use the Counter class very often, or random stuff from itertools.) For this reason I might like to have comments that specify what my imports are for; that way if I no longer need them, I can just delete the whole chunk. Is it considered bad style to have comments in with my import statements? A: Comments are there to help explain/remind. If they are useful to you, use them. Also, tools such as pylint can help spot unneeded imports, as well as many other things. A: It's not bad practice at all. It's better to have more comments than less comments. By documenting the reasons you are using certain imports, it will explain to to the reader of your code the reason you have them, and maybe the reader might see why you did something and be able to come up with a better way to do it. You shouldn't really ever shy away from properly commenting your code. A: Well, the beautiful thing about python is that it is (or should be) explicit. In this case, so long as you're not doing * imports, (which is considered bad practice), you'll KNOW whether an import is referenced simply by doing a grep for the namespace. And then you'll know whether you can delete it. Allow me to also add a counterpoint to the other answers. 'Too much' commenting can indeed be bad practice. You shouldn't be adding redundant comments to code which is patently obvious as to its function. Additionally, comments, just like code, must be maintained. If you're creating excessive comments, you're creating a ton more work for yourself. A: I'm pretty sure if you're adding meaningful comments anywhere in the code, it can only be a plus. I will sometimes add comments to strange/confusing imports, so I'd say go for it. A: I wouldn't call it a bad practice. Comments are to provide clarity, and that is what you're trying to do. However, if you're getting confused on what imports are being used for, I would recommend determining if perhaps your modules are getting too big anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: service/products for audio and video embedding What is the easiest solution that will allow me to embed audio and video on a webpage so that it will be supported by all recent browser versions (Firefox, Safari, IE) and devices (iOS, Android)? I've read a few things on stackoverflow and at other sources. Holy crap what a pain in the ass. Is there a service that will handle all the issues? I would just like to post the media files on my site or elsewhere then paste some code into a webpage. I'm willing to pay for a service ( Ideally I would like to post one file and have the service/product do whatever encoding is necessary to support compatibility. Perhaps I am living in a fantasy world that is 5+ years in the future. A: For video, your best bet is YouTube. Here is a video about how to embed with it http://www.youtube.com/watch?v=ZnehCBoYLbc For audio, try SoundCloud (soundcloud.com). Here is how to post player links with it: http://en.support.wordpress.com/audio/soundcloud-audio-player/ Both use Flash, have specialized clients for devices, and are either currently or in the near future going to support HTML5. A: The solution we settled on is using http://vimeo.com for video which has a cheap yearly plan that allows for private videos and has a richly customizable player that we embed. For audio we just use html5 and allow the user to download the mp3 file if they don't have html 5
{ "language": "en", "url": "https://stackoverflow.com/questions/7533052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Maps - avoid overlapping pushpins without clustering - programming strategies? Some of our maps have 10 - 14 pushpins rendered as icon overlays on our maps using stock Google Maps icons. Each icon overlay has a number rendered inside of it. So the numbering typically goes from 1 - 14. In many cases at needed zoom levels, the icon overlays overlap one another, thereby hiding the numbers in the pushpins. The pushpins are created with the mapiconmaker API. The maps are Google Maps 2.0 API. The physical pixel width/height of the map container can't be changed, nor can overlapping be done. Smaller alternative image icons are not the solution either since they would still overlap one another in many scenarios. Are there any programming techniques or third party utilities out there that can render pushpins in a way that prevents them from overlapping? I.e. perhaps drawing a long line to the lat/long, with the pushpin at the other end, or some other annotative fashion, all the while keeping unique numbering assigned within the maps to each pushpin? Edit Google Maps API 2 or 3 solutions most welcome! Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7533054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Jquery - Be able to select items in drop down by group? I have a drop down that has the group label: <optgroup label="Numbers"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </optgroup> <optgroup label="Letters" disabled="true"> <option value="4">A</option> <option value="5">B</option> <option value="6">C</option> </optgroup> Is there a jquery plugin that exist that will allow me to click the group label and that will auto select all the options in that group? Or if not does anyone know how this can be done in jquery, if it can be done at all? Basically I want to click the optgroup label as an option, when I do that all options assigned to that group will be selected/checked. A: Using a combination of css classes and the jquery children() method should do the trick. This answer gives a good example: Easy way to quick select a whole optgroup in select box
{ "language": "en", "url": "https://stackoverflow.com/questions/7533058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running multiple PHPUnit tests within a single file with Zend? I'm trying to setup unit testing for a controller class in the Zend Framework. I'd like to write multiple tests for the same controller, and keep them all in the same test class. But when I follow the directions on the home page, I get the following exception when the second test function runs: Zend_Controller_Exception: No default module defined for this application When I comment out the first test function, so only one test functions runs, the error goes away. I've used PHPUnit with other frameworks and not had this problem. Does anyone know why this is happening only when I try running multiple test methods within the same class? UPDATE: Managed to fix the exception by following the bootstrapping method outlined here: http://kelmadics.blogspot.com/2011/07/setting-up-phpunit-in-zend-framework.html A: It sounds like to me that you have modules enabled but don't have a /application/modules/default/ module. So you either need to create a module called default, or in your bootstrap somewhere add: $front->setControllerDirectory(array( 'default' => '/path/to/application/controllers', )); For more clarity, post some of your application.ini, especially if there's anything about modules in there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VB.NET Public Property on a single line Is there any way I can put Public Properties on a single line in VB.NET like I can in C#? I get a bunch of errors every time I try to move everything to one line. C#: public void Stub{ get { return _stub;} set { _stub = value; } } VB.NET Public Property Stub() As String Get Return _stub End Get Set(ByVal value As String) _stub = value End Set End Property Thanks EDIT: I should have clarified, I'm using VB 9.0. A: Yes you can Public Property Stub() As String : Get : Return _stub : End Get : Set(ByVal value As String) :_stub = value : End Set : End Property and you can even make it shorter and not at all readable ;-) Public Property Stub() As String:Get:Return _stub:End Get:Set(ByVal value As String):_stub = value:End Set:End Property A: You can use automatically implemented properties in both VB 10 and C#, both of which will be shorter than the C# you've shown: public string Stub { get; set; } Public Property Stub As String For non-trivial properties it sounds like you could get away with putting everything on one line in VB - but because it's that bit more verbose, I suspect you'd end up with a really long line, harming readability... A: It is possible to define a variable on one line, that behaves like a property, if one is willing to use a slightly different syntax, and link to a C# assembly (or play around with IL). Tested with VS2017 and .Net 4.7.2. The C# code (currently not available in VB.Net): public class Propertor<T> { public T payload; private Func<Propertor<T>, T> getter; private Action<Propertor<T>, T> setter; public T this[int n = 0] { get { return getter(this); } set { setter(this, value); } } public Propertor(Func<T> ctor = null, Func<Propertor<T>, T> getter = null, Action<Propertor<T>, T> setter = null) { if (ctor != null) payload = ctor(); this.getter = getter; this.setter = setter; } private Propertor(T el, Func<Propertor<T>, T> getter = null) { this.getter = getter; } public static implicit operator T(Propertor<T> el) { return el.getter != null ? el.getter(el) : el.payload; } public override string ToString() { return payload.ToString(); } } Then in your VB program, for example: Private prop1 As New Propertor(Of String)(ctor:=Function() "prop1", getter:=Function(self) self.payload.ToUpper, setter:=Sub(self, el) self.payload = el + "a") Private prop2 As New Propertor(Of String)(ctor:=Function() "prop2", getter:=Function(self) self.payload.ToUpper, setter:=Sub(self, el) self.payload = el + "a") public Sub Main() Console.WriteLine("prop1 at start : " & prop1.ToString) Dim s1 As String = prop1 Console.WriteLine("s1 : " & s1) Dim s2 As String = prop1() Console.WriteLine("s2 : " & s2) prop1() = prop1() Console.WriteLine("prop1 reassigned : " & prop1.ToString) prop1() = prop2() Console.WriteLine("prop1 reassigned again : " & prop1.ToString) prop1() = "final test" Console.WriteLine("prop1 reassigned at end : " & prop1.ToString) end sub This results in: prop1 at start : prop1 s1 : PROP1 s2 : PROP1 prop1 reassigned : PROP1a prop1 reassigned again : PROP2a prop1 reassigned at end : final testa
{ "language": "en", "url": "https://stackoverflow.com/questions/7533060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Rails render route path Im still new to Rails and have a hard time understanding how the path system works in Rails. In my routes.rb i create an alias for signup: match 'signup' => 'user#new' resource :user, :controller => 'user' The action is there and going to /signup shows the correct action. So far so good. Now, when i submit my signup form it runs the create action with POST as usual. And here is where im stuck. If the signup fails, i would like to present the user with the signup form again. One option would be to do a render "new", but that takes the user to /user instead of /signup. UserController class UserController < ApplicationController def new @user = User.new end def create @user = User.new(params[:user]) if @user.save redirect_to root_url else render "new" end end end Any help appreciated! UPDATE - SOLUTION FOUND Added 2 match routings for /signup, using the :via option match 'signup' => 'user#new', :as => :signup, :via => 'get' match 'signup' => 'user#create', :as => :signup, :via => 'post' This way the application knows that when posting to /signup it should run the create action, and when http method is get, it uses the new action. Controller markup is the same as posted above. A: Try adding the ":as" to you route like this: match 'signup' => 'user#new', :as => :signup and then do redirect_to signup_url in your controller. That worked for me. I still don't know why. Maybe someone else has an explanation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery - pulling part of a url through regex I am trying to set a variable. The variable should be parts of a Search query in the URL. I'm assuming to use REGEX to achieve this. IE URL: http://tsqja.deznp.servertrust.com/SearchResults.asp?Search=true+ glass&x=0&y=0 I want to pull the words 'true' and 'glass' in the example above and throw them in a jQuery variable. ie. var newKeys = $(search keys = some code); I am no good at using REGEX but would this just be my variable? /^http:\/\/(tsqja\.)?deznp\.servertrust\./i,/Search=([^&]+)/i A: is this for a url alone or for the current url of the page the javascript is on? if the latter, it's as simple as location.search.split("&")[0].split("=")[1] otherwise you could do var url = "http://tsqja.deznp.servertrust.com/SearchResults.asp?Search=true+glass&x=0&y=0"; url.match(/[?]Search=([^&]*)/)[1]; EDIT So something like this might work (per your comments) var url = "http://tsqja.deznp.servertrust.com/SearchResults.asp?Search=true+glass&x=0&y=0"; var theKeys = url.split("Search=")[1].split("&")[0].replace("+"," ");
{ "language": "en", "url": "https://stackoverflow.com/questions/7533062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Making PLINQ and BlockingCollection work together I have put together a simple application that monitors file creation events, creates some objects from the files content, and does some processing. Here is the sample code: class Program { private const string Folder = "C:\\Temp\\InputData"; static void Main(string[] args) { var cts = new CancellationTokenSource(); foreach (var obj in Input(cts.Token)) Console.WriteLine(obj); } public static IEnumerable<object> Input(CancellationToken cancellationToken) { var fileList = new BlockingCollection<string>(); var watcher = new FileSystemWatcher(Folder); watcher.Created += (source, e) => { if (cancellationToken.IsCancellationRequested) watcher.EnableRaisingEvents = false; else if (Path.GetFileName(e.FullPath) == "STOP") { watcher.EnableRaisingEvents = false; fileList.CompleteAdding(); File.Delete(e.FullPath); } else fileList.Add(e.FullPath); }; watcher.EnableRaisingEvents = true; return from file in fileList.GetConsumingEnumerable(cancellationToken) //.AsParallel() //.WithCancellation(cancellationToken) //.WithDegreeOfParallelism(5) let obj = CreateMyObject(file) select obj; } private static object CreateMyObject(string file) { return file; } } It all works fine, but when I uncomment AsParallel (and the next two lines) it doesn't yield results right away. This delay is probably caused by PLINQ partitioning? However, I expect this query to yield items as soon as they are added to the BlockingCollection. Is this possible to achieve using PLINQ? A: That is what .WithMergeOptions(ParallelMergeOptions.NotBuffered) should be designed for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: "Pre load" of Wordpress site very slow I have a Wordpress site where when you type the domain and hit enter, it takes 1.5 - 4 seconds before the first piece of content even loads: http://undergroundhealthreporter.com/ First, I have almost a dozen Wordpress sites on this host, and don't have that issue with any of them, so I don't believe it's a hosting issue. Second, I know the site itself is content and script heavy, but the actual loading time of the site once the first piece of content appears isn't bad. Third, I've experimented with various Wordpress caching plugins and while they help, nothing seems to eliminate that early loading issue. I thought maybe it was slow DNS, but I also have sites with DNS hosted at GoDaddy that aren't this slow. Any ideas of how to debug this issue? Thanks. A: You can look into tools like YSlow, which is a Firebug extension designed to help with that very question: http://developer.yahoo.com/yslow/ I would throw a custom page inside your theme dir, with NO code in it, and see how long it takes your server to request the file outside the context of WP. By this I mean pointing your browser at something like http://undergroundhealthreporter.com/wp-content/themes/your_theme_dir/testpage.php. If this runs quickly you know the issue isn't with apache or with mysql or anything like that. If it runs quickly, I'd then continue by adding in js and wp functions (maybe by making a custom page template), and watching for the point at which things slow down. If it does not run quickly, unfortunately you need to dig deeper into the world of Apache logs and MySQL optimizations... but hopefully this is a good start.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: deploy .net 4.0 wpf application problem I been working on a application that I am planing on distributing. For some reason I am not able to install it on other computers. first let me show you my deployment settings maybe I am doing something wrong in there (I left all the defaults). Deployment settings: after doing that I get the following files: So far everything looks great! Let me show you what happens when I try installing this app on several computers: . Computer 1: (Running windows 7 with Service Pack 1) application installs in a matter of seconds and it works fine. I am able to uninstall it as: THE APPLICATION WORKS GREAT! . Computer 2: (Running windows vista with service pack) IT DOES NOT INSTALL: when I click on install I get the following error: so as you can see I was not able to install it on that machine. I tried uninstalling it then installing it again and I get the same problem. . . computer 3: (running windows xp with service pack 2) when I ran the setup.exe file it took a while to download and install whatever requirements it needed. It took 1 hour to install what I believe was the: and when that part finished at the end I got an error saying: "you do not have enough disk space" and I have 50GB of free disk space on my c drive. SO IT DID NOT WORK WITH THIS COMPUTER EATHER. . . Computer 4: (windows xp with service pack 2) I get the following error: . . . . . . why is it so difficult to deploy an application. this application works great in all the computers that have visual studio installed. Should I try to downgrade to .Net 3.0 or maybe .Net 2.0? Edit Could this be because I might not be able to publish applications? I got visual studio for free because my university gave it to me. I know there are student versions where you can try and also that they expire every six months. I been using visual studio ultimate edition for about 1 year know and every time I launch visual studio it does NOT say for evaluation purposes only like on my laptop. My splash screen actually comes out as: A: You selected in your prerequisites the "Microsoft .NET Framework 4 Client Profile", but is that what your application is targeting? Check your application properties -> Application tab. Usually a WPF application will target the full .Net framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't parse (then loop) a variable that has multiple values separated by commas I have database of companies and each can ship to only a certain number of states. I manage them with a form that sends to a MySQL field for all the states (seperating each state with a comma). I'm having trouble parsing the string so that it will check the boxes attributed with the states when the page loads $check ="NY,CA,FL"; function state_list($check) { $arr = array('AL'=>"Alabama",'AK'=>"Alaska",'AZ'=>"Arizona",'AR'=>"Arkansas",'CA'=>"California",'CO'=>"Colorado",'CT'=>"Connecticut",'DE'=>"Delaware",'DC'=>"DC",'FL'=>"Florida",'GA'=>"Georgia",'HI'=>"Hawaii",'ID'=>"Idaho",'IL'=>"Illinois", 'IN'=>"Indiana", 'IA'=>"Iowa", 'KS'=>"Kansas",'KY'=>"Kentucky",'LA'=>"Louisiana",'ME'=>"Maine",'MD'=>"Maryland", 'MA'=>"Massachusetts",'MI'=>"Michigan",'MN'=>"Minnesota",'MS'=>"Mississippi",'MO'=>"Missouri",'MT'=>"Montana",'NE'=>"Nebraska",'NV'=>"Nevada",'NH'=>"New Hampshire",'NJ'=>"New Jersey",'NM'=>"New Mexico",'NY'=>"New York",'NC'=>"North Carolina",'ND'=>"North Dakota",'OH'=>"Ohio",'OK'=>"Oklahoma", 'OR'=>"Oregon",'PA'=>"Pennsylvania",'PR'=>"Puerto Rico ",'RI'=>"Rhode Island",'SC'=>"South Carolina",'SD'=>"South Dakota",'TN'=>"Tennessee",'TX'=>"Texas",'UT'=>"Utah",'VT'=>"Vermont",'VA'=>"Virginia",'WA'=>"Washington",'WV'=>"West Virginia",'WI'=>"Wisconsin",'WY'=>"Wyoming"); foreach($arr as $k => $v){ $checked = ($check == $k) ? ' checked="yes"' : ''; echo '<li><input class="checkStates" name="states" type="checkbox" value="'.$k.'"'.$checked.'>'.$v.'</li>'; } } A: I'm thinking it has something to do with your comparison. Be sure that $check is uppercase. And if that passes then it must be something do with the value of $check being passed in. EDIT: What you will need to do is this... $ary = explode(",", $check); foreach($arr as $k => $v) { $checked = (in_array($k, $ary)) ? ' checked="yes"' : ''; echo '<li><input class="checkStates" name="states" type="checkbox" value="'.$k.'"'.$checked.'>'.$v.'</li>'; } A: If $check is comma delimited you can explode the string and convert it into an array, then in the for loop, simply check if the state is in the array. $check ="NY,CA,FL"; $arr = array('AL'=>"Alabama",'AK'=>"Alaska",'AZ'=>"Arizona",'AR'=>"Arkansas",'CA'=>"California",'CO'=>"Colorado",'CT'=>"Connecticut",'DE'=>"Delaware",'DC'=>"DC",'FL'=>"Florida",'GA'=>"Georgia",'HI'=>"Hawaii",'ID'=>"Idaho",'IL'=>"Illinois", 'IN'=>"Indiana", 'IA'=>"Iowa", 'KS'=>"Kansas",'KY'=>"Kentucky",'LA'=>"Louisiana",'ME'=>"Maine",'MD'=>"Maryland", 'MA'=>"Massachusetts",'MI'=>"Michigan",'MN'=>"Minnesota",'MS'=>"Mississippi",'MO'=>"Missouri",'MT'=>"Montana",'NE'=>"Nebraska",'NV'=>"Nevada",'NH'=>"New Hampshire",'NJ'=>"New Jersey",'NM'=>"New Mexico",'NY'=>"New York",'NC'=>"North Carolina",'ND'=>"North Dakota",'OH'=>"Ohio",'OK'=>"Oklahoma", 'OR'=>"Oregon",'PA'=>"Pennsylvania",'PR'=>"Puerto Rico ",'RI'=>"Rhode Island",'SC'=>"South Carolina",'SD'=>"South Dakota",'TN'=>"Tennessee",'TX'=>"Texas",'UT'=>"Utah",'VT'=>"Vermont",'VA'=>"Virginia",'WA'=>"Washington",'WV'=>"West Virginia",'WI'=>"Wisconsin",'WY'=>"Wyoming"); $states = explode(',', $check); foreach($arr as $k => $v){ $checked = in_array($k, $states) ? ' checked="yes"' : ''; echo '<li><input class="checkStates" name="states" type="checkbox" value="'.$k.'"'.$checked.'>'.$v.'</li>'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7533072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: error collection in asp.net webforms I am trying to change the css of a textbox based on an error on the page. Say to turn the background of the textbox red. I want to do this through the base page so that each codebehind that inherits this base page will perform this function. I am trying to do this in the OnLoad event protected override void OnLoad(EventArgs e) { //code here base.OnLoad(e); } How do I access the error collection in the base page something like this... for each(var error in Page.Errors) { TextBox textBox = error.textboxInError; textBox.Background - Color = "Red"; } To be more specific I want to trigger on page validation errors. A: If you're using web forms validators, you could do something like this: // Get a collection of all validators to check, sort of like this var allValidators = new[] { validator1, validator2, validator3 }; foreach (var validator in allValidators) { validator.Validate(); var ctrl = (WebControl)Page.FindControl(validator.ControlToValidate); ctrl.BackColor = validator.IsValid ? Colors.Red : Colors.White; } Update Apparently, the Page object has a collection of validators. See Page.Validators. Here's some revised code using that: foreach (var validator in Page.Validators) { validator.Validate(); var ctrl = (WebControl)Page.FindControl(validator.ControlToValidate); ctrl.BackColor = validator.IsValid ? Colors.Red : Colors.White; } A: Check This tutorial Out. It will help you create a Custom Error Page, and trap the error at either Application, Page or Web.Config level.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: where do i put my method for adding users to groups? the model? the mapper? My question is mostly about OOP and ORM design. I'm creating models in Zend for Users and Groups, and using mappers for the db (and also using dependency injection). I have a relational table, user_groups, for linking. I'm trying to figure out the best way to go about getting and setting a user's groups, or a group's users. I am currently looking at 3 options, let me know if I'm forgetting something: * *Take care of joining db tables in mapper so user's groups look like part of the User model *Add a UserGroupsMapper: create functions like user->addToGroup($group) *Add a UserGroupsMapper and UserGroup model: create functions like userGroup->add($user, $group) Thoughts about option 1: Is there supposed to be a one-to-one relationship between models and db tables, or can one model represent multiple tables? If so, when would it not be ok? Another example: If I have a color table and a color_type table (with things like "warm" or "cool" as rows), does Color contain the colorType as an attribute/instance variable? Or does it reference ColorType as an object by means of color_type_id, or does it have an actual ColorType object as an ivar? Thoughts about option 2: For a function like user->addToGroup($group), would it call the UserMapper method, which then calls the method in the UserGroupsMapper, or would it call the method in the UserGroupsMapper directly? From my understanding, the mapper is supposed to abstract the model from the data, but what does that mean as far as relationships between models? Are the models supposed to know how they are linked, or just the mappers? Thoughts about option 3: Adding a UserGroup model creates the possibility of accessing that model in a controller. Should the Group controller know the model relationships, like userGroup objects, or should it only be able to do things like tell a group to add a user? I hope the question is clear enough. I know it is pretty involved, but I haven't been able to find a good answer yet. A: Usually your models are just simple objects that represent data in a table and allow you to get and set values. The mapper is where you would have all of your database access and logic. Typically they are one to one relationships with your data, but they don't have to be. As long as you know how to manage what objects where. You would pass the model to the mapper function and it would get its information from there. So I would put your addUserToGroup in one of the mappers, not in the model itself. Generally your model should only have getters and setters, and maybe a helper function or two for manipulating data in the model. If you have a query that needs to join data from multiple tables and may comprise one or more models, or part of one model and part of another, you can just return an array rather than a model object, but this would still be done in the mapper. I have instances of both of these cases in some of my applications. Also, I extend my models from a base class that gives me an easy way to take an array of data and set the properties of the model from the array. Also they contain a toArray method so I can easily turn a model into an array if need be. A: (Quick answer) I might do something like the following: $oMyGroup->addUser( $oMyUser ); You're adding the user to the group, regardless of what strategy you would use for persisting/materializing the objects (datamapper, activerecord, etc) in some type of data "storage": database, serialized objects in a text file, in-memory storage, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Twitter API statuses_count include retweets or not? In twitter API "users/show", there is a statuses_count, does it include retweet, or not? One issue about twitter API is that they don't have an exact definition for each of the items in the returned result. You can only guess the meaning by the name. A: It includes retweets. Manual testing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: MVC and ADFS Development Not Impossible Easily? Using VS2010 and MVC3 and the latest Razor engine bits. I have a request to integrate ADFS to allow the app to support single-sign-on for an existing Windows domain. This does not look like a trivial operation, and it also appears that I would have to develop on Windows 2008 and not Windows 7 in order to develop/test ADFS. Looking at urls like ADFS v2.0 Error : MSIS7042: The same client browser session has made '6' requests in the last '1' seconds and http://blogs.msdn.com/b/eugeniop/archive/2010/04/03/wif-and-mvc-how-it-works.aspx are making me think this is going to be a lot of work. Any comments on how to make MVC3 and AFDS work quickly and well? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mongoid: find through Array of ids I've fetched a number of ids through MapReduce. I've sorted those ids by some criteria and now I need to get those objects in this particular order: MyModel.find(ids) Right? But it returns objects not in the order ids are stored. Looks like this is just the same as MyModel.where(:_id.in => ids) which won't return fetched objects in just the same order as stored ids. Now I can do this ids.map{|id| MyModel.find(id)} which will do the job but it will knock the database many many times. A: Was working on a similar problem and found a bit more concise solution: objs = MyModel.find(ids).sort_by{|m| ids.index(m.id) } basically just using the sort block to snag the index of the the element. A: You can do the ordering by hand after you have all your objects. Something like this: ordering = { } ids.each_with_index { |id, i| ordering[id] = i } objs = MyModel.find(ids).sort_by { |o| ordering[o.id] }
{ "language": "en", "url": "https://stackoverflow.com/questions/7533104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Creating a next feature without adding fields to a table? I have a polling web application, which has a bunch of polls. There are two tables, one with poll question's and answers, and one with people's votes on those polls. For each user I want to provide next functionality, so that when they press a next button it will take them to a new poll that they have not answered. I don't want to add anymore fields to the table, and I am not sure how to "save" the poll id's for a specific user which have not been answered. This has definitely been done many times before, What are solutions/design patterns you have used? A: Get a random poll user hasn't answered yet: SELECT p.poll_id FROM polls p WHERE p.poll_id NOT IN (SELECT r.poll_id FROM poll_to_user r WHERE r.user_id = [current_user_id]) ORDER BY RAND() LIMIT 1; A: You will just have to query for a poll id that you have no vote on from this user. SELECT p.id FROM polls p WHERE p.id NOT IN (SELECT v.poll_id FROM votes v WHERE v.user_id = $this_user_id) ORDER BY p.date_added LIMIT 1; or ORDER BY RAND() LIMIT 1 if you prefer to get one at random. If your table structure for votes does not store poll ID and user ID then there must be some other way to uniquely identify poll and user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: URLLoader how to get the URL that was loaded? Using the URLLoader is there anyway to get the filename of the file that has been loaded? public function loadCSS():void { var urlLoader:URLLoader = new URLLoader(); urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete); urlLoader.load(new URLRequest("cssFile1")); urlLoader.load(new URLRequest("cssFile2")); urlLoader.load(new URLRequest("cssFile3")); } private function urlLoader_complete(evt:Event):void { // *****How can I get the file name here? var css:String = URLLoader(evt.currentTarget).data; // Do lots of stuff } A: First of all, since the load method is asynchronous, those three calls in your code are going to override each other in succession. The only call that will lead to the COMPLETE event being dispatched would be the final one. If you want to load the files asynchronously, you need to create an instance of URLLoader for each one. Second, (and more to your question) there are no properties in the URLLoader class that allow you to access the URLRequest that a load() was initially called with. A simple way around this would be to extend URLLoader. Eg, if you only needed the url: public class MyURLLoader extends URLLoader { private var _url:String; public function MyURLLoader(request:URLRequest=null) { super(request); } override public function load(request:URLRequest):void { super.load(request); _url = request.url; } public function get url():String { return _url; } } Then in your code you could still use a single event handler: public function loadAllCSS():void { loadCSSFile("cssFile1"); loadCSSFile("cssFile2"); loadCSSFile("cssFile3"); } private function loadCSSFile(cssURL:String):void { var urlLoader:MyURLLoader = new MyURLLoader(); urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete); urlLoader.load(new URLRequest(cssURL)); } private function urlLoader_complete(evt:Event):void { var cssURL:String = evt.target.url; //now I know where this came from var css:String = evt.data; } A: Create three URLLoaders. In the complete function, you can check the identity of the event target to determine which on you're getting the event from, which will tell you which file is loaded. You could also have three different handlers instead, depending in how you want to factor the code. The docs aren't clear on what happens when you call load multiple times on the same URLLoader, which (to me) means it's not well-defined behavior and you should avoid it. For your example, the documentation doesn't specify whether your event handler will be called once or three times, and if it is called multiple time whether the data will be different each time or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Disable PDF/CSV Output Formats on report level in SSRS 2005 I am wondering if there is a way to disable certain output types for SSRS on a report by report basis. I am aware of the way to do it with all reports in the rsreportserver.config file, but this is not what I want. This Post mentioned something about doing it with a query string, but didn't say anything past that. I cannot find anything that explains how to do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: string.replace(/""\n/g,"\"\""+ "\n") will this work? string.replace(/""\n/g,"\"\""+ "\n") I am trying to parse a string and for using JSON parser. I need to replace the occurrence ""\n (quote, quote, newline) with \\"\\"\n (slash, quote, slash, quote, newline). I tried to do this by using escape sequence, but am not able to do so. A: Try using the single quote (') string form to avoid escaping double-quotes unnecessarily this: string.replace(/""\n/g, '\\"\\"\n') A: Try this regular expression /\"\"[\n|\r]/g str.replace( /\"\"[\n|\r]/g, '\\"\\"\r' ); It works for me :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7533110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to drag and drop list view items from one app to another? There is one win forms application with some list view items. I'd like to drag several selected items from that app to my another win forms app. Each list view item should contain some custom data and recieving app needs to get it also. A: For a lengthy example, see MSDN, Control.DoDragDrop Method. Important for your specific task is * *Call yourDragSourceControl.DoDragDrop(data, effects) with the data you want to transfer to the drop target. You can specify any serializable object or a string. *You deserialize the transferred data in the handler of the DragDrop event of the drop target; use var data = (YourDTO)e.Data.GetData(typeof(YourDTO));
{ "language": "en", "url": "https://stackoverflow.com/questions/7533111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Are Where(condition).Any() and Any(condition) equivalent About half of the examples I see for Linq queries using the Any method do so by applying it to the results of a Where() call, the other half apply it directly to the collection. Are the two styles always equivalent, or are there cases wheres that they could return different results? My testing supports the former conclusion; but edge cases aren't always easy to find. List<MyClass> stuff = GetStuff(); bool found1 = stuff.Where(m => m.parameter == 1).Any(); bool found2 = stuff.Any(m => m.parameter == 1); A: It comes down to 2 important questions: * *is it a standard "Where"/"Any" (such as Enumerable.* or Queryable.*), or is it custom? (if the latter, all bets are off) *if it is Queryable.*, what is the provider? The latter matters hugely. For example, LINQ-to-SQL and LINQ-to-EF behave differently re Single, so I would not assume that they behave identically for Any. A more esoteric provider could do anything. But more: LINQ-to-SQL does different things (re the identity-manager) for Single(predicate) vs Where(predicate).Single (and for First too). In fact, there are 3 different behaviours available in LINQ-to-SQL there depending on 3.5, 3.5SP1, or 4.0. Additionally, IIRC LINQ-to-ADO.NET-Data-Services had different (opposite, from memory) support to EF - so (again from memory) while one provider only supported Single(predicate), the other only supported Where(predicate).Single(); it is not a great leap to suggest that Any() could be similarly affected by different providers. So: while Any(predicate) and Where(predicate).Any() are semantically equivalent - it is impossible to say if they are actually the same without very detailed information to the context. A: Logically, no difference, but performance wise the latter: stuff.Any(m => m.parameter == 1); is more performant than: stuff.Where(m => m.parameter == 1).Any(); because the former does not use an iterator (yield return) to produce it's result. The Where() clause does, iterators are nice, but they do add extra processing overhead. Is it huge? No, but typically I'd go with the most concise and readable expression for both performance and maintainability. A: Using standard LINQ functions, there is no difference, since where is deferred operation -- only an additional function call. A: Here is little code in C# : class Program { List<string> data = new List<string>(){ "ABC", "DEF", "H" }; static void Main(string[] args) { var p = new Program(); } private Program() { UseWhereAndAny(); UseAny(); } private void UseWhereAndAny() { var moreThan2 = data.Where(m => m.Length > 2).Any(); } private void UseAny() { var moreThan2 = data.Any(m => m.Length > 2); } } If you check the IL code you notice a little difference between the two : .method private hidebysig instance void UseAny () cil managed { // Method begins at RVA 0x2134 // Code size 45 (0x2d) .maxstack 4 .locals init ( [0] bool moreThan2 ) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldfld class [mscorlib]System.Collections.Generic.List`1<string> AnyWhere.Program::data IL_0007: ldsfld class [mscorlib]System.Func`2<string, bool> AnyWhere.Program::'CS$<>9__CachedAnonymousMethodDelegate4' IL_000c: brtrue.s IL_0021 IL_000e: ldnull IL_000f: ldftn bool AnyWhere.Program::'<UseAny>b__3'(string) IL_0015: newobj instance void class [mscorlib]System.Func`2<string, bool>::.ctor(object, native int) IL_001a: stsfld class [mscorlib]System.Func`2<string, bool> AnyWhere.Program::'CS$<>9__CachedAnonymousMethodDelegate4' IL_001f: br.s IL_0021 IL_0021: ldsfld class [mscorlib]System.Func`2<string, bool> AnyWhere.Program::'CS$<>9__CachedAnonymousMethodDelegate4' IL_0026: call bool [System.Core]System.Linq.Enumerable::Any<string>(class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0>, class [mscorlib]System.Func`2<!!0, bool>) IL_002b: stloc.0 IL_002c: ret } // end of method Program::UseAny While the UserWhere method is : .method private hidebysig instance void UseWhereAndAny () cil managed { // Method begins at RVA 0x20d8 // Code size 50 (0x32) .maxstack 4 .locals init ( [0] bool moreThan2 ) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldfld class [mscorlib]System.Collections.Generic.List`1<string> AnyWhere.Program::data IL_0007: ldsfld class [mscorlib]System.Func`2<string, bool> AnyWhere.Program::'CS$<>9__CachedAnonymousMethodDelegate2' IL_000c: brtrue.s IL_0021 IL_000e: ldnull IL_000f: ldftn bool AnyWhere.Program::'<UseWhereAndAny>b__1'(string) IL_0015: newobj instance void class [mscorlib]System.Func`2<string, bool>::.ctor(object, native int) IL_001a: stsfld class [mscorlib]System.Func`2<string, bool> AnyWhere.Program::'CS$<>9__CachedAnonymousMethodDelegate2' IL_001f: br.s IL_0021 IL_0021: ldsfld class [mscorlib]System.Func`2<string, bool> AnyWhere.Program::'CS$<>9__CachedAnonymousMethodDelegate2' IL_0026: call class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0> [System.Core]System.Linq.Enumerable::Where<string>(class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0>, class [mscorlib]System.Func`2<!!0, bool>) IL_002b: call bool [System.Core]System.Linq.Enumerable::Any<string>(class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0>) IL_0030: stloc.0 IL_0031: ret } // end of method Program::UseWhereAndAny From what I understand, the the use of Where and Any cause more overhead with an additional Enumeration. A: While they are semantically equivalent in most cases, it is possible for an object to provide its own Where method that could cause stuff.Where(foo).Any() to be very different from stuff.Any(foo). A: There is a subtle difference. Calling Any() checks the enumerable for emptiness and returns false if it is. Calling Any(Func<TSource, bool> predicate) checks if any of the items in the enumerable match the predicate and returns false if they don't. However I can't think of a way that this difference would effect execution, since Any isn't called until the enumerable is enumerated. If another thread changes the enumerable between the where part being run and the any part being run there will be an exception thrown, so that won't change the results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: python: in parent class's method, call classmethod of that class, but bound to a child class Say I have the following code: class Parent(object): classattr1 = 'parent' def __init__(self): Parent.foo() @classmethod def foo(cls): print cls.classattr1 class Child(Parent): classattr1 = 'child' def foo(cls): raise Exception("I shouldn't be here") Child() In Parent.__init__, I need to call 'foo' that is defined within Parent, but I need to call it bound to Child, so that accessing cls.classattr1 will actually access the attribute as it is overridden in Child. Any ideas how to do this? A: Here is an option: class Parent(object): classattr1 = 'parent' def __init__(self): Parent.foo(self) def foo(self): print self.classattr1 # or self.__class__.classattr1 class Child(Parent): classattr1 = 'child' def foo(cls): raise Exception("I shouldn't be here") Child() Parent.foo() is not a class method anymore, but the end result should be the same as what you want. >>> c = Child() # prints 'child' by calling Parent.foo() child >>> c.foo() # Child.foo() raises an exception Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in foo Exception: I shouldn't be here A: This should work: Parent.foo.im_func(Child) but looks kinda evil. A: Do you really need foo to be a classmethod? If not, this works.: class Parent(object): classattr1 = 'parent' def __init__(self): Parent.foo(self) def foo(self): print self.classattr1 class Child(Parent): classattr1 = 'child' def foo(self): raise AttributeError("Wrong foo!") Child() # prints 'child'
{ "language": "en", "url": "https://stackoverflow.com/questions/7533120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iOS: How to make UIWebView 50% transparent? I want to make a UIWebView whose background is 50% transparent, but whose content e.g. are not transparent at all. Is such a thing possible? Thanks. A: It looks like this is possible, maybe. See this blog post: http://erikloehfelm.blogspot.com/2009/04/transparent-background-on-iphone.html Making the background semi-transparent depends on whether or not you can set the CSS color of the web page's BODY element to a semi-transparent color (instead of "transparent"). Also, this blog post doesn't show how to do this if you don't control the HTML of the web page you're trying to display, but it's possible with the UIWebView to programmatically change this color once the page contents have loaded. A: webView.alpha=0.5f; [webView setBackgroundColor:[UIColor clearColor]]; [webView setOpaque:NO]; A: Play around with changing transparent to whatever color / alpha for the webView.backgroundColor and the html <body> css style to find a combination that you like best. Example with loadHTMLString: - (void)embedYouTubeWithVideoID:(NSString *)videoID { webView.backgroundColor = [UIColor clearColor]; CGFloat w = webView.frame.size.width; CGFloat h = webView.frame.size.height; NSString *ytUrlString = [NSString stringWithFormat:@"http://www.youtube.com/v/%@&version=3&autohide=1&autoplay=1&cc_load_policy=1&fs=1&hd=1&modestbranding=1&rel=0&showsearch=0", videoID]; NSString *embed = [NSString stringWithFormat:@"\ <html>\ <head>\ <meta name=\"viewport\" content=\"initial-scale = 1.0, user-scalable = no, width = %0.0f\"/>\ </head>\ <body style=\"background:transparent; margin-top:0px; margin-left:0px\">\ <div>\ <object width=\"%0.0f\" height=\"%0.0f\">\ <param name=\"movie\" value=\"%@\" />\ <param name=\"wmode\" value=\"transparent\" />\ <param name=\"allowFullScreen\" value=\"true\" />\ <param name=\"quality\" value=\"high\" />\ <embed src=\"%@\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" allowscriptaccess=\"always\" wmode=\"transparent\" width=\"%0.0f\" height=\"%0.0f\" />\ </object>\ </div>\ </body>\ </html>", w, w, h, ytUrlString, ytUrlString, w, h]; [webView loadHTMLString:embed baseURL:nil]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7533123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Rotating a UIImageView around the bottom axis - Objective-C/iOS I have a UIImage view that I want to flip to being flat like a flip clock does. This is the first part to the horizontal plane (where I will change the image or add a new view or something). My problem is getting the view to flip on the bottom axis. it's 100px square. How can I get it to rotate by the bottom axis. I have read many many stack problems and answers, googled it and what ever answers I have don't work. This is the closest I have which seems to flip by moving the view before it does so and I can't get it to flip but stay still. Looking at the Applying the Animation section of http://www.voyce.com/index.php/2010/04/10/creating-an-ipad-flip-clock-with-core-animation/ it would seem that I have the axis correct, but I clearly don't! [UIView beginAnimations:nil context:nil]; [UIView setAnimationDelegate:self]; [UIView setAnimationDuration:1]; [UIView setAnimationCurve:UIViewAnimationCurveEaseIn]; boxView.center = CGPointMake(0.5, 1); boxViewImage.layer.anchorPoint = CGPointMake(0.5, 1); boxViewImage.layer.transform = CATransform3DMakeRotation(M_PI_2,-1.0,0,0); [UIView commitAnimations]; boxViewImage is a UIImageView What do I need to add to get it to flip in the right way? Been trying to do this for 2 days now! EDIT: I allocated the UIImageView with this: CGRect frameRect = CGRectMake(0, 0, 100,100); boxViewImage = [[UIImageView alloc] initWithFrame:frameRect]; boxViewImage.image = [UIImage imageNamed:@"1.png"]; [self.view addSubview:boxViewImage]; EDIT 2: I have discovered that if I create my UIImageView when I click (not what I want to do) after the view is loaded, it rotates where I want it too. I think that it might be due to the UINavigationController having a height, as the offset seems to be the same as it's height! A: You've got few things wrong in your code. First I have no idea why do you set boxView.center to (0.5, 1). Second you shouldn't set anchor point inside animation block and third M_PI_2 is just half animation you really want. Here is the solution. I used UILabel instead of UIImageView. UILabel *testLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20, 20, 100, 100)] autorelease]; testLabel.backgroundColor = [UIColor blackColor]; testLabel.text = @"Test"; testLabel.textColor = [UIColor whiteColor]; [self.view addSubview:testLabel]; testLabel.layer.anchorPoint = CGPointMake(0.5, 1); [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction animations:^{ testLabel.layer.transform = CATransform3DMakeRotation(M_PI, -1, 0, 0); } completion:^(BOOL finished) { }]; A: I actually made a small framework out of the voice tutorial. Perhaps that helps: https://github.com/jaydee3/JDFlipNumberView It contains three classes: * *JDFlipNumberView (a single animated digit) *JDGroupedFlipNumberView (a grouped and chained choosable number of flipviews for higher numbers) *JDDateCountdownFlipView (a date countdown, just init with a date, set a frame and there you go.) In any case, you just need to do three steps: * *Init the class *Set an int value (or a date) *Start the animation
{ "language": "en", "url": "https://stackoverflow.com/questions/7533125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Apache + Python + Mongo: Object Ids aren't equal We are running two copies of a django-based application within an Apache instance. We have this python code when loading an object from the database: id = pymongo.objectid.ObjectId(hex_string) d = self.collection.find_one({ '_id': id }) assert id == d['_id'] On one of the two applications (whichever we hit second) the assert fails. We've looked at the ids, and they are the same. Plus, when we change it to: assert str(id) == str(d['_id']) The assert passes. On our development machines (Win 7 64-bit, django dev server instead of Apache) this seems to work fine. Stack: Ubuntu 10.04 LTS, Apache 2.2.14, Python 2.6.5, MongoDB 2.0, Pymongo 2.0.1 Update: We ran into another problem like this. We actually started referring to the objects as BSON object ids, and that fixed the second problem. However, the problem in this question is still occurring, even with using BSON object ids. A: Kind of a shot in the dark, but you aren't using sharding by any chance, are you? I haven't tested it, but it seems like there is a possibility of having two docs with the same _id if you shard on a non-_id field. Are you generating the _id values yourself or letting pymongo do it for you on insert?
{ "language": "en", "url": "https://stackoverflow.com/questions/7533126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hoping to increase the speed of my WebService with Asynchronous calls, but not sure how I am writing a WebService that consumes a third party webservice and greatly extends the functionality. For example, in one portion of the workflow I have to loop through the results of one API call, and for each result make another API call in order to return results which are actually usable. Currently this results in roughly 7,500 lines of XML, as well as a 3-4 minute load time (Granted, this load time is based upon running the WebService in debug mode from Visual Studio on a crappy PC with a crappy internet connection, and I expect it to be quite a bit snappier when run from a high-end Windows server). What I would like to do is find some way to spawn a new Asyncronous thread for each API call (so that each iteration does not have to wait for the previous iteration to finish), but I'm not sure how to do this and still have the ability to return the XML output in the same function call. Any ideas? ::EDIT:: -- Here is the code with which I generate my XML. Note that all function calls are just wrappers to API calls for the third party API. public List<AvailabilityList> getResortsForDate(String month, int year) { List<RegionList> regions = this.getRegionLists( ); List<AvailabilityList> availability = new List<AvailabilityList>(); foreach(RegionList parent in regions) { foreach(Region child in parent.Regions) { if (!String.Equals(child.ID, "?")) { int countryID = Int32.Parse(parent.CountryID); AvailabilityList current = this.getExchangeAvailability(countryID, month, year, child.ID); if (current.ListCount != 0) { availability.Add(current); } } } } return availability; } ::EDIT #2:: SOLUTION! This is the solution I ended up using, which is a minor adjustment to the Answer I have chosen. Thanks! After timing my previous code (5 minutes and 1 second), this code is a huge improvement at 1 minute and 6 seconds, with 30 seconds of time belonging to another method which I will be optimizing as well! public List<AvailabilityList> _asyncGetResortsForDate(String month, int year) { List<RegionList> regions = this.getRegionLists(); List<AvailabilityList> availability = new List<AvailabilityList>(); List<WaitHandle> handles = new List<WaitHandle>(); List<AvailabilityList> _asyncResults = new List<AvailabilityList>(); regions.ForEach(parent => { parent.Regions.ForEach(child => { if (!String.Equals(child.ID, "?")) { int countryID = Int32.Parse(parent.CountryID); Func<AvailabilityList> _getList = () => this.getExchangeAvailability(countryID, month, year, child.ID); IAsyncResult res = _getList.BeginInvoke(new AsyncCallback( x => { AvailabilityList result = (x.AsyncState as Func<AvailabilityList>).EndInvoke(x); if (result.ListCount > 0) { _asyncResults.Add(result); } }), _getList); while (handles.Count >= 60) { int item = WaitHandle.WaitAny(handles.ToArray( )); handles.RemoveAt(item); } handles.Add(res.AsyncWaitHandle); } }); }); WaitHandle.WaitAll(handles.ToArray()); return _asyncResults; } A: Mucking about with arrays of wait handles like this is a sign that there's something entirely too complicated in your code. You can do a much cleaner job with the Task Parallel Library. For example: public List<AvailabilityList> _asyncGetResortsForDate(String month, int year) { List<RegionList> regions = this.getRegionLists(); List<AvailabilityList> availability = new List<AvailabilityList>(); List<Task> tasks = new List<Task>(); List<AvailabilityList> _asyncResults = new List<AvailabilityList>(); regions.ForEach(parent => { parent.Regions.ForEach(child => { if (!String.Equals(child.ID, "?")) { int countryID = Int32.Parse(parent.CountryID); var childId = child.ID; Task t = Task.Factory.StartNew((s) => { var rslt = getExchangeAvailability(countryId, month, year, childId); lock (_asyncResults) { _asyncResults.Add(rslt); } }); tasks.Add(t); } }); }); Task.WaitAll(tasks); return _asyncResults; } (I haven't tried to compile that, but you get the gist of the idea.) Let the TPL worry about the 64 wait handle limit. Also note that your code had a bug just waiting to happen. Since multiple tasks could be trying to add results to the _asyncResults list, you have to protect it with a lock. List<T>.Add is not thread safe. If two threads try to access it concurrently, you'll end up with either corrupt data or an exception. The above might also be faster. I'm not sure what happens if you start multiple asynchronous calls. It's likely that the thread pool will create the maximum number of threads for them, and start them all running. You could end up with 25 or more running threads with the accompanying context switches, etc. The TPL, on the other hand, is much smarter about using threads. It will create fewer concurrent threads, thus avoiding a large amount of context switching. You can avoid the lock altogether if you use Task<List<AvailabilityList>>. Your code then becomes something like: Task<List<AvailabilityList>> t = Task<List<AvailabilityList>>.Factory.StartNew((s) => { return getExchangeAvailability(countryId, month, year, childId); } And then, after your Task.WaitAll(tasks): foreach (var t in tasks) { _asyncResults.Add(t.Result); } In fact, you can get rid of the Task.WaitAll(tasks), since Task<T>.Result blocks until a result is available. A: Here is one way to do it asynchronously, where each time you call getExchangeAvailability() it does so on a seperate thread, then waits for all threads to complete before returning the final list. public List<AvailabilityList> _asyncGetResortsForDate(String month, int year) { List<RegionList> regions = this.getRegionLists(); List<AvailabilityList> availability = new List<AvailabilityList>(); List<WaitHandle> handles = new List<WaitHandle>(); List<AvailabilityList> _asyncResults = new List<AvailabilityList>(); regions.ForEach(parent => { parent.Regions.ForEach(child => { if (!String.Equals(child.ID, "?")) { int countryID = Int32.Parse(parent.CountryID); Func<AvailabilityList> _getList = () => this.getExchangeAvailability(countryID, month, year, child.ID); IAsyncResult res = _getList.BeginInvoke(new AsyncCallback( x => { AvailabilityList result = (x.AsyncState as Func<AvailabilityList>).EndInvoke(x); _asyncResults.Add(result); }), _getList); handles.Add(res.AsyncWaitHandle); } }); }); WaitHandle.WaitAll(handles.ToArray()); return _asyncResults; } Keep in mind however that if the number of iterations exceeds 64, being that the default maximum number of concurrent threads (using BeginInvoke()) is 64, you won't be processing anything asynchronously after that point until one of the 64 already running threads becomes free. There also may or may not be some overhead in making the context switches between threads. One thing you might want to check is how long each API call takes by itself to see if its really worth it. EDIT - Concerning the 64 thread limit error, I would suggest two things, 1) You should group the asynchronous calls so that only each 'parent' is executing on its own thread, rather than every single child. That should reduce the # of threads, something like: public List<AvailabilityList> _getAllChildren(RegionList parent, string month, int year) { List<AvailabilityList> list = new List<AvailabilityList>(); parent.Regions.ForEach(child => { if (!String.Equals(child.ID, "?")) { int countryID = Int32.Parse(parent.CountryID); AvailabilityList result = this.getExchangeAvailability(countryID, month, year, child.ID); list.Add(result); } }); return list; } public List<AvailabilityList> _asyncGetResortsForDate(String month, int year) { List<RegionList> regions = this.getRegionLists(); List<AvailabilityList> availability = new List<AvailabilityList>(); List<WaitHandle> handles = new List<WaitHandle>(); List<AvailabilityList> _asyncResults = new List<AvailabilityList>(); regions.ForEach(parent => { Func<List<AvailabilityList>> allChildren = () => _getAllChildren(parent, month, year); IAsyncResult res = allChildren.BeginInvoke(new AsyncCallback( x => { List<AvailabilityList> result = (x.AsyncState as Func<List<AvailabilityList>>).EndInvoke(x); _asyncResults.AddRange(result); }), allChildren); handles.Add(res.AsyncWaitHandle); }); WaitHandle.WaitAll(handles.ToArray()); return _asyncResults; } 2) You might need to add a check before adding to the List of WaitHandles to see if you are at risk of exceeding 64 threads: var asyncHandle = res.AsyncWaitHandle; if (handles.Count >= 64) asyncHandle.WaitOne(); // wait for this one now else if (handles.Count < 64) handles.Add(asyncHandle);
{ "language": "en", "url": "https://stackoverflow.com/questions/7533132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: In Reporting Services I have 2 datasets that share a parameter name. Can I Pass a different value to each dataset for this parameter? I have a report that has 2 charts in it. Each chart has its own dataset with a different stored procedure. These 2 stored procedure share a common parameter name in this case. Is there any way to pass a different value for this parameter to each dataset, or a workaround? As these procedures are called elsewhere I do not want to change the parameter name in either. I could copy one of the procedures, rename it and one of the parameters, but that also does not seem quite ideal. A: [I started typing the answer below then saw that you are on 2005. It was a while ago, but I think there is similar functionality to what I describe below in 2005. But if you are doing much report development 2008 (or better, 2008R2) are massively improved. ] Not hard: In Business Intelligence Development Studio, open your report, then right click on the dataset for your SP. In the resulting "Dataset Properties" dialog, you can choose the Parameters pane on the left side. Leave Parameter Name set to the name that the SP requires, but set the "Parameter Value" to whatever parameter or value the SP should be getting from your report.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "Subscript indices must either be real positive integers or logicals" error. unable to understand why? I have these 3 functions function r = RingRead(n,p) r=( p * RingReadggg(n-1,p))+( (1-p)* RingReadggb(n-1,p)); end function r = RingReadggb(n , p) if n <= 1 r = 0; else r = ((1-p)* RingReadggb(n-1,p) )+ p^2 +( p(1-p)* RingReadggb(n-2,p)); end end function r = RingReadggg(n , p) if n == 1 r = p; else r = (p+p(1-p)+( (1-p)^2 * RingReadggb(n-2,p))); end end Below given program uses above given functions. for p = 0.50:0.05:1 r = RingRead(4,p); plot(p,r) hold on end When i run this it gives error ??? Subscript indices must either be real positive integers or logicals. Error in ==> RingRead>RingReadggg at 18 r = (p+p(1-p)+( (1-p)^2 * RingReadggb(n-2,p))); Error in ==> RingRead at 3 r=( p * RingReadggg(n-1,p))+( (1-p)* RingReadggb(n-1,p)); Error in ==> RingAvailability at 2 r = RingRead(4,p); A: Your code crashes right here: r = (p+p(1-p)+( (1-p)^2 * RingReadggb(n-2,p))) n is 3 and p is 0.5 but what is p(1-p) supposed to be? do you mean p * (1-p) ? A: As the message says, the error occurs on this line: r = (p+p(1-p)+( (1-p)^2 * RingReadggb(n-2,p))); By p(1-p), do you really mean p * (1-p)? Entered as p(1-p) is interpreted as indexing into p at the index 1-p. Try changing the line to: r = (p+p*(1-p)+( (1-p)^2 * RingReadggb(n-2,p))); It looks like you have the same issue in RingReadggb as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Android: Change button insets I have the following button: http://dl.dropbox.com/u/3564087/button.png However this image has a blank area on the right side, border and shadow (which doesn't exist on the right side). This means that when I insert some text on the button and set the gravity to center, the text doesn't really gets centered because the area in which i want it to be centered isn't the total area of the image. My question is, can I set an inset Rect (the same way as you can do in iOS), in which I want to display the text? Or do I need to create a separate TextView in front of the Button? A: You can do it by creating a 9 patch image. It won't only allow to define a rect where the text will go, but also will allow your button to stretch to any size screen and resolution. A: Although I can do this using 9-patch, I found that it is simpler to do it using the "padding" property of the Button view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Identical query plan with radically different performance based on one improbable parameter? I have an ad-hoc query that should be pretty zippy (I have a DBA background and I'm pretty good at optimization) and in almost all cases it is. HOWEVER, when I supply a specific parameter to the query, (a pretty selective value with a smaller than average expected result set) the tempdb starts growing and dies when it runs out of disk. This is a one-time report against a Lawson AP system on a SQL Server 2005 system, if anyone cares. I have examined the query plans against a performant run and a non-performant run, not just the estimated query plans but the actual query plans, and they are exactly identical. I have updated the statistics and the query plans remain identical. The only thing that should be different is the actual data. The data for the nonperformant group does look strange... id columns are char(9) and char(22), left padded spaces and then padded zeroes added in for good measure. A typical ID value would be something like ' 00112' ...which is strange, but it is a valid char(9) and therefore legit. The columns are well indexed, as with all cases except one, this works quite well. I'm thinking the problem has to do with the indexes working on the data, although I don't see how. The number of result records for the nonperformant query are less than half the number of the largest ones that return results in seconds. the query I'm using is as follows (this is against a Lawson v9 database schema): insert into dbo.rptPayments with (tablock) ( VendorGroup, VendorID, VendorName, ChargedToCompany, ChargedToAccount, ChargedToSubAccount, InvoiceID, PaymentAmount ) select top 100 percent vm.VENDOR_GROUP as VendorGroup, rtrim(ltrim(vm.VENDOR)) as VendorID, vm.VENDOR_VNAME as VendorName, gm.NAME as ChargedToCompany, dist.DIS_ACCOUNT as ChargedToAccount, dist.DIS_SUB_ACCT as ChargedToSubAccount, inv.INVOICE as InvoiceID, dist.ORIG_TRAN_AMT as PaymentAmount from dbo.APVENMAST vm with (nolock) inner join dbo.APINVOICE inv with (nolock) on inv.VENDOR = vm.VENDOR and inv.VENDOR_GROUP = vm.VENDOR_GROUP inner join dbo.APDISTRIB dist with (nolock) on dist.COMPANY = inv.COMPANY and dist.VENDOR = inv.VENDOR and dist.INVOICE = inv.INVOICE inner join dbo.APPAYMENT pay with (nolock) on pay.COMPANY = inv.COMPANY and pay.VENDOR = vm.VENDOR and pay.INVOICE = inv.INVOICE and pay.VENDOR_GROUP = inv.VENDOR_GROUP inner loop join dbo.GLSYSTEM gm with (nolock, index(GLSSET1)) on gm.COMPANY = dist.DIST_COMPANY where vm.VENDOR_GROUP = @VendorGroup and vm.VENDOR_STATUS = 'A' and inv.INVOICE_DTE between '2009-09-01' and '2011-08-31' and pay.VOID_SEQ = 0 and pay.CANCEL_SEQ = 0 ...as you can see, I'm using some hints to force the query down the right path... the optimizer was making some truly poor choices. I'm expecting a result set of 20000 - 30000 records. Schemas for the referenced tables may be found here. Definitions for the custom indexes I've built for this are as follows: CREATE NONCLUSTERED INDEX [tmpAPDISTRIB] ON [dbo].[APDISTRIB] ( [COMPANY] ASC, [VENDOR] ASC, [INVOICE] ASC ) INCLUDE ( [DIST_COMPANY], [ORIG_TRAN_AMT], [DIS_ACCOUNT], [DIS_SUB_ACCT]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] CREATE NONCLUSTERED INDEX [tmpAPPAYMENT] ON [dbo].[APPAYMENT] ( [COMPANY] ASC, [VENDOR] ASC, [INVOICE] ASC, [VENDOR_GROUP] ASC ) INCLUDE ( [VOID_SEQ], [CANCEL_SEQ]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] CREATE NONCLUSTERED INDEX [tmpAPINVOICE] ON [dbo].[APINVOICE] ( [VENDOR] ASC, [VENDOR_GROUP] ASC, [INVOICE_DTE] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] Any help or suggestion would be enormously helpful. UPDATE Upon deeper investigation, I discovered that the records from the problem @VendorGroup were stored differently... apparently there is functionality available in the AP Distributions (represented by the dbo.APDISTRIB table) to support 'recurring' invoices with the same invoice number, causing a cartesian product on my joins, as I had not joined against this column. No other vendor group was using this feature. A: As per my update, the reason the query plan looked different was one company was using a table considerably more than any other.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: best way to transfer multi encoded characters over boost::asio I want to transfer xml in single byte characters, but some of the values will be in unicode. i.e. <value>Unicode string</value> I'm using boost::asio. A: Network/Socket transfer => single byte encoding XML => mostly UTF-8 Conclusion: convert everything to UTF-8 before pushing it to boost::asio.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Email Provider Design I was thinking of creating an email provider using the provider pattern. Our Email system is in disarray. We have different areas in the same app as well as different apps using their own way of handling email. I would like to create an email provider because the information across the board is roughly the same. By using the provider pattern I can have our default way of handling email but also by using an interface I can have more specific/custom email handling introduced. So I'm not quite sure how I would setup the interface to handle each areas specific/custom handling and was looking for some guidance. I would have my abstract class to house default settings/functionality then have my email provider which would execute call to sproc to send email. Now not sure how I would introduce a new interface so that if another dev needed to do some customization pertaining to the area hes working on he could the extend the provider to handle his changes. Any ideas on this approach or maybe suggest other approaches? If you like the provider approach and know how to implement what I'm suggesting a bit of pseudo code would be nice. :) public Interface IEmail abstract class EmailProviderBase : ProviderBase, IEmail //Default settings and methods public virtual SendEmail(){} //Used to handle default implementation public class EmailProvider : EmailProviderBase //But want other classes to be used to handle other devs custom implementations //I guess I could create another provider per say based on EmailProviderBase. public class CustomEmail : EmailProviderBase Can anyone tell me if they like this approach or not? Also if not, how would you design it using interfaces? Thanks, DND A: This may be just me, but it seems to me the System.Net.Mail classes already do a good job of abstracting the details and strike a good balance between customizability and ease of use. If you attempt to simplify much more, you'll lose the ability to customize when you need to. We started to do something along this path with emails and as we did more projects, and our needs changed, we ended up having to customize our classes to the point where it became apparent that the entire exercise was a waste of time. However, I understand where you're coming from, and here's another possibility for unifying how you send emails from your apps. It's not what you asked for, but presented as a possible different way of approaching the problem, based on what worked for our team. What we settled on was based SOLELY on our biggest pain point, which was that our administrators would swap out the Exchange server every few years, OR they would change the IP address for some reason or another. Every time this happened, we'd have to go recompile a bunch of code, which was pretty frustrating. We ended up setting up a web service that has email functions. Now, all of our emails in our internal apps use the web service. When our Admins change something on the server, we only need to adjust just the .config file in our web service and don't have to re-compileor edit the .config in every app that sends emails. This worked especially well for us, because we were able to integrate error handling to our central error logging database, so all of our apps have just a couple of lines of code to send an email. Error handling is included free of charge. The only adjustment we've had to make since we implemented this was to have the web service send emails via the PickupDirectory instead of communicating directly with the Exchange server. This allows the service to work when the Exchange server is down (maintenance, rebooting to apply patches, etc.) The code in the web service is fairly straightforward as well, and handles sanitation using the Microsoft.Security.AntiXss component. The references to the Overseer system in code are references to our central error logging database. I'm not going to include that code as this is already WAY too long an answer, and all it really does is log errors to a SQL database. Sorry it's in VB where you specified C#, but if you're interested, it should be very easy to convert. <WebMethod()> _ Public Function SendEmailViaPickupDir(ByVal FromAddress As String, ByVal ToList As String, ByVal CcList As String, ByVal BccList As String, _ ByVal Subject As String, ByVal MessageBody As String, ByVal IsBodyHtml As Boolean) As Boolean Dim msg As System.Net.Mail.MailMessage = BuildMessage(FromAddress, ToList, CcList, BccList, Subject, MessageBody, IsBodyHtml) If Not msg Is Nothing Then Return SendMessageViaPickupDir(msg) Else Return False End If End Function Private Function BuildMessage(ByVal FromAddress As String, ByVal ToList As String, ByVal CcList As String, ByVal BccList As String, _ ByVal Subject As String, ByVal MessageBody As String, ByVal IsBodyHtml As Boolean) As System.Net.Mail.MailMessage Dim msg As New System.Net.Mail.MailMessage Try msg.From = New System.Net.Mail.MailAddress(FromAddress) If Not ToList Is Nothing Then For Each Address As String In ToList.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) msg.To.Add(New System.Net.Mail.MailAddress(Address.Trim())) Next End If If Not CcList Is Nothing Then For Each Address As String In CcList.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) msg.CC.Add(New System.Net.Mail.MailAddress(Address.Trim())) Next End If If Not BccList Is Nothing Then For Each Address As String In BccList.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) msg.Bcc.Add(New System.Net.Mail.MailAddress(Address.Trim())) Next End If msg.Subject = Microsoft.Security.Application.AntiXss.HtmlEncode(Subject) If (IsBodyHtml) Then msg.Body = Microsoft.Security.Application.AntiXss.GetSafeHtmlFragment(MessageBody) Else ' This was causing formatting issues... msg.Body = MessageBody End If msg.IsBodyHtml = IsBodyHtml Catch ex As Exception Dim s As New OverseerService s.WriteToSql(Convert.ToInt64(ConfigurationManager.AppSettings("OverseerWebSiteResourceid")), User.Identity.Name, _ My.Computer.Name, ex.ToString(), MyCompany.Overseer.EventLogger.SeverityLevel.Critical) Return Nothing End Try Return msg End Function Private Function SendMessageViaPickupDir(ByVal msg As System.Net.Mail.MailMessage) As Boolean Dim ret As Boolean = False Try ' try to send through pickup dir Dim c1 As New System.Net.Mail.SmtpClient("localhost") c1.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis c1.Send(msg) ret = True Catch ex As Exception Try ' log as a known error Dim s As New OverseerService s.WriteToSql(Convert.ToInt64(ConfigurationManager.AppSettings("OverseerWebSiteResourceid")), User.Identity.Name, _ My.Computer.Name, "failed to write email to pickup dir " + ex.ToString(), MyCompany.Overseer.EventLogger.SeverityLevel.KnownError) Catch ' ignore error from writing the error End Try End Try Return ret End Function A: Have you checked out http://mailsystem.codeplex.com/? That's probably the most elaborate of the OSS email utilities on codeplex. There's a much more simple product on codeplex that is more akin to what you described above, but I'm not having any luck finding it right now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: tags are being inserted into the head of my document from jQueryMobile I have just started getting a very strange error when using jQueryMobile for my mobile website/app edit i am adding a picture, probably a lot easier to understand the question edit2 i have found the issue. still curious as to why this is the way it is if you wish to see the original post please read the edits So in my master.js file I had the following code Object.prototype.hasAttr = function(attr) { var _attr; if(this.attr) { _attr = this.attr(attr); } else { _attr = this.getAttribute(attr); } return (typeof _attr !== "undefined" && _attr !== false && _attr !== null); }; If I remove the code everything works! I have also run the code through jsLint and it does not contain errors. I've looked in the docs and the jQueryMobile framework does not have a function called hasAttr so where is the conflict? PLEASE NOTE: THIS FUNCTION IS NEVER ACTUALLY RUN! JUST INCLUDING IT BREAKS THINGS A: I think I see the problem. You are mixing and matching Jquery with prototype here. I think the function getAttribute is the problem, because that is not a jquery function and yet it is trying to act on a jquery object here A: Object.prototype.hasAttr = function(attr) { var _attr; if(this.attr) { _attr = this.attr(attr); } else { _attr = this.getAttribute(attr); } return (typeof _attr !== "undefined" && _attr !== false && _attr !== null); }; conflicting code was the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I select literal values in an sqlalchemy query? I have a query which looks like this: query = session.query(Item) \ .filter(Item.company_id == company_id) \ .order_by(Item.id) It's a pretty basic query. In addition to pulling out the values for the Item, I want to append an additional value into the mix, and have it returned to me. In raw SQL, I would do this: SELECT *, 0 as subscribed FROM items WHERE company_id = 34 ORDER BY id How can I manually add that value via sqlalchemy? A: You'll need to use a literal_column, which looks a bit like this: sqlalchemy.orm.Query(Item, sqlalchemy.sql.expression.literal_column("0")) Beware that the text argument is inserted into the query without any transformation; this may expose you to a SQL Injection vulnerability if you accept values for the text parameter from outside your application. If that's something you need, you'll want to use bindparam, which is about as easy to use; but you will have to invent a name: sqlalchemy.orm.Query(Item, sqlalchemy.sql.expression.bindparam("zero", 0)) A: As mentioned in the comments of the accepted answer there's a "shorthand" for bindparam() that alleviates the need to come up with a name for the literal bindparam, literal(): Return a literal clause, bound to a bind parameter. So one does not have to write session.query(Item, bindparam("zero", 0).label("subscribed")) but just session.query(Item, literal(0).label("subscribed")) without having to worry about quoting etc., if passing strings or such.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "66" }
Q: Simple file reader wont work I trying to learn Xcode, Cocoa, Objective C. Today I thought I was going to make a simple app the uses the Nac file browser, reads the file and displays it in an NSTevtView. Everything acts like it wants to work but the file never displays. If I debug it, it shows my string has the file contents but I can't get it to display to the TextView. Here is my code, OpenUp.h and OpenUp.m #import <Foundation/Foundation.h> @interface OpenUp : NSObject { NSString *reader; IBOutlet NSTextField *mainField; } @property(readwrite,copy)NSString *reader; - (void)awakeFromNib; - (IBAction)openExistingDocument:(id)sender; @end //OpenIt.m #import "OpenUp.h" @implementation OpenUp @synthesize reader; - (id)init { self = [super init]; if (self) { // Initialization code here. } return self; } - (IBAction)openExistingDocument:(id)sender{ NSOpenPanel* panel = [NSOpenPanel openPanel]; [panel retain]; // This method displays the panel and returns immediately. // The completion handler is called when the user selects an // item or cancels the panel. [panel beginWithCompletionHandler:^(NSInteger result){ if (result == NSFileHandlingPanelOKButton) { NSURL* theDoc = [[panel URLs] objectAtIndex:0]; NSLog(@"%@", theDoc); //open the document NSError *error; self.reader = [[NSString alloc] initWithContentsOfURL: theDoc encoding:NSUTF8StringEncoding error:&error]; NSLog(@"%@",error); } // Balance the earlier retain call. [panel release]; }]; [mainField setStringValue: self.reader];//this should display the contents of the string } - (void)awakeFromNib { self.reader = @"";//initialize reader } @end I'm not sure if I'm doing something wrong with memory allocation, or if a string read from a file won't use this windows. I've tried both the NSScrollViewer and the NSTextField Everything compiles and acts like it wants to work it just wont display the string. Any help is very much appreciated. Mike A: Make sure the IBOutlet is actually connected in the XIB. Try logging its value after you set its string. A: The answer is in your comment. As it correctly states to the beginWithCompletionHandler: method, this will return immediatly (before the user selects the file). So the [mainField setStringValue: self.reader]; call should be inside the completion handler block, right after self.reader = [[[NSString alloc] initWithContentsOfURL:theDoc encoding:NSUTF8StringEncoding] autorelease]; By the way, note that I added an autorelease call. You define the property as copy, so you would be leaking memory if you don't autorelease. Also, don't write NSError *error; but NSError *error = nil; A: Since I am not familiar with the Nac file browser you are using, I provided a different method to display your file. I found some code for a file chooser I use in my encryption tool that was especially helpful - The code is below: NSOpenPanel* openDlg = [NSOpenPanel openPanel]; [openDlg setCanChooseFiles:YES]; [openDlg setCanChooseDirectories:YES]; [openDlg setPrompt:@"Select"]; [openDlg setAllowsMultipleSelection:NO]; if ([openDlg runModalForDirectory:nil file:nil] == NSOKButton ) { NSArray* files = [openDlg filenames]; for(NSString* filePath in [openDlg filenames]) { NSLog(@"File Path:%@", filePath); [filePathName setStringValue:filePath]; // get filepath } } With this, when a user selects a file, you can return the filepath name in the console. Now what you want to do is get the data using the filepath. You can do this using dataWithContentsOfFile: method. NSData *data = [NSData dataWithContentsOfFile:filePath] You now have the data of the file the user selected. We use the pointer 'data' to refer back to the data later on. You now want to display the data somewhere. I'm not sure why you would want to display the data on an NSTextfield however, because it would only work if the user would select a text file, unless you were just displaying the bytes (which wouldn't make sense). You can then convert this data to a string: NSString *yourStuff = [[[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding] autorelease]; Now that you have your string, you can write it to the NSTextView: [yourNstextiview setStringValue:yourstuff]; I hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I open a "get" php window from jquery without a parent page refresh? I know the question itself may seem a little vague. Let me elaborate. I am trying to post data to a php file from a page controlled by jquery. Here is what I have on the jquery end: var openURL = "http://derp.com/restr/js/addfood.php?fname=" + encodeURI(food_n) + "&fcals=" + encodeURI(food_c); window.open(openURL); The Problem is not that it wont go to the page, the problem is that the parent page reloads once the code is executed. Is there any way to keep this from happening? A: You need to look into using jQuery's ajax() methods. They have special functions that will run when data from your PHP script is loaded, without refreshing the page. The basic idea is to use something like... $.ajax({ url: "file_to_load.php", data: {}, success: function(data){ //it worked! alert(data); } }); ...using the data object to hold your get or post params. A: I believe your only options is to reload the content into the current page. In other words, the entire second page has to replace the original via ajax. Depending on where you want the performance, you could either load the entire second page with "display:none;" off the bat, minus the new content, Then add that in after the ajax. Or pass the "new page," of course minus anything that doesn't change, with ajax and replace accordingly. I haven't mastered ajax inside and out, so there possibly be another method, but I've sure never heard of one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: store and use select statement result in stored proc? Is it possible to store the results of a select query in a stored proc and then use those results from within the stored proc to further query the result set? Example // my stored proc (simplified example) ALTER PROCEDURE [dbo].[users] AS BEGIN Declare @users nvarchar(1000) set @users = select * from users // query @users result for counts, sums where clauses, etc... END A: You want users to be a table variable or temp table instead of an nvarchar type. Table Variable Version DECLARE @users TABLE ( UserId int, ... ) INSERT INTO @users (UserId, ...) SELECT * FROM users SELECT * FROM AnotherTable t INNER JOIN @users u ON ... Temp Table Version CREATE TABLE #users ( UserId int, ... ) INSERT INTO #users (UserId, ...) SELECT * FROM users SELECT * FROM AnotherTable t INNER JOIN #users u ON ... You could also implicitly create the temp table. SELECT * INTO #users FROM users SELECT * FROM AnotherTable t INNER JOIN #users u ON ... A: You can use a table variable: DECLARE @users TABLE (...columns...); INSERT @users SELECT * FROM dbo.Users; Though depending on the number of rows, a #temp table can often be safer because it will have statistics, you can create additional indexes, etc. CREATE TABLE #users (...columns...); INSERT #users SELECT * FROM dbo.Users; A: You can use a temp table or a table variable to do just that. Here is a blog post comparing the options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Lion: Problem with RVM installing rubies - problem related to openssl I'm desparate, fuddling with the following problem for two(!!) days now w/o a solution. After an update to Lion I wanted to install additional rubies using the most recent version of rvm. Here's what happens when I call bundler afterwards: /Users/felix/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': dlopen(/Users/janroesner/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/x86_64-darwin11.1.0/digest/sha1.bundle, 9): Symbol not found: _SHA1_Init (LoadError) Ok, openssl problem. So I checked there is no openssl but the system one in /usr with libraries in /usr/lib and headers in /usr/include/openssl. Check. I decided to install a more recent version with brew. After that no ruby compiles with the error that BN_rand_range and BN_peudo_rand_range are defined already. Seems to be more strict type checking of the most recent gcc, so I uncommented lines 411 and 412 in /usr/include/openssl/bn.h that caused the conflict cause ruby defines both on it's own. Now ruby compiles but I receive the same error Symbol not found: _SHA1_Init. So I removed the comments from the openssl header file bn.h I put there before and tried the opposite. I commented these lines out in ~/.rvm/src/ruby-1.9.2-p290/ext/openssl/openssl_missing.h Same result. After that I completely removed ~/.rvm, reinstalled it and ... have the same problem. Now I tried: rvm pkg install openssl rvm remove 1.9.2-p290 rvm install 1.9.2-p290 -C --with-openssl-dir=$rvm_path/usr Same result. I'm desparate. Can anyone help? Regards Felix A: For anyone who should ever have this problem on Lion ... it's some Problem with duplicate headers that come from openssl. You can simply install openssl locally and tell rvm to use that local openssl version. You can compile opnessl by hand with the prefix /usr/local or simply let rvm do the job: rvm pkg install openssl And then tell rvm to link against that version during ruby install: rvm install 1.9.2 --with-openssl-dir=/path/to/your/home/.rvm/usr In case you already have a local installation replace with: rvm install 1.9.2 --with-openssl-dir=/usr/local DO NOT try what can be read often: rvm install 1.9.2 -C --with-openssl-dir=/path/to/your/home/.rvm/usr That does not work. A: I just went through this tutorial and it worked without any problems: Getting Rails Up: http://www.frederico-araujo.com/2011/07/30/installing-rails-on-os-x-lion-with-homebrew-rvm-and-mysql/
{ "language": "en", "url": "https://stackoverflow.com/questions/7533163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Uploading large files but POST expires? I have a form on which the user uploads a file, a video file around 500mb, it takes over an hour sometime(slow and paintful) but when it does upload, seems like the $_POST has expired? Anyone could help? Thank you! A: There are several directives you have to set up in the php.ini: * *post_max_size *upload_max_filesize and so on EDIT: Didn't have time to finish the answer but you will need to set the memory limit and the time limit. set_time_limit(0); ini_set('memory_limit', -1); These settings will make the script to run without time or memory limits. This may fix the situation but the script becomes quite vunerable to attacks. Also any network problems will break the upload which is something that happens quite often when uploading 500mb files. A: If $_POST and $_FILES are empty, most likely you exceeded the POST_MAX_SIZE allowed. A: Check post_max_size in php.ini. If it's anything less than your file size, there's your problem. You can read more here: http://php.net/manual/en/ini.core.php A: You pretty much must use chunking for large uploads over the Internet. This can be possible with HTML 5 or Flash, prominent example being the YouTube uploader service. Flash: http://swfupload.org/ Multiple plugin support: http://www.plupload.com/ Spiffy HTML5: http://aquantum-demo.appspot.com/file-upload
{ "language": "en", "url": "https://stackoverflow.com/questions/7533167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Net::SSH works from production rails console, AuthenticationFailed from production webapp I have a rails app where a user can submit a form and it goes off and connects to a remote server via ssh to call a script. Eventually I plan to use delayed_job or something like that but I can't get it to work in production with even a simple test. The odd thing is, Net::SSH works just fine from the console in production, but it fails with AuthenticationFailed when I submit the form in production. Both the console and the webapp work fine in development. The error: Net::SSH::AuthenticationFailed (my_ssh_username): app/models/branch.rb:69:in `ssh_to_machine' app/controllers/branches_controller.rb:55:in `update' Controller's update action: def update @branch = Branch.find(params[:id]) if @branch.update_attributes(params[:branch]) @branch.ssh_to_machine(@branch.hostname, @branch.user_name, @branch.command_to_run) redirect_to @branch, :notice => "Update request now processing." else render :action => 'edit' end end Method I'm calling, mostly copy/pasted from the Net::SSH api example: def ssh_to_machine(host_name, user_name, command_to_run) require 'net/ssh' Net::SSH.start(host_name, user_name, { :verbose => Logger::DEBUG, :keys => %w{ /home/www-data/.ssh/my_ssh_username_id_rsa }, :auth_methods => %w{ publickey } }) do |ssh| # capture all stderr and stdout output from a remote process output = ssh.exec!("hostname") # run multiple processes in parallel to completion ssh.exec command_to_run ssh.loop end end I've tried it with and without :verbose, :keys, :auth_methods; being careful to restart apache each time, but in production it always works from the console (with RAILS_ENV=production exported before calling 'rails c') and never works from the webapp. I would also welcome any recommendations on how to get enhanced logging when I do call it from the webapp - :verbose worked for me at the console but didn't add anything to my production.log. A: When you run it from the console, you're using your own account, right? This is kinda bizarre, but my guess is that your production web app is running under an account that doesn't have read access to "/home/www-data/.ssh/my_ssh_username_id_rsa". From your description it almost has to be a permissions issue of some sort.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Localization does not work in one nib I have simple app with some nib files. Some of them (with TabBarController or NavigationController) are localized with Xcode. Strings and almost every nib works like a charm when try to change language. But there is one nib which do not accept my localized version of itself. I done the localization the same way as the rest. Even try to clean the project and recompile it. But still when launching the app in specific language, everything is translated except this one nib. It's unfortunately the first screen seen by user. When app starts it runs this nib as a modal controller and show it on the top of the main TabBarController. There are 4 custom (custom set in Xcode not by code) buttons in the nib file and in viewDidLoad I only change the font to custom one (I've tried to remove this one also but did not help). Any ideas what I'm doing wrong? Thx A: I've found that after newly localizing a file that wasn't previously localized, in addition to cleaning and rebuilding, I have to delete the app from the simulator or device and do a clean install. This is only for XCode-deployed builds; installing from an ipa doesn't require a clean install. A: Are you sure the file has been marked as localized in the language you are missing? Is this file located in the .proj folder? If both seem to be correct, change something on the xib of this file (eg moving a Btn or so) and recompile then check if you can really see the Btn in the new position. If not, XCode still points to an old version of this file somewhere and does not use the file you think - that happens regularly when renaming files in Xcode. You have to manually get the file back into Xcode - often deleting the file and then drag it back in helps (but not always). Make sure you have a backup of the project before you do any of this - who knows where Xcode is pointing to.... So far I did not find a singe way to correct this - but once you know which file is the problem, playing around with drag and delete etc will always work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iOS Contacts Favorites I am trying to access the favorite contacts via the private frameworks. I followed the siphon code and got the frameworks from iOS-Runtime-Headers The code that I wrote to access the list is: NSBundle *b = [NSBundle bundleWithPath:@"/System/Library/Frameworks/AddressBookUI.framework"]; BOOL success = [b load]; Class favs = NSClassFromString(@"ABFavoritesList"); id favList = [favs sharedInstance]; NSLog(@"Favs count = %d", [[favList entries] count]); For some reason the the entries are being fetched as nil. Any help would be appreciated. A: I just tried your code and success is equals to NO, and favs and favList are equals to nil, I guess the AddressBookUI.framework fail to load. After that, I tried adding (linking) my project with the AddressBook.framework and AddressBookUI.framework frameworks, and executing this code (note that the bundle load part is removed): Class favs = NSClassFromString(@"ABFavoritesList"); id favList = [favs sharedInstance]; NSLog(@"Favs count = %d", [[favList entries] count]); and it works. Maybe you can try that. By the way, you probably know it, but it is never a good idea to directly use private code (in this case ABFavoritesList), as this code may change in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IQueryable Question Currently I return everything from my Repo as a List. I am looking to change these to IQueryable just so people can refine the results and not suffer from another sql request(I am using nhibernate). I have a question though to make life easier on everyone I have something like this in my repo public List<CalendarAppointment> GetAppointment(Student student, DateTime start, DateTime end) { List<CalendarAppointment> appointments = session.Query<CalendarAppointment>().Where(x => x.Student.Id == student.Id && x.Start.Date >= start.Date && x.End.Date <= end.Date) .Take(QueryLimits.Appointments).ToList(); return appointments.ConvertToLocalTime(student); } public static List<CalendarAppointment> ConvertToUtcTime(this List<CalendarAppointment> appointments, Student student) { if (student != null) { TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(student.TimeZoneId); foreach (var appointment in appointments) { appointment.Start = TimeZoneInfo.ConvertTimeToUtc(appointment.Start,info); appointment.End = TimeZoneInfo.ConvertTimeToUtc(appointment.End,info); } } return appointments; } So I get currently the results back and then convert the times into local time. This way we don't have to worry about it. What happens if I do this with IQueryable. Will it go off and trigger the sql anyways? A: Currently I return everything from my Repo as a List. I am looking to change these to IQueryable just so people can refine the results and not suffer from another sql request(I am using nhibernate). There are few potential problems with what you have right now and how you want to fix it. Repository should not return all objects in the first place. It encapsulates data access and provides business-driven 'collection like' interface. Repository implementation belongs to data access layer that is smart enough to not return everything: ordersRepo.FindDelinquent(); Returning IQueryable from public method is not the solution itself, it just shifts the problem somewhere else, somewhere where it does not belong. How would you test the code that consumes this repository? What is the point of generic repository, you might as well just use NHibernate directly and couple everything to it. Please take a look at these two articles and this answer: * *How To Write A Repository *The Generic Repository Timezone conversion can be moved to the CalendarAppointment itself: DateTime end = appointement.EndTimeInStudentTimeZone(Student t) or in List<CalendarAppointment> appts = GetAppointmentInStudentTimeZone( Student student, DateTime start, DateTime end) Or better yet convert it before you actually need to use these times (in UI or Service).
{ "language": "en", "url": "https://stackoverflow.com/questions/7533179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generate .exe from my web service So I have created a Web Service the same way as every other one I normally create. Problem is, I want to run it to test if it starts correctly. If I right click the project -> properties -> debug, you should be able to tell it to start an external .exe which always seemed to be in the /bin/debug folder of the solution for me, but this project is not generating one, so I can't actually start it. Do you know if there's a setting where I can get it to generate an .exe? A: I think the best approach would be to create a console app which starts your service this will be your server and you could make a console app as a test client or use some Test framework for testing your service like NUnit MS-Test A: To test a WCF you can use the WCF Test Client C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\WcfTestClient.exe You then start debugging (f5) your WCF application and add the service URL to the test client If you are using a webservice then you can start debugging (f5) and since it is local you can pass non complex parameters to test the methods, otherwise you would need to create a new project to test the service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect the number of times a word shows up in a string - iphone xcode objective-c iphone xcode objective-c: I have a string with alot of text.. I want to detect how many times @"hello" is in the string... I know how to detect if it is or isn't but how do I detect the number of times it appears in the string? A: You can use regular expressions for this: NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\bhello\\b" options:NSRegularExpressionCaseInsensitive error:NULL]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:someString options:0 range:NSMakeRange(0, [string length])]; A: NSUInteger count = 0, length = [yourString length]; NSRange range = NSMakeRange(0, length); while(range.location != NSNotFound) { range = [yourString rangeOfString: @"hello" options:0 range:range]; if(range.location != NSNotFound) { range = NSMakeRange(range.location + range.length, length - (range.location + range.length)); count++; } } A: NSRegularExpression *aRegex = [[NSRegularExpression alloc] initWithPattern:@"Hello" options:NSRegularExpressionCaseInsensitive error:nil]; NSString *targetString = @"Hello, Albert! Hello, again!"; NSInteger numberOfMatches = [aRegex numberOfMatchesInString:targetString options:0 range:NSMakeRange(0, [targetString length])]; [aRegex release]; NSLog(@"number of matches: %d", numberOfMatches); // 2 You may need to play a little with the regex.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Export a class from a CoffeeScript file If I have a CoffeeScript class defined in a separate file, which I'm calling from my main script, I can make the functions within the file globally visible, but not the class. The included file is: root = exports ? this root.add = (a, b) -> return a + b class root.userModel username: 'Aaaa' name: 'Bbbb' I can access the function from my main code. How can I create the class? A: Your code will indeed make userModel a global, assuming that exports is undefined and this is window. If you're having problems, check those conditions. A: The class ... form is an expression that returns a value. So, you'll want to assign the result of that class expression to a property on your export object. Like so: root.userModel = class userModel username: 'Aaaa' name: 'Bbbb' Update: Oops, not true, should work fine either as class root.userModel or as root.userModel = class userModel. A: Just define your class with a '@' before its name: class @ClassName blablabla: -> blablalblablabla
{ "language": "en", "url": "https://stackoverflow.com/questions/7533191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: RTOS: windows ce : Real mode and protected mode memory accessibility overhead I have a control loop between hardware and software using RTOS: windows ce. I read data in from a device through Real mode. I process the data in protected mode, due to limited memory in Real mode. I then switch back to real mode to set another device based on results. There is a lot of overhead in this and it slows things down. Is there a way to access the same memory on the heap? Is there a means of making this efficient so the overhead is at a minimum? thanks A: Use the VirtualCopy API to map physical addresses into a process's virtual address space. There should be no need to drop down to real mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using metasearch's contains search option for non-string data types While using metasearch gem to do a somewhat complex search I got an error when using the "_contains" option an numerical(decimal) field and later found out in the documentation that it in only works on string data type fields. Since metasearch doesn't work with virtual attributes I can't think of a way to achieve this .Are there any workarounds for this? Thanks, Alex
{ "language": "en", "url": "https://stackoverflow.com/questions/7533198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Would This Be A Simple iPhone App to Create? I created and launched an Android app a couple months ago (with lots of help from this site, thanks!). Well, I've a made a couple hundred dollars. So naturally I'm thinking that if I can sell this on Android,it should sell on the iPhone. I pieced together the Android app by just searching forums on the individual parts of the app. I don't have a Mac or iPhone. But I'm looking to purchase a Mini and borrow a friends iPhone 3. However, since creating the Android app was free, I'm wondering if creating it on iPhone would be fairly simple before I drop $800 on a mini and developer's license. Would this type of app be fairly easy to make? * *Splash screen - 3 seconds *Main Menu with 5 buttons. Each button leads to a sub menu *Sub Menu with anywhere from 3-9 image buttons. Each button goes a full view of the image. *Full screen view - has play button, which when pressed, plays a 3-6 second video. Example: * *Main Menu - Buttons that say: Cat, Dog, Fish, whatever. Users selects Dog *Sub Menu (thumbnail images act as buttons)- Retriever, Lab, German Shepherd,... User selects Retriever *Full image view of Retriever with a play button. User selects play button. *Video is played of Retriever running around. It was pretty simple on Android but without any experience with Objective C and such, I'm not sure how difficult it would be to build on iPhone. Also, I'm not thinking that this would be a quick app for me to build. Because I started with no experience in Java and using Eclipse, my android app took me about 100 hours to create. I've seen on here suggestions for checking out the Standford iPhone course in iTunes as well as a few other sites for reference. One thing to mention is that I have Flash Professional 5.5. I read that I could use this to create an iPhone app as well (without having to purchase a mac). I've never used flash before. Would this program be easy to create in Flash as well. Ideally, I know it's better to create in native code, but this would save me purchasing a mini. Thanks again. A: All things are relative, of course, but that's about as simple as apps get. The splash screen is simply a case of dropping an image in, the main menu is just a load of buttons, you can use a navigation controller to go from screen to screen, an image view for the full screen image, and a movie player to play the movie. There's very little code to write, it's just hooking up things that are built into the platform. A: Yes this app is about as simple as you can get while still including a decent range of concepts for a starter project (multiple controllers, buttons, videos, images). I think it would make a good introduction project to Objective-C and CocoaTouch (the iOS interface APIs -- which at least in my opinion are much more intuitive than the Android APIs). Objective-C is very similar to Java in concept, just very different in syntax. Once you get over the syntax differences, you should feel right at home. I learned in the opposite direction, but I was able to pick up Java very quickly because of my Objective-C knowledge. I think it should be similarly easy to go the other way. I highly recommend you utilize Apple's documentation. They do a great job of explaining everything without needing to read third party books. I learned iOS programming directly from the Apple documentation without even having any object oriented programming experience (I had only done some light procedural PHP). The first thing you should read is this guide for an overview of Objective-C: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html Then spend a day before you even touch the code reading this guide for a good overview of iOS programming concepts: http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Introduction/Introduction.html Then just utilize the iOS class references first (usually just searching google for a class name like UIView will have the class reference as the top link) and this site for everything else. That should be all you need. You can buy some iOS books if you want, but I haven't found them necessary. A: Sample codes are available that can easily help you figure out how to implement features. http://developer.apple.com/library/ios/navigation/#section=Resource%20Types&topic=Sample%20Code I would recommend once you have the mac for programming, taking a look at the same code. In Xcode 4 you can hit the alt key and select an object such as NSString or UILabel and it will show you quick references and then you can go to the resourced material from it. For the type of app you are wanting to do, it would easily be possible to perform the actions you listed. I have done them in some of my apps. A standard view with your splash screen on it and you can use interface builder for a lot of the things you want to display. I would recommend watching tutorial videos on the web for insight on how things work. You can pick up a lot of basics. Just be careful not to pick up bad habits. If in doubt refer the apple docs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Catch-all Controller/Route If I want to catch every single non existing URL that was passed to my web application and serve them a view without serving a 404, how would I do that? Essentially I need to record the statistics based on these hits, but I need to do it by serving content and not a 404 error. As far as I can tell from application/config/routes.php, I could use $route['default_controller'] = 'catchall'; but I need that for my actual web application. I could also use $route['404_override'] = 'catchall'; but I don't want to throw 404s. I tried using $route['(:any)'] = '$1'; but I need to record the entire URL (e.g. any length of segments), not just the first segment. A: Use $route['(:any)'] = 'catchall_controller'. Then in your controller you can access the URI segments using $this->uri->segment(n). A: Have you tried adding multiple catch all routes for different amounts of segments? $route['(:any)'] = '$1'; $route['(:any)/(:any)'] = '$1/$2'; $route['(:any)/(:any)/(:any)'] = '$1/$2/$3'; I'm guessing that would work, but there might be a more elegant way to do it. A: I don't know the difference between codeigniter and normal PHP, but, in normal php, you can edit the htaccess or whatever to define a custom 404 page. In the custom 404 page, do something like the equivalent of this: $requested=$_SERVER['REQUEST_URI']; to get the URL which was requested.... do your handling... and do this to clear the 404: header("HTTP/1.1 200 OK"); header("Status: 200 OK"); Then, include your html or whatever you want to serve.
{ "language": "en", "url": "https://stackoverflow.com/questions/7533201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Using raw sockets with C# I want to write a port scanner in C# and I can't use SocketType.Raw as raw sockets were taken out from desktop versions of windows. I can't use SharpPcap either or other wrapper for Winpcap as I use PPPoE for internet connection and Winpcap doesn't support PPP devices. I need to use a library which implements raw sockets and doesn't rely on winpcap. Any ideas? Basically I need to send SYN, receive SYN/ACK or RST but don't send ACK back. edit: For people who doesn't believe RAW sockets are gone from desktop versions of Windows, see here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms740548(v=vs.85).aspx On Windows 7, Windows Vista, Windows XP with Service Pack 2 (SP2), and Windows XP with Service Pack 3 (SP3), the ability to send traffic over raw sockets has been restricted in several ways: * *TCP data cannot be sent over raw sockets. *UDP datagrams with an invalid source address cannot be sent over raw sockets. The IP source address for any outgoing UDP datagram must exist on a network interface or the datagram is dropped. This change was made to limit the ability of malicious code to create distributed denial-of-service attacks and limits the ability to send spoofed packets (TCP/IP packets with a forged source IP address). *A call to the bind function with a raw socket for the IPPROTO_TCP protocol is not allowed. Note The bind function with a raw socket is allowed for other protocols (IPPROTO_IP, IPPROTO_UDP, or IPPROTO_SCTP, for example). A: Take note on how nmap did it and that for now I believe your option would be to go to a lower level at the ethernet frame. "Nmap only supports ethernet interfaces (including most 802.11 wireless cards and many VPN clients) for raw packet scans. Unless you use the -sT -Pn options, RAS connections (such as PPP dialups) and certain VPN clients are not supported. This support was dropped when Microsoft removed raw TCP/IP socket support in Windows XP SP2. Now Nmap must send lower-level ethernet frames instead." So - that brings us to: http://www.codeproject.com/KB/IP/sendrawpacket.aspx A: Just like this: http://www.winsocketdotnetworkprogramming.com/clientserversocketnetworkcommunication8h.html Also, at what point was it removed from Windows? I did a chat client for a friend last week; as well, http://msdn.microsoft.com/en-us/library/system.net.sockets.sockettype.aspx , still lists it as being active. A: Try running Visual Studio as Adminitrator Right click ---> run as administrator Then execute programs with raW sockets..
{ "language": "en", "url": "https://stackoverflow.com/questions/7533205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }