text
stringlengths
8
267k
meta
dict
Q: WCF Data Services with Custom Entities I have a set of custom entities which reflect the business representation of data. Then I also have a set of entities that map 1-to-1 to the database that represent the storage of the data. My business layer converts between the 2 types and performs any other logic needed. I only expose the custom objects through my service interface. From what I can tell I cannot use WCF Data Services. Data services * *need to be bound directly to a db source (or some slight abstraction of the direct db connection) and, *that results in using the data entities. Correct me if I'm wrong, but I can't see any way to use WCF Data Services and its built-in queryability with custom entities while using my business layer. A: I do not necessarily agree with that. If you look at the Architecture Overview in http://msdn.microsoft.com/en-us/library/cc668794.aspx you see two other options next to the EF / DB connectivity. You can have Data Service Providers that just take an alternative (your custom) information model made up of queryable CLR classes and expose them using WCF data services. So if you create your Business Layer using this approach, your custom entities can just as easy be exposed with WCF data services.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I use two datasources in a CFQUERY? I am using ColdFusion 9.1. I need to use two different datasources in some of my queries. I know it can be done because I see other code that uses two different datasources and it works fine. I've tried lots of combinations but can't get anything to work, but I know that both of my datasources are working properly. I have a default database set up in the THIS scope. The default is "DatasourceOne". <cfquery> SELECT UserID FROM DatasourceOne.TableOne IN (SELECT Userid FROM DatasourceTwo.TableTwo ) </cfquery What are the rules or guidelines about using multiple datasources? CLARIFICATION I should have originally asked how I could use two database (not datasources) in a single query. I am sure your answers would have been different. We do have both databases set up as datasources though and I was a little confused myself. A: ColdFusion can only talk to one data*source* at a time in a given query. However, if you need to talk to more than one data*base* on the same server, you can do that by explicitly giving the full paths to the databases, tables, and columns you need to access or join together. Also note that the user that the data*source* in ColdFusion is configured to use must have access to both databases in order for this to work. A: Depending on your database, if the second database is on the same server (or is defined as a linked server) and the user in the datasource has permission, you can usually reference the other database. SELECT * FROM myTable WHERE myField IN (SELECT otherField FROM otherDatabase.dbo.tableName) A: You can't talk to two CF (JDBC) datasources in a single CFQUERY. What you can do: * *Use two databases on the same datasource. For example, if you have a SQL Server instance with two database you can run a query through the JDBC connection that talks to both databases. This looks like what you're describing in your question. Here's a more thorough explanation. *Use Queries of Queries. Pull your data from the two database individually and join the results using a QoQ in your CFC or page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: ASP.NET Permission Frameworks? Problem ASP.NET has no concept of associating permissions to roles. My app Current web application is using custom user membership and role providers. The app has 4 roles: superuser, admin, principal, and teacher. When the user logs in, they are redirected to their appropriate UI. For example, admins are redirected to admin interface, teachers are redirected to teacher interface. Each interface has its own master page and aspx pages. A new requirement is that teachers are no longer allowed to view specific information or do specific functions. Information could be a field or a row in a gridview control, it could be functional as well (e.g. not able to click on a link to open a popup window, but still be able to see the link's text). Other roles also have need of specific "permission" requirements, but completely different than the teachers ones. Proposed Solution Create a database table to centralize mapping of permissionsToRoles like so: CREATE TABLE [dbo].[PermissionToRole]( [PermissionID] [int] IDENTITY(1,1) NOT NULL primary key, [Role] int NOT NULL, [Control] [varchar](50) NOT NULL, [ControlType] [varchar](50) NOT NULL, [Function] [varchar](50) NOT NULL, [Read] [bit] NULL, [Write] [bit] NULL, [Execute] [bit] NULL, [Delete] [bit] NULL ) Using the link example above we would get something like: "teacher", "labelName", "asp:label", "click", 1, 0, 0, 0 (can read the link but not "execute" the click) The plan is to be able to do a few things: * *Use permissions to consolidate multiple aspx and logic into a single page (aspx). To reduce maintenance every time a new role is needed. *Control at a all levels (tab -> control) a roles' aka groups' permissions. E.g. use this table to control visibility of controls at every level (tab, page, control). As well as individual functionality (e.g. click on a link control) *Control what data is returned to the UI and what CRUD operations are allowed. Are there frameworks out there for ASP.NET that can do this already? I'm pretty sure Content Management Systems (CMS) can do this, but this app will not use a CMS :). I really want to avoid reinventing the wheel. Thanks! A: Look at AzMan. I have a feeling that it's what you seek. With AzMan you define operations and check if user authorized to do an operation in code. You can then define which roles allowed to do which operations and assign roles to users -- because you're checking against operations, not roles, no code changes will be necessary if you want to introduce a new role or reassign operations between roles. A: Decided on trying NetSqlAzMan because: * *Not COM and IS .NET 4 *RDBMS for Data Store *AOP (Aspect Oriented Programming) (Can use attributes instead of massive if/else checks) *Lously coupled *Handles Permissions to Roles scenarios *Free A: In truth, the ASP.net membership controls ought to be able to do what you want. Setting up a database with the appropriate schema allows you to use a huge suite of methods and objects to control user access. Like Luis mentions, you can access control pages and folders to certain roles, but if you want to lock out individual functions based on a user's role, you can use the IsUserInRole() method. There isn't a whole lot of point in reinventing the wheel if you can use a built-in, well-tested process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Help with an if then statement. Apple Remote Desktop and setting Computer Info Field This is a great script for network admins. It's able to set the AppleCare expiration date of the computer the script is run on in a computer info field allowing for easy sorting in Apple Remote Desktop. My issue is when a computer has an expired warranty I would like the script to set the info field to "Out of Coverage". The script runs as is and I've commented out the code that I think will be needed to do this. Any help would be appreciated. Thanks everyone. #!/bin/bash # warranty.sh # Description: looks up Apple warranty info for # this computer, or one specified by serial number # Based on a script by Scott Russell, IT Support Engineer, # University of Notre Dame # http://www.nd.edu/~srussel2/macintosh/bash/warranty.txt # Edited to add the ASD Versions by Joseph Chilcote # Last Modified: 09/16/2010 # Edited 02/10/2011 # Updated support url # Added function to write data to plist ## Add function to cycle through a csv file ############### ## GLOBALS ## ############### # make sure you use a full path PlistLocal=".appwarranty.plist" WarrantyTempFile="/tmp/warranty.txt" AsdCheck="/tmp/asdcheck.txt" if [[ $# == 0 ]] ; then SerialNumber=`system_profiler SPHardwareDataType | grep "Serial Number" | grep -v "tray" | awk -F ': ' {'print $2'} 2>/dev/null` else SerialNumber="${1}" fi [[ -n "${SerialNumber}" ]] && WarrantyInfo=`curl -k -s "https://selfsolve.apple.com/warrantyChecker.do?sn=${SerialNumber}&country=USA" | awk '{gsub(/\",\"/,"\n");print}' | awk '{gsub(/\":\"/,":");print}' | sed s/\"\}\)// > ${WarrantyTempFile}` curl -k -s https://github.com/chilcote/warranty/raw/master/asdcheck -o ${AsdCheck} > /dev/null 2>&1 ################# ## FUNCTIONS ## ################# AddPlistString() { # $1 is key name $2 is key value $3 plist location # example: AddPlistString warranty_script version1 /Library/ETC/appwarranty.plist /usr/libexec/PlistBuddy -c "add :"${1}" string \"${2}\"" "${3}" } SetPlistString() { # $1 is key name $2 is key value $3 plist location # example: SetPlistString warranty_script version2 /Library/ETC/appwarranty.plist /usr/libexec/PlistBuddy -c "set :"${1}" \"${2}\"" "${3}" } GetWarrantyValue() { grep ^"${1}" ${WarrantyTempFile} | awk -F ':' {'print $2'} } GetWarrantyStatus() { grep ^"${1}" ${WarrantyTempFile} | awk -F ':' {'print $2'} } GetModelValue() { grep "${1}" ${WarrantyTempFile} | awk -F ':' {'print $2'} } GetAsdVers() { #echo "${AsdCheck}" | grep -w "${1}:" | awk {'print $1'} grep "${1}:" ${AsdCheck} | awk -F':' {'print $2'} } ################### ## CREATE PLIST ## ################### if [[ ! -e "${PlistLocal}" ]]; then AddPlistString warrantyscript version1 "${PlistLocal}" for i in purchasedate warrantyexpires warrantystatus modeltype asd do AddPlistString $i unknown "${PlistLocal}" done fi ################### ## APPLICATION ## ################### echo "$(date) ... Checking warranty status" InvalidSerial=`grep "wc.check.err.usr.pd04.invalidserialnumber" "${WarrantyTempFile}"` ### # this is the part I'm struggling with # ### # # WarrantyStatus=`GetWarrantyStatus HW_SUPPORT_COV_SHORT` # echo "WarrantyStatus == ${WarrantyStatus}" # SetPlistString warrantystatus "${WarrantyStatus}" "${PlistLocal}" # ### # if above is equal to "Out of Coverage" then # /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -configure -computerinfo -set4 -4 "Out of Coverage" # and stop # Else do below ### if [[ -e "${WarrantyTempFile}" && -z "${InvalidSerial}" ]] ; then WarrantyExpires=`GetWarrantyValue HW_END_DATE` echo "WarrantyExpires == ${WarrantyExpires}" SetPlistString warrantyexpires "${WarrantyExpires}" "${PlistLocal}" else if [[ -z "${SerialNumber}" ]]; then echo " No serial number was found." SetPlistString warrantystatus "Serial Not Found: ${SerialNumber}" "${PlistLocal}" fi if [[ -n "${InvalidSerial}" ]]; then echo " Warranty information was not found for ${SerialNumber}." SetPlistString warrantystatus "Serial Invalid: ${SerialNumber}" "${PlistLocal}" fi fi #################################### ## MONTH CONVERSION & ARD ENTRY ## #################################### expdate=`date -j -f "%B %d, %Y" "${WarrantyExpires}" "+%Y-%m-%d"` /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -configure -computerinfo -set4 -4 "$expdate" exit 0 A: Seems pretty straightforward. I assume the WarrantyStatus variable is the thing that's supposed to hold this string: if [[ "$WarrantyStatus" = "Out of Coverage" ]]; then .../kickstart -configure -computerinfo -set4 -4 "$WarrantyStatus" exit fi
{ "language": "en", "url": "https://stackoverflow.com/questions/7574109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Saving URL content with javascript and pass it to PHP as variable I want to save the url content of some website with javascript (from a client side) and pass it over as a variable to my php file, it's ok that the javascript will be in the php file. is there a way to do so? A: from javascript to php you have to use form submit, change url including query parameters, or ajax
{ "language": "en", "url": "https://stackoverflow.com/questions/7574114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSF 2 facelets in template and page I have the following template (masterLayout.xhtml): <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets"> <f:view contentType="text/html"> <ui:insert name="metadata"/> <h:head> <title><ui:insert name="windowTitle"/> | MySite</title> </h:head> <h:body> <div id="container"> <div id="header"> <ui:insert name="header"> <ui:include src="/WEB-INF/templates/header.xhtml"/> </ui:insert> </div> <div id="content"> <ui:insert name="content"/> </div> <div id="footer"> <ui:insert name="footer"> <ui:include src="/WEB-INF/templates/footer.xhtml"/> </ui:insert> </div> </div> </h:body> </f:view> </html> and page that uses it (search.xhtml): <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <title></title> </h:head> <h:body> <ui:composition template="/WEB-INF/templates/masterLayout.xhtml"> <ui:define name="metadata"> <f:metadata> <f:viewParam name="address" value="#{searchBean.address}"/> <f:event type="preRenderView" listener="#{userSessionBean.preRenderViewCookieLogin(e)}"/> <f:event type="preRenderView" listener="#{searchBean.preRenderView(e)}"/> </f:metadata> </ui:define> <ui:define name="windowTitle">#{searchBean.address}</ui:define> <ui:define name="content"> <!-- Content goes here --> </ui:define> </ui:composition> </h:body> </html> The problem is that I want to place the call to userSessionBean.preRenderViewCookieLogin(e) in the template because there are many other pages. This method checks that the user is logged in (according to session state) and, if not, checks that a cookie is available which can be used to log the user in and, if so (and if valid), logs the user in automatically. The system works in the code above, but when I try to push this into the template, my view parameters are no longer being set. Here's the modified version of the above, with userSessionBean.preRenderViewCookieLogin(e) pushed up to the template. masterLayout.xhtml: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets"> <f:view contentType="text/html"> <f:metadata> <f:event type="preRenderView" listener="#{userSessionBean.preRenderViewCookieLogin(e)}"/> <ui:insert name="metadata"/> </f:metadata> <h:head> <title><ui:insert name="windowTitle"/> | MySite</title> </h:head> <h:body> <div id="container"> <div id="header"> <ui:insert name="header"> <ui:include src="/WEB-INF/templates/header.xhtml"/> </ui:insert> </div> <div id="content"> <ui:insert name="content"/> </div> <div id="footer"> <ui:insert name="footer"> <ui:include src="/WEB-INF/templates/footer.xhtml"/> </ui:insert> </div> </div> </h:body> </f:view> </html> search.xhtml <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <title></title> </h:head> <h:body> <ui:composition template="/WEB-INF/templates/masterLayout.xhtml"> <ui:define name="metadata"> <f:viewParam name="address" value="#{searchBean.address}"/> <f:event type="preRenderView" listener="#{searchBean.preRenderView(e)}"/> </ui:define> <ui:define name="windowTitle">#{searchBean.address}</ui:define> <ui:define name="content"> <!-- Content goes here --> </ui:define> </ui:composition> </h:body> </html> Notice that I've moved the <f:metadata/> tag to the template. That alone is the problem as removing userSessionBean.preRenderViewCookieLogin(e) makes no difference. I also tried a variation on the code that worked, which was to just move userSessionBean.preRenderViewCookieLogin(e) into the template which means it can't be inside the <f:metadata/> tag. In this case, that method executed after all the view parameters had been set and searchBean.preRenderView(e) called. I want userSessionBean.preRenderViewCookieLogin(e) to be called before any page's preRenderView(e) is called, not after. And just for fun I tried putting an <f:metadata/> around userSessionBean.preRenderViewCookieLogin(e), which called this method, but didn't set the view parameters. So, I would like to know: * *Why is this happening and is there a way to fix it? *Is there a better way to ensure the same method is called for each page before anything else? Edit: I just tried something else - a phase event: <f:view contentType="text/html" beforePhase="#{userSessionBean.beforePhase(e)}"> This is in masterLayout.xhtml. It is not being called at all; not for any phase. Edit: Removed the e (damn you NetBeans!): <f:view contentType="text/html" beforePhase="#{userSessionBean.beforePhase}"> This is only called before the render response phase, which of course means it's called after the preRenderView event is raised. A: Why is this happening and is there a way to fix it? From the <f:metadata> tag documentation (emphasis of 2nd paragraph is mine): Declare the metadata facet for this view. This must be a child of the <f:view>. This tag must reside within the top level XHTML file for the given viewId, or in a template client, but not in a template. The implementation must insure that the direct child of the facet is a UIPanel, even if there is only one child of the facet. The implementation must set the id of the UIPanel to be the value of the UIViewRoot.METADATA_FACET_NAME symbolic constant. So, it really has to go in the top view, not in the template. Is there a better way to ensure the same method is called for each page before anything else? In your particular case, store the logged-in user as a property of a session scoped managed bean instead of a cookie and use a filter on the appropriate URL pattern to check it. Session scoped managed beans are in the filter available as HttpSession attributes. Homegrown cookies are unnecessary as you're basically reinventing the HttpSession here. Unless when you want a "remember me" facility, but this should not be solved this way. Do it in a filter as well. See also: * *Prevent accessing restricted page without login in Jsf2 A: I got this working using a PhaseListener instead. public class CookieLoginPhaseListener implements PhaseListener { @Override public void beforePhase(PhaseEvent event) { } @Override public void afterPhase(PhaseEvent event) { UserSessionBean userSessionBean = Util.lookupCdiBean("userSessionBean"); userSessionBean.handleAuthCookie(); } @Override public PhaseId getPhaseId() { return PhaseId.RESTORE_VIEW; } } and the little bit of bean lookup magic is here: public static <T> T lookupCdiBean(String name) { return (T) FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{" + name + "}", Object.class); } Thanks to @BalusC for this: JSF - get managed bean by name. Since I'm using CDI, I can't use the more declarative @ManagedProperty option. Not a big deal though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: to OLAP or not to OLAP I want to ask what are the performance gains of pulling reports in Sharepoint 2010 directly from an Oracle DW using an ODBC Connection as opposed to building an OLAP Layer using SSAS and accessing the data that way. A: It sounds like you're confusing terminologies and technologies. Comparing ODBC to OLAP and SSAS is like comparing apples to oranges. They are very different things used for very different purposes. The commonality is that they both deal with data... and apples and oranges are both fruit. But, trying to read between the lines, OLAP, if configured correctly, will deliver actionable information (biz intel etc.) much more quickly and readily than data aggregated from a standard RDBMS. After all, that's what OLAP is designed for: In computing, online analytical processing, or OLAP (play /ˈoʊlæp/), is an approach to swiftly answer multi-dimensional analytical (MDA) queries.1 OLAP is part of the broader category of business intelligence, which also encompasses relational reporting and data mining.[2] A: Now that SQL Server 2012 is released, you may want to look into building a BISM (using SSAS) over your Oracle data and then displaying the results in SharePoint. Although you can use the 'PowerPivot on SharePoint' mode to be able to host (render) the BISM using SharePoint resources, you'd rather get a separate server to host SSAS, so that effort of rendering (presumably) large reports doesn't slow down your SharePoint server. Of course it is still possible build an OLAP cube using SSAS, but unless you need one or more of the features not yet available in the BISM model, you'd rather just build a BISM than an OLAP cube, as the BISM leverages Vertipaq (so it's simpler to build, i.e. requires less ETL from Oracle). For more check out my deck on slideshare on the BISM
{ "language": "en", "url": "https://stackoverflow.com/questions/7574117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EXC_BAD_ACESS error I get that error EXC_BAD_ACESS at the following line: NSString *titleVarName = [[NSString alloc] initWithFormat:@"%@%@",@"occasionTitle",i]; Here is the for loop where the above code line is located: for (i=0; i < count; ++i) { //Save the occasionS details to NSUserDefaults NSString *titleVarName = [[NSString alloc] initWithFormat:@"%@%@",@"occasionTitle",i]; NSString *dateVarName = [[NSString alloc] initWithFormat:@"%@%@",@"occasionDate",i]; NSString *imageVarName = [[NSString alloc] initWithFormat:@"%@%@",@"occasionImage",i]; [[NSUserDefaults standardUserDefaults] setValue:[[[self displayedObjects] objectAtIndex:i] title] forKey:titleVarName]; [[NSUserDefaults standardUserDefaults] setValue:[[[self displayedObjects] objectAtIndex:i] date] forKey:dateVarName]; [[NSUserDefaults standardUserDefaults] setValue:[[[self displayedObjects] objectAtIndex:i] imagePath] forKey:imageVarName]; //release [titleVarName release]; [dateVarName release]; [imageVarName release]; [self dismissModalViewControllerAnimated:YES]; } Isn't ok to alloc objects and release them inside a for loop? A: Assuming i is an int, that line should be NSString *titleVarName = [[NSString alloc] initWithFormat:@"%@%i",@"occasionTitle",i]; %@ is used for Cocoa objects, not primitives like an int, float or bool; A: You need to use %d or %i specifier instead of %@ to specify an integer. If %@ is used with int then it will try to access the object at the address specified by the int. For example, if the value of i is one then it is trying to access the object at address one which will cause a bad access. NSString *titleVarName = [[NSString alloc] initWithFormat:@"%@%d",@"occasionTitle",i]; And also you don't need alloc and release here, though that is not the reason of bad access. You can use a convenience constructor. NSString *titleVarName = [NSString stringWithFormat:@"occasionTitle%d", i]; // release not required Do the same for dateVarName and imageVarName too. A: Use the %@ format specifier only for NSObject objects. As i is an integer in your code, you have to use %d or %i for integers. Moreover, there is no need to include the string using %@, you can use the static string directly in your format string: NSString *titleVarName = [[NSString alloc] initWithFormat:@"occasionTitle%i",i];
{ "language": "en", "url": "https://stackoverflow.com/questions/7574124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiplying a matrix and a vector in GLM (OpenGL) I have a transformation matrix, m, and a vector, v. I want to do a linear transformation on the vector using the matrix. I'd expect that I would be able to do something like this: glm::mat4 m(1.0); glm::vec4 v(1.0); glm::vec4 result = v * m; This doesn't seem to work, though. What is the correct way to do this kind of operation in GLM? Edit: Just a note to anyone who runs into a similar problem. GLM requires all operands to use the same type. Don't try multiplying a dvec4 with a mat4 and expect it to work, you need a vec4. A: glm::vec4 is represented as a column vector. Therefore, the proper form is: glm::vec4 result = m * v; (note the order of the operands) A: Since GLM is designed to mimic GLSL and is designed to work with OpenGL, its matrices are column-major. And if you have a column-major matrix, you left-multiply it with the vector. Just as you should be doing in GLSL (unless you transposed the matrix on upload).
{ "language": "en", "url": "https://stackoverflow.com/questions/7574125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: What's the difference between adding and cloning a remote repository? What's the difference between adding a remote repository and cloning a remote repository? I'm reading the pragmatic guide to git and they are talking about distributed environments and using git remote add. I'm finding the section difficult to understand, and why I should use it over clone. Many thanks A: Using git remote add is connecting another (remote) repository to the current repository so you can pull and push with the remote repository. For example, I do this when I push things to Github, because I already have my own "master" repository as origin. Using git clone creates a new repository on your local system that is set up to connect to a remote repository. I would do this when getting a clone of another published project from somewhere, or making another copy of one of my own projects (perhaps on a different computer). A: Git clone sets up a new repository similar to the one you are cloning ( hence the name clone!) and "adds" the remote repository from which you cloned as the remote with the name origin Just doing the last part of setting up a remote is "adding a remote repository" and doing the whole thing and getting a new clone is cloning. Note that when you add a remote repository, you already have a repository. When you clone, you do not already have the repository. A repository can have muliple remotes added to it via git remote add. Usually these are remote repositories of the same repo's clones on peers and servers with which you push and pull.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Which version TortoiseHG and Mercurial are compatible and stable for Linux RedHat ? I am thinking about installing Mercurial and TortoiseHG for our redhat linux server. I found out there are many package versions. I searched online and found out some people encounter incompatible problems when they install Mercurial and TortoiseHG. If anyone has successfully install TortoiseHG and Mercurial, may I know what versions you used for TortoiseHG and Mercurial ? I used command "cat /etc/redhat-release" to find the version of my linux is" Red Hat ENterprise Linux CLient release 5.3 (Tikarga) and the bits number is "x86_64". Python is version 2.4.3. I do not need to use the latest version as long as they are stable and compatible. Thank you very much, A: TortoiseHG is mainly known for being a Windows shell extention, but there also seems to be a Linux version. Take a look at the description on the web site (I made the important parts bold): TortoiseHg is a Windows shell extension and a series of applications for the Mercurial distributed revision control system. It also includes a Gnome/Nautilus extension and a CLI wrapper application so the TortoiseHg tools can be used on non-Windows platforms. and: Supported Platforms Microsoft Windows XP, Vista, Windows 7 Command line support via thg Mac OS X port via source install Gnome/Nautilus integration Note the link in the second part. Plus, there are non-Windows versions on the download page. There is also this section in the release notes which describes which TortoiseHG version should be used with which Mercurial version if you have to install from source (which seems to be the case whan you're using Linux, as I understood it). EDIT: Sorry, but I have absolutely no clue about Linux, so I can't help you about the installation. What I can tell you is that msi files are usually Windows installer files. As I said, I have no clue about Linux, but I can hardly imagine that you can get a Windows installer to work on Linux. Where exactly did you see the TortoiseHG packages? The Nautilus link I posted above doesn't have any msi downloads (or I don't see them). The only msi downloads that I can find are the Windows-only downloads on the download page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: splitting a delimited field into separate columns in same record I need to split a pipe-delimited field ('Y|N|Y|Y'). I found the recursive function listed here T-SQL: Opposite to string concatenation - how to split string into multiple records but it creates the values into new records. row field 1 Y 2 N 3 Y 4 N I need to transform 'Y|N|Y|Y' field 'Y|N|Y|Y' into field1 | field2 | field3 | field4 y N Y N Can someone point me in the right direction? Would it make it easier if I said the number of values is fixed (it will probably be 8 values delimited in one field). Update: A possible field value could be this (note the blank value): 'Y|10|N|1||Y' A: If the widths of the fields are always fixed as well, i.e., 1 character (Y/N), then it's as simple as using the substring function to get all the individual field values: ;with Data as ( select 'Y|N|Y|Y' as choices union select 'Y|Y|Y|Y' as choices union select 'Y|N|N|Y' as choices union select 'Y|N|N|N' as choices union select 'N|N|Y|N' as choices union select 'Y|Y|N|Y' as choices ) select substring(choices, 1, 1) as field1, substring(choices, 3, 1) as field2, substring(choices, 5, 1) as field3, substring(choices, 7, 1) as field4 from Data Output: field1 field2 field3 field4 N N Y N Y N N N Y N N Y Y N Y Y Y Y N Y Y Y Y Y If you can't guarantee that the widths of the fields are the same, you can make use of charindex and a helper table of field indexes to generate the output you are looking for. This becomes very verbose as the number of fields grows larger, but you should only have to write it once if the number of fields is going to be fixed: ;with Data as ( select 1 as id, 'Y|N|Y|Y' as choices union select 2,'Y|Y|Y|Y' as choices union select 3,'Y|No|N|Y' as choices union select 4,'Yes|N|N|N' as choices union select 5,'N|N|Yes|No' as choices union select 6,'Y|Y|N|Yes' as choices ), Fields as ( select id, charindex('|', choices) as field1end, charindex('|', choices, charindex('|', choices) + 1) as field2end, charindex('|', choices, charindex('|', choices, charindex('|', choices) + 1) + 1) as field3end, len(choices) + 1 as field4end from Data ) select substring(choices, 1, field1end - 1) as field1, substring(choices, field1end + 1, field2end - field1end - 1) as field2, substring(choices, field2end + 1, field3end - field2end - 1) as field3, substring(choices, field3end + 1, field4end - field3end - 1) as field4 from Data D inner join Fields F on D.id = F.id Output: field1 field2 field3 field4 Y N Y Y Y Y Y Y Y No N Y Yes N N N N N Yes No Y Y N Yes A: **EDIT: **Mine still works for the sample string Here's an alternative answer, since you know the widths are a fixed length: DECLARE @myString AS nvarchar(20) = 'Y|10|N|1||Y' ;WITH cte AS ( SELECT KeyCol = @@IDENTITY, CONVERT(XML,'<i>' + REPLACE(@myString, '|', '</i><i>') + '</i>') AS delimited_str ) SELECT [1] AS Field1, [2] AS Field2, [3] AS Field3, [4] AS Field4, [5] AS Field5, [6] AS Field6, [7] AS Field7, [8] AS Field8 FROM( SELECT KeyCol, ROW_NUMBER() OVER (partition by KeyCol order by KeyCol)as col_nbr, x.i.value('.', 'VARCHAR(50)') AS delimited_VAL FROM cte CROSS APPLY delimited_str.nodes('//i') AS x(i) ) as PivotedDataTable PIVOT (MAX(delimited_VAL) FOR col_nbr IN ([1], [2], [3], [4], [5], [6], [7], [8]) ) AS PivotTable; EDIT: I knew I saw this somewhere before when I came across a similar problem: http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/381e4164-f1e0-4b54-828f-2795d2cdcb3e/
{ "language": "en", "url": "https://stackoverflow.com/questions/7574129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Showing one row for each calendar week in SQL I have a SQL query which pulls unit sales by item, by week: SELECT sls_vendor, sls_item, sls_units, DATEPART(week, sls_week) AS sls_date FROM mytable Assume I'm looking at a 8 week period, but not every item/vendor combination has a full 8 weeks of sales. However I need my query to show a null value in that instance. So the query would return 8 rows for each item/vendor combination regardless of existence. I tried creating a temp table which has the numbers 28 to 35 and performing a left join on the query above, but that doesn't show null values. The results are no different than running the original query alone. I can think of how this would be done using a crosstab/pivot query, but isn't this something the join should be doing? Edit: Updated to show my join query. Datetable just has 8 rows with 1 incremental number for each calendar week. SELECT * FROM @datetable LEFT JOIN (SELECT sls_vendor, sls_item, sls_units, datepart(week,sls_week) AS sls_date FROM mytable) AS QRY ON temp_week = qry.sls_date A: Does it work for you? SELECT sls_vendor, sls_item, sls_units, DATEPART(WEEK, sls_week) AS sls_date FROM ( SELECT VALUE = 28 UNION ALL SELECT VALUE = 29 UNION ALL SELECT VALUE = 30 UNION ALL SELECT VALUE = 31 UNION ALL SELECT VALUE = 32 UNION ALL SELECT VALUE = 33 UNION ALL SELECT VALUE = 34 UNION ALL SELECT VALUE = 35 ) dates LEFT JOIN mytable m ON dates.value = DATEPART(WEEK, m.sls_week) A: Your method should work just fine: ;with mytable as ( select 1 as sls_vendor, 'Test' as sls_item, 30 as sls_units, '8/7/2011' as sls_week union select 1 as sls_vendor, 'Test' as sls_item, 30 as sls_units, '8/14/2011' as sls_week union select 1 as sls_vendor, 'Test' as sls_item, 30 as sls_units, '8/21/2011' as sls_week ) ,datetable as ( select 28 as temp_week union select 29 union select 30 union select 31 union select 32 union select 33 union select 34 union select 35 ) SELECT * FROM datetable LEFT JOIN (SELECT sls_vendor, sls_item, sls_units, datepart(week,sls_week) AS sls_date FROM mytable) AS QRY ON temp_week=qry.sls_date Output: temp_week sls_vendor sls_item sls_units sls_date 28 NULL NULL NULL NULL 29 NULL NULL NULL NULL 30 NULL NULL NULL NULL 31 NULL NULL NULL NULL 32 NULL NULL NULL NULL 33 1 Test 30 33 34 1 Test 30 34 35 1 Test 30 35 Edit: If you want to include all week values for every sales vendor, include a cross join with the distinct selection of vendors: ;with mytable as ( select 1 as sls_vendor, 'Test' as sls_item, 30 as sls_units, '8/7/2011' as sls_week union select 2 as sls_vendor, 'Test' as sls_item, 30 as sls_units, '8/14/2011' as sls_week union select 3 as sls_vendor, 'Test' as sls_item, 30 as sls_units, '8/21/2011' as sls_week ) ,datetable as ( select 28 as temp_week union select 29 union select 30 union select 31 union select 32 union select 33 union select 34 union select 35 ) SELECT * FROM datetable cross join (select distinct sls_vendor from mytable) v LEFT JOIN (SELECT sls_vendor, sls_item, sls_units, datepart(week,sls_week) AS sls_date FROM mytable) AS QRY ON temp_week=qry.sls_date and v.sls_vendor=qry.sls_vendor Output: temp_week sls_vendor sls_vendor sls_item sls_units sls_date 28 1 NULL NULL NULL NULL 29 1 NULL NULL NULL NULL 30 1 NULL NULL NULL NULL 31 1 NULL NULL NULL NULL 32 1 NULL NULL NULL NULL 33 1 1 Test 30 33 34 1 NULL NULL NULL NULL 35 1 NULL NULL NULL NULL 28 2 NULL NULL NULL NULL 29 2 NULL NULL NULL NULL 30 2 NULL NULL NULL NULL 31 2 NULL NULL NULL NULL 32 2 NULL NULL NULL NULL 33 2 NULL NULL NULL NULL 34 2 2 Test 30 34 35 2 NULL NULL NULL NULL 28 3 NULL NULL NULL NULL 29 3 NULL NULL NULL NULL 30 3 NULL NULL NULL NULL 31 3 NULL NULL NULL NULL 32 3 NULL NULL NULL NULL 33 3 NULL NULL NULL NULL 34 3 NULL NULL NULL NULL 35 3 3 Test 30 35 A: The following query works in Data.StackExchange. See here. It gets the top Post per week by score. WITH weeksyears AS (SELECT w.NUMBER AS week, y.NUMBER AS year FROM (SELECT v.NUMBER FROM MASTER..spt_values v WHERE TYPE = 'P' AND v.NUMBER BETWEEN 1 AND 52) w, (SELECT v.NUMBER FROM MASTER..spt_values v WHERE TYPE = 'P' AND v.NUMBER BETWEEN 2008 AND 2012) y), topPostPerWeek AS (SELECT score, Datepart(week, creationdate) week, Datepart(YEAR, creationdate) YEAR, Row_number() OVER (PARTITION BY Datepart(wk, creationdate), Datepart( YEAR, creationdate) ORDER BY score DESC) row FROM posts) SELECT * FROM weeksyears wy LEFT JOIN topPostPerWeekt ON wy.week = t.week AND wy.YEAR = t.YEAR WHERE row = 1 OR row IS NULL ORDER BY wy.YEAR, wy.WEEK ​ Every row prior to the 38 week in 2008 is empty except for week and year. As well as the rows after the 35 week in 2011. However if you edit the query and remove OR row IS NULL the query will act just as if it were an INNER JOIN My guess is that there's somthing in your WHERE that's referring to the "RIGHT" table. Just add OR [rightTable.field] IS NULL and you'll be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JDBC returning MySQLSyntaxError Exception with correct statement I'm writing an application in java which communicates with a MySQL db, and while I was testing it I noticed that the code to insert new rows in a table threw a MySQLSyntaxError Exception, so I tried to execute the same INSERT using MySQL Workbench, and it worked. The code in question is this: public static boolean aggiungiElem(String nome, GrafoGenerico g){ if(connessioneAperta()){ try{ String sqlCommandUser="SELECT USER()"; String sqlCommandInserim="INSERT INTO salvataggi VALUES ( ? , ? , DEFAULT , NULL );"; PreparedStatement sUser=conn.prepareStatement(sqlCommandUser); ResultSet risultatiUtente=sUser.executeQuery(); String utente = null; while(risultatiUtente.next()){ utente=risultatiUtente.getString(1); } sUser.close(); PreparedStatement sInserim=conn.prepareStatement(sqlCommandInserim); sInserim.setString(1, utente); sInserim.setString(2, nome); //sInserim.setObject(3,g); System.out.println(sInserim.toString()); sInserim.executeUpdate(sqlCommandInserim); sInserim.close(); return true; } catch(SQLException e){ e.printStackTrace(); return false; } } else return false; } EDIT: sorry, the stack trace is: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? , ? , DEFAULT , NULL )' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:407) at com.mysql.jdbc.Util.getInstance(Util.java:382) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2620) at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1664) at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1583) at se.diag.control.clientspec.UtilsClientSQL.aggiungiElem(UtilsClientSQL.java:67) at se.diag.control.clientspec.UtilsClientSQLTest.testAggiungiElem(UtilsClientSQLTest.java:67) at se.diag.control.clientspec.UtilsClientSQLTest.testCaricaElem(UtilsClientSQLTest.java:99) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99) at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81) at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34) at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75) at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45) at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:66) at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35) at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42) at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34) at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196) A: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? , ? , DEFAULT , NULL )' at line 1 Those placeholders ? should not appear in the MySQL side at all. Look here, sInserim.executeUpdate(sqlCommandInserim); you're passing the raw SQL string into executeUpdate() instead of executing the PreparedStatement with the set values. Replace it by sInserim.executeUpdate(); The executeUpdate(sqlString) should be used on Statement only. Unrelated to the concrete problem, you should be closing the PreparedStatement in the finally block to prevent resource leaking in case of exceptions. The same applies to Connection, Statement and ResultSet by the way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to add large amounts of HTML to IE without crippling the CPU i've been experimenting with a more ajax approach to loading data on a page, mostly to avoid postbacks. i can easily acquire server-constructed html via an ajax call and adding it to the dom is simple enough with the help of jquery's .append or .replaceWith. both of these methods are extremely fast in chrome/firefox but terribly slow in ie (7,8,9). $.ajax( { url: url, dataType: 'html', cache: false, success: function (responseHtml) { //document.getElementById('targetElementId').outerHTML = responseHtml; $('#targetElementId').replaceWith(responseHtml); } }); you will see from my code block, i've also attempted to use a non-jquery approach. both lines perform horrendously in ie. so my question, what is the best practice for adding large amounts of html to a page so it doesnt crush ie? A: If you can, you're better off returning JSON to the browser, and using a template plugin like jQuery tmpl to map the json to the HTML to display, since tmpl does some wonderful caching that speeds performance in slower browsers like IE. It also makes the JSON response snappier. Example: <script id="template" type="text/x-jquery-tmpl"> <span class="message">${text}</span> </script> <script type="text/javascript"> $.ajax( { url: url, dataType: 'json', cache: false, success: function (data) { $("#targetElementId").html($("#template").tmpl(data)); } }); </script> Your JSON response would need to be formatted such that it matched the template: { text: "Blah!" } A: You can try .text() or .html().
{ "language": "en", "url": "https://stackoverflow.com/questions/7574138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Compile only some classes in project Is there a way to only build certain classes? I am testing code in one part of the application and I don't want to have to change it all across the program if it is not going to work correctly. A: You have multiple possibilities: * *Select the file you want to compile, then select the "Compile" item in the "Build" menu *Create a new target in your project (target dedicated for this debugging) using item "New Target" of the "Project" menu (Xcode3), then only include the classes/files you want to build in this Xcode target. If you choose to create a dedicated target, you can easily switch between this new target (to compile only the selected classes) and the main target (to compile the whole app) and vice-versa, at any time. (if you only need to compile one class for the day until you finish your refactoring but won't need this later, it's probably not worth creating a target; But creating a target could be useful if you intend to test this class on its own in multiple occasions during your development phases)
{ "language": "en", "url": "https://stackoverflow.com/questions/7574139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can I display a ABPersonViewController with Edit button in a UIPopOverController I am trying to enabling the editing of a Contact in a universal app, with a ABPersonViewController displayed in a UIPopoverController. The person does get displayed, but there is no Edit button. In actual fact, I would prefer it if the user saw the details already in an Editable form, but it would be ok if they could do the edit after hitting the Edit button. On the iPhone, it works fine. Can anyone help, please. ABPersonViewController *view = [[ABPersonViewController alloc] init]; view.personViewDelegate = self; ABAddressBookRef addressBook = ABAddressBookCreate(); ABRecordRef contact = ABAddressBookGetPersonWithRecordID(addressBook,(ABRecordID)recId); view.displayedPerson = contact; view.displayedProperties = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonFirstNameProperty], [NSNumber numberWithInt:kABPersonLastNameProperty], [NSNumber numberWithInt:kABPersonAddressProperty], nil]; view.allowsEditing = YES; view.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Back",nil) style:UIBarButtonItemStylePlain target:self action:@selector(ReturnFromPersonView)] ; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { UIPopoverController *addressPopup; addressPopup = [[UIPopoverController alloc] initWithContentViewController:view]; addressPopup.delegate = self; self.popoverController = addressPopup; [addressPopup release]; [self.popoverController presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES]; } else { [self.navigationController pushViewController:view animated:YES]; } if (addressBook) CFRelease(addressBook); [view release]; A: You need to add your ABPersonViewController *view explicitly to a UINavigationController. ABPersonViewController *view = [[ABPersonViewController alloc] init]; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:view]; UIPopoverController *personViewPopover = [[UIPopoverController alloc] initWithContentViewController:navController];
{ "language": "en", "url": "https://stackoverflow.com/questions/7574148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET 4: Can the managed code alone cause a heap corruption? I have a heap corruption in my multi-threaded managed program. Doing some tests I found that the corruption happens only when the background threads active in the program (they are switchable). The threads use some 3rd party components. After examining the code of the threads and 3rd party components (with .NET Reflector) I found that they are all managed, i.e. no "unsafe" or "DllImportAttribute" or "P/Invoke". It seems that the purely managed code causes a heap corruption, is this possible? UPDATE Apart from using Marshal class, is it possible to corrupt the heap with threads not being correctly synchronized? An example would be very appreciated. A: It's definitely possible to corrupt the heap without any use of unsafe code. The Marshal class is your friend / enemy here IntPtr ptr = new IntPtr(50000); // Random memory byte[] b = new byte[100]; Marshalp.Copy(b, 0, ptr, 100); This effectively copies 100 consecutive 0's into the heap at address 50000. Another way is with explicit struct layouts [StructLayout(LayoutKind.Explicit)] struct S1 { [FieldOffset(0)] internal string str; [FieldOffset(0)] internal object obj; } S1 s = new S1(); s.obj = new Program(); s.str.Trim(); // Hope that works ... :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7574153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Jython wsadmin: get nodeName of server In Jython WebSphere Wsadmin: It appears that I can get to the server's names from the nodeName, however I haven't managed to find a direct way to find the nodeName of a server. I thought about creating a map of all the nodes, but that is expensive. Can anyone help? A: You can get the node name of the server using the Server MBean. You can find info on the Server MBean here http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=%2Fcom.ibm.websphere.ejbfep.multiplatform.doc%2Finfo%2Fae%2Fae%2Fcjmx_overview.html objNameString = AdminControl.completeObjectName('WebSphere:type=Server,*') print AdminControl.getAttribute(objNameString, 'nodeName') A: You can also get the node name using the getNode() method on AdminControl: wsadmin>objn = AdminControl.completeObjectName('WebSphere:type=Server,*') wsadmin>print AdminControl.getAttribute(objn, 'nodeName') Node01 wsadmin>print AdminControl.getNode() Node01 References * *Commands for the AdminControl object using wsadmin scripting
{ "language": "en", "url": "https://stackoverflow.com/questions/7574158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: javascript document.write vs jQuery replaceWith I have some pages that will use the path portion of the URL to place text on the page, like so.. urlPath=window.location.pathname; urlPathArray = urlPath.split('/'); urlPath2=urlPathArray[2]; if (urlPath2 == "sometext") { document.write("Title for Some Text") } else if (urlPath2 == "othertext") { document.write("Title for Other Text") } else { document.write ("Generic Title") } Is it worth figuring out how to do this with jQuery and the replaceWith function? A: I would create a div or some other container with an ID like so: <div id="content"></div> and then use javascript DOM manipulation to populate it: urlPath=window.location.pathname; urlPathArray = urlPath.split('/'); var oput = document.getElementById("content"); switch(urlPath2) { case "sometext": oput.innerHTML = "Title for Some Text"; break; case "othertext": oput.innerHTML = "Title for Some Other Text"; break; default: oput.innerHTML = "Default Text"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7574163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to read until a given character in Lua 5.1? Up to lua 2.4, there used to be an readuntil function that can read until the first occurence of a specified character; in 2.5 this is removed and you have to pass an appropriate pattern to file:read instead; and in 5.1 it seems that the available formatting option for read has been further reduced, and the patterns valid in version 2.5 are no longer available. How do I read from an input stream until the first occurence of a given character, say TAB? Trying to write an enhanced REPL with tab-completion. A: For tab-completion you need to read input in raw mode, that is, without waiting for a newline. This cannot be done in ANSI C. Try a curses binding for instance: https://github.com/rrthomas/luaposix.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: submit one or another query I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app. I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present, the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my understanding (and guess-ology). I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php, etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other. Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up) cheers, s <?php // CASE I: 'EDIT RECORD': // If there's an ID ... if (isset($_GET['ID']) && is_numeric($_GET['ID'])) { $id = $_GET['ID']; echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>"; // ... retrieve the record .... $query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id); $result = mysql_query($query) or die(mysql_error()); $row = mysql_fetch_array($result); // ... assign variables to pre-populate the form $id = $row['ID']; $invNumber = $row['invNumber']; $invDate = $row['invDate']; // [ snip: more variables > field data ] // on submit: get the form values ... // no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) { if (isset($_POST['submit'])) { $invNumber = $_POST['invoice-number']; $invDate = $_POST['invoice-date']; $projNumber = $_POST['project-number']; // [ snip: more variables > field data ] // ... and UPDATE the db: $qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'"; $result = mysql_query($qUpdate) or die(mysql_error()); if($result) { echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>"; } else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error()); } // CLOSE '(isset($_POST['submit'])) } // END CASE I: ID present // CASE II: 'NEW RECORD'; query = INSERT elseif (empty($_GET['ID'])) { echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>"; // on submit: get the form values ... if (isset($_POST['submit'])) { $invNumber = $_POST['invoice-number']; $invDate = $_POST['invoice-date']; $projNumber = $_POST['project-number']; // [ snip: more variables > field data ] $qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments) VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')"; $result = mysql_query($qInsert) or die(mysql_error()); if($result) { echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>"; } else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error()); } // CLOSE '(isset($_POST['submit'])) } // END CASE II: No ID present ?> and: <form id="invoiceData" method="post" action="/html/form.php"> A: When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this: <form id="invoiceData" method="post" action="/html/form.php?ID=<?php echo $_GET['ID']; ?>" > This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure. Hope this helps! A: $_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to <form id="invoiceData" method="post" action="/html/form.php?ID=12"> Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tried everything, but can not remove duplicate XML lines using xsl stylesheet As someone new to xsl, I have tried various examples from these posts, but for my particular XML file I cannot remove duplicate "TaskName" lines. I HAVE been successful eliminating multiple "ResourceName" entries, but only want a given task to appear once under the ResourceName. I would greatly appreciate any suggestions. Here is my xml (sorry for the long file, but I think needed for clarity), my xsl, the output I am getting, and showing the output I'd like to get. XML source: <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="ResourceAssignments.xsl"?> <ResourceAllocationReport> <DetailedData> <ResourceAllocation> <Group>Week Starting on 7/24/11</Group> <TaskResourceAllocation> <TaskName>DEV-23876 Task A</TaskName> <TaskDuration>5 days</TaskDuration> <ResourceName>John Smith</ResourceName> <AllocatedHours>2.400</AllocatedHours> </TaskResourceAllocation> </ResourceAllocation> <ResourceAllocation> <Group>Week Starting on 7/31/11</Group> <TaskResourceAllocation> <TaskName>DEV-23873 Task B</TaskName> <TaskDuration>2 days</TaskDuration> <ResourceName>John Smith</ResourceName> <AllocatedHours>4.000</AllocatedHours> </TaskResourceAllocation> </ResourceAllocation> <ResourceAllocation> <Group>Week Starting on 8/7/11</Group> <TaskResourceAllocation> <TaskName>DEV-23879 Task C</TaskName> <TaskDuration>10 days</TaskDuration> <ResourceName>John Smith</ResourceName> <AllocatedHours>1.600</AllocatedHours> </TaskResourceAllocation> </ResourceAllocation> <ResourceAllocation> <TaskResourceAllocation> <TaskName>DEV-22837 List edit</TaskName> <TaskDuration>10 days</TaskDuration> <ResourceName>Sam Adams</ResourceName> <AllocatedHours>5.000</AllocatedHours> </TaskResourceAllocation> </ResourceAllocation> <ResourceAllocation> <Group>Week Starting on 9/4/11</Group> <TaskResourceAllocation> <TaskName>DEV-19006 System Configuration Report</TaskName> <TaskDuration>12 days</TaskDuration> <ResourceName>Kimberly Clark</ResourceName> <AllocatedHours>7.000</AllocatedHours> </TaskResourceAllocation> </ResourceAllocation> <ResourceAllocation> <TaskResourceAllocation> <TaskName>DEV-19006 System Configuration Report</TaskName> <TaskDuration>12 days</TaskDuration> <ResourceName>Sam Adams</ResourceName> <AllocatedHours>7.000</AllocatedHours> </TaskResourceAllocation> </ResourceAllocation> <ResourceAllocation> <TaskResourceAllocation> <TaskName>DEV-22837 List edit</TaskName> <TaskDuration>10 days</TaskDuration> <ResourceName>Sam Adams</ResourceName> <AllocatedHours>8</AllocatedHours> </TaskResourceAllocation> </ResourceAllocation> <ResourceAllocation> <Group>Week Starting on 9/25/11</Group> <TaskResourceAllocation> <TaskName>DEV-15997 Change modifiers for components</TaskName> <TaskDuration>15 days</TaskDuration> <ResourceName>Kimberly Clark</ResourceName> <AllocatedHours>8.000</AllocatedHours> </TaskResourceAllocation> </ResourceAllocation> <ResourceAllocation> <Group>Week Starting on 10/2/11</Group> <TaskResourceAllocation> <TaskName>DEV-15997 Change modifiers for components</TaskName> <TaskDuration>15 days</TaskDuration> <ResourceName>Kimberly Clark</ResourceName> <AllocatedHours>2.000</AllocatedHours> </TaskResourceAllocation> </ResourceAllocation> </DetailedData> </ResourceAllocationReport> Stylesheet: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" indent="yes" /> <xsl:key name="ResourceKey" match="TaskResourceAllocation" use="ResourceName" /> <xsl:template match="ResourceAllocation"> <body> <xsl:apply-templates select="TaskResourceAllocation[generate-id(.) = generate-id(key('ResourceKey',ResourceName)[1])]"/> </body> </xsl:template> <xsl:template match="TaskResourceAllocation"> <h2><xsl:value-of select="ResourceName" /></h2> <table border="1"> <xsl:for-each select="key('ResourceKey',ResourceName)"> <xsl:if test="not(. = preceding::TaskName)"> <tr> <td> <xsl:value-of select="TaskName" /> </td> <td> <xsl:value-of select="TaskDuration" /> </td> </tr> </xsl:if> </xsl:for-each> </table> </xsl:template> </xsl:stylesheet> Output (But I do NOT want duplicated tasks): John Smith DEV-23876 Task A 5 days DEV-23873 Task B 2 days DEV-23879 Task C 10 days Sam Adams DEV-22837 List edit 10 days DEV-19006 System Configuration Report 12 days DEV-22837 List edit 10 days Kimberly Clark DEV-19006 System Configuration Report 12 days DEV-15997 Change modifiers for components 15 days DEV-15997 Change modifiers for components 15 days Desired output: John Smith DEV-23876 Task A 5 days DEV-23873 Task B 2 days DEV-23879 Task C 10 days Sam Adams DEV-19006 System Configuration Report 12 days DEV-22837 List edit 10 days Kimberly Clark DEV-19006 System Configuration Report 12 days DEV-15997 Change modifiers for components 15 days A: Your idea is sound enough - the problem seems to be that you are comparing ResourceName against TaskName, which will never match: <xsl:for-each select="key('ResourceKey',ResourceName)"> <xsl:if test="not(. = preceding::TaskName)"> following up ... if you want to correct this (and stay w/xslt 1.0), try something like: <xsl:template match="TaskName[not(preceding::TaskName=.)]"> ... desired output here ... </xsl:template> run this template from some enclosing context using <xsl:apply-templates /> or <xsl:apply-templates select=".//TaskName" /> A: Off top of my head you could do for-each-group something like this <xsl:for-each-group select="key('ResourceKey',ResourceName)" group-by="TaskName"> <tr> <td> <xsl:value-of select="TaskName" /> </td> <td> <xsl:value-of select="TaskDuration" /> </td> </tr> </xsl:for-each>
{ "language": "en", "url": "https://stackoverflow.com/questions/7574169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Solving android SDK "failed to parse output of adb version" I've run into the "failed to parse output of adb version"... i done it before and managed somehow to make it work again, but this time all my efforts were in vain. So please help!!! I've tried: * *closing the adb process from taskmanager or by cmd, by "adb kill-server" and restarting eclipse ... + other variations *re-installed a fresh Eclipse 3.7 and the latest android-sdk-r13 ... *did a "netstat -o" (some forums mention this... to see if my 5537 is used by another process...) Basically I can't connect Eclipse to a emulator. My latest triumph: by cmd "adb connect 127.0.0.1:5555" and it says "connected to 127.0.0.1:5555" but obviously I'm NOT! But I've noticed that after this command, for 1-2 fractions of a second, the emulator appears in devices tab in DDMS perspective, but just for 1-2 fractions of a second, with a "offline" tag... Oh yeah, i use a virtual machine in Virtual Box (I use NAT+PCFASTIII + port forwarding on 5555, witch means it should work, but it doesn't), also tried with the classic emulator ... same result. - also when i do the "adb start-server" it starts it on 5537 (as expected) Does anyone know how to resolve this problem? A: Sorry Bill... I managed to make it work again. What i did is added port forwarding for my Virtual Box machine for port 5554 (i already had it for port 5555) and it works now. It still has bogus sens for me, but works. A: I had similar problem. My firewall was blocking adb, so making it "trusted application" solves it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Is there any graphic effects library compatible with MonoTouch? Is there any graphic effects library compatible with MonoTouch? I can't find any library, not even one able to do a simple sharpen or a "non fake" motion blur. :( Thanks in advance. A: MonoTouch is build upon Mono which again is C#, so I think you should be able to search for tutorials for C#/.NET or Mono and see if there arent anything. I havent searched myself, but is going to, as I am testing MonoTouch and iOS now too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lead backslash at the beginning of dynamic class name The code: $className = '\MyNamespace\MyClass'; $object = new $className(); throws error 'Class not found' But this code: $object = new \MyNamespace\MyClass(); is not. First code fragment works at staging but not at my local. Do I need to enable something at my local server? Many thanks for help A: Dynamic functions always require a fully-qualified namespace name and as such a leading \ would be redundant. That's why you shouldn't specify it: $className = 'MyNamespace\MyClass'; $object = new $className(); But still, it shouldn't throw an error. Demo: http://codepad.viper-7.com/D8H19r A: Just see what the string $className contains. You'll notice, that you should always skip the first slash. You may create some helper to create the object for you, and strip the trailing slash if any. new is evil anyway ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7574183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pantone Color Picker I'd like to use a color picker on my web site similar to http://www.eyecon.ro/colorpicker/#about, but which only allows the choice from set Pantone colors (instead of all RGB / HEX colors). Does anyone know if this exists? It looks like something like the "Really Simple Color Picker" at http://laktek.com/2008/10/27/really-simple-color-picker-in-jquery/ could be used, but I'd prefer not to have to code in all the pantone colors if it has already been done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: need help with this compile error for getline function error: no matching function for call to 'getline(std::istream&, char&)'| I have a source code file with getline function in it and I receive and error when I compile it (code and error below). My problem is that I copied and pasted the whole function from an already compiled and working program (included below as well). I also have the getline function in 2 other source code files in the program, both of which compile fine. I am fairly new to programming and just started c++ programing (much better at Java) so try to keep answers simple. I looked through some of the already posted questions and answers here (and google) but all the ones I found the answers say that the parameters for the function are not correct. But I know they are correct here because it works in the other program just fine. Also as you can see in the working file the only #included is iostream and it works, that's with g++ complier in Code::Blocks. I made sure to include all the variables/constants needed as well. Here is the code for the function and file I am getting the error from. The parts I am refering to are marked by 3 * (sorry best I could do). The error is reprinted at the bottom of post as well. #include <iostream> #include <istream> #include "candidates.h" using namespace std; int nCandidatesInPrimary; int delegatesForThisState; const int maxCandidates = 10; int delegatesWon[maxCandidates]; int totalVotes; int totalDelegates = 0; int votesForCandidate[maxCandidates]; string candidate[maxCandidates]; int nCandidates; string candidateNames; void readCandidates () { cin >> nCandidates; string line; getline (cin, line); for (int i = 0; i < nCandidates; ++i) { ***getline (cin, candidateNames[i]);*** delegatesWon[i] = 0; } } int findCandidate (std::string name) { int result = nCandidates; for (int i = 0; i < nCandidates && result == nCandidates; ++i) if (candidateNames[i] == name) result = i; return result; } void printCandidateReport (int candidateNum) { int requiredToWin = (2 * totalDelegates + 2) / 3; // Note: the +2 rounds up if (delegatesWon[candidateNum] >= requiredToWin) cout << "* "; else cout << " "; cout << delegatesWon[candidateNum] << " " << candidateNames[candidateNum] << endl; } void assignDelegatesToCandidates () { int remainingDelegates = delegatesForThisState; for (int i = 0; i < nCandidatesInPrimary; ++i) { int candidateNum = findCandidate(candidate[i]); int nDel = (delegatesForThisState * votesForCandidate[i] + (totalVotes-1)) / totalVotes; if (nDel > remainingDelegates) nDel = remainingDelegates; delegatesWon[candidateNum] += nDel; remainingDelegates -= nDel; } } here is the code from the already working program. #include <iostream> using namespace std; // Max # of candidates permitted by this program const int maxCandidates = 10; // Names of the candidates participating in this state's primary string candidate[maxCandidates]; // Names of all candidates participating in the national election std::string candidateNames[maxCandidates]; // How many delegates are assigned to the state being processed int delegatesForThisState; // How many delgates have been won by each candidate int delegatesWon[maxCandidates]; // How many candidates in the national election? int nCandidates; // How many candidates in the primary for the state being processed int nCandidatesInPrimary; // How many states participate in the election int nStates; // How many delegates in the election (over all states) int totalDelegates = 0; // How many votes were cast in the primary for this state int totalVotes; // How many votes wone by each candiate in this state's primary int votesForCandidate[maxCandidates]; int findCandidate (std::string name); /** * For the most recently read primary, determine how many delegates have * been won by each candidate. */ void assignDelegatesToCandidates () { int remainingDelegates = delegatesForThisState; for (int i = 0; i < nCandidatesInPrimary; ++i) { int candidateNum = findCandidate(candidate[i]); int nDel = (delegatesForThisState * votesForCandidate[i] + (totalVotes-1)) / totalVotes; if (nDel > remainingDelegates) nDel = remainingDelegates; delegatesWon[candidateNum] += nDel; remainingDelegates -= nDel; } } /** * Find the candidate with the indicated name. Returns the array index * for the candidate if found, nCandidates if it cannot be found. */ int findCandidate (std::string name) { int result = nCandidates; for (int i = 0; i < nCandidates && result == nCandidates; ++i) if (candidateNames[i] == name) result = i; return result; } /** * Print the report line for the indicated candidate */ void printCandidateReport (int candidateNum) { int requiredToWin = (2 * totalDelegates + 2) / 3; // Note: the +2 rounds up if (delegatesWon[candidateNum] >= requiredToWin) cout << "* "; else cout << " "; cout << delegatesWon[candidateNum] << " " << candidateNames[candidateNum] << endl; } /** * read the list of candidate names, initializing their delegate counts to 0. */ void readCandidates () { cin >> nCandidates; string line; getline (cin, line); for (int i = 0; i < nCandidates; ++i) { ***getline (cin, candidateNames[i]);***//already working delegatesWon[i] = 0; } } /** * read the info on one state's primaries */ void readState () { totalVotes = 0; cin >> nCandidatesInPrimary >> delegatesForThisState; totalDelegates += delegatesForThisState; // "x += y" is a shorthand for "x = x + y" string word, line; getline (cin, line); for (int i = 0; i < nCandidatesInPrimary; ++i) { cin >> votesForCandidate[i]; totalVotes = totalVotes + votesForCandidate[i]; cin >> word; getline (cin, line); candidate[i] = word + line; } } /** * Generate the report on the national primary election. */ int main(int argc, char** argv) { readCandidates(); int nStates; cin >> nStates; for (int i = 0; i < nStates; ++i) { readState(); assignDelegatesToCandidates(); } for (int i = 0; i < nCandidates; ++i) { printCandidateReport(i); } return 0; } error: no matching function for call to 'getline(std::istream&, char&)'| A: Looks like you intended candidateNames to be declared as a vector<string> candidateNames; vector<string> candidateNames; void readCandidates () { cin >> nCandidates; string line; getline (cin, line); candidateNames.resize(nCandidates); for (int i = 0; i < nCandidates; ++i) { getline (cin, candidateNames[i]); } } A: candidateNames is a single string, not a collection of strings. What about setting up a vector of them? std::vector<string> candidateNames; And then before your for loop: candidateNames.resize(nCandidates); A: Looks like you forgot to #include <string> It's likely that the other headers have pulled in the string class itself, but not all the supporting functions such as getline overloads that accept std::string. A: Sorry I might have been unfair when posting this question. I was able to find the problem, it was in my header file, I messed up the variables there. for candidateNames[] I forgot the [] at the end in the header file. And since I didn't include that file in my post you couldn't see that. Thanks for the help though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you test methods as you are coding? Currently using VS2010 Ultimate. In a prior version of VS there was a utility that you could use to test methods while you were coding (Some sort of test bench, I think). The benefit of this, was in the case of a large web app, you didn't need to spin up and wait for the entire application to be ready before testing your method. What sorts of tests / jigs do you use to test static and instance methods in your apps w/o firing up the entire application? A: LINQPad works great for running small bits of code. A: Using the MSTest Project and have it reference your app you are trying to test. A: VS2010 comes with a system that allow you made unit tests... and let you run each tests individually if you want. You may be interested in this channel9 video about unit testing with vs2010: http://channel9.msdn.com/blogs/visualstudio/test-driven-development-with-visual-studio-2010 A: I think the question here is how to start your method from anywhere, to have an entry point to quickly test something. If I remember correctly, TestDriven.Net allowed you to do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to validate a JSON String JQuery I tried that: var c = $.parseJSON(something here) and I control that: c === undefined This works however it throws error while trying to parse an invalid JSON string. I don't want it throw that error. Any advices? A: It's generally considered bad practice to suppress/ignore errors, instead why not use a try-catch block to capture the exception and do something with it: try { var c = $.parseJSON(something here); } catch (err) { // Do something about the exception here } If you really don't need to do anything about the exception at least put a comment to that effect in your try-catch block, it'll make your code more readable when you come back to it later.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: **make: *** [out/target/common/obj/JAVA_LIBRARIES/core_intermediates/classes.dex] Error 1**** Im new to Linux.Im porting android on devkit8000(copy of beagleboard) but getting so many errors in compiling the android source code.Below is the result of "make" command. ============================================ PLATFORM_VERSION_CODENAME=REL PLATFORM_VERSION=2.2 TARGET_PRODUCT=devkit8000 TARGET_BUILD_VARIANT=eng TARGET_SIMULATOR= TARGET_BUILD_TYPE=release TARGET_BUILD_APPS= TARGET_ARCH=arm HOST_ARCH=x86 HOST_OS=linux HOST_BUILD_TYPE=release BUILD_ID=MASTER ============================================ Install: out/host/linux-x86/framework/apicheck.jar Install: out/host/linux-x86/framework/clearsilver.jar Install: out/host/linux-x86/framework/droiddoc.jar Install: out/host/linux-x86/lib/libneo_util.so Install: out/host/linux-x86/lib/libneo_cs.so Install: out/host/linux-x86/lib/libneo_cgi.so Install: out/host/linux-x86/lib/libclearsilver-jni.so Copying: out/target/common/obj/JAVA_LIBRARIES/core_intermediates/classes-full-debug.jar Install: out/host/linux-x86/framework/dx.jar Install: out/host/linux-x86/bin/dx **target Dex: core Exception in thread "main" java.lang.NoClassDefFoundError: com/android/dx/command/Main **make: *** [out/target/common/obj/JAVA_LIBRARIES/core_intermediates/classes.dex] Error 1**** i couldnt find correct solution for this error.plz help:(
{ "language": "en", "url": "https://stackoverflow.com/questions/7574211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Keydown in jquery - Can I target specific letters with any kind of plugin? I need to call a function when a certain letter is pressed, i.e. pressing 'l' changes a div's class, and pressing 'g' changes it to another class. Can this be done natively in jquery, or will I have to find a plugin? Thanks. A: jQuery: $(document).bind('keydown', function(e) { if (e.which == 39) { rightArrowFunction(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7574212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I change a string twice (building on the previous changes) in Java? (code inside) for example, say I have a string called names and I want to .toUpperCase and then use the .replaceAll function before printing it. The problem I'm having is that only one step is applied at a time and the two functions are handled separately. System.out.format(names[i].toUpperCase()); System.out.format(names[i].replaceAll("SMITH", "<>JENKINS<>")); System.out.println(names[i]); Thanks in advance! A: .toUpperCase() returns a String. You need to something like: names[i].toUpperCase().replaceAll("SMITH", "<>JENKINS<>"); or names[i] = names[i].toUpperCase(); names[i].replaceAll("SMITH", "<>JENKINS<>") A: Because Strings are immutable in java, none of these functions work in-place. They don't change names[i]. So you'd have assign them to a temp variable (or names[i]). Do something like this. String tmp = names[i].toUpperCase(); System.out.format(tmp); tmp = tmp.replaceAll("SMITH", "<>JENKINS<>") System.out.format(tmp); System.out.println(tmp); A: You can chain method calls, since String instances are immutable and each method returns the string as transformed by its operations. String changed = names[i].toUpperCase().replaceAll("SMITH", "<>JENKINS<>"); System.out.format(changed); The variable changed has been extracted to make the code more readable. A: Strings in Java are immutable, they do not change themselves. The methods you use return a new, changed string: names[i] = names[i].toUpperCase(); System.out.format(names[i]); names[i] = names[i]..replaceAll("SMITH", "<>JENKINS<>"); System.out.format(names[i]); does what you expected your code to do. A: names[i].replaceAll("SMITH", "<>JENKINS<>") this code only returs the replaced string. you need to set it to a variable; string str = names[i].replaceAll("SMITH", "<>JENKINS<>"); or to replace the current reference; names[i]= names[i].replaceAll("SMITH", "<>JENKINS<>"); A: Extract a variable? String str = names[i].toUpperCase().replaceAll("SMITH", "<>JENKINS<>"); System.out.println(str); A: System.out.println(names[i].toUpperCase().replaceAll("SMITH", "<>JENKINS<>"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7574213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: call Actionscript method from JS without loading SWF Well yeah, it sounds funny, but all I want is to read the value of Capabilities.version to get the right version of the Flash player? I have tried getting the version info from swfObject library, but it doesn't give the complete version info: http://www.adobe.com/devnet/flashplayer/articles/swfobject.html FP version info have 4 numbers: major, minor, release and build. I couldn't find an API which can give me all four on all browsers without loading SWF. Hence I am looking for help here. A: SWFObject has a detection function built into it and for the most part it is cross-browser capable. The function name is getFlashPlayerVersion It returns an object with 3 attributes major, minor,release [EDIT] SWFObject also has a function called testPlayerVersion. I shortened it up for you but I think it gets what you want. var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); alert( doc.getElementsByTagName("body")[0].appendChild(o).GetVariable("$version") ) doc.getElementsByTagName("body")[0].removeChild(o); Remember this is not browser compliant. Pretty sure you need to test for plugin or active x also. A: You do not need to load flash to know what is the version of the player. There for is JS. http://www.featureblend.com/javascript-flash-detection-library.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7574215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I programmatically add build files to Xcode4? I've been trying to figure out how to programmatically add files to an Xcode4 project and it seemed like AppleScript would be the way to go, however I'm running into "missing value" errors. Here's the code I've got: tell application "Xcode" set theProject to first project set theTarget to first target of theProject set theBuildPhase to compile sources phase of theTarget tell first group of theProject set theFileRef to make new file reference with properties {full path:"/Users/jeff/Projects/XcodeTest/XcodeTest/MyViewController.h", name:"MyViewController.h", path:"XcodeTest/MyViewController.h", path type:group relative} add theFileRef to theProject end tell --tell theBuildPhase to make new build file with properties {build phase:theBuildPhase, name:"MyViewController.h", file reference:theFileRef, target:theTarget, project:theProject} end tell I've tried the commented-out line instead of the add-command as well, but that doesn't work either (I get "missing value"). The 'add' error is: error "Xcode got an error: file reference id \"251AD3431432472E006E300F\" of Xcode 3 group id \"251AD32C14324645006E300F\" of project \"XcodeTest\" of workspace document \"XcodeTest.xcodeproj/project.xcworkspace\" doesn’t understand the add message." number -1708 from file reference id "251AD3431432472E006E300F" of Xcode 3 group id "251AD32C14324645006E300F" of project "XcodeTest" of workspace document "XcodeTest.xcodeproj/project.xcworkspace" The "make new reference" does add the file to the list of files in Xcode, but I also need it to be added to the project target so that I can add actions and outlets to the file from Xcode w/o having to first check the checkbox to add it to the "target membership". A: I ended up sending this question to the devs on the xcode developer list and the response I got was effectively "you can't". A: This appears to be completely broken in Xcode4, but I've seen a project that does it. I think what they are doing is parsing and modifying the "project.pbxproj" file directly. (this file is hidden inside the xcodeproj bundle) The file is a GUID soup, but once you look at it for a while it seems possible to safely modify it, especially if you are only adding stuff. Edit: Found this stackoverflow answer that might help. Tutorial or Guide for Scripting XCode Build Phases A: There is a poorly documented user defined build setting that can be added. Files can be both excluded and included from compilation Go to your target's Build Settings > Tap the + button > Add User-Defined Setting The key is either INCLUDED_SOURCE_FILE_NAMES or EXCLUDED_SOURCE_FILE_NAMES The value is a space separated list of file paths See reference: http://lists.apple.com/archives/xcode-users/2009/Jun/msg00153.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7574217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Access as the front end and sql server as the backend I have some Access tables with many number of fields. I have migrated each access table to 6 or 7 sql server tables. I am using sql server 2008. Now I want to use Access as the front end so that I can enter the data in access but it will be stored in sql server. I know that I have to make a ODBC connection. But I am not sure of how to create a access form to use it as a front-end. I am sorry if it's a basic question... A: The most versatile way is to use ODBC links to your SQL Server tables and views. That approach allows you the flexibility to link to other ODBC data sources, tables in other Jet/ACE database files, create Jet/ACE tables locally in your database, link to Excel spreadsheets, and so forth. You can incorporate a broad range of data sources. If you choose ADP, you will be limited to OLE DB connection to a single SQL Server instance. And you will be essentially locked in to SQL Server. You would not be able to switch the application to a different client-server database without a major re-development effort. Regarding deployment overhead with ODBC, although you may find it convenient to use a DSN during development, you should convert your ODBC links to DSN-less connections before deployment. That way your user's won't each require the DSN. See Doug Steele's page: Using DSN-Less Connections A: You will probably want to start with an empty Access database (since the table structures and any existing forms and reports will not match what you created in SQL server). First step is to establish an ODBC connection to your SQL Server database. Then you will "link" the tables in SQL Server to your Access database. Now, you have an Access database with all the tables that you linked from SQL Server. Those tables still "live" in SQL Server and when you edit them in Access the data will be stored in SQL Server. You can then build Access forms and reports using these tables just as if the tables were native to Access. A: Well you can create an ODBC connection. You can also create an ADODB connection as well. If your objective is to update or modify a SQL database, both connections will do the trick. Now, I guess you have to get familiar with the corresponding objects. These should be tables, queries, commands, etc .., that will allow you, for example, to build recordsets out of SQL queries ... Once you are clear with that, you can, for example, assign a recordset to a form through the Set myForm.recordset = myRecordset.open ... method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: jQuery webcam: Save mode results in: ''error: No save mode compiled in." I am currently implementing a photo snapshot function to allow users to set their profile photo via webcam. To accomplish this, I am using jQuery Webcam Plugin. The problem arises in that I would like to have the user click a "Take Photo" and have the snapshot saved to the server in the appropriate location to be retrieved by the user image APIs. It seems this should be pretty easy to do, but for some reason I am running into problems. When my button is pressed, the photo capture takes place alright, but the saving doesn't execute properly as I am receiving the error error: No save mode compiled in. NOTE: My Save URL contains a hash variable like ?hash=XYZ123. This is how the image is named in the PHP file. I've attempted to remove the hash and ref variable from the url, thinking perhaps this caused the image data to be lost/ignored somehow, but that yielded no difference. Can anyone see something I did wrong here? I am pretty sure I followed the documentation as well as several other posts located here on SO, like this one. Screenshot HTML <div id="camera"></div> <!-- WebCam Live Display --> <div id="wcStatus"></div> <!-- Debug Text Display --> <button onclick="showWebcam();">Use Webcam Instead</button> <!--This button is normally hidden until camera initialized, but for sake for demo--> <button onclick="saveWebCam('XYZ123', '66');">Take a picture!</button> JS function showWebcam(){ $("#camera").webcam({ width: 320, height: 240, mode: "save", swffile: "/webcam/jscam_canvas_only.swf", debug: function(type, string) { $('#wcStatus').append(type + ": " + string + '<br /><br />'); } }); } function saveWebCam(hash, id){ var url = '/accountFiles/userImages/saveFromWebCam.php?hash=' + hash + '&ref=' + randomString(30); $('#wcStatus').append('Capturing: ' + url + '<br /><br />'); webcam.capture(); webcam.save(url); } PHP (saveFromWebCam.php) <?php $destFile=$_REQUEST['hash'].'.jpg'; $str = file_get_contents('php://input'); file_put_contents($destFile, pack("H*", $str)); ?> Debug Output notify: Camera started Capturing: /accountFiles/userImages/saveFromWebCam.php notify: Capturing started. notify: Capturing finished. error: No save mode compiled in. A: This is your error: swffile: "/webcam/jscam_canvas_only.swf", should be: swffile: "js/jscam.swf", quote from plugin webpage: Points to the swf file of the Flash movie, which provides the webcam API. There are two swf files provided via the download archive: jscam.swf, which provides the full API and jscam_canvas_only.swf which have no embedded JPEG library (I embedded an adjusted JPGEncoder of the AS 3 corelib). Thereby, the file is only one third as large as the original. A: As is often the case, time constraints have forced me to seek alternatives to this project. I have decided, as many all over the web have, to use the jpegCam Project. I got it up and running in about 15 minutes. SIMPLE! The only reason I am not deleting this question is for future seekers of such knowledge.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to disable concurrent gc for C# class library I have found answers to disable concurrent garbage collection for an application that uses config file. But my C# app is a class library built for ArcGIS, and don't have a config file. How to disable the concurrent gc in this case? Thanks! A: The decision over which GC flavor to use is up to the application (host) and not external DLLs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OCaml: applied to too many arguments Why the code if some_bool_var then begin output_string some_file "some string"; (* <--- error here *) end generates "applied to too many arguments" error. But if I change it to if some_bool_var then output_string some_file "some string"; it compiles fine. Why is it so? Thank you. A: I'm pretty skeptical that what you've presented doesn't compile. I copied it into the top level and sure enough I'm not getting an error at all. The problem is most likely not what you've typed but what is after what you've typed. I'm guessing you've got more lines of code for this particular function, thus end should have a semi-colon after it denoting the end of that command. Think of begin ... end as an alternative to ( ... ), and ...; as an alternative to let () = ... in. Thus, using begin ... end is not a replacement for the use of a semicolon. Also, the semi-colon that ends your output_string call between begin and end is unnecessary since that block does not continue with more commands.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How should I go about capturing a custom form in Magento that is stored with the order? I am working on a module to add a new step called Rental into the Onepage Checkout module in magento. The problem is not adding a step it is the data capture. I want to be able to take the custom form I have created and store it with the rest of the order information so when I click view order in the backend, it shows the information in the form as a seperate box. Preferably I want to seperate the concerns by creating a standalone module. How would you go about doing this? What would be your personal strategy for implementing this? A: Firstly, it should all depend on what data 'Rental' would be. Could it fit/be appropriately placed inside a product's custom option? Or do you need to create a custom sales attribute to store the data in? If you want the latter, you should use Magento Module Creator by SilkSoftware to create a module to implement sales attributes. Also: a good thread / scenario in using sales attributes: Magento: Setting a custom attribute on the sales/order_shipment model Secondly, is capturing the form data -- this is assuming you already have a block/form created and showing on the checkout page. I highly encourage you name the fields in the following semantic: <input type="text" name="rental[text_data]" /> <input type="text" name="rental[text_data2]" /> Where text_data and text_data2 are your desired variable names. An order is submitted / saved finally via a Controller action called saveOrderAction in Mage_Checkout_OnepageController or whatever Controller class you are using currently for your checkout page. Don't edit the corresponding PHP Class file for this found at app/code/core/Mage/Checkout/controllers/OnepageController.php ! Since you want to separate this into another module, you should try and rewrite this controller then so that your custom Controller class inside your module that extends the aforementioned base class (Mage_Checkout_OnepageController) should be used by Magento in its stead. A good tutorial on rewriting controllers can be found here. You can then do either of the two options from here: 1.) you could copy the entire saveOrderAction function and create routines to save Rental data there. if you followed the naming semantic I suggested, you should be able to retrieve the form data doing so: <?php // app/code/local/Namespace/Module/controllers/Checkout.php class Namespace_Module_Checkout extends Mage_Checkout_OnepageController { public function saveOrderAction() { ..... $this->getOnepage()->getQuote()->save(); $rental = $this->getRequest->getParam('rental'); $text_data = $rental['text_data']; $text_data = $rental['text_data2']; someSaveRoutine($text_data, $text_data2); //..or someSaveRoutine($rental); ..... } } 2.) secondly, you could replace the above code with a custom event dispatch $rental = $this->getRequest->getParam('rental'); Mage::dispatchEvent('checkout_onepage_controller_saveorder', array('rental'=> $rental)); then make an appropriate observer to save your custom data somewhere. I know this isn't much, but it's a start. I will look into editing this to elaborate more in the near future.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android - How to accept any certificates using HttpClient and passing a certificate at the same time I have a scenario in which I must pass a certficate to my server, then the server sends me his certificate, which I must accept to access the server. I was using HttpURLConnection for this, with no problems. However, I recently had a problem with HttpURLConnection. The code I was using retrieved an image from a HTTPS server. If the image was small (< 500kb), no problem whatsoever occured. However, with larger images I got this: javax.net.ssl.SSLProtocolException: Read error: ssl=0x3c97e8: Failure in SSL library, usually a protocol error I was reading about it on the Internet, and many people said that using HttpClient instead of HttpURLConnection was the way to go (an example is this site http://soan.tistory.com/62 , think that is written in korean, I can't read it but that's what I think it says). This is my old code, using URLConnection: public static URLConnection CreateFromP12(String uri, String keyFilePath, String keyPass, TrustManager[] trustPolicy, HostnameVerifier hv) { try { SSLContext sslContext = SSLContext.getInstance("TLS"); KeyStore keyStore = KeyStore.getInstance("PKCS12"); KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509"); keyStore.load(new FileInputStream(keyFilePath), keyPass.toCharArray()); kmf.init(keyStore, keyPass.toCharArray()); sslContext.init(kmf.getKeyManagers(), trustPolicy, null); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext .getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (Exception ex) { return null; } URL url; URLConnection conn; try { url = new URL(uri); conn = url.openConnection(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } return conn; } And this is the new one, using HttpClient: public class HttpC2Connection { public static HttpEntity CreateHttpEntityFromP12(String uri, String keyFilePath, String keyPass) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(new FileInputStream(keyFilePath), keyPass.toCharArray()); SSLSocketFactory sf = new MySSLSocketFactory(keyStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); HttpClient httpclient = new DefaultHttpClient(ccm, params); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); return entity; } But now, using HttpClient, my server returns me an error saying that I must pass a certificate, so I guess that SSLSocketFactory sf = new MySSLSocketFactory(keyStore); isn't loading my certificate. So, how can I do the following two things at the same time: 1.) Pass a certificate to my server; 2.) Accept any certificate from my server Using the HttpClient class? PS: I'm using Android 3.0 Thanks A: The following code disables SSL certificate checking for any new instances of HttpsUrlConnection: https://gist.github.com/aembleton/889392 /** * Disables the SSL certificate checking for new instances of {@link HttpsURLConnection} This has been created to * aid testing on a local box, not for use on production. */ private static void disableSSLCertificateChecking() { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { // Not implemented } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { // Not implemented } } }; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } A: Don't just accept any certificates. Don't use home-made SSLSocketFactory's that compromise security. Use the SSLSocketFactory from the SDK, and pass both a trust store (containing the server certificate or the CA certificate that issued it) and a keystore (containing your client certificate and private key). You can use this constructor to achieve this, the JavaDoc has details on how to create the key stores.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to change UdpClient IP address? Is there a way to change the UdpClient IP address on the fly? StartUpd() throws a System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted even after doing a StopUpd(). private static UdpClient udpClientR; void StartUpd() { try { udpClientR = new UdpClient(); udpClientR.Connect(Settings.rxIPAddress, PORT_RX_LOCAL); var t1 = new Thread(() => UdpReceiveThread(PORT_RX_REMOTE)) { IsBackground = true }; t1.Start(); ... private void StopUpd() { try { udpClientR.Close(); ... A: You are setting ip and port from the settings in the call to Connect method. try to call the connect again with different ip and port. A: You'll need some time for the thread to start, and to stop before you can call StartUpd and StopUpd. You can wait for the thread to exit once you Close the UDP client. This will ensure that its closed before you try to reconnect. So the code would like something like this: private UdpClient udpClientR; private Thread t1; void StartUpd() { udpClientR = new UdpClient(); udpClientR.Connect(Settings.rxIPAddress, PORT_RX_LOCAL); t1 = new Thread(() => UdpReceiveThread(PORT_RX_REMOTE)) { IsBackground = true }; t1.Start(); // Give it some time here to startup, incase you call StopUpd too soon Thread.Sleep(1000); } private void StopUpd() { udpClientR.Close(); // Wait for the thread to exit. Calling Close above should stop any // Read block you have in the UdpReceiveThread function. Once the // thread dies, you can safely assume its closed and can call StartUpd again while (t1.IsAlive) { Thread.Sleep(10); } } Other random note, looks like you misspelled the function names, probably should be StartUdp and StopUdp A: The call to Connect establishes the default remote address to which the UdpClient connects, which means you do not have to specify this address in calls to the Send method. This code should really not cause the error you're seeing. This error is the result of trying to listen on the same port with two clients, which makes me believe that it might be your UdpReceiveThread that is actually the problem here. You can specify the local port/address to bind to in the constructor of the UdpClient.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extending existing project and installing both of them at same time on android mobile Hi i made an app barcodescanner using ZXing project.actually i added some code in this BarCodeScanner project now its running fine on my wildfire s and on emulator.but when i installed zxing barcode scanner app from android market .and again try to install it then it is not installing on my phone.and same when i installed it on my phone then i am not able to install barcode scanner from android market.please suggest any way or any modification in manifest file so that i can install both of them at same time or is it not possible? A: Since you haven't stated what the error message is when you try to install the second time, I am assuming there is a package name conflict. Are you sure you have used your own package name in the code, including the manifest (and parts that may have the package name hardcoded)? If not, you must make sure your code uses your own package name, and that the manifest file reflects that. (Note that it's probably unwise to tamper with the package name in the ZXing code) A: You are getting this error because you have so extensively copied and pasted our code from http://code.google.com/p/zxing that you didn't bother to change the package name. We find this unethical. I would request that you not publish a simple copy-and-paste version of our work. Write your own app. Use pieces of ours for inspiration if you need to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: gcc dump resolved defines I have code like #define ONE 1 #define TWO 2 #define SUM (ONE+TWO) How do I dump SUM as "3", the resolved value, in gcc 4.3+? gcc -dM -E foo.h only seems to dump it as is. How do I get the actual value like it's inserted on compilation stage? A: You can't. As far as the compiler is concerned, the line printf("%d\n", SUM) before preprocessing is indistinguishable from the line printf("%d\n", 1+2). The compiler just happens to perform an optimization called constant folding, even at the default optimization level (-O0), which turns the result into a constant 3 at runtime. There's not really a good way to see the output of these optimizations. You could use the -S option to view the generated assembly code and see what that looks like, but if your program is anything larger than a toy, that will be a lot of manual effort. You could also look at the parse tree by using one of the -fdump-tree options (see the GCC man page). A: You can't "dump" SUM as 3 because SUM isn't 3 in any meaningful sense, it's just a sequence of the three tokens ONE, + and TWO. What it turns into depends on the context where it is expanded. Macros are expanded where they appear in the source, macro replacements are just strings of tokens until then. You can test this like this. #include <stdio.h> #define ONE 1 #define TWO 2 #define SUM ONE+TWO int a = SUM; #undef ONE #define ONE 2 int b = SUM; int main() { printf("a = %d\nb = %d\n", a, b); return 0; } Here's another example: #include <stdio.h> #define ONE 1 #define TWO 2 #define SUM ONE+TWO int main() { /* prints 6, not 2 */ printf("5 - SUM = %d\n", 5 - SUM); return 0; } With this example there's no way you can justify SUM being 3. A: Contrary to the other answers, there's definitely a solution to this problem, especially with gcc extensions. Parse the output of gcc -dM and generate a C file containing lines of the form __typeof__(MACRO) foo = MACRO; and go from there. Without __typeof__ you could still handle all arithmetic types fairly well by just using long double. A: One way is to stop at the precompiler stage (-E) and examine that output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Oracle free space after deleting data from tables I recently deleted a big chunk of data from some tables in the database. Now I wish to free up the space that was being held by that data. After that I would like to rebuild indexes. What is the best way to free up the space? A: What do you mean by "free up the space"? When you deleted the data, space was freed up in the blocks. That space is now available for subsequent inserts (or updates) in the table you deleted data from. That's normally sufficient because the table will normally grow again in the future. You could shrink the table if you want to decrease the size of the table segment and make the space available to other segments in the same tablespace ALTER TABLE table_name ENABLE ROW MOVEMENT; ALTER TABLE table_name SHRINK SPACE CASCADE; There is generally no need at that point to rebuild the indexes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to manually set an array in Java? How do you manually assign variables to an array? I have a code fragment below. I don't want to manually put shortStraight[0] = "211100", shortStraight[1] = "021110", and so on. Any help? private String [] shortStraight; public Sample () { shorty = new String [12]; shorty = {211100, 021110, 002111, 121100, 112100, 111200, 012110, 011210, 011120, 001211, 001121, 001112 } //this line doesn't work. Any help? A: String[] shorty = {"211100", "021110", "002111", "121100", "112100", "111200", "012110", "011210", "011120", "001211", "001121", "001112"} ; http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html A: String[] shorty = {"211100", "021110", "002111", "121100", "112100", "111200", "012110", "011210", "011120", "001211", "001121", "001112"} ;
{ "language": "en", "url": "https://stackoverflow.com/questions/7574252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is the proper/canonical way to serve JSON data with Django? I would like to deliver JSON responses with Django to my jQuery based clients. I could just design a template that instead of markup delivers JSON, but there must be a way to do this easier. What is the common practice in the Django community? A: If using python 2.6 or higher: import json Else: import simplejson as json Then you can use this in your view code: foo = {'bar': ['baz', 'etc']} return HttpResponse(json.dumps(foo), content_type="application/json") A: "Serializing Django objects" json
{ "language": "en", "url": "https://stackoverflow.com/questions/7574257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java. Save file as root in Linux How I can save file generated by java application in folder with root access? A: The straight forward way to do that is to run your application as the root user. Another solution is to ask to the user the root password. To do that, you have to ask the "su" command of your system. Be careful, your user must have the "wheel" group. Or, you can use sudo (make sure that sudo is installed and configured for the current user). As caarlos0 said in the comments, you can use "kdesu" or "gtksu/gksudo" if you prefer. Of course, your application is not portable ! On windows, there's no "su", "sudo", etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Connection Reset on Large File Upload Regardless Correct Setting I am having a very common problem which it seems that all the available solutions found are not working. We have a LAMP server which is receiving high amount of traffic. Using this server, we perform a regular file submission upload. On small file uploads, it works perfectly. On files of around 4-5MB, this submission upload failed intermittently (sometimes it works but many times it failed). We have the following configuration on our PHP: max_input_time: 600 max_execution_time: 600 max_upload_size: 10M post_max_size: 10M Apache setting: Timeout: 600 Keep-Alive Timeout: 15 Keep-Alive: On Per Child: 1000 Max Conn: 100 Thus, I wonder if anyone can help me with this. We have found the issues and solutions online but none of them work in our case. Thank you so much. Any input / feedback is much appreciated! A: The connection coud be terminating at several places: * *Apache *Post size limit inside of php.ini *Memory limit inside of php.ini *Input time limit inside of php.ini *Execution time limit inside of php.ini or set_time_limit() I would increase all of these, and see if it still persists. But you will have to bounce apache for the changes inside of php.ini to take affect. These are also affected by what kind of connection speed the end user has, if it is failing for certain users, it's because their connection is slower than others, and their connection with the server is terminating.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: NSTableview and SearchField I have an action for searching in NSMutableArray with name searcharray, which is equal to array with which NSTableView are connected.And I wrote a method for adding items to TableView just by sending NSMutableArray to my method. The problem is that after searching if I delete what I have typed in SearchField and SearchField is empty, the compiler doesn't feel that it's empty and my TableView getting empty too, but due my code it's have to be with data from searcharray. Here is my code: #import "myTableViewAppDelegate.h" @implementation myTableViewAppDelegate @synthesize window; @synthesize searcharray; -(void)addItems:(NSMutableArray *)ar{ array = ar; [array retain]; [tableView reloadData]; } - (int)numberOfRowsInTableView:(NSTableView *)tableView{ return (int)[array count]; } - (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row { return [array objectAtIndex:row]; } - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Insert code here to initialize your application NSMutableArray *animals = [[NSMutableArray arrayWithObjects:@"Cat", @"Dog", @"Fish", @"Squirrel", @"Bear", @"Turtle", nil] retain]; NSLog(@"%@",animals); searcharray = animals; [self addItems:animals]; } - (IBAction)search:(id)sender { //NSLog(@"%@",searcharray); NSString *filter = [[NSString alloc] initWithString:[search stringValue]]; NSMutableArray *result = [[NSMutableArray alloc] init]; if (filter != nil) { for (NSString *item in searcharray) { if ([item rangeOfString:[search stringValue]].location !=NSNotFound ) { NSLog(@"Item %@ contains %@",item,[search stringValue]); [result addObject:item]; } } } else{ result = searcharray; } NSLog(@"%@",result); [self addItems:result]; [result release]; [filter release]; } @end A: Fixed it. if (filter != nil || filter.length != 0) I don't know why, but just checking variable equal to NULL wasn't enough....
{ "language": "en", "url": "https://stackoverflow.com/questions/7574262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regular Expression replace single character in a word multiple times I have the following string: INSERT INTO testtable ('Reference', 'Date', 'Address', 'Amount', 'ChequeNo') VALUES How would I return only the quotes ' I basically need to do a replace on all the quotes from INSERT INTO up until VALUES as its invalid SQL. A: since you didn't mention your development environment, I assume that you just want to fix this sql problem. this awk line can fix that for you: awk -F'VALUES' '{gsub(/\x027/,"",$1);print $1FS$2;}' yourFile test kent$ echo "NSERT INTO testtable ('Reference', 'Date', 'Address', 'Amount', 'ChequeNo') VALUES('a','b','c','d','e')"|awk -F'VALUES' '{gsub(/\x027/,"",$1);print $1FS$2;}' NSERT INTO testtable (Reference, Date, Address, Amount, ChequeNo) VALUES('a','b','c','d','e') A: Note: I had made the assumption you were using Objective-C, given the presence of the NSRegularExpression tag. Split it by lines, and on each line, do this: [yoursqlstring stringByReplacingOccurrencesOfString:@"'" withString:@"" options:NULL range:NSMakeRange(0, [[yoursqlstring rangeOfString:@"VALUES"] location])] Regular expressions aren't meant to do what you're wanting. A: If you need to remove all the single quotes, just do this: NSString *newString = [originalString stringByReplacingOccurrencesOfString:@"'" withString:@""];
{ "language": "en", "url": "https://stackoverflow.com/questions/7574263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS Game Center: Creating Lifetime Achievements I'm trying to add a Lifetime achievement to my iOS app. That is, how many times the user performed the single action since he played the game for the first time. In other words, how many kills he got since... ever. I'm using the code based on the one provided by Apple: .h file: int64_t lifetimeScore; IBOutlet UILabel *lifetimeScoreLabel; .m file: - (IBAction) increaseScore { self.lifetimeScore = self.lifetimeScore + 1; lifetimeScoreLabel.text = [NSString stringWithFormat: @"%ld", self.lifetimeScore]; // Saving the Score: NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults]; [defaults setInteger:lifetimeScore forKey: @"Score"]; [defaults synchronize]; [self checkAchievements]; } - (void)viewDidLoad { [super viewDidLoad]; // Loading the Lifetime Score: self.lifetimeScore = [[NSUserDefaults standardUserDefaults] integerForKey: @"Score"]; lifetimeScoreLabel.text = [NSString stringWithFormat: @"%ld", self.lifetimeScore]; (...) } I works great, no warnings, but each time I close the app, deletes it from the Multitask bar and open the app again, the lifetimeScore goes back to zero. I'm trying to save the int_64 using NSUserDefaults but so far I can't make it work... any ideas? EDIT: The code was fixed and now it's working 100% in case anyone wants to use it. The complete source code can found here: http://mobile.tutsplus.com/tutorials/iphone/ios-sdk-game-center-achievements-and-leaderboards-part-2/ A: @"Store" should be @"Score", just so I can get the points... :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7574265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can windows managed service be a wcf client? On 1st server, there is wcf service hosted in windows managed service. On the 2nd server, there is another wcf service, hosted in their own windows managed service. I try to connect to 1st service from the inside of the 2nd service, but I become a exception "The socket connection was aborted". With same configuration and same code I successfully connect from console application and winform application, but not from this windows managed service. A: * *Configure your WCF services on both servers to perform diagnostic logging. Follow the instructions in http://msdn.microsoft.com/en-us/library/ms730064.aspx to achieve that. *Make sure the account your service on server 2 is running under is capable of connecting to server 1. This is a typical difference between the client test you did (and worked) and a service running on that system. For a test, make the service on server 2 run under your personal login credentials.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: DataGrid, Star, Auto, layout I have DataGrids that are getting resized when certain Grids are collapsed. In the default scenario, I'd like to have two rows in a column be like this: <Grid.RowDefinitions> <RowDefinition Height="0.65*"/> <RowDefinition Height="0.35*"/> </Grid.RowDefinitions> When I resize in the code behind, I seem to only have the option for the height/widths to be of type: .RowDefinitions[i].Height = GridLength.Auto; .ColumnDefinitions[i].Width = new GridLength(1, GridUnitType.Star); Is there a way I can revert back to my original .65* and .35*? Thanks. A: What's wrong with the following? .RowDefinitions[0].Height = new GridLength(0.65, GridUnitType.Star); .RowDefinitions[1].Height = new GridLength(0.35, GridUnitType.Star); This should be equivalent to: <RowDefinition Height="0.65*"/> <RowDefinition Height="0.35*"/> A: .65* can be written as new GridLength(.65, GridUnitType.Star); The first parameter in the GridLength constructor is the number in front of the *, and Height="*" is really Height="1*"
{ "language": "en", "url": "https://stackoverflow.com/questions/7574277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: If I remove a git submodule... is it REALLY gone from the repo? I have, for the last year, TouchJSON via a submodule. I no longer need to use the library and want to remove it but I am not sure if doing this: How do I remove a submodule? will remove even the 'history' of TouchJSON. basically, if I delete the submodule and then need to roll back for some odd reason, will it remember which version of TouchJSON to check out? A: It will remember it; if you do a diff between two commits in which the only change is a submodule being updated to a new revision, git will report the two commit hashes of that subproject
{ "language": "en", "url": "https://stackoverflow.com/questions/7574283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Word2011 doesn't support "FormattingShowClear", causing a problem on restricted style templates I have created a Word Template I would like to use in a mixed Office 2010/2011 environment. I am restricting formatting to using recommended styles, which removes the ability to select font, font size, etc.... However I want to allow the template user to still "Clear Formatting". In Word 2010 (Windows) this works great, the document property FormattingShowClear is set to True. Unfortunately in Word 2011 (Mac), this property does not exist, so the button and function are disabled. Also, paradoxically in Word 2011 the Bold and Italicize font style buttons are enabled! I have verified that FormattingShowClear is in the list of removed (or never implemented) properties not supported in Office for Mac 2011 (check this list out here if you like). Is my only recourse to write my own function using Word.Selection.ClearFormatting and assign it to a custom button? Is there a different property in Word for Mac 2011 equivalent to FormattingShowClear that I can set to True to enable the existing button? Update I went ahead and duplicated the Clear Formatting function, but removing the functionality of Bold and Italics on the Home tab of the Ribbon is still frustrating me. I've tried replicating those functions in Macros (shown below) and commenting the functions out. This blocks hotkey and using the formatting toolbar but not the Bold and Italicize buttons on the Home tab of the ribbon. Sub Bold() 'Selection.Font.Bold =WdToggle 'Selection.Range.Bold = wdToggle End Sub Sub Italic() ' Bold Italics 'Selection.Font.Italic=WdToggle 'Selection.Range.Italic =WdTogg End Sub A: Ctrl + Space does still work to clear formatting. But it's unconscionable that MS have removed the function behind the menus, while leaving the function label Clear Formatting there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSMutableDictionary vs CFMutableDictionary I have a requirement for a dictionary with keys that are not copied. This has lead me on a merry dance and I've ended up at the door of CFMutableDictionary. I am trying to understand the extent to which they are interchangeable. In Apple's docs for CFMutableDictionary they state: in a method where you see an NSMutableDictionary * parameter, you can pass in a CFMutableDictionaryRef, and in a function where you see a CFMutableDictionaryRef parameter, you can pass in an NSMutableDictionary instance. But I wondered whether it would be possible to cast a CFMutableDictionary to NSMutableDictionary and call NSMutableDictionary's methods on it, and it seems in some cases you can; If I create a CFMutableDictionary using CFDictionaryCreateMutable() and cast it to an NSMutableDictionary. I can call: [cfDictionaryCastToNSDictionary objectForKey:someKey] I can also call: [cfDictionaryCastToNSDictionary setObject:someObject forKey:someKey] ... which will copy the key or raise an exception if it doesn't implement NSCopying. I can also iterate through its values using a for in loop. However if I call: [cfDictionaryCastToNSDictionary count] I get an exception. My question is what exactly is going on here under the hood? At no point does the Apple documentation mention being able to call some methods that do not exist on CFMutableDictionary by casting to NSDictionary. A: If you are looking to understand problems using toll-free bridging, you should start with Mike Ash's "Toll-Free Bridging Internals" and go from there. If you just want to get back to work, the answer is, don't do that; avoid the problem entirely by using the CF functions with the CFDictionary rather than toll-free bridging. The CFDictionary API should be enough to do whatever you're trying to do if the dictionary is being used purely internally.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Django makemessages ignore switch doesn't work for me I have problems localizing a django-nonrel project, which is deployed to GAE. Because of GAE I have to put everything into my project folder, so it looks like something like this project + django + dbindexer + registration + myapp ... + locale + templates I have strings to localize in templates directory, and in the myapp directory. When I run python manage.py makemessages -l en --ignore django\* from the project dir it crawl through all the directories of the project, including django, so I get a quite big po file. My strings from the templates are there, along with all of the strings from django directory. after --ignore ( or just -i ) I tried to pu django django/* , but nothing changed. Any ideas? A: ./manage.py help makemessages -i PATTERN, --ignore=PATTERN Ignore files or directories matching this glob-style pattern. Use multiple times to ignore more. I have just tested it, and this command successfully ignored my application: ./manage.py makemessages -l da -i "django*" But beware that before you test it, you should delete the old .po file, as I think it will not automatically remove the translation lines from your previous makemessages execution. A: The problem is with the pattern - maybe the shell was expanding it for you. In general - it is good to avoid path separators (whether / or \) in the pattern. If you need to always pass specific options to the makemessages command, you could consider your own wrapper, like this one, which I use myself: from django.conf import settings from django.core.management.base import BaseCommand from django.core.management import call_command class Command(BaseCommand): help = "Scan i18n messages without going into externals." def handle(self, *args, **options): call_command('makemessages', all=True, extensions=['html', 'inc'], ignore_patterns=['externals*']) This saves you typing, and gives a common entry point for scanning messages across the project (your translator colleague will not destroy translations by missing out some parameter). Don't delete the old .po file, once you have cleared it from the totally unwanted (i.e. - those from 'django' directory) messages. This allows gettext to recycle old unused messages, once they are used again (or simmilar ones, which will be marked as #, fuzzy. Edit - as mt4x noted - the wrapper above doesn't allow for passing the options to the wrapped command. This is easy to fix: from django.core.management import call_command from django.core.management.commands.makemessages import ( Command as MakeMessagesCommand ) class Command(MakeMessagesCommand): help = "Scan i18n messages without going into externals." def handle(self, *args, **options): options['all'] = True options['extensions'] = ['html', 'inc'] if 'ignore_patterns' not in options: options['ignore_patterns'] = [] options['ignore_patterns'] += ['externals*'] call_command('makemessages', **options) Thus - you can fix what needs to be fixed, and flex the rest. And this needs not be blind override like above, but also some conditional edit of the parameters passed to the command - appending something to a list or only adding it when it's missing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: c# read byte array from resource I've been trying to figure out how to read a byte array from one of my resource files, I have tried the most popular hits on Google without clear success. I have a file stored in the resource collection of my program, I'd like to read this file as a byte array I'm currently just reading the file from the root directory of my program with the following code: FileStream fs = new FileStream(Path, FileMode.Open); BinaryReader br = new BinaryReader(fs); byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length)); fs.Close(); br.Close(); However I want to store this file as a resource in my application, so that I don't have to ship an extra file with my program. This file holds encrypted data that part of my program uses. Any help or pointers would be greatly appreciated! A: Assuming you are talking about files that are embedded as resources in your assembly: var assembly = System.Reflection.Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestResourceStream("SomeNamespace.somefile.png")) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); // TODO: use the buffer that was read } A: You can add resources to your application by going in the properties of the project, "Resources" tab (create one if needed), Add Resource (existing file). When your file is added, you can set its FileType (in its properties) to Binary. Documentation After that, you can access to your file as a byte[] easily: var myByteArray = Properties.Resources.MyFile; A: byte[] capacity = Properties.Resources.excel; Confusion: here we reading txt resource file .so it not return byte[] but it return string (file content). A: maybe you can try using StreamResourceInfo. Here is a link to a Silverlight example, but if I am not mistaken you should be able to apply the same principles in any .NET application: http://msdn.microsoft.com/en-us/library/system.windows.resources.streamresourceinfo(v=VS.95).aspx Regards, Anders @ Cureos A: Here's a little class we're using for this purpose: static class EmbeddedResource { /// <summary> /// Extracts an embedded file out of a given assembly. /// </summary> /// <param name="assemblyName">The namespace of your assembly.</param> /// <param name="fileName">The name of the file to extract.</param> /// <returns>A stream containing the file data.</returns> public static Stream Open(string assemblyName, string fileName) { var asm = Assembly.Load(assemblyName); var stream = asm.GetManifestResourceStream(assemblyName + "." + fileName); if (stream == null) throw new ConfigurationErrorsException(String.Format( Strings.MissingResourceErrorFormat, fileName, assemblyName)); return stream; } } Usage is pretty straightforward: using (var stream = EmbeddedResource.Open("Assembly.Name", "ResourceName")) // do stuff A: var rm = new ResourceManager("RessourceFile", typeof(ClassXY).Assembly); return Encoding.UTF8.GetBytes(rm.GetString("key"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7574307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Efficiently compute Intersection of two Sets in Java? What is the most efficient way to find the size of the intersection of two non-sparse Sets in Java? This is an operation I will be calling on large sets a very large number of times, so optimisation is important. I cannot modify the original sets. I have looked at Apache Commons CollectionUtils.intersection which appears to be quite slow. My current approach is to take the smaller of the two sets, clone it, and then call .retainAll on the larger of the two sets. public static int getIntersection(Set<Long> set1, Set<Long> set2) { boolean set1IsLarger = set1.size() > set2.size(); Set<Long> cloneSet = new HashSet<Long>(set1IsLarger ? set2 : set1); cloneSet.retainAll(set1IsLarger ? set1 : set2); return cloneSet.size(); } A: Can the members of the sets be easily mapped into a relatively small range of integers? If so, consider using BitSets. Intersection then is just bitwise and's - 32 potential members at a time. A: You can avoid all manual work by using the Set method retainAll(). From docs: s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements common to both sets.) A: If both sets can be sorted, like TreeSet running both iterators could be a faster way to count the number of shared objects. If you do this operation often, it might bring a lot if you can wrap the sets so that you can cache the result of the intersection operation keeping a dirty flag to track validity of the cached result, calculating again if needed. A: Using Java 8 stream: set1.stream().filter(s -> set2.contains(s)).collect(Collectors.toList()); A: Run some tests with the posted approach and versus constructing a new HashSet. That is, let A be the smaller of the sets and B be the larger set and then, for each item in A, if it also exists in B then add it to C (a new HashSet) -- for just counting, the intermediate C set can be skipped. Just as the posted approach, this should be a O(|A|) in cost as the iteration is O(|A|) and probe into B is O(1). I have no idea how it will compare vs. the clone-and-remove approach. Happy coding -- and post some results ;-) Actually, on further thinking, I believe this has slightly better bounds than the method in the post: O(|A|) vs O(|A| + |B|). I have no idea if this will make any difference (or improvement) in actuality and I would only expect it to be relevant when |A| <<< |B|. Okay, so I was really bored. At least on JDK 7 (Windows 7 x64), it appears the method in presented in the post is slower than the above approach -- by a good (albeit what appears to be mostly constant) factor. My eye-ball guesstimate says it is about four times as slow than the above suggestion that just uses a counter and twice as slow of when creating a new HashSet. This seems to be "roughly consistent" across the different initial set sizes. (Please keep in mind that, as Voo pointed out, the numbers above and this micro-benchmark assume a HashSet is being used! And, as always, there are dangers with micro-benchmarks. YMMV.) Here are the ugly results (times in milliseconds): Running tests for 1x1 IntersectTest$PostMethod@6cc2060e took 13.9808544 count=1000000 IntersectTest$MyMethod1@7d38847d took 2.9893732 count=1000000 IntersectTest$MyMethod2@9826ac5 took 7.775945 count=1000000 Running tests for 1x10 IntersectTest$PostMethod@67fc9fee took 12.4647712 count=734000 IntersectTest$MyMethod1@7a67f797 took 3.1567252 count=734000 IntersectTest$MyMethod2@3fb01949 took 6.483941 count=734000 Running tests for 1x100 IntersectTest$PostMethod@16675039 took 11.3069326 count=706000 IntersectTest$MyMethod1@58c3d9ac took 2.3482693 count=706000 IntersectTest$MyMethod2@2207d8bb took 4.8687103 count=706000 Running tests for 1x1000 IntersectTest$PostMethod@33d626a4 took 10.28656 count=729000 IntersectTest$MyMethod1@3082f392 took 2.3478658 count=729000 IntersectTest$MyMethod2@65450f1f took 4.109205 count=729000 Running tests for 10x2 IntersectTest$PostMethod@55c4d594 took 10.4137618 count=736000 IntersectTest$MyMethod1@6da21389 took 2.374206 count=736000 IntersectTest$MyMethod2@2bb0bf9a took 4.9802039 count=736000 Running tests for 10x10 IntersectTest$PostMethod@7930ebb took 25.811083 count=4370000 IntersectTest$MyMethod1@47ac1adf took 6.9409306 count=4370000 IntersectTest$MyMethod2@74184b3b took 14.2603248 count=4370000 Running tests for 10x100 IntersectTest$PostMethod@7f423820 took 25.0577691 count=4251000 IntersectTest$MyMethod1@5472fe25 took 6.1376042 count=4251000 IntersectTest$MyMethod2@498b5a73 took 13.9880385 count=4251000 Running tests for 10x1000 IntersectTest$PostMethod@3033b503 took 25.0312716 count=4138000 IntersectTest$MyMethod1@12b0f0ae took 6.0932898 count=4138000 IntersectTest$MyMethod2@1e893918 took 13.8332505 count=4138000 Running tests for 100x1 IntersectTest$PostMethod@6366de01 took 9.4531628 count=700000 IntersectTest$MyMethod1@767946a2 took 2.4284762 count=700000 IntersectTest$MyMethod2@140c7272 took 4.7580235 count=700000 Running tests for 100x10 IntersectTest$PostMethod@3351e824 took 24.9788668 count=4192000 IntersectTest$MyMethod1@465fadce took 6.1462852 count=4192000 IntersectTest$MyMethod2@338bd37a took 13.1742654 count=4192000 Running tests for 100x100 IntersectTest$PostMethod@297630d5 took 193.0121077 count=41047000 IntersectTest$MyMethod1@e800537 took 45.2652397 count=41047000 IntersectTest$MyMethod2@76d66550 took 120.8494766 count=41047000 Running tests for 100x1000 IntersectTest$PostMethod@33576738 took 199.6269531 count=40966000 IntersectTest$MyMethod1@2f39a7dd took 45.5255814 count=40966000 IntersectTest$MyMethod2@723bb663 took 122.1704975 count=40966000 Running tests for 1x1 IntersectTest$PostMethod@35e3bdb5 took 9.5598373 count=1000000 IntersectTest$MyMethod1@7abbd1b6 took 2.6359174 count=1000000 IntersectTest$MyMethod2@40c542ad took 6.1091794 count=1000000 Running tests for 1x10 IntersectTest$PostMethod@3c33a0c5 took 9.4648528 count=733000 IntersectTest$MyMethod1@61800463 took 2.302116 count=733000 IntersectTest$MyMethod2@1ba03197 took 5.4803628 count=733000 Running tests for 1x100 IntersectTest$PostMethod@71b8da5 took 9.4971057 count=719000 IntersectTest$MyMethod1@21f04f48 took 2.2983538 count=719000 IntersectTest$MyMethod2@27e51160 took 5.3926902 count=719000 Running tests for 1x1000 IntersectTest$PostMethod@2fe7106a took 9.4702331 count=692000 IntersectTest$MyMethod1@6ae6b7b7 took 2.3013066 count=692000 IntersectTest$MyMethod2@51278635 took 5.4488882 count=692000 Running tests for 10x2 IntersectTest$PostMethod@223b2d85 took 9.5660879 count=743000 IntersectTest$MyMethod1@5b298851 took 2.3481445 count=743000 IntersectTest$MyMethod2@3b4ac99 took 4.8268489 count=743000 Running tests for 10x10 IntersectTest$PostMethod@51c700a0 took 23.0709476 count=4326000 IntersectTest$MyMethod1@5ffa3251 took 5.5460785 count=4326000 IntersectTest$MyMethod2@22fd9511 took 13.4853948 count=4326000 Running tests for 10x100 IntersectTest$PostMethod@46b49793 took 25.1295491 count=4256000 IntersectTest$MyMethod1@7a4b5828 took 5.8520418 count=4256000 IntersectTest$MyMethod2@6888e8d1 took 14.0856942 count=4256000 Running tests for 10x1000 IntersectTest$PostMethod@5339af0d took 25.1752685 count=4158000 IntersectTest$MyMethod1@7013a92a took 5.7978328 count=4158000 IntersectTest$MyMethod2@1ac73de2 took 13.8914112 count=4158000 Running tests for 100x1 IntersectTest$PostMethod@3d1344c8 took 9.5123442 count=717000 IntersectTest$MyMethod1@3c08c5cb took 2.34665 count=717000 IntersectTest$MyMethod2@63f1b137 took 4.907277 count=717000 Running tests for 100x10 IntersectTest$PostMethod@71695341 took 24.9830339 count=4180000 IntersectTest$MyMethod1@39d90a92 took 5.8467864 count=4180000 IntersectTest$MyMethod2@584514e9 took 13.2197964 count=4180000 Running tests for 100x100 IntersectTest$PostMethod@21b8dc91 took 195.1796213 count=41060000 IntersectTest$MyMethod1@6f98c4e2 took 44.5775162 count=41060000 IntersectTest$MyMethod2@16a60aab took 121.1754402 count=41060000 Running tests for 100x1000 IntersectTest$PostMethod@20b37d62 took 200.973133 count=40940000 IntersectTest$MyMethod1@67ecbdb3 took 45.4832226 count=40940000 IntersectTest$MyMethod2@679a6812 took 121.791293 count=40940000 Running tests for 1x1 IntersectTest$PostMethod@237aa07b took 9.2210288 count=1000000 IntersectTest$MyMethod1@47bdfd6f took 2.3394042 count=1000000 IntersectTest$MyMethod2@a49a735 took 6.1688936 count=1000000 Running tests for 1x10 IntersectTest$PostMethod@2b25ffba took 9.4103967 count=736000 IntersectTest$MyMethod1@4bb82277 took 2.2976994 count=736000 IntersectTest$MyMethod2@25ded977 took 5.3310813 count=736000 Running tests for 1x100 IntersectTest$PostMethod@7154a6d5 took 9.3818786 count=704000 IntersectTest$MyMethod1@6c952413 took 2.3014931 count=704000 IntersectTest$MyMethod2@33739316 took 5.3307998 count=704000 Running tests for 1x1000 IntersectTest$PostMethod@58334198 took 9.3831841 count=736000 IntersectTest$MyMethod1@d178f65 took 2.3071236 count=736000 IntersectTest$MyMethod2@5c7369a took 5.4062184 count=736000 Running tests for 10x2 IntersectTest$PostMethod@7c4bdf7c took 9.4040537 count=735000 IntersectTest$MyMethod1@593d85a4 took 2.3584088 count=735000 IntersectTest$MyMethod2@5610ffc1 took 4.8318229 count=735000 Running tests for 10x10 IntersectTest$PostMethod@46bd9fb8 took 23.004925 count=4331000 IntersectTest$MyMethod1@4b410d50 took 5.5678172 count=4331000 IntersectTest$MyMethod2@1bd125c9 took 14.6517184 count=4331000 Running tests for 10x100 IntersectTest$PostMethod@75d6ecff took 25.0114913 count=4223000 IntersectTest$MyMethod1@716195c9 took 5.798676 count=4223000 IntersectTest$MyMethod2@3db0f946 took 13.8064737 count=4223000 Running tests for 10x1000 IntersectTest$PostMethod@761d8e2a took 25.1910652 count=4292000 IntersectTest$MyMethod1@e60a3fb took 5.8621189 count=4292000 IntersectTest$MyMethod2@6aadbb1c took 13.8150282 count=4292000 Running tests for 100x1 IntersectTest$PostMethod@48a50a6e took 9.4141906 count=736000 IntersectTest$MyMethod1@4b4fe104 took 2.3507252 count=736000 IntersectTest$MyMethod2@693df43c took 4.7506854 count=736000 Running tests for 100x10 IntersectTest$PostMethod@4f7d29df took 24.9574096 count=4219000 IntersectTest$MyMethod1@2248183e took 5.8628954 count=4219000 IntersectTest$MyMethod2@2b2fa007 took 12.9836817 count=4219000 Running tests for 100x100 IntersectTest$PostMethod@545d7b6a took 193.2436192 count=40987000 IntersectTest$MyMethod1@4551976b took 44.634367 count=40987000 IntersectTest$MyMethod2@6fac155a took 119.2478037 count=40987000 Running tests for 100x1000 IntersectTest$PostMethod@7b6c238d took 200.4385174 count=40817000 IntersectTest$MyMethod1@78923d48 took 45.6225227 count=40817000 IntersectTest$MyMethod2@48f57fcf took 121.0602757 count=40817000 Running tests for 1x1 IntersectTest$PostMethod@102c79f4 took 9.0931408 count=1000000 IntersectTest$MyMethod1@57fa8a77 took 2.3309466 count=1000000 IntersectTest$MyMethod2@198b7c1 took 5.7627226 count=1000000 Running tests for 1x10 IntersectTest$PostMethod@8c646d0 took 9.3208571 count=726000 IntersectTest$MyMethod1@11530630 took 2.3123797 count=726000 IntersectTest$MyMethod2@61bb4232 took 5.405318 count=726000 Running tests for 1x100 IntersectTest$PostMethod@1a137105 took 9.387384 count=710000 IntersectTest$MyMethod1@72610ca2 took 2.2938749 count=710000 IntersectTest$MyMethod2@41849a58 took 5.3865938 count=710000 Running tests for 1x1000 IntersectTest$PostMethod@100001c8 took 9.4289031 count=696000 IntersectTest$MyMethod1@7074f9ac took 2.2977923 count=696000 IntersectTest$MyMethod2@fb3c4e2 took 5.3724119 count=696000 Running tests for 10x2 IntersectTest$PostMethod@52c638d6 took 9.4074124 count=775000 IntersectTest$MyMethod1@53bd940e took 2.3544881 count=775000 IntersectTest$MyMethod2@43434e15 took 4.9228549 count=775000 Running tests for 10x10 IntersectTest$PostMethod@73b7628d took 23.2110252 count=4374000 IntersectTest$MyMethod1@ca75255 took 5.5877838 count=4374000 IntersectTest$MyMethod2@3d0e50f0 took 13.5902641 count=4374000 Running tests for 10x100 IntersectTest$PostMethod@6d6bbba9 took 25.1999918 count=4227000 IntersectTest$MyMethod1@3bed8c5e took 5.7879144 count=4227000 IntersectTest$MyMethod2@689a8e0e took 13.9617882 count=4227000 Running tests for 10x1000 IntersectTest$PostMethod@3da3b0a2 took 25.1627329 count=4222000 IntersectTest$MyMethod1@45a17b4b took 5.8319523 count=4222000 IntersectTest$MyMethod2@6ca59ca3 took 13.8885479 count=4222000 Running tests for 100x1 IntersectTest$PostMethod@360202a5 took 9.5115367 count=705000 IntersectTest$MyMethod1@3dfbba56 took 2.3470254 count=705000 IntersectTest$MyMethod2@598683e4 took 4.8955489 count=705000 Running tests for 100x10 IntersectTest$PostMethod@21426d0d took 25.8234298 count=4231000 IntersectTest$MyMethod1@1005818a took 5.8832067 count=4231000 IntersectTest$MyMethod2@597b933d took 13.3676148 count=4231000 Running tests for 100x100 IntersectTest$PostMethod@6d59b81a took 193.676662 count=41015000 IntersectTest$MyMethod1@1d45eb0c took 44.6519088 count=41015000 IntersectTest$MyMethod2@594a6fd7 took 119.1646115 count=41015000 Running tests for 100x1000 IntersectTest$PostMethod@6d57d9ac took 200.1651432 count=40803000 IntersectTest$MyMethod1@2293e349 took 45.5311168 count=40803000 IntersectTest$MyMethod2@1b2edf5b took 120.1697135 count=40803000 And here is the ugly (and possibly flawed) micro-benchmark: import java.util.*; public class IntersectTest { static Random rng = new Random(); static abstract class RunIt { public long count; public long nsTime; abstract int Run (Set<Long> s1, Set<Long> s2); } // As presented in the post static class PostMethod extends RunIt { public int Run(Set<Long> set1, Set<Long> set2) { boolean set1IsLarger = set1.size() > set2.size(); Set<Long> cloneSet = new HashSet<Long>(set1IsLarger ? set2 : set1); cloneSet.retainAll(set1IsLarger ? set1 : set2); return cloneSet.size(); } } // No intermediate HashSet static class MyMethod1 extends RunIt { public int Run (Set<Long> set1, Set<Long> set2) { Set<Long> a; Set<Long> b; if (set1.size() <= set2.size()) { a = set1; b = set2; } else { a = set2; b = set1; } int count = 0; for (Long e : a) { if (b.contains(e)) { count++; } } return count; } } // With intermediate HashSet static class MyMethod2 extends RunIt { public int Run (Set<Long> set1, Set<Long> set2) { Set<Long> a; Set<Long> b; Set<Long> res = new HashSet<Long>(); if (set1.size() <= set2.size()) { a = set1; b = set2; } else { a = set2; b = set1; } for (Long e : a) { if (b.contains(e)) { res.add(e); } } return res.size(); } } static Set<Long> makeSet (int count, float load) { Set<Long> s = new HashSet<Long>(); for (int i = 0; i < count; i++) { s.add((long)rng.nextInt(Math.max(1, (int)(count * load)))); } return s; } // really crummy ubench stuff public static void main(String[] args) { int[][] bounds = { {1, 1}, {1, 10}, {1, 100}, {1, 1000}, {10, 2}, {10, 10}, {10, 100}, {10, 1000}, {100, 1}, {100, 10}, {100, 100}, {100, 1000}, }; int totalReps = 4; int cycleReps = 1000; int subReps = 1000; float load = 0.8f; for (int tc = 0; tc < totalReps; tc++) { for (int[] bound : bounds) { int set1size = bound[0]; int set2size = bound[1]; System.out.println("Running tests for " + set1size + "x" + set2size); ArrayList<RunIt> allRuns = new ArrayList<RunIt>( Arrays.asList( new PostMethod(), new MyMethod1(), new MyMethod2())); for (int r = 0; r < cycleReps; r++) { ArrayList<RunIt> runs = new ArrayList<RunIt>(allRuns); Set<Long> set1 = makeSet(set1size, load); Set<Long> set2 = makeSet(set2size, load); while (runs.size() > 0) { int runIdx = rng.nextInt(runs.size()); RunIt run = runs.remove(runIdx); long start = System.nanoTime(); int count = 0; for (int s = 0; s < subReps; s++) { count += run.Run(set1, set2); } long time = System.nanoTime() - start; run.nsTime += time; run.count += count; } } for (RunIt run : allRuns) { double sec = run.nsTime / (10e6); System.out.println(run + " took " + sec + " count=" + run.count); } } } } } A: Just use Google Guava's Sets#intersection(Set, Set) method. A: If you are computing the intersection just for the sake of counting how many elements are there in the set, I suggest you just need to count the intersection directly instead of building the set and then calling size(). My function for counting: /** * Computes the size of intersection of two sets * @param small first set. preferably smaller than the second argument * @param large second set; * @param <T> the type * @return size of intersection of sets */ public <T> int countIntersection(Set<T> small, Set<T> large){ //assuming first argument to be smaller than the later; //however double checking to be sure if (small.size() > large.size()) { //swap the references; Set<T> tmp = small; small = large; large = tmp; } int result = 0; for (T item : small) { if (large.contains(item)){ //item found in both the sets result++; } } return result; } A: That is a good approach. You should be getting O(n) performance from your current solution. A: FYI, if any collection of sets are all sorted using the same comparision relation, then you can iterate their intersection in time N * M, where N is the size of the smallest set and M is the number of sets. Implementation left as exercise to reader. Here's an example. A: Intersection counting through streams/reduce (it assumes you figure out which set is larger before calling it): public int countIntersect(Set<Integer> largerSet, Set<Integer> smallerSet){ return smallerSet.stream().reduce(0, (a,b) -> largerSet.contains(b)?a+1:a); } However somewhere else I have read that no java code can be faster than the Set methods for set operations because they are implemented as native code instead of java code. Therefore I back up the suggestion to try BitSet to achieve faster results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: Running a Loop through $message in mail() This is a follow on to this question. I'm putting together a simple HTML email confirming an order to my database. As each order is obviously dynamic, i need part of $message to run through a loop. For example i query my database outside of the $message and end up with $emailinfo=mysql_fetch_assoc($result) or die(mysql_error()); I begin my $message... $message = <<<END <html> <head> <title>Whatever</title> </head> <body> <p>{$emailinfo['itemname']}</p> </body> </html> END; The above is fine if someone has only ordered one item, but what i need to do is account for if someone orders more than one item, looping through each one and echoing out in $message. Outside of $message i can do this (which works) do { echo $emailinfo['itemname']; } while ($emailinfo=mysql_fetch_assoc($result)); But when i wrap my $message within the loop, as was suggested in the comments on the previous question, it still only echos out the first row/order. E.g. do { $message = <<<END <html> <head> <title>Whatever</title> </head> <body> <p>{$emailinfo['itemname']}</p> </body> </html> END; } while ($emailinfo=mysql_fetch_assoc($result)); Can someone help? Outside of $message, the loop, query etc work fine, i just need it to work within $message. And it's only part of the order i need to loop through. I don't need to loop through customer info, delivery address etc as there'll only be one of those (if that helps at all). Thanks as always A: what's happening here is that you are overwriting the $message variable with each iteration of the loop. $message = <<<END <html> <head> <title>Whatever</title> </head> <body> END; do { $message .= <<<END <p>{$emailinfo['itemname']}</p> END; } while ($emailinfo=mysql_fetch_assoc($result)); $message .= <<<END </body> </html> END;
{ "language": "en", "url": "https://stackoverflow.com/questions/7574316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data extraction recommendation software (email, name, country) I would like to extract some data from plain files (thunderbird mailboxes, html files, csv). I usually get strings like this (into files) user: pepito phone: 11233213 email: user@domain.com Then I am searching a software that lets me extract by string (scripts, macros, it) and export to CSV by separated columns, Could you recommend me a software or way for doing it? Your help will be very appreciated Thank you very much A: For extracting I would recommend NLP grammar tools such as GATE/JAPE or GExp.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Interpolate Django template include variable I'm doing something like {% for part in parts %} {% include "inc.html" with o=part prefix="part{{ forloop.counter0 }}_" %} {% endfor %} where inc.html could be something of such kind: <p id="{{ prefix }}para">{{ o.text }}</p> I just discovered the prefix variable isn't interpolated and "part{{ forloop.counter0 }}_" is passed literally. Any relatively elegant work-around? A: I think the best solution would be to register an inclusion_tag, that would handle the part and forloop.counter operations: @register.inclusion_tag("inc.html") def inc_tag(part, loop_counter): prefix = 'part%s_' % (loop_counter,) context = { 'part': part, 'prefix': prefix, } return context And you would call it like that {% for part in parts %} {% inc_tag part=part loop_counter=forloop.counter0 %} {% endfor %} Your way is also doable like so, but I wouldn't recommend that {% for part in parts %} {% with "part"|add:forloop.counter0|add:"_" as prefx %} {% include "inc.html" with o=part prefix=prefix %} {% endwith %} {% endfor %}
{ "language": "en", "url": "https://stackoverflow.com/questions/7574323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Jquery fullscreen image with borders I have some code which gives me a fullscreen image which is kept in its original proportions (ie. landscape is fully stretched width ways and portrait height ways). I need to be able to have varied borders around the page (ie top:100,left&right:120,bottom:200) that the image will stop at and not encroach into. Is there an easy fix with what I have? Any help is appreciated! function FullScreenBackground(theItem,imageWidth,imageHeight){ var winWidth=$(window).width(); var winHeight=$(window).height(); var picHeight = imageHeight / imageWidth; var picWidth = imageWidth / imageHeight; if ((winHeight / winWidth) > picHeight) { $(theItem).attr("width",winWidth); $(theItem).attr("height",picHeight*winWidth); } else { $(theItem).attr("height",winHeight); $(theItem).attr("width",picWidth*winHeight); }; $(theItem).css("margin-left",(winWidth-$(theItem).width())/2); $(theItem).css("margin-top",(winHeight-$(theItem).height())/2); } Dear lord....someone help me please!! The answer from Swatkins did give me the borders, but the image is not scaled in constraint proportions. I am using this great plugin from Malihu: http://manos.malihu.gr/simple-jquery-fullscreen-image-gallery but just trying to put varied borders around the image as I said above. Any help would be great A: Check the fiddle here : http://jsfiddle.net/leifparker/CSS5e/2/ This image will resize on click. The border margins are set according to a data-attribute (fullmargins) attached to the img. It follows regular margin shorthand (top, right, bottom, left) in pixels. It is presently animating, but you can turn the delay on the animate to 0 for an instantaneous resize. HTML <img src="http://www.airhorns.co.uk/imgs/85/klaxon_chrome.jpg" data-fullmargins="10 20 10 20" class="background_sizer_image" > Jquery function FullScreenBackground(theItem){ var imageWidth = theItem.width(); var imageHeight = theItem.height(); var theItemMargins = theItem.data('fullmargins').split(' '); var heightMarginDifference = parseInt(theItemMargins[0]) + parseInt(theItemMargins[2]); var widthMarginDifference = parseInt(theItemMargins[1]) + parseInt(theItemMargins[3]); var widthProportion = imageWidth / ($(window).width() - widthMarginDifference); var heightProportion = imageHeight / ($(window).height() -heightMarginDifference); if (widthProportion > heightProportion){ theItem.animate({ width : (imageWidth / widthProportion) , height : (imageHeight / widthProportion) }, 150) } else { theItem.animate({ width : (imageWidth / heightProportion) , height : (imageHeight / heightProportion) }, 150) } } $('.background_sizer_image').click(function(){ FullScreenBackground($(this))}); A: Not tested, but you might try: function FullScreenBackground(theItem,imageWidth,imageHeight){ var winWidth=$(window).width(); var winHeight=$(window).height(); var picHeight = imageHeight / imageWidth; var picWidth = imageWidth / imageHeight; if ((winHeight / winWidth) > picHeight) { $(theItem).attr("width",winWidth - 240); $(theItem).attr("height",picHeight*winWidth - 300); } else { $(theItem).attr("height",winHeight - 300); $(theItem).attr("width",picWidth*winHeight - 240); }; $(theItem).css("margin-left",(winWidth-$(theItem).width())/2 + 120); $(theItem).css("margin-top",(winHeight-$(theItem).height())/2 + 100); } This should decrease the height and width by the totals of the margins, then offset the top and left with the margins needed for those.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Referenced WebService not showing up when I attempt to debug my code I am in the process of attempting to consume a WCF webservice in my application, but after adding the service reference and the appropriate using statement, I am unable to compile my code, and I get the following error 11 times with 11 line numbers: Error 7 The type name 'SignOnService' does not exist in the type 'FTXService.FTXService' C:\Users\bdugan\documents\visual studio 2010\Projects\FTXService\FTXService\Service References\SignOnService\Reference.cs 130 20 FTXService I know the service exists since I have used it in PHP in the past, but I can't seem to figure out why it isn't working. Here is Reference.cs: //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.237 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace FTXService.SignOnService { using System.Runtime.Serialization; using System; [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="SimpleItem", Namespace="http://schemas.datacontract.org/2004/07/")] [System.SerializableAttribute()] public partial class SimpleItem : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool AuthenticatedField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string[] ContractIDsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string MessageStringField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string[] OwnerIDsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool PasswordChangedField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public bool Authenticated { get { return this.AuthenticatedField; } set { if ((this.AuthenticatedField.Equals(value) != true)) { this.AuthenticatedField = value; this.RaisePropertyChanged("Authenticated"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string[] ContractIDs { get { return this.ContractIDsField; } set { if ((object.ReferenceEquals(this.ContractIDsField, value) != true)) { this.ContractIDsField = value; this.RaisePropertyChanged("ContractIDs"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string MessageString { get { return this.MessageStringField; } set { if ((object.ReferenceEquals(this.MessageStringField, value) != true)) { this.MessageStringField = value; this.RaisePropertyChanged("MessageString"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string[] OwnerIDs { get { return this.OwnerIDsField; } set { if ((object.ReferenceEquals(this.OwnerIDsField, value) != true)) { this.OwnerIDsField = value; this.RaisePropertyChanged("OwnerIDs"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public bool PasswordChanged { get { return this.PasswordChangedField; } set { if ((this.PasswordChangedField.Equals(value) != true)) { this.PasswordChangedField = value; this.RaisePropertyChanged("PasswordChanged"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(ConfigurationName="SignOnService.ISignOn")] public interface ISignOn { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ISignOn/Authentication_Complex", ReplyAction="http://tempuri.org/ISignOn/Authentication_ComplexResponse")] FTXService.SignOnService.SimpleItem Authentication_Complex(string UserName, string Password); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ISignOn/Authentication_Simple", ReplyAction="http://tempuri.org/ISignOn/Authentication_SimpleResponse")] FTXService.SignOnService.SimpleItem Authentication_Simple(string Parameter1, string Parameter2); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ISignOn/Authentication_ChangePassword", ReplyAction="http://tempuri.org/ISignOn/Authentication_ChangePasswordResponse")] FTXService.SignOnService.SimpleItem Authentication_ChangePassword(string Parameter1, string Parameter2, string Parameter3); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ISignOn/Authentication_Reset", ReplyAction="http://tempuri.org/ISignOn/Authentication_ResetResponse")] FTXService.SignOnService.SimpleItem Authentication_Reset(string Parameter1); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public interface ISignOnChannel : FTXService.SignOnService.ISignOn, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class SignOnClient : System.ServiceModel.ClientBase<FTXService.SignOnService.ISignOn>, FTXService.SignOnService.ISignOn { public SignOnClient() { } public SignOnClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public SignOnClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public SignOnClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public SignOnClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public FTXService.SignOnService.SimpleItem Authentication_Complex(string UserName, string Password) { return base.Channel.Authentication_Complex(UserName, Password); } public FTXService.SignOnService.SimpleItem Authentication_Simple(string Parameter1, string Parameter2) { return base.Channel.Authentication_Simple(Parameter1, Parameter2); } public FTXService.SignOnService.SimpleItem Authentication_ChangePassword(string Parameter1, string Parameter2, string Parameter3) { return base.Channel.Authentication_ChangePassword(Parameter1, Parameter2, Parameter3); } public FTXService.SignOnService.SimpleItem Authentication_Reset(string Parameter1) { return base.Channel.Authentication_Reset(Parameter1); } } } Any ideas? A: There is a class in the service called FTXService, embedded in a namespace also called FTXService. When generating a client proxy out of that service, the service generator of Visual Studio messes up. It generates code that seems to reference to the re-occurring namespace used in the servicerefence instead of the service class method to be called. To solve this, rename the class of your service implementation to (for example) FTXServiceImpl and regenerate your client proxy (remove and add your service reference in the client project). A: When you use the Add Service Reference dialog in Visual Studio it usually asks you to specify a namespace. By default it is ServiceReference1. It also generates strongly typed proxy client classes that usually end up with. So the client proxy might look something like this: using (var client = new ServiceReference1.SomeNamespace.SignOnServiceClient()) { ... } Simply right click on the generated service proxy and browse the source code to see what classes exactly were created. A: According to the Reference.cs you posted the service client is called SignOnClient so you'll want something like: var client = new SignOnClient(); Or to fully-qualify it: var client = new FTXService.SignOnService.SignOnClient(); In other words the type SignOnService does not exist in the namespace (this is what the error is telling you) but SignOnClient does.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can you set up Eclipse to remove trailing whitespace when saving a JavaScript file? I am running Eclipse 3.6 (Helios 20110218-0911) on Ubuntu 11.04. Under Preferences, I have gone to the following panel: JavaScript -> Editor -> Save Actions. The "Additional actions" checkbox is checked and "Remove trailing whitespaces on all lines" is selected. Nevertheless, when I save my JavaScript file in Eclipse, there is still trailing whitespace at the end of my lines. What am I missing? A: 'Save Actions' for JavaScript is available in the JavaScript project(the project with JavaScript nature) only. (If you can see 'Convert to JavaScript Project' in 'Configure' menu when right-click the project, try it) A: I recently faced the same problem. The only way I found is to convert your project to Javascript project. Right click your project folder in the Explorer, choose [Configure] -> [Convert to Javascript project] and the Javascript Save Action will start to work. Unfortunately, I don't know how to convert it back. Since it's not a big problem for me, the way Converting it to javascript project indeed helps me a lot. A: For the latest Eclipse - Version: Oxygen.3a Release (4.7.3a) Build id: 20180405-1200 The default key-binding shift+ctrl+backspace, which binds to the function "Removes the trailing whitespace of each line" will remove trailing space chars for the entire file. (The key-binding shift+ctrl+backspace is probably already there in many earlier releases as well.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7574340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: IOS simulator problem app only runs when started for the second time.. My app runs fine on my physical device (iphone 4), it also runs fine on the IOS simulator, but only after the second time I ty to run it from Xcode. So the sequence in which things are happening is: * *IOS simulator closed. *I press "ctrl R" in XCode *IOS simulator starts, app starts but gets no further then the splash screen (does not crash it just sits at the splash screen) *I press the stop Button in Xcode (app stops running in Simulator) *I Press "ctrl R" again *App starts in IOS simulator and runs like a charm.. If I close the IOS simulator reopen open it from finder and run the installed version, it runs without problems. Two questions, * *has anyone had a similar experience? *am I in trouble when submitting my app to the appStore Thnx, Sebastian A: The problem went away when I removed the majority of my logging messages (I had ton's of them). So either there was an issue with one of the messages or it had to do with the amount of them , hope this helps anyone who experiences the same problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Changing size of MainWindow.xib's Window Is there a way to change the dimensions of the main window in Xcode, the Window object stored in the MainWindow.xib from an iphone size to an iPad size? Other dimensions are editable of other nib file objects, like views, etc, but the main Window appears to not be. If it cannot be changed, then I guess I would need to create a new nib window nib file for the iPad device family, and then manually add the viewcontroller and other information into it, is this the only option? A: You could just right click on the target and select Duplicate. A dialog box will show up, select Duplicate and Transition to iPad. Then all you need to do is select which scheme you want to build for, iPad or iPhone. This way Xcode will duplicate all the needed xib files in your project and you will not have to manually add the needed view controllers. To choose the scheme, select the left side of the bar that says iPhone 4.3 Simulator. Select the one with copy at the end and you should be good to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom date units for javascript I'm working on a javascript app that does a lot of Date arithmetic, and for convenience (and readable code), I've found it useful to create some constants that I load into each page: var oneSecond = 1000; var oneMinute = 60*oneSecond; var oneHour = 60*oneMinute; var oneDay = 24*oneHour; var oneWeek = 7*oneDay; I'm going through a code refactor (down with cruft!), and it occurs to me that I can't be the first one who needed constants like these. Is there an canonical javascript library that provides these (or something comparable) so I can just use it and be nicer to my readers? A: I think you're looking for datejs: http://www.datejs.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7574349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Segmentation fault using FFTW I have a pretty involving program that uses an in house FFT algorithm. I recently decided to try using FFTW for a performance increase. Just as a simple test to ensure that FFTW would link and run, I added the following code to the beginning of the application, however, when I run, I get a segmentation fault when I create the fftwf_plan: const size_t size = 1024; vector<complex<float> > data(size); for(size_t i = 0; i < size; ++i) data[i] = complex<float>(i, -i); fftwf_plan plan = fftwf_plan_dft_1d(size, (fftwf_complex*)&data[0], (fftwf_complex*)&data[0], FFTW_FORWARD, FFTW_ESTIMATE); // ^ seg faults here ^ fftwf_execute(plan); fftwf_destroy_plan(plan); Any ideas what would be causing this? Using FFTW 3.3. Tried 2 different compilers, g++ 4.1.1 and icc 11.1. Also, the core file file shows nothing of significance: Thread 1.1: Error at 0x00000000 Stack Trace: PC: 000000, FP=Hex Address EDIT I reconfigured FFTW to add debug, using the following commands: setenv CFLAGS "-fPIC -g -O0" configure --enabled-shared --enable-float --enable-debug make make install When the program has a segmentation fault, it is in a random location in the fftwf_plan_dft_1d() method, however, the stack trace allways shows that is in or below the function search which is called by mkplan. A: Aparently the issue stems from multi-threading. Even though the main functions are thread safe in FFTW (e.g. fftwf_execute), the functions to create a plan are not. This doesn't fully explain why just running a test on startup failed, however, when I excapsulated the plan creation in mutex locks, the segmentation faults ceased. A: The creation and destruction of plans must be single threaded fftw_init_threads(); #pragma omp parallel for for(i=0;i<n;i++) { #pragma omp critical { plan = fftw_create_plan.... } fftw_execute(plan); // or the fftw_execute_dft for multiple in/out fft operations #pragma omp critical { fftw_destroy_plan(plan); } } fftw_cleanup_threads(); A: I'm 3 years late, but I've just stumbled upon a very similar problem, also when using multi-threading (--enable-openmp and fftw_plan_with_nthreads(omp_get_max_threads())). Mine seg faulted on fftw_destroy_plan(p). It turned out that I didn't pay attention when restructuring my code, and I was calling fftw_cleanup_threads() before calling fftw_destroy_plan(p) ... silly, I know, but it got me chasing my tail for about 1h. When using multi-threading, fftw_cleanup_threads() needs to be called after all fftw* functions, just as fftw_init_threads() needs to be called before any fftw* function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Recursive data structures in haskell: prolog-like terms I have a question about recursive data structures in Haskell (language that I'm currently trying to learn). I would like to encode in Haskell Prolog-like terms, but every solution I came up with has different drawbacks that I would really like to avoid. I would like to find a cheap and elegant way of encoding a BNF grammar in Haskell types, if you wish to see my problem from this perspective. Just as a reminder, some prolog terms could be male, sum(2, 3.1, 5.1), btree(btree(0, 1), Variable). Solution 1 data Term = SConst String | IConst Integer | FConst Double | Var String | Predicate {predName :: String, predArgs :: [Term]} With this solution I can have nested predicates (since predArgs are Term), but I can't distinguish predicates from other terms in type signatures. Solution 2 data Term = SConst String | IConst Integer | FConst Double | Var String data Predicate = Predicate {predName :: String, predArgs ::[Either Term Predicate} In this variant I can clearly distinguish predicates from basic terms, but the Either type in the predArgs list can be quite a nuisance to manage later in the code (I think... I'm new to Haskell). Solution 3 data Term = SConst String | IConst Integer | FConst Double | Var String | Struct String [Term] data Predicate = Predicate String [Term] With this last solution, I split terms in two different types as before, but this time I avoid Either Term Predicate adding a Struct constructor in Term with basically the same semantics as Predicate. It's just like solution 1 with two predicate constructors for terms. One is recursion-enabled, Struct, and the other one, Predicate is to be able to distinguish between predicates and regular terms. The problem with this try is that Struct and Predicate are structurally equivalent and have almost the same meaning, but I will not be able to write functions that works - in example - both on (Predicate "p" []) and (Struct "p" []). So again my question is: please, is there a better way to encode my predicates and terms such that: * *I'm able to distinguish between predicate and terms in type signatures; *nested predicates like p(q(1), r(q(3), q(4))) are supported; *I can write functions that will work uniformly on predicates, without any distinction like the one in solution #3? Please feel free to ask me for further clarifications should you need any. Thank you very much. A: You could add a term constructor to wrap a predicate. Here, I also factored all of the literals into their own data type: data Term = TLit Literal | TVar String | TPred Predicate data Literal = LitS String | LitI Int | LitF Double data Predicate = Predicate String [Term] A: Here's one way (that's probably not worth the trouble): {-# LANGUAGE EmptyDataDecls #-} -- 'T' and 'F' are short for 'True' and 'False' data T = T data F -- 'p' is short for 'mayNotBeAPredicate' data Term p = SConst !p String | IConst !p Integer | FConst !p Double | Var !p String | Predicate {predName :: String, predArgs :: [Term T]} sconst :: String -> Term T iconst :: Integer -> Term T fconst :: Double -> Term T var :: String -> Term T predicate :: String -> [Term T] -> Term p sconst = SConst T iconst = IConst T fconst = FConst T var = Var T predicate = Predicate checkPredicate :: Term p -> Maybe (Term F) checkPredicate (Predicate name args) = Just (Predicate name args) checkPredicate _ = Nothing forgetPredicate :: Term p -> Term T forgetPredicate (SConst _ s) = sconst s forgetPredicate (IConst _ i) = iconst i forgetPredicate (FConst _ f) = fconst f forgetPredicate (Var _ s) = var s forgetPredicate (Predicate name args) = predicate name args You can now write functions which only accept predicates by giving them an input type of Term F, and functions which accept any input type by giving them an input type of Term p.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Remove javascript console sentences from source using gsub Im noob in ruby and i coding a simple rakefile ... one of my task remove from javascript files the "console" lines, what do you thing about the current snippet? def self.remove_debug() FileList[File.join(DIST_DIR, '**/console-nodebug.js')].each do |file_name| puts "file: #{file_name}" content = File.read(file_name).gsub(/console\..*?;/m, "// console removed") File.open(file_name, 'wb') { |file| file.write(content) } end end its fine?? i need to change something? i test the code and all goes fine, but ... im looking for good practices ... thks! A: I would recommend having a debug variable and have ruby initialize that variable (I really don't know much about ruby, I leave this to you, I guess something like injecting it in the html file). And then in you js file you may do like this: if (debug) { console.log("I'm debugging! Yay!! XD"); } In my humble opinion this is better than modifying the file. Hope it helped, good luck! ==EDIT== If it's a minified file that you need to shrink I would suggest replacing your regex bu "/* console removed */" instead of "// console removed", just in case that there is some more code after that line. Other than that I think you will be ok. Is it working?
{ "language": "en", "url": "https://stackoverflow.com/questions/7574356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails 3.1 Jquery Ajax CRUD Operations I am working on Rails 3.1 Jquery Ajax demo app listed here https://github.com/samnang/ajax_rails31_demo. I am trying to add code to delete comments. I have modified comments_controller.rb and added a destroy action. I also added a link to the app/views/_comment.html.erb to include a Destroy link. I am able to get the comment to delete and the comment count is decremented by 1, but the comment partial does not update removing the entry. Only upon page refresh does the page display correctly. Here is my code app/controllers/comments_controller.rb class CommentsController < ApplicationController respond_to :html, :js def index @comments = Comment.all end def create @comment = Comment.new(params[:comment]) @comment.save respond_with @comment, :location => comments_url end def destroy @comment = Comment.find(params[:id]) @comment.destroy respond_with @comment, :location => comments_url end end app/views/comments/index.html.erb <% title "Comments for Ajax in Rails 3.1" %> <div id="comments_count"><%= comments_count %></div> <div id="comments"> <%= render @comments %> </div> <h3>Add your comment:</h3> <%= form_for Comment.new, :remote => true do |f| %> <%= f.error_messages %> <p> <%= f.label :name %><br /> <%= f.text_field :name %> </p> <p> <%= f.label :content, "Comment" %><br /> <%= f.text_area :content, :rows => '12', :cols => 35 %> </p> <p><%= f.submit %></p> <% end %> app/views/comments/_comment.html.erb <div class="comment"> <strong><%= comment.name %></strong> <em><%= comment.created_at.strftime('%b %d, %Y at %I:%M %p') %></em> <%= simple_format comment.content %> <%= link_to "Destroy", comment,:remote => true, :confirm => "You Sure", :method => :delete %> </div> app/vews/comments/create.js.coffee $('<%= escape_javascript(render(:partial => @comment))%>') .appendTo('#comments') .hide() .fadeIn() $('#new_comment')[0].reset() $('#comments_count').html '<%= comments_count %>' app/views/comments/destroy.js.coffee $('#new_comment')[0].reset() $('#comments_count').html '<%= comments_count %>' The destroy jquery portion is where I believe I am messing up. How do I reload the partial to remove the deleted comment? A: I have updated my example on Github to support destroy action. In your example you didn't remove dom element in your destroy.js.coffee. Check out full code on Github again or look at below snippets: app/views/comments/_comment.html.erb <div id=<%= dom_id(comment) %> class="comment"> <strong><%= comment.name %></strong> <em>on <%= comment.created_at.strftime('%b %d, %Y at %I:%M %p') %></em> <%= link_to "Remove", comment, :method => :delete, :remote => true %> <%= simple_format comment.content %> </div> app/views/comments/destroy.js.coffee $('#comments_count').html '<%= comments_count %>' $('#<%= dom_id(@comment) %>') .fadeOut -> $(this).remove()
{ "language": "en", "url": "https://stackoverflow.com/questions/7574358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Producing lists in Intl/ICU with PHP I'm using PHP 5.3's Intl extension for formatting strings on my website. However, I have happened upon a string that requires a list of items. The list given to the website can be any number of items, and should appear in however the language renders lists. In English, it would appear as "a, b, c, and d" or "a, b, c, d, e, f, g, and h". Rendering this English form is easy enough, but I don't know if this is a generic, international way of producing lists (I would bet that it isn't). Is there some way to do this with the intl extension, or ICU formatting? A: so, CLDR (from which ICU data comes) does have lists. However, it is not implemented in ICU yet- it's scheduled for ICU v49 (March, 2012) for both ICU4J and ICU4C. Then, php intl will need to pick it up. You might file a bug now on php intl to start tracking this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Pulling from a very very specific location imbedded in a text file I finished every piece of code in my program save for one tid bit, how to pull two numbers from a text file. I know how to pull lines, I know how to pull search strings, but I cant figure out this one to save my life. Anyways here is a sample of the automatically generated text that I need to pull from... ....................................................................... Applications Memory Usage (kB): Uptime: 6089044 Realtime: 6089040 ** MEMINFO in pid 764 [com.lookout] ** native dalvik other total size: 27908 8775 N/A 36683 allocated: 3240 4216 N/A 7456 free: 24115 4559 N/A 28674 (Pss): 1454 1142 6524 *9120* (priv dirty): 1436 628 5588 *7652* Objects Views: 0 ViewRoots: 0 AppContexts: 0 Activities: 0 Assets: 3 AssetManagers: 3 Local Binders: 15 Proxy Binders: 41 Death Recipients: 3 OpenSSL Sockets: 0 SQL heap: 98 MEMORY_USED: 98 PAGECACHE_OVERFLOW: 16 MALLOC_SIZE: 50 DATABASES pgsz dbsz Lookaside(b) Dbname 1 14 120 google_analytics.db Asset Allocations zip:/system/app/com.lookout_6.0.1_r8234_Release.apk:/resources.arsc: 161K ............................................................................. The two numbers that I need out of this are the two ones that I put in the **'s (the asterisks are not normally there). These numbers will be different every time this sheet is generated, and the number placement might be different as well as some of the numbers could have 4 digits, 5 digits, or 6 digits. If anyone could shed any light on the subject it would be greatly appreciated Thanks, Zach A: You just need to read in the last word of the line and convert it to a number. Use String.LastIndexOf to find the last space " " in the file and read the data from that point forwards. Dim line as String = " (Pss): 1454 1142 6524 9120" Dim value as Integer If line.IndexOf("(Pss)") > 0 Then value = CInt(line.Substring(line.LastIndexOf(" ") + 1)) End If
{ "language": "en", "url": "https://stackoverflow.com/questions/7574362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Different paints for Textsize Is it more efficeint to create a new Paint() or modify and exsisting one when you want to print something in a different font size or style? - this is for a game so the changes would be made each frame A: As far as I know object creation is always expensive. You should avoid that if you can, especially in your case when this happens each frame. Android always suggest you to reuse objects (see this doc). I don't think that Paint should have such a big memory footprint but why not just reuse. Or create two of them and use them? When should I reuse an object (paint in this case)? If you're just changing text size and color I would reuse one paint. If you're changing changing nearly every attribute of paint to draw another text I would suggest to create another paint object for that because you culd initialize it once, reuse it for the same kind of text and your code will be cleaner. A: If the Paint object does not have to change each frame, then I would trade a small memory penalty for better performance by creating one Paint object for each size you need, but not on each frame. Do it in the class constructor and use it each frame, so they are created once only. Moreover, if the Paint will not change for different instances, make the Paints static and you'll have one set for all instances.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XCode Instruments Allocations: Look at Live Bytes or Overall Bytes? I am getting some memory warning in my iOS app so I am running Instruments to see the allocations. Should I look at the * All Allocations * Live Bytes or Overall Bytes? Someone said the iOS can close my app if I use for 22MB, is that from the Live or Overall bytes section? A: Live Bytes is the current usage and is what you are interested in, overall bytes includes all released allocation. The other thing is to look at the graph and look for peaks. As an example I saw a huge peak of about 27MB in an app I was working on, knowing that I was able to reduce peak memory usage to 8MB. Also watch over time as you exercise your app, it is possible to have substantial memory growth over time that is not leaked, just not not used anymore. For a description of the memory columns see Explanation of Live Bytes & Overall Bytes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: jQuery Expanding Navigation with Body classes Every page on my site has multiple body classes that I use CSS selectors with, like so: <body class="category subcategory page"> I would like to be able to automatically add the class 'expanded' to the menu item in the left nav if it matches the final class in that declaration. So far, my understanding of it is that I can set a variable to the body's last class name using className().last(); and then just write and if statement to determine if the menu item (an unordered list item) matches it and addClass('expanded'); But it's not working. Would someone be kind enough to help me with the syntax? I'm still a bit new to JavaScript. $(document).ready(function () { var pageclass=('body').className().last(); if ($('div.nav-menu li').hasClass(pageclass)){ $(this).addClass('current'); } }); A: Not sure if className() is a real method.. Try this: var last_class = $('body').attr('class').split(' ').slice(-1); if ($('div.nav-menu li.arrowed').hasClass(last_class)){ .. }
{ "language": "en", "url": "https://stackoverflow.com/questions/7574365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: writing UI content to a file on a server I've got a pop-up textarea, where the user writes some lengthy comments. I would like to store the content of the textarea to a file on the server on "submit". What is the best way to do it and how? THanks, A: This would be very easy to do. The text could be just a string or stringBuffer for size and formatting, then just pass that to your java code and use file operations to write to a file. This is some GWT code, but it's still Ajax, so it will be similar. Get a handler for an event to capture the button submittal, then get the text in the text area. textArea.addChangeHandler(new ChangeHandler() { public void onChange(ChangeEvent changeEvent) { String text = textArea.getText(); } }); The passing off mechanism I don't know because you don't show any code, but I just created a file of filenames, line by line by reading filenamesout of a list of files with this: private void writeFilesListToFile(List<File> filesList) { for(File file : filesList){ String fileName = file.getName(); appendToFile(fileName); } } private void appendToFile(String text){ try { BufferedWriter out = new BufferedWriter(new FileWriter<file path andfile name>)); out.write(text); out.newLine(); out.close(); } catch (IOException e) { System.out.println("Error appending file with filename: " + text); } } You could do something similar, only write out the few lines you got from the textarea. Without more to go on I can't really get more specific. HTH, James
{ "language": "en", "url": "https://stackoverflow.com/questions/7574366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I delete an unretrievable file from a Perforce repository? In my Perforce repository there's a file that was submitted a while ago and was at one point valid. I need to move the file and its parent directory to a different location in the repository. However, I'm unable to retrieve a copy of the file from the repository due to the following error reported in P4V (2010.2) and p4 on Linux & Mac OS X: Bad AppleSingle/Double header. Malformed FInfo/FXInfo structure! File not updated. The file is an Apple DMG (disk image) installer. It appears that the file in the repository is corrupted and I'm unable to retrieve it. Is it possible to retrieve the file regardless of errors in the file in the repository? Is it possible to move the file in the repository without have a local copy of the file in my workspace? A: Use the command line tool: p4 delete -n //path/to/the/rotten/file As long as your client maps //path/... you can delete things without fetching them (eg, don't do a p4 sync first)
{ "language": "en", "url": "https://stackoverflow.com/questions/7574368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Intent from Android Notepad example action: android.intent.action.PICK data: content://com.google.provider.NotePad/notes Asks the activity to display a list of the notes under content://com.google.provider.NotePad/notes. The user can then pick a note from the list, and the activity will return the URI for that item back to the activity that started the NoteList activity. action: android.intent.action.GET_CONTENT data type: vnd.android.cursor.item/vnd.google.note Asks the activity to supply a single item of Note Pad data. The above is directly from Android Notepad example. My question is, why have they defined two intent actions that perform the same task?? When will one or the other action be performed? Also in the code, they have defined String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { Could someone please clarify, when will an action be set and on ListItemClick how will getAction resolve to either ACTION_PICK or ACTION_GET_CONTENT Thanks in advance A: My question is, why have they defined two intent actions that perform the same task? They are not the same task. Quoting the documentation for ACTION_GET_CONTENT: This is different than ACTION_PICK in that here we just say what kind of data is desired, not a URI of existing data from which the user can pick. A ACTION_GET_CONTENT could allow the user to create the data as it runs (for example taking a picture or recording a sound), let them browser over the web and download the desired data, etc. When will one or the other action be performed? When somebody calls startActivity() with an Intent containing one of those two actions, plus a content Uri pointing to this application (in this case). Could someone please clarify, when will an action be set It is set in the Intent used with the startActivity() call that was used to start the activity. how will getAction resolve to either ACTION_PICK or ACTION_GET_CONTENT By executing the code you included in your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extracting numeric range "values" from a Ruby Hashtable or JSon object I am quite new to Ruby (1.8.7), and would like to be able to extract values from a Hashtable which are within a specific numeric range (without having to iterate through the values). If I have Hashtable with: my_hash = { 55 => {:value=>61, :rating=>147}, 89 => {:value=>72, :rating=>200}, 78 => {:value=>64, :rating=>300} } How would I parse the Hashtable so the rating=>300 was returned (if a range of 250..350) was specified? Alternatively I will sort the Hashtable on the rating value and iterate checking each value individually. Thanks, Miles. A: To return my_hash entries within a range of ratings: my_hash.select { |k,v| (250..350).include?(v[:rating]) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7574377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: type wrapper error with boost::mpl::for_each (section 9.1.1 from Abrahams & Gurtovoy book) The following code is copied almost verbatim from section 9.1.1 of the book C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond by David Abrahams & Aleksey Gurtovoy. The only change is that I want to be able to change the type wrapper template from the book with the regular Boost template mpl::identity. However, under Microsoft Visual C++ Express 2010 (SP1) I get a mysterious compiler warning if I do that. It seems somehow related to the fact that the type wrapper template has an inner typedef named "type". Changing that typedef to "Type" (or simply removing that line) will make the code work correctly. Does anyone have an explanation for this weird behavior? #include <iostream> #include <typeinfo> #include <boost/mpl/for_each.hpp> #include <boost/mpl/vector.hpp> namespace mpl = boost::mpl; // added a nested typedef named "type" is equivalent to mpl::identity template <class T> struct wrap { // changing type -> Type or removing this line // makes the code compile and produce correct output! typedef T type; }; struct print_type { template <class T> void operator() (wrap<T>) const { std::cout << typeid(T).name() << std::endl; } }; class A { A() {} // private constructor }; class B { B() {} // private constructor }; typedef boost::mpl::vector<A,B> AB; int main() { boost::mpl::for_each<AB, wrap<mpl::_> >( print_type() ); /* Output: class A class B */ return 0; } Output of /I"C:\Program Files\boost\boost_1_47" /I"C:\Program Files\boost" /Zi /nologo /W3 /WX- /O2 /Oi /Oy- /GL /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Gm- /EHsc /GS /Gy /fp:precise /Zc:wchar_t /Zc:forScope /Fp"Release\mpl.pch" /Fa"Release\" /Fo"Release\" /Fd"Release\vc100.pdb" /Gd /analyze- /errorReport:queue : 1>------ Build started: Project: mpl, Configuration: Release Win32 ------ 1> main.cpp 1>C:\Program Files\boost\boost_1_47\boost/mpl/for_each.hpp(75): error C2784: 'void print_type::operator ()(wrap<T>) const' : could not deduce template argument for 'wrap<T>' from 'arg' 1> ..\..\..\mpl\main.cpp(20) : see declaration of 'print_type::operator ()' 1> C:\Program Files\boost\boost_1_47\boost/mpl/for_each.hpp(101) : see reference to function template instantiation 'void boost::mpl::aux::for_each_impl<false>::execute<first,last,TransformOp,F>(Iterator *,LastIterator *,TransformFunc *,F)' being compiled 1> with 1> [ 1> TransformOp=wrap<boost::mpl::_>, 1> F=print_type, 1> Iterator=first, 1> LastIterator=last, 1> TransformFunc=wrap<boost::mpl::_> 1> ] 1> ..\..\..\mpl\main.cpp(42) : see reference to function template instantiation 'void boost::mpl::for_each<AB,wrap<T>,print_type>(F,Sequence *,TransformOp *)' being compiled 1> with 1> [ 1> T=boost::mpl::_, 1> F=print_type, 1> Sequence=AB, 1> TransformOp=wrap<boost::mpl::_> 1> ] ========== Build: 0 succeeded, 1 failed, 2 up-to-date, 0 skipped ========== A: Some terminology, paraphrased from the Boost.MPL reference manual: * *A metafunction is a type with a nested type named type *A metafunction class is a type with a nested metafunction named apply *A placeholder expression is a type that is either an MPL placeholder or a class template specialization with at least one argument that itself is a placeholder expression Thus we know that wrap<> is a metafunction, and that wrap<mpl::_> is both a placeholder expression and a metafunction. When mpl::for_each<> is passed a metafunction or a metafunction class for the TransformOp template argument, it evaluates that metafunction/metafunction class to obtain the result of the transformation. Consequently, if you want to pass a raw placeholder expression without further evaluation, your placeholder expression must not meet the criteria of a metafunction or metafunction class. In your scenario, because wrap<> is a metafunction, mpl::for_each<> is evaluating it and producing A and B as the transformed types; meanwhile, print_type::operator()<> is expecting a wrap<A> and wrap<B> -- of course this will refuse to compile.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How does one omit the closing slash on elements using WTForms? I've been noticing that WTForms (and Flask-WTF) output <input> elements with a closing slash like so: <input name="text" type="text" value="" /> My documents are HTML5 and therefore need no XHTML-type closure. How would I make WTForms output the input tag as such? <input name="text" type="text" value=""> I've been tearing through the docs and the source code an am finding no clues. I could create a series of custom widgets, of course, but that seems a bit excessive for something so simple. Is there an easier way? Or is this perhaps a Jinja2 configuration issue that I'm missing? A: Use any revision past this one (or simply download tip) - WTForms is moving to the HTML5 way of generating form elements and adding some new widgets too (I believe). See this thread and this one for a bit more information. * There is also an extension for WTForms that adds the XHTML back in, if you decide you need it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: String to unique int algorithm We are trying to implement the following case. We have a invoice table and there is a column which has email address. We want to somehow generate a unique int value from this email address and store that in a separate column. This will be used as a FK and indexed. So what I am looking for is an algorithm for generating ints from strings (please note that the email string should always output the same int so each email address as a unique int representation). We can use a bigint as well A: Simplest solution is to put the email address into its own table along with an identity/auto_increment type column. Then you can simply carry around that identify field (a standard int), and you don't run into any issues with potential hash collisions, and no hashing overhead. A: It seems a simple hashcode (MD5, SHA1, ...) should fit your needs; depending on your RDBMS, you might be able to use built-in packages (e.g. Oracle's dbms_crypto) or have to compute them externally. Some things to keep in mind: * *convert everything to lower/uppercase before computing the hashcode (so USER@DOMAIN.COM gets the same hashcode as user@domain.com) *apparently, you have a denormalized schema. It would make more sense to have a separate customer table containing the E-Mail adress; invoice should then contain only a foreign key customer_fk A: MD5 - gives you a 128-bit integer. (Admittedly, this is bigger than the int datatype in most languages, but you won't get near guaranteed uniqueness with with just 32-bits.) A: I don't know if you can get away with a 64-bit int: the max length of an email address is 254 characters and, in this case where you need to preserve the uniqueness of each, hashing will not do it. So it seems you are stuck with having to get over this 254-character hurdle. My approach (always the brute force approach for me) would be to take the alphabet of allowable characters in an email address, map those to 6-bit values, and use the map to pack them into a series of words. Take a look at rfc3696 which deals with email addresses in a way that's actually comprehensible. Sorry to be of so little help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Master pages for GAE project (python) I've got a project running on GAE and I am quite sick of manual support of headers and footers in all the page templates I have. Is there any way to use master pages for GAE? A: You can have a _base.htm template with header and footer: <!-- header --> {% block bodycontent %} {% endblock %} <!-- footer --> And expand it using specific templates: {% extends "_base.htm" %} {% block bodycontent %} <!-- template-specific stuff --> {% endblock %} Example This is a template folder of my cms-app on github: templates/ ├── _404.htm ├── _base.htm ├── _edit.htm ├── _login.htm ├── _unavailable.htm ├── blog.htm └── default.htm Where blog.htm and default.htm templates extend the _base.htm template with headers, footers and counters. Side note, On my other app, which is not on github, I use naming convention with names like search.foo.base.htm which means that it's a templates that extends foo.base.htm template, which extends base.htm template - I think this is a useful tip if you have complex hierarchy of templates. Documentation GAE uses django templates version 0.96 (by default), which docs could not be found on djangoproject.com site. However, some good people put them online, see this question: Missing Django 0.96 Template documentation (used by Google AppEngine developers)
{ "language": "en", "url": "https://stackoverflow.com/questions/7574385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does one change the color for text highlighting in Xcode 4 for warnings and errors? Possible Duplicate: Fix for Xcode's indiscernible highlighting of inline errors? Does anyone know how to change the color of the in-line highlighting for warnings and errors in Xcode 4? With almost every theme, the yellow warning highlight makes the underlying code impossible to read. Example picture A: Just came across this, which seems to be able to modify some of Xcode's behaviors by creating some sort of plugin. Maybe one can be developed to change text highlight color. http:/github.com/davekeck/Xcode-4-Fixins Update: I've finally managed to implement a Xcode "fixin" to do it. You just need to open the project and build it. Doing so will install an Xcode plugin called "XCFixin_CustomizeWarningErrorHighlights.xcplugin" into ~/Library/Application Support/Developer/Shared/Xcode/Plug-ins. You can of course customize the colors to your liking. Get the "fixin" here: https://github.com/armadillu/Xcode-4-Fixins/tree/master/XCFixin_CustomizeWarningErrorHighlights A: There is no (official) way to do this and I believe that it's like that for a reason... We all know how much attention to details and UI paradigms Apple is paying. An error colored in Green for example would break that paradigm and possibly confuse the user. That being said, I think that a (somewhat) solution would be instead of recoloring the warning/error bubbles, to recolor the theme in such a way that every color would make a strong contrast with red/yellow (ie avoid reddish/yellowish tones) tints. A: there is no options which you can change color of warning and errors.its inbuilt with Theme you are using for xcode. but you can change the style from xcode->fonts & colors and select different theme.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: eclipse shiro ini problem Honestly, before posting question did googling and 2 days tried to solve problem on my own... I want to get Apache Shiro working with GAE. Before that, I had success with Spring Security, but here I can't do a simple thing: to get the filter find my shiro.ini ! After introducing ShiroFilter in web.xml, in init-param tag I give a value of classpath:shiro.ini for the param-name called configPath, as standard way. Next, I put shiro.ini in my src root, won't work, then under /web-inf/shiro.ini, again didn't work... any help please? A: Maybe this tutorial of integrtating Shiro with GAE will be useful?
{ "language": "en", "url": "https://stackoverflow.com/questions/7574390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VBA Outlook Script I have a script I've pieced together over time. Recently a plugin we need to use in Outlook has caused some issues. Basically we get prompted twice because when the plugin is used the e-mail ends up being destroyed and re-created with a specific attachment filename. At this point the user is prompted again. I've tried to work in a For loop to skip the script if it finds this attachment. However, when I added the For loop it just seems to skip the entire script. I have limited experience with VBA and so I'm sure it's an issue with my syntax or usage. See script below: Private Sub Application_ItemSend _ (ByVal Item As Object, Cancel As Boolean) Dim strMsg As String Dim Atmt As Variant 'strMsg = Item.Class If Item.Class = "43" Then For Each Atmt In Item.Attachments If VBA.Right(Atmt.FileName, 3) = ".sf" Then GoTo NonEmailError End If Next Atmt If Item.CC = "" Then strMsg = "To recipients: " & Item.To & vbCrLf & _ "Are you sure you want to send this message?" Else strMsg = "To recipients: " & Item.To & vbCrLf & _ "Cc recipients: " & Item.CC & vbCrLf & _ "Bcc recipients: " & Item.BCC & vbCrLf & _ "Are you sure you want to send this message?" End If Else GoTo NonEmailError End If ' Exit Sub ' Ignore errors for now. On Error GoTo NonEmailError ' Prompt user to fill in subject If Item.Subject = "" Then MsgBox "You must enter a subject.", 48, "Empty Subject" Cancel = True GoTo NonEmailError End If ' Exit Sub ' Prompt user to verify E-Mails If MsgBox(strMsg, vbYesNo + vbQuestion _ , "Send Confirmation") = vbNo Then Cancel = True End If Exit Sub NonEmailError: ' The item being sent was not an e-mail and so don't prompt the user anything Exit Sub End Sub A: I am not that familiar with outlook and VBA, but my first guess in this case is that item.class should be compared to the numeric value 43 rather than the string-literal value "43". The one thing that gives me pause is that I would expect the statement to throw an error because "43" is the wrong type for Item.Class, but this may just reflect my unfamiliarity with the material. According to msdn reference, item.class (in this case a mailItem) is an OlObjectClass constant, and 43 is olMail. It would probably be advisable to change: If Item.Class = "43" Then to If Item.Class = olMail Then or at least to: If Item.Class = 43 Then ( see: http://msdn.microsoft.com/en-us/library/bb208118%28v=office.12%29.aspx and http://msdn.microsoft.com/en-us/library/bb207137%28v=office.12%29.aspx )
{ "language": "en", "url": "https://stackoverflow.com/questions/7574392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using maven to copy war via ssh I want to copy war file via ssh. I have the following pom: <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>wagon-maven-plugin</artifactId> <version>1.0-beta-3</version> <executions> <execution> <id>default-cli</id> <goals> <goal>upload-single</goal> </goals> <configuration> <fromFile>${project.build.directory}/${project.build.finalName}.war</fromFile> <toFile>ROOT.war</toFile> <url>scpexe://my.server.com</url> <serverId>my.server.id</serverId> </configuration> </execution> </executions> </plugin> When I trying to execute mvn wagon:upload-single, I got the following message: Embedded error: Error executing command for transfer Exit code 255 - Permission denied (publickey,gssapi-with-mic,password). My settings.xml have proper username and password set. Also i can copy file to remote host manually without any propblem via scp. Please, help me to solve this problem. A: It works for me if I change <toFile>ROOT.war</toFile> <url>scpexe://my.server.com</url> to <toFile>/tmp/ROOT.war</toFile> <url>scp://my.server.com</url> A: You copy your file to the root folder. If you use this: <toFile>ROOT.war</toFile> <url>scpexe://my.server.com</url> Then it is like saying: copy to my.server.com, us this file path: /ROOT.war It is unlikely you have access to that folder. Try using for example your home folder: <toFile>/home/username/ROOT.war</toFile> <url>scpexe://my.server.com</url>
{ "language": "en", "url": "https://stackoverflow.com/questions/7574393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to align elements inside a tabPanel in Sencha touch I have this simple tabBar inside a TabPanel: MyApp.views.Viewport = Ext.extend(Ext.TabPanel, { fullscreen: true, tabBar: { dock: 'bottom', layout: { type: 'hbox', align: 'stretch' }, }, items: [ { xtype: 'homecard', id: 'home'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'spacer'}, { xtype: 'settingscard', id: 'settings'}, ], }); I'd like to be able to make 'elements' float left, center and right, adding bunch of spacer's isn't a 'really' good choice. Any idea on how to achieve this ? A: By default the spacer component will take up a flex of 1 unless a width is set. Which I think means to put a button on each side of the tabBar you should only need 1 spacer as long as you don't specify a width. However the tabBar must have a different default layout to the toolbar which works: MyApp.views.Viewport = Ext.extend(Ext.Panel({ fullscreen: true, layout: 'card', dockedItems: [{ xtype: 'toolbar', dock: 'bottom', defaults: { handler: function (btn, e) { MyApp.views.Viewport.setActiveItem(Ext.getCmp(btn.value)); } }, items: [{ text: 'homecard', value: 'home' }, { xtype: 'spacer' }, { text: 'settingscard', value: 'settings' }], layout: { type: 'hbox', align: 'center' } }], items: [{ title: 'homecard', id: 'home', html: 'home' }, { title: 'settingscard', id: 'settings', html: 'settings' }] }); you might be able to overload the tabBar to display the same as a toolbar but i wouldn't hold my breath. NB: stretch : Components are stretched vertically to fill the container.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How I do a function C# for i can receive messages from Server Chat in PC and Chat Client in Android device? In my C # application Chat Client I don`t not know how to do a function to receive messages from the Chat Server in C # and presents them in a TextView Chat Client I'm programming in Visual Studio in C # using Mono for Android. The question is... How I do a function for i can receive messages from Chat Server in PC and Chat Client in Android device? When i use Chat Client in windows 7 works good but when i make for a android device i can`t receive mensages from Server Chat to Chat Client. I think the problem as in public void RecievedMessage and private void UpdateTextbox. Sorry, my bad english. Thanks your atention. The Source Code, Chat Client: using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Android.Widget.EditText; using Android.Widget.Button; using Android.Widget.TextView; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading; using System.Runtime.InteropServices; namespace ChatClient_Android { [Activity(Label = "ChatClient_Android", MainLauncher = true, Icon = "@drawable/icon")] public class MainChat : Activity { public delegate void OnRecievedMessage(string message); public MainChat form; const int WM_VSCROLL = 0x115; const int SB_BOTTOM = 7; string msgrecebida; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); Button enviar = FindViewById<Button>(Resource.Id.btenviar); Button ligar = FindViewById<Button>(Resource.Id.btligar); TextView text1 = FindViewById<TextView>(Resource.Id.text1); EditText text2 = FindViewById<EditText>(Resource.Id.text2); //Conexão com o servidor ligar.Click += delegate { Connect(); ligar.Enabled = false; text1.Text = "Connected"; }; enviar.Click += delegate { if (text2.Text != "") { if (text2.Text.ToLower().StartsWith("/")) { text2.Text = ""; } else { SendMessage("MSG :" + text2.Text); text2.Text = ""; } } }; } private void Invoke(OnRecievedMessage onRecievedMessage, string message) { throw new NotImplementedException(); } public bool InvokeRequired { get; set; } public void RecievedMessage(string message) { if (InvokeRequired) { this.Invoke(new OnRecievedMessage(RecievedMessage), message); } else { UpdateTextbox(message); } } private void UpdateTextbox(string text) { msgrecebida += "\r\n"; msgrecebida += text; } //Interligações Classes MainChat & Connection public void Disconnected(string reason) { form.Disconnected(reason); } //TCP Connection public StreamWriter Outgoing; private StreamReader Incoming; private TcpClient Connection; private Thread Messages; private IPAddress IP; //public string host; //public string nick; //MainChat m_ParentForm; bool isConnected; //Função Conectar public void Connect() { try { IP = IPAddress.Parse("10.0.2.2"); Connection = new TcpClient(); Connection.Connect(IP, 1986); Outgoing = new StreamWriter(Connection.GetStream()); Outgoing.WriteLine("EcoDuty"); Outgoing.Flush(); //m_ParentForm.Vis(true); Messages = new Thread(new ThreadStart(this.Communication)); Messages.Start(); } catch (Exception e) { Disconnected(e.Message); } } private void Communication() { Incoming = new StreamReader(Connection.GetStream()); string check = Incoming.ReadLine(); if (check[0] == '1') { //m_ParentForm.Vis(true); isConnected = true; } else { string Reason = "Disconnected: "; Reason += check.Substring(2, check.Length - 2); Disconnected(Reason); return; } while (isConnected == true) { try { ServerMessage(Incoming.ReadLine()); } catch (Exception e) { if (isConnected == true) { Disconnected("Connection to server lost"); Console.WriteLine("Connection Lost: " + e.ToString()); } break; } } } private void ServerMessage(string message) { try { RecievedMessage(message); } catch { } } public void CloseConnection() { isConnected = false; Incoming.Close(); Outgoing.Close(); Connection.Close(); Messages.Abort(); } public void SendMessage(string message) { Outgoing.WriteLine(message); Outgoing.Flush(); } } } A: It looks to me like (one) problem is that you are trying to access text1 as if it is a field or property when it is a local variable declared in onCreate. You either need to push text1 up a level in scope, or grab a new reference to it in RecievedMessage. This is not a problem with Android, specifically, but is a difference with how the code is set up with Mono for Android. Typically, when working with Winforms in Windows, you'll be working in a partial class with all your controls defined in the designer.cs file as fields. But in your Mono code, you are binding to TextViews instead, and in your OnCreate instead of at instance scope. When you copy/pasted your code, you likely didn't account for that difference. As an aside, I highly doubt that the user32.dll function you are importing is going to do anything useful on Android. Unless the Mono folks are doing something magical, the win32 API will not be available on Android.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why 'bundle install' fails in Rails generator? I'm trying to create custom generator for Rails 3.1. And I wrote this: module SomeGem module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) desc "This adds devise" def install gem "devise" run "bundle install" end end end end But when I run this generator (rails g somegem:install, in the fresh-generated rails app) I've get this error: gemfile devise run bundle install Could not find gem 'devise (>= 0)' in any of the gem sources listed in your Gemfile. Run `bundle install` to install missing gems. My generator adds Devise into Gemfile properly, but it fails when run 'bundle install' command from generator. When I run 'bundle install' from console it installs all gems without any errors. Why is this happening? Here is my Gemfile after I run 'rails g somegem:install' (I removed comments from listing): source 'http://rubygems.org' source 'http://gemcutter.org' source "http://gems.github.com" gem 'rails', '3.1.0' gem 'mysql2' group :assets do gem 'sass-rails', " ~> 3.1.0" gem 'coffee-rails', "~> 3.1.0" gem 'uglifier' end gem 'jquery-rails' group :test do # Pretty printed test output gem 'turn', :require => false end gem 'therubyracer' gem "devise" A: As pointed here, this is a bug in Bundler. To make it work: module SomeGem module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) desc "This adds devise" def install gem "devise" Bundler.with_clean_env do run "bundle install" end end end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7574400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: From where can I install Report Application Server? I need RAS installed in my machine in order to create dynamic reports with the RAS SDK in .NET. I don't know how to install it. In which version of Crystal Report Server is it available? A: MSDN suggests RAS is available in Crystal Reports 10 and up. And from another MSDN page on RAS: Using the RAS API without a RAS server In Crystal Reports, you can access the advanced report creation and modification functionality of the ReportClientDocument Object Model (RAS) from the CR .NET SDK. The deployment package in this scenario requires only the .NET assemblies, meaning you are using the RAS API in-process. However, if you use the RAS API in-process, you lose the performance and stability benefits of a server-oriented, out-process system. To gain these benefits, use the RAS API in conjunction with a RAS Server in a Crystal Reports Server or BusinessObjects Enterprise environment. For additional information and sample code, see the ReportClientDocument property of the CrystalDecisions.CrystalReports.Engine.ReportDocument class in the API reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Summing values in Sencha List via Grouping and displaying in Group Header list item Could somebody give me a little info on how I might go about adding a summarized value to the header of a grouped list. For example. I have the model {firstname, lastname} and say 10 records. I want to group by lastname, but while I group I'd like to keep track of the number of records in the current grouping and display that in the "Header" or "Group Header". Like this.. Thompson -- 3 Results David Susan Audrey Smith -- 1 Result Cassy I have to do this client-side and can not group or summarize on the server. Thanks in advance. A: I think the only way to do this is to dynamically grouping the list. I have googled for some answers and figured out something similar to it from sencha forum. Its not the solution to your problem, but you can resolve it from the idea discussed there. Here is the link http://www.sencha.com/forum/showthread.php?104400-Dynamically-adding-removing-grouped-amp-indexBar-to-from-a-List Hope it will help...
{ "language": "en", "url": "https://stackoverflow.com/questions/7574404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use of predefined sounds in AudioServicesPlayAlertSound? Is it possible to use predefined sound ids in AudioServicesPlayAlertSound (http://www.iphonedevwiki.net/index.php/AudioServices) or can this cause my app to be rejected?
{ "language": "en", "url": "https://stackoverflow.com/questions/7574406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VBA function returns to calling routine on an assignment statement I have a mid-level function that is called and calls other functions. Inside the function a dynamic arrary is "Dim myarrary() As Variant" is loaded from called function. The arrary "myarrary" is loaded with the proper data. When I attempt to assign the arrary to range Dim datarng as Range datarng = WorkSheets("DATA").Range("A1:H3700").Value The debugger executes the statement and immediately returns to the top level routine that initiated the process. I'm thinking I crashed the stack somehow but I've place strings around myarray and they are intact. if I comment out the assignment statement the routine executes the remaining code in the function. A: My guess is that you have an error handler in the top-level routine but not in the lower-level functions. In that type of situation, when the code hits a run-time error it steps immediately to the routine that had an error handler. Also, Dim myarrary() As Variant creates an array of variants, which I don't think is what you want. It looks like you just want a variant, like: Dim myarrary As Variant You can then assign a range to it, e.g.: myarrary = WorkSheets("DATA").Range("A1:H3700").Value A: Your example code will not compile for two reasons: Dim datarng as Range datarng = WorkSheets("DATA").Range("A1:H3700").Value * *You can't assign a "value" to a Range. Right hand side should be WorkSheets("DATA").Range("A1:H3700"), and not WorkSheets("DATA").Range("A1:H3700").Value. *datarng is an object (of type Range), so you need the Set keyword to make the assignment. Left hand side should be Set datarng. The correct syntax is therefore: Set datarng = WorkSheets("DATA").Range("A1:H3700") Of course you can also dump the value content of datarng into a Variant like this: Dim myArray as Variant myArray = datarng ' or datarng.Value A: You are missing the Set in front of datarng = WorkSheets("DATA").Range("A1:H3700").Value should be Set datarng = WorkSheets("DATA").Range("A1:H3700")
{ "language": "en", "url": "https://stackoverflow.com/questions/7574408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using "FindControl" on a base page My page, Default.aspx inherits form BasePage.cs. In the base page I am trying to find the control Label1 that is actually in Default.aspx. var labelControl = (TextBox)Page.FindControl("Label1"); However, this is always coming back as null. Can I find controls of other pages through the base page? A: FindControl is not recursive (ASP.NET team haven't implemented it for performance reasons). A: If FindControl() doesn't wind up working, it should be possible by declaring your controls as properties in your BasePage class. Assuming that Default.aspx and other .aspx pages will all inherit from BasePage, you should be able to do this: public class BasePage { protected Label Label1; } In BasePage methods, check if your properties are not null. If so, the control exists and can be manipulated: protected void SomeBasePageMethod() { if (this.Label1 != null) { // Do something with Label1 } } A: Set the ClientIDMode of the Label & then try to find the label in BasePage.cs protected override void OnLoad(EventArgs e) { Label lbl = this.FindControl("Label1") as Label; } Hope this will help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I configure an ExtJS 4.0 xmlTreeStore for a treePanel with Designer 1.2? The tutorials for xml treePanels are too simple. I don't know if what I want is even possible. What I want is to see a tree with a root folder called "contenttype" (or simply "root" is acceptable). Inside the root folder is one folder called "config" and inside of that should be any number of folders called "block" and within each block folder should be any number of "input" nodes. Below is a typical XML input that should produce the tree structure described above. Notice the tree should ignore the "form" and "title" nodes as well as the child nodes of "input". <contenttype> <config name="Person" version="1.0"> <form> <title name="last-name"/> <block name="Personal info"> <input name="last-name" type="text" required="true"> <display>Last name</display> <xpath>contentdata/last-name</xpath> <help>Enter the last name</help> </input> <input name="first-name" type="text" required="true"> <display>First name</display> <xpath>contentdata/first-name</xpath> <help>Enter the first name</help> </input> <input name="personal-history" type="textarea" required="true"> <display>Personal history</display> <xpath>contentdata/personal-history</xpath> <help>Enter relevant information</help> </input> </block> <block name="Pictures" group="contentdata/pictures"> <input name="portrait" type="image"> <display>Portrait picture</display> <xpath>contentdata/portrait</xpath> <help>Should be a passport type picture</help> </input> </block> </form> </config> </contenttype> Furthermore, I would like the name of the block folders to be the same as the name attribute of the block nodes and the name of the input nodes in the treePanel to be the same as the name attribute of the input elements in the XML. I tried all sorts of configurations for the TreeStore, Ajax Proxy, Xml Reader and fields. I eventually got a root folder and two folders named "undefined" but they did not appear in the preview or when I loaded the page in a browser. Also, it says records loaded but does not say how many the way other datastores do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7574412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: my own interpose function as an exercise I'm resolving a 4Clojure exercise, this exercise asks you to build your own interpose function. My answer follows: (fn my-interpose ([separator input] (my-interpose separator input nil)) ([separator input result] (if (empty? input) (reverse (rest result)) (my-interpose separator (rest input) (cons separator (cons (first input) result)))))) I'm doing these exercises to learn the language as I read a Clojure book. I will like to know the opinion about my code of people with an experience in the language. Could I avoid the reverse call? Are there any conventions I'm breaking hardly with this kind of code? A: What you have is a good proper starting point :). Excellent work. Starting with what you have you may want to: * *Replace your recursive call with a call to recur because as written it will hit a stack overflow (defn foo [stuff] (dostuff ... ) (foo (rest stuff))) becomes: (defn foo [stuff] (dostuff ...) (recur (rest stuff))) to avoid blowing the stack. this then often becomes: (map dostuff stuff) *Replace the recustion entirely with the for function (for [a one-list b another-list] (dont-give-away-the-answer)) A: Yes you can avoid the reverse call, (defn my-interpose [sep coll] (when (seq coll) (lazy-cat [(first coll) sep] (my-interpose sep (rest coll))))) as arthur suggest you can use recur in order to not to blow the stack but 99% of the time you don't need it. EDIT: This is a bit cleaner, (defn my-interpose [sep coll] (if-let [[first & rest] coll] (lazy-cat [first sep] (my-interpose sep rest)))) A: Got to various answers using mapcat and for but in the end I found this: #(rest (interleave (repeat %1) %2)) Where the first argument is the separator and the second is the collection. Just posting this answer for pure curiosity of other Clojure noobs like me. A: Here is my solution, trying to rely on lower-level lisp or scheme-like functions. (defn my-interpose[sep coll] (letfn [(f [c] (when-not (empty? c) (cons sep (cons (first c) (f (next c))))))] (next (f coll)))) A: You may want to use map (defn my-interpose [sep coll] (rest (apply concat (map #(vector sep %) coll)))) or a directly a reduce and compute the answer as you go (defn my-interpose [sep coll] (rest (reduce #(conj %1 sep %2) [] coll))) The idea behind this is to compute a sequence like (sep x0 sep x1 sep x2 ... sep xn) and then skip the first element to get (x0 sep x1 sep x2 ... xn). A: Using just reduce and conj: (defn my-interpose [sep a-seq] (if (empty? a-seq) a-seq (reduce (fn [e1 e2] (if (empty? e1) (conj e1 e2) (conj e1 sep e2))) [] a-seq)))
{ "language": "en", "url": "https://stackoverflow.com/questions/7574416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }